How to Write SQL Queries in Latte?

Latte can also be useful for generating really complex SQL queries.

If the creation of a SQL query contains many conditions and variables, it can be really clearer to write it in Latte. A very simple example:

SELECT users.* FROM users
	LEFT JOIN users_groups ON users.user_id = users_groups.user_id
 	LEFT JOIN groups ON groups.group_id = users_groups.group_id
	{ifset $country} LEFT JOIN country ON country.country_id = users.country_id {/ifset}
WHERE groups.name = 'Admins' {ifset $country} AND country.name = {$country} {/ifset}

Using $latte->setContentType() we tell Latte to treat the content as plain text (not as HTML) and then we prepare an escaping function that escapes strings directly by the database driver:

$db = new PDO(/* ... */);

$latte = new Latte\Engine;
$latte->setContentType(Latte\ContentType::Text);
$latte->addFilter('escape', fn($val) => match (true) {
	is_string($val) => $db->quote($val),
	is_int($val), is_float($val) => (string) $val,
	is_bool($val) => $val ? '1' : '0',
	is_null($val) => 'NULL',
	default => throw new Exception('Unsupported type'),
});

The usage would look like this:

$sql = $latte->renderToString('query.sql.latte', ['country' => $country]);
$result = $db->query($sql);

This example requires Latte v3.0.5 or higher.

version: 3.0