4 * Dear God Why Do I Have To Write This (Dumb SQL Builder)
8 * $select = CRM_Utils_SQL_Select::from('civicrm_activity act')
9 * ->join('absence', 'inner join civicrm_activity absence on absence.id = act.source_record_id')
10 * ->where('activity_type_id = #type', array('type' => 234))
11 * ->where('status_id IN (#statuses)', array('statuses' => array(1,2,3))
12 * ->where('subject like @subj', array('subj' => '%hello%'))
13 * ->where('!dynamicColumn = 1', array('dynamicColumn' => 'coalesce(is_active,0)'))
14 * ->where('!column = @value', array(
15 * 'column' => $customField->column_name,
16 * 'value' => $form['foo']
18 * echo $select->toSQL();
23 * - No knowledge of the underlying SQL API (except for escaping -- CRM_Core_DAO::escapeString)
24 * - No knowledge of the underlying data model
26 * - SQL clauses correspond to PHP functions ($select->where("foo_id=123"))
27 * - Variable escaping is concise and controllable based on prefixes, eg
28 * - similar to Drupal's t()
29 * - use "@varname" to insert the escaped value
30 * - use "!varname" to insert raw (unescaped) values
31 * - use "#varname" to insert a numerical value (these are validated but not escaped)
32 * - to disable any preprocessing, simply omit the variable list
33 * - control characters (@!#) are mandatory in expressions but optional in arg-keys
34 * - Variables may be individual values or arrays; arrays are imploded with commas
35 * - Conditionals are AND'd; if you need OR's, do it yourself
36 * - Use classes/functions with documentation (rather than undocumented array-trees)
37 * - For any given string, interpolation is only performed once. After an interpolation,
38 * a string may never again be subjected to interpolation.
40 * The "interpolate-once" principle can be enforced by either interpolating on input
41 * xor output. The notations for input and output interpolation are a bit different,
42 * and they may not be mixed.
45 * // Interpolate on input. Set params when using them.
46 * $select->where('activity_type_id = #type', array(
50 * // Interpolate on output. Set params independently.
52 * ->where('activity_type_id = #type')
53 * ->param('type', 234),
56 class CRM_Utils_SQL_Select
implements ArrayAccess
{
59 * Interpolate values as soon as they are passed in (where(), join(), etc).
63 * Pro: Every clause has its own unique namespace for parameters.
64 * Con: Probably slower.
65 * Advice: Use this when aggregating SQL fragments from agents who
66 * maintained by different parties.
68 const INTERPOLATE_INPUT
= 'in';
71 * Interpolate values when rendering SQL output (toSQL()).
73 * Pro: Probably faster.
74 * Con: Must maintain an aggregated list of all parameters.
75 * Advice: Use this when you have control over the entire query.
77 const INTERPOLATE_OUTPUT
= 'out';
80 * Determine mode automatically. When the first attempt is made
81 * to use input-interpolation (eg `where(..., array(...))`) or
82 * output-interpolation (eg `param(...)`), the mode will be
83 * set. Subsequent calls will be validated using the same mode.
85 const INTERPOLATE_AUTO
= 'auto';
88 private $insertInto = NULL;
89 private $insertIntoFields = array();
90 private $selects = array();
92 private $joins = array();
93 private $wheres = array();
94 private $groupBys = array();
95 private $havings = array();
96 private $orderBys = array();
97 private $limit = NULL;
98 private $offset = NULL;
99 private $params = array();
101 // Public to work-around PHP 5.3 limit.
102 public $strict = NULL;
105 * Create a new SELECT query.
107 * @param string $from
108 * Table-name and optional alias.
109 * @param array $options
110 * @return CRM_Utils_SQL_Select
112 public static function from($from, $options = array()) {
113 return new self($from, $options);
117 * Create a partial SELECT query.
119 * @param array $options
120 * @return CRM_Utils_SQL_Select
122 public static function fragment($options = array()) {
123 return new self(NULL, $options);
127 * Create a new SELECT query.
129 * @param string $from
130 * Table-name and optional alias.
131 * @param array $options
133 public function __construct($from, $options = array()) {
135 $this->mode
= isset($options['mode']) ?
$options['mode'] : self
::INTERPOLATE_AUTO
;
139 * Make a new copy of this query.
141 * @return CRM_Utils_SQL_Select
143 public function copy() {
148 * @param CRM_Utils_SQL_Select $other
149 * @param array|NULL $parts
150 * ex: 'joins', 'wheres'
153 public function merge($other, $parts = NULL) {
154 if ($other === NULL) {
158 if ($this->mode
=== self
::INTERPOLATE_AUTO
) {
159 $this->mode
= $other->mode
;
161 elseif ($other->mode
=== self
::INTERPOLATE_AUTO
) {
164 elseif ($this->mode
!== $other->mode
) {
165 // Mixing modes will lead to someone getting an expected substitution.
166 throw new RuntimeException("Cannot merge queries that use different interpolation modes ({$this->mode} vs {$other->mode}).");
169 $arrayFields = array('insertIntoFields', 'selects', 'joins', 'wheres', 'groupBys', 'havings', 'orderBys', 'params');
170 foreach ($arrayFields as $f) {
171 if ($parts === NULL ||
in_array($f, $parts)) {
172 $this->{$f} = array_merge($this->{$f}, $other->{$f});
176 $flatFields = array('insertInto', 'from', 'limit', 'offset');
177 foreach ($flatFields as $f) {
178 if ($parts === NULL ||
in_array($f, $parts)) {
179 if ($other->{$f} !== NULL) {
180 $this->{$f} = $other->{$f};
189 * Add a new JOIN clause.
191 * Note: To add multiple JOINs at once, use $name===NULL and
192 * pass an array of $exprs.
194 * @param string|NULL $name
195 * The effective alias of the joined table.
196 * @param string|array $exprs
197 * The complete join expression (eg "INNER JOIN mytable myalias ON mytable.id = maintable.foo_id").
198 * @param array|null $args
199 * @return CRM_Utils_SQL_Select
201 public function join($name, $exprs, $args = NULL) {
202 if ($name !== NULL) {
203 $this->joins
[$name] = $this->interpolate($exprs, $args);
206 foreach ($exprs as $name => $expr) {
207 $this->joins
[$name] = $this->interpolate($expr, $args);
215 * Specify the column(s)/value(s) to return by adding to the SELECT clause
217 * @param string|array $exprs list of SQL expressions
218 * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
219 * @return CRM_Utils_SQL_Select
221 public function select($exprs, $args = NULL) {
222 $exprs = (array) $exprs;
223 foreach ($exprs as $expr) {
224 $this->selects
[$expr] = $this->interpolate($expr, $args);
230 * Limit results by adding extra condition(s) to the WHERE clause
232 * @param string|array $exprs list of SQL expressions
233 * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
234 * @return CRM_Utils_SQL_Select
236 public function where($exprs, $args = NULL) {
237 $exprs = (array) $exprs;
238 foreach ($exprs as $expr) {
239 $evaluatedExpr = $this->interpolate($expr, $args);
240 $this->wheres
[$evaluatedExpr] = $evaluatedExpr;
246 * Group results by adding extra items to the GROUP BY clause.
248 * @param string|array $exprs list of SQL expressions
249 * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
250 * @return CRM_Utils_SQL_Select
252 public function groupBy($exprs, $args = NULL) {
253 $exprs = (array) $exprs;
254 foreach ($exprs as $expr) {
255 $this->groupBys
[$expr] = $this->interpolate($expr, $args);
261 * Limit results by adding extra condition(s) to the HAVING clause
263 * @param string|array $exprs list of SQL expressions
264 * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
265 * @return CRM_Utils_SQL_Select
267 public function having($exprs, $args = NULL) {
268 $exprs = (array) $exprs;
269 foreach ($exprs as $expr) {
270 $this->havings
[$expr] = $this->interpolate($expr, $args);
276 * Sort results by adding extra items to the ORDER BY clause.
278 * @param string|array $exprs list of SQL expressions
279 * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
280 * @return CRM_Utils_SQL_Select
282 public function orderBy($exprs, $args = NULL) {
283 $exprs = (array) $exprs;
284 foreach ($exprs as $expr) {
285 $this->orderBys
[$expr] = $this->interpolate($expr, $args);
291 * Set one (or multiple) parameters to interpolate into the query.
293 * @param array|string $keys
294 * Key name, or an array of key-value pairs.
295 * @param null|mixed $value
298 public function param($keys, $value = NULL) {
299 if ($this->mode
=== self
::INTERPOLATE_AUTO
) {
300 $this->mode
= self
::INTERPOLATE_OUTPUT
;
302 elseif ($this->mode
!== self
::INTERPOLATE_OUTPUT
) {
303 throw new RuntimeException("Select::param() only makes sense when interpolating on output.");
306 if (is_array($keys)) {
307 foreach ($keys as $k => $v) {
308 $this->params
[$k] = $v;
312 $this->params
[$keys] = $value;
318 * Set a limit on the number of records to return.
322 * @return CRM_Utils_SQL_Select
323 * @throws CRM_Core_Exception
325 public function limit($limit, $offset = 0) {
326 if ($limit !== NULL && !is_numeric($limit)) {
327 throw new CRM_Core_Exception("Illegal limit");
329 if ($offset !== NULL && !is_numeric($offset)) {
330 throw new CRM_Core_Exception("Illegal offset");
332 $this->limit
= $limit;
333 $this->offset
= $offset;
338 * Insert the results of the SELECT query into another
341 * @param string $table
342 * The name of the other table (which receives new data).
343 * @param array $fields
344 * The fields to fill in the other table (in order).
346 * @see insertIntoField
348 public function insertInto($table, $fields = array()) {
349 $this->insertInto
= $table;
350 $this->insertIntoField($fields);
355 * @param array $fields
356 * The fields to fill in the other table (in order).
359 public function insertIntoField($fields) {
360 $fields = (array) $fields;
361 foreach ($fields as $field) {
362 $this->insertIntoFields
[] = $field;
368 * @param array|NULL $parts
369 * List of fields to check (e.g. 'selects', 'joins').
373 public function isEmpty($parts = NULL) {
388 if ($parts !== NULL) {
389 $fields = array_intersect($fields, $parts);
391 foreach ($fields as $field) {
392 if (!empty($this->{$field})) {
400 * Enable (or disable) strict mode.
402 * In strict mode, unknown variables will generate exceptions.
404 * @param bool $strict
407 public function strict($strict = TRUE) {
408 $this->strict
= $strict;
413 * Given a string like "field_name = @value", replace "@value" with an escaped SQL string
415 * @param $expr SQL expression
416 * @param null|array $args a list of values to insert into the SQL expression; keys are prefix-coded:
417 * prefix '@' => escape SQL
418 * prefix '#' => literal number, skip escaping but do validation
419 * prefix '!' => literal, skip escaping and validation
420 * if a value is an array, then it will be imploded
422 * PHP NULL's will be treated as SQL NULL's. The PHP string "null" will be treated as a string.
424 * @throws CRM_Core_Exception
428 public function interpolate($expr, $args, $activeMode = self
::INTERPOLATE_INPUT
) {
429 if ($args === NULL) {
433 if ($this->mode
=== self
::INTERPOLATE_AUTO
) {
434 $this->mode
= $activeMode;
436 elseif ($activeMode !== $this->mode
) {
437 throw new RuntimeException("Cannot mix interpolation modes.");
441 return preg_replace_callback('/([#!@])([a-zA-Z0-9_]+)/', function($m) use ($select, $args) {
442 if (isset($args[$m[2]])) {
443 $values = $args[$m[2]];
445 elseif (isset($args[$m[1] . $m[2]])) {
446 // Backward compat. Keys in $args look like "#myNumber" or "@myString".
447 $values = $args[$m[1] . $m[2]];
449 elseif ($select->strict
) {
450 throw new CRM_Core_Exception('Cannot build query. Variable "' . $m[1] . $m[2] . '" is unknown.');
453 // Unrecognized variables are ignored. Mitigate risk of accidents.
456 $values = is_array($values) ?
$values : array($values);
459 $parts = array_map(array($select, 'escapeString'), $values);
460 return implode(', ', $parts);
463 return implode(', ', $values);
466 foreach ($values as $valueKey => $value) {
467 if ($value === NULL) {
468 $values[$valueKey] = 'NULL';
470 elseif (!is_numeric($value)) {
471 //throw new API_Exception("Failed encoding non-numeric value" . var_export(array($key => $args[$key]), TRUE));
472 throw new CRM_Core_Exception("Failed encoding non-numeric value");
475 return implode(', ', $values);
478 throw new CRM_Core_Exception("Unrecognized prefix");
485 * @param string|NULL $value
487 * SQL expression, e.g. "it\'s great" (with-quotes) or NULL (without-quotes)
489 public function escapeString($value) {
490 return $value === NULL ?
'NULL' : '"' . CRM_Core_DAO
::escapeString($value) . '"';
497 public function toSQL() {
499 if ($this->insertInto
) {
500 $sql .= 'INSERT INTO ' . $this->insertInto
. ' (';
501 $sql .= implode(', ', $this->insertIntoFields
);
504 if ($this->selects
) {
505 $sql .= 'SELECT ' . implode(', ', $this->selects
) . "\n";
508 $sql .= 'SELECT *' . "\n";
510 if ($this->from
!== NULL) {
511 $sql .= 'FROM ' . $this->from
. "\n";
513 foreach ($this->joins
as $join) {
514 $sql .= $join . "\n";
517 $sql .= 'WHERE (' . implode(') AND (', $this->wheres
) . ")\n";
519 if ($this->groupBys
) {
520 $sql .= 'GROUP BY ' . implode(', ', $this->groupBys
) . "\n";
522 if ($this->havings
) {
523 $sql .= 'HAVING (' . implode(') AND (', $this->havings
) . ")\n";
525 if ($this->orderBys
) {
526 $sql .= 'ORDER BY ' . implode(', ', $this->orderBys
) . "\n";
528 if ($this->limit
!== NULL) {
529 $sql .= 'LIMIT ' . $this->limit
. "\n";
530 if ($this->offset
!== NULL) {
531 $sql .= 'OFFSET ' . $this->offset
. "\n";
534 if ($this->mode
=== self
::INTERPOLATE_OUTPUT
) {
535 $sql = $this->interpolate($sql, $this->params
, self
::INTERPOLATE_OUTPUT
);
540 public function offsetExists($offset) {
541 return isset($this->params
[$offset]);
544 public function offsetGet($offset) {
545 return $this->params
[$offset];
548 public function offsetSet($offset, $value) {
549 $this->param($offset, $value);
552 public function offsetUnset($offset) {
553 unset($this->params
[$offset]);