SQL fragment abstraction

SQL fragment abstraction

par Petr Skoda,
Nombre de réponses : 0

Do you find dealing with two separate variables for SQL code and parameters confusing?

Did you ever get parameter name conflicts or did you receive wrong paramter types when constructing a complex SQL query from different sources?

Lets create a new class that encapsulates SQL code and relevant parameters. And while at it let the new object handle concatenation of SQL with conflicting parameter names and even different parameter types.

Example for illustration:

$part1 = new \core_dml\query('deleted = :param', ['param' => 0]);
$part2 = new \core_dml\query('confirmed = ?', [1]);
$part3 = new \core_dml\query('AND mnethostid = :param', ['param' => $CFG->mnet_localhost_id]);

$sql = new \core_dml\query('SELECT u.* FROM {user} WHERE');
$sql = $sql->append($part1)->append('AND')->append($part2)->append($part3);

[$sqlquery, $params] = $sql;
['sql' => $sqlquery, 'params' => $params] = $sql;

var_export($sql->sql);
// SELECT * FROM {user} WHERE deleted = :param AND confirmed = :qm_param_1 AND mnethostid = :nm_param_1
var_export($sql->params);
// ['param' => 0, 'qm_param_1' => 1, 'nm_param_1' => 1]

$users = $DB->get_records_sql($sql);
$users = $DB->get_records_select('user', $part1->append('AND')->append($part2));

Note that coding this and patching existing DB drivers is easy, the difficult part here is to persuade Moodle HQ to include this in core...