3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Dear God Why Do I Have To Write This (Dumb SQL Builder)
33 * $select = CRM_Utils_SQL_Select::from('civicrm_activity act')
34 * ->join('absence', 'inner join civicrm_activity absence on absence.id = act.source_record_id')
35 * ->where('activity_type_id = #type', array('type' => 234))
36 * ->where('status_id IN (#statuses)', array('statuses' => array(1,2,3))
37 * ->where('subject like @subj', array('subj' => '%hello%'))
38 * ->where('!dynamicColumn = 1', array('dynamicColumn' => 'coalesce(is_active,0)'))
39 * ->where('!column = @value', array(
40 * 'column' => $customField->column_name,
41 * 'value' => $form['foo']
43 * echo $select->toSQL();
48 * - No knowledge of the underlying SQL API (except for escaping -- CRM_Core_DAO::escapeString)
49 * - No knowledge of the underlying data model
51 * - SQL clauses correspond to PHP functions ($select->where("foo_id=123"))
52 * - Variable escaping is concise and controllable based on prefixes, eg
53 * - similar to Drupal's t()
54 * - use "@varname" to insert the escaped value
55 * - use "!varname" to insert raw (unescaped) values
56 * - use "#varname" to insert a numerical value (these are validated but not escaped)
57 * - to disable any preprocessing, simply omit the variable list
58 * - control characters (@!#) are mandatory in expressions but optional in arg-keys
59 * - Variables may be individual values or arrays; arrays are imploded with commas
60 * - Conditionals are AND'd; if you need OR's, do it yourself
61 * - Use classes/functions with documentation (rather than undocumented array-trees)
62 * - For any given string, interpolation is only performed once. After an interpolation,
63 * a string may never again be subjected to interpolation.
65 * The "interpolate-once" principle can be enforced by either interpolating on input
66 * xor output. The notations for input and output interpolation are a bit different,
67 * and they may not be mixed.
70 * // Interpolate on input. Set params when using them.
71 * $select->where('activity_type_id = #type', array(
75 * // Interpolate on output. Set params independently.
77 * ->where('activity_type_id = #type')
78 * ->param('type', 234),
82 * @copyright CiviCRM LLC (c) 2004-2015
84 class CRM_Utils_SQL_Select
implements ArrayAccess
{
87 * Interpolate values as soon as they are passed in (where(), join(), etc).
91 * Pro: Every clause has its own unique namespace for parameters.
92 * Con: Probably slower.
93 * Advice: Use this when aggregating SQL fragments from agents who
94 * maintained by different parties.
96 const INTERPOLATE_INPUT
= 'in';
99 * Interpolate values when rendering SQL output (toSQL()).
101 * Pro: Probably faster.
102 * Con: Must maintain an aggregated list of all parameters.
103 * Advice: Use this when you have control over the entire query.
105 const INTERPOLATE_OUTPUT
= 'out';
108 * Determine mode automatically. When the first attempt is made
109 * to use input-interpolation (eg `where(..., array(...))`) or
110 * output-interpolation (eg `param(...)`), the mode will be
111 * set. Subsequent calls will be validated using the same mode.
113 const INTERPOLATE_AUTO
= 'auto';
115 private $mode = NULL;
116 private $insertInto = NULL;
117 private $insertIntoFields = array();
118 private $selects = array();
120 private $joins = array();
121 private $wheres = array();
122 private $groupBys = array();
123 private $havings = array();
124 private $orderBys = array();
125 private $limit = NULL;
126 private $offset = NULL;
127 private $params = array();
129 // Public to work-around PHP 5.3 limit.
130 public $strict = NULL;
133 * Create a new SELECT query.
135 * @param string $from
136 * Table-name and optional alias.
137 * @param array $options
138 * @return CRM_Utils_SQL_Select
140 public static function from($from, $options = array()) {
141 return new self($from, $options);
145 * Create a partial SELECT query.
147 * @param array $options
148 * @return CRM_Utils_SQL_Select
150 public static function fragment($options = array()) {
151 return new self(NULL, $options);
155 * Create a new SELECT query.
157 * @param string $from
158 * Table-name and optional alias.
159 * @param array $options
161 public function __construct($from, $options = array()) {
163 $this->mode
= isset($options['mode']) ?
$options['mode'] : self
::INTERPOLATE_AUTO
;
167 * Make a new copy of this query.
169 * @return CRM_Utils_SQL_Select
171 public function copy() {
176 * Merge something or other.
178 * @param CRM_Utils_SQL_Select $other
179 * @param array|NULL $parts
180 * ex: 'joins', 'wheres'
183 public function merge($other, $parts = NULL) {
184 if ($other === NULL) {
188 if ($this->mode
=== self
::INTERPOLATE_AUTO
) {
189 $this->mode
= $other->mode
;
191 elseif ($other->mode
=== self
::INTERPOLATE_AUTO
) {
194 elseif ($this->mode
!== $other->mode
) {
195 // Mixing modes will lead to someone getting an expected substitution.
196 throw new RuntimeException("Cannot merge queries that use different interpolation modes ({$this->mode} vs {$other->mode}).");
199 $arrayFields = array('insertIntoFields', 'selects', 'joins', 'wheres', 'groupBys', 'havings', 'orderBys', 'params');
200 foreach ($arrayFields as $f) {
201 if ($parts === NULL ||
in_array($f, $parts)) {
202 $this->{$f} = array_merge($this->{$f}, $other->{$f});
206 $flatFields = array('insertInto', 'from', 'limit', 'offset');
207 foreach ($flatFields as $f) {
208 if ($parts === NULL ||
in_array($f, $parts)) {
209 if ($other->{$f} !== NULL) {
210 $this->{$f} = $other->{$f};
219 * Add a new JOIN clause.
221 * Note: To add multiple JOINs at once, use $name===NULL and
222 * pass an array of $exprs.
224 * @param string|NULL $name
225 * The effective alias of the joined table.
226 * @param string|array $exprs
227 * The complete join expression (eg "INNER JOIN mytable myalias ON mytable.id = maintable.foo_id").
228 * @param array|null $args
229 * @return CRM_Utils_SQL_Select
231 public function join($name, $exprs, $args = NULL) {
232 if ($name !== NULL) {
233 $this->joins
[$name] = $this->interpolate($exprs, $args);
236 foreach ($exprs as $name => $expr) {
237 $this->joins
[$name] = $this->interpolate($expr, $args);
245 * Specify the column(s)/value(s) to return by adding to the SELECT clause
247 * @param string|array $exprs list of SQL expressions
248 * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
249 * @return CRM_Utils_SQL_Select
251 public function select($exprs, $args = NULL) {
252 $exprs = (array) $exprs;
253 foreach ($exprs as $expr) {
254 $this->selects
[] = $this->interpolate($expr, $args);
260 * Limit results by adding extra condition(s) to the WHERE clause
262 * @param string|array $exprs list of SQL expressions
263 * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
264 * @return CRM_Utils_SQL_Select
266 public function where($exprs, $args = NULL) {
267 $exprs = (array) $exprs;
268 foreach ($exprs as $expr) {
269 $evaluatedExpr = $this->interpolate($expr, $args);
270 $this->wheres
[$evaluatedExpr] = $evaluatedExpr;
276 * Group results by adding extra items to the GROUP 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 groupBy($exprs, $args = NULL) {
283 $exprs = (array) $exprs;
284 foreach ($exprs as $expr) {
285 $evaluatedExpr = $this->interpolate($expr, $args);
286 $this->groupBys
[$evaluatedExpr] = $evaluatedExpr;
292 * Limit results by adding extra condition(s) to the HAVING clause
294 * @param string|array $exprs list of SQL expressions
295 * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
296 * @return CRM_Utils_SQL_Select
298 public function having($exprs, $args = NULL) {
299 $exprs = (array) $exprs;
300 foreach ($exprs as $expr) {
301 $evaluatedExpr = $this->interpolate($expr, $args);
302 $this->havings
[$evaluatedExpr] = $evaluatedExpr;
308 * Sort results by adding extra items to the ORDER BY clause.
310 * @param string|array $exprs list of SQL expressions
311 * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
312 * @return CRM_Utils_SQL_Select
314 public function orderBy($exprs, $args = NULL) {
315 $exprs = (array) $exprs;
316 foreach ($exprs as $expr) {
317 $evaluatedExpr = $this->interpolate($expr, $args);
318 $this->orderBys
[$evaluatedExpr] = $evaluatedExpr;
324 * Set one (or multiple) parameters to interpolate into the query.
326 * @param array|string $keys
327 * Key name, or an array of key-value pairs.
328 * @param null|mixed $value
331 public function param($keys, $value = NULL) {
332 if ($this->mode
=== self
::INTERPOLATE_AUTO
) {
333 $this->mode
= self
::INTERPOLATE_OUTPUT
;
335 elseif ($this->mode
!== self
::INTERPOLATE_OUTPUT
) {
336 throw new RuntimeException("Select::param() only makes sense when interpolating on output.");
339 if (is_array($keys)) {
340 foreach ($keys as $k => $v) {
341 $this->params
[$k] = $v;
345 $this->params
[$keys] = $value;
351 * Set a limit on the number of records to return.
355 * @return CRM_Utils_SQL_Select
356 * @throws CRM_Core_Exception
358 public function limit($limit, $offset = 0) {
359 if ($limit !== NULL && !is_numeric($limit)) {
360 throw new CRM_Core_Exception("Illegal limit");
362 if ($offset !== NULL && !is_numeric($offset)) {
363 throw new CRM_Core_Exception("Illegal offset");
365 $this->limit
= $limit;
366 $this->offset
= $offset;
371 * Insert the results of the SELECT query into another
374 * @param string $table
375 * The name of the other table (which receives new data).
376 * @param array $fields
377 * The fields to fill in the other table (in order).
379 * @see insertIntoField
381 public function insertInto($table, $fields = array()) {
382 $this->insertInto
= $table;
383 $this->insertIntoField($fields);
388 * @param array $fields
389 * The fields to fill in the other table (in order).
392 public function insertIntoField($fields) {
393 $fields = (array) $fields;
394 foreach ($fields as $field) {
395 $this->insertIntoFields
[] = $field;
401 * @param array|NULL $parts
402 * List of fields to check (e.g. 'selects', 'joins').
406 public function isEmpty($parts = NULL) {
421 if ($parts !== NULL) {
422 $fields = array_intersect($fields, $parts);
424 foreach ($fields as $field) {
425 if (!empty($this->{$field})) {
433 * Enable (or disable) strict mode.
435 * In strict mode, unknown variables will generate exceptions.
437 * @param bool $strict
440 public function strict($strict = TRUE) {
441 $this->strict
= $strict;
446 * Given a string like "field_name = @value", replace "@value" with an escaped SQL string
448 * @param $expr SQL expression
449 * @param null|array $args a list of values to insert into the SQL expression; keys are prefix-coded:
450 * prefix '@' => escape SQL
451 * prefix '#' => literal number, skip escaping but do validation
452 * prefix '!' => literal, skip escaping and validation
453 * if a value is an array, then it will be imploded
455 * PHP NULL's will be treated as SQL NULL's. The PHP string "null" will be treated as a string.
457 * @param string $activeMode
461 public function interpolate($expr, $args, $activeMode = self
::INTERPOLATE_INPUT
) {
462 if ($args === NULL) {
466 if ($this->mode
=== self
::INTERPOLATE_AUTO
) {
467 $this->mode
= $activeMode;
469 elseif ($activeMode !== $this->mode
) {
470 throw new RuntimeException("Cannot mix interpolation modes.");
474 return preg_replace_callback('/([#!@])([a-zA-Z0-9_]+)/', function($m) use ($select, $args) {
475 if (isset($args[$m[2]])) {
476 $values = $args[$m[2]];
478 elseif (isset($args[$m[1] . $m[2]])) {
479 // Backward compat. Keys in $args look like "#myNumber" or "@myString".
480 $values = $args[$m[1] . $m[2]];
482 elseif ($select->strict
) {
483 throw new CRM_Core_Exception('Cannot build query. Variable "' . $m[1] . $m[2] . '" is unknown.');
486 // Unrecognized variables are ignored. Mitigate risk of accidents.
489 $values = is_array($values) ?
$values : array($values);
492 $parts = array_map(array($select, 'escapeString'), $values);
493 return implode(', ', $parts);
495 // TODO: ensure all uses of this un-escaped literal are safe
497 return implode(', ', $values);
500 foreach ($values as $valueKey => $value) {
501 if ($value === NULL) {
502 $values[$valueKey] = 'NULL';
504 elseif (!is_numeric($value)) {
505 //throw new API_Exception("Failed encoding non-numeric value" . var_export(array($m[0] => $values), TRUE));
506 throw new CRM_Core_Exception("Failed encoding non-numeric value (" . $m[0] . ")");
509 return implode(', ', $values);
512 throw new CRM_Core_Exception("Unrecognized prefix");
519 * @param string|NULL $value
521 * SQL expression, e.g. "it\'s great" (with-quotes) or NULL (without-quotes)
523 public function escapeString($value) {
524 return $value === NULL ?
'NULL' : '"' . CRM_Core_DAO
::escapeString($value) . '"';
531 public function toSQL() {
533 if ($this->insertInto
) {
534 $sql .= 'INSERT INTO ' . $this->insertInto
. ' (';
535 $sql .= implode(', ', $this->insertIntoFields
);
538 if ($this->selects
) {
539 $sql .= 'SELECT ' . implode(', ', $this->selects
) . "\n";
542 $sql .= 'SELECT *' . "\n";
544 if ($this->from
!== NULL) {
545 $sql .= 'FROM ' . $this->from
. "\n";
547 foreach ($this->joins
as $join) {
548 $sql .= $join . "\n";
551 $sql .= 'WHERE (' . implode(') AND (', $this->wheres
) . ")\n";
553 if ($this->groupBys
) {
554 $sql .= 'GROUP BY ' . implode(', ', $this->groupBys
) . "\n";
556 if ($this->havings
) {
557 $sql .= 'HAVING (' . implode(') AND (', $this->havings
) . ")\n";
559 if ($this->orderBys
) {
560 $sql .= 'ORDER BY ' . implode(', ', $this->orderBys
) . "\n";
562 if ($this->limit
!== NULL) {
563 $sql .= 'LIMIT ' . $this->limit
. "\n";
564 if ($this->offset
!== NULL) {
565 $sql .= 'OFFSET ' . $this->offset
. "\n";
568 if ($this->mode
=== self
::INTERPOLATE_OUTPUT
) {
569 $sql = $this->interpolate($sql, $this->params
, self
::INTERPOLATE_OUTPUT
);
574 public function offsetExists($offset) {
575 return isset($this->params
[$offset]);
578 public function offsetGet($offset) {
579 return $this->params
[$offset];
582 public function offsetSet($offset, $value) {
583 $this->param($offset, $value);
586 public function offsetUnset($offset) {
587 unset($this->params
[$offset]);