Complex classes like QueryBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use QueryBuilder, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
23 | class QueryBuilder extends \yii\base\Object |
||
24 | { |
||
25 | /** |
||
26 | * The prefix for automatically generated query binding parameters. |
||
27 | */ |
||
28 | const PARAM_PREFIX = ':qp'; |
||
29 | |||
30 | /** |
||
31 | * @var Connection the database connection. |
||
32 | */ |
||
33 | public $db; |
||
34 | /** |
||
35 | * @var string the separator between different fragments of a SQL statement. |
||
36 | * Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement. |
||
37 | */ |
||
38 | public $separator = ' '; |
||
39 | /** |
||
40 | * @var array the abstract column types mapped to physical column types. |
||
41 | * This is mainly used to support creating/modifying tables using DB-independent data type specifications. |
||
42 | * Child classes should override this property to declare supported type mappings. |
||
43 | */ |
||
44 | public $typeMap = []; |
||
45 | |||
46 | /** |
||
47 | * @var array map of query condition to builder methods. |
||
48 | * These methods are used by [[buildCondition]] to build SQL conditions from array syntax. |
||
49 | */ |
||
50 | protected $conditionBuilders = [ |
||
51 | 'NOT' => 'buildNotCondition', |
||
52 | 'AND' => 'buildAndCondition', |
||
53 | 'OR' => 'buildAndCondition', |
||
54 | 'BETWEEN' => 'buildBetweenCondition', |
||
55 | 'NOT BETWEEN' => 'buildBetweenCondition', |
||
56 | 'IN' => 'buildInCondition', |
||
57 | 'NOT IN' => 'buildInCondition', |
||
58 | 'LIKE' => 'buildLikeCondition', |
||
59 | 'NOT LIKE' => 'buildLikeCondition', |
||
60 | 'OR LIKE' => 'buildLikeCondition', |
||
61 | 'OR NOT LIKE' => 'buildLikeCondition', |
||
62 | 'EXISTS' => 'buildExistsCondition', |
||
63 | 'NOT EXISTS' => 'buildExistsCondition', |
||
64 | ]; |
||
65 | |||
66 | |||
67 | /** |
||
68 | * Constructor. |
||
69 | * @param Connection $connection the database connection. |
||
70 | * @param array $config name-value pairs that will be used to initialize the object properties |
||
71 | */ |
||
72 | 651 | public function __construct($connection, $config = []) |
|
77 | |||
78 | /** |
||
79 | * Generates a SELECT SQL statement from a [[Query]] object. |
||
80 | * @param Query $query the [[Query]] object from which the SQL statement will be generated. |
||
81 | * @param array $params the parameters to be bound to the generated SQL statement. These parameters will |
||
82 | * be included in the result with the additional parameters generated during the query building process. |
||
83 | * @return array the generated SQL statement (the first array element) and the corresponding |
||
84 | * parameters to be bound to the SQL statement (the second array element). The parameters returned |
||
85 | * include those provided in `$params`. |
||
86 | */ |
||
87 | 441 | public function build($query, $params = []) |
|
88 | { |
||
89 | 441 | $query = $query->prepare($this); |
|
90 | |||
91 | 441 | $params = empty($params) ? $query->params : array_merge($params, $query->params); |
|
92 | |||
93 | $clauses = [ |
||
94 | 441 | $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption), |
|
95 | 441 | $this->buildFrom($query->from, $params), |
|
96 | 441 | $this->buildJoin($query->join, $params), |
|
97 | 441 | $this->buildWhere($query->where, $params), |
|
98 | 441 | $this->buildGroupBy($query->groupBy), |
|
99 | 441 | $this->buildHaving($query->having, $params), |
|
100 | 441 | ]; |
|
101 | |||
102 | 441 | $sql = implode($this->separator, array_filter($clauses)); |
|
103 | 441 | $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset); |
|
104 | |||
105 | 441 | if (!empty($query->orderBy)) { |
|
106 | 74 | foreach ($query->orderBy as $expression) { |
|
107 | 74 | if ($expression instanceof Expression) { |
|
108 | 2 | $params = array_merge($params, $expression->params); |
|
109 | 2 | } |
|
110 | 74 | } |
|
111 | 74 | } |
|
112 | 441 | if (!empty($query->groupBy)) { |
|
113 | 6 | foreach ($query->groupBy as $expression) { |
|
114 | 6 | if ($expression instanceof Expression) { |
|
115 | 2 | $params = array_merge($params, $expression->params); |
|
116 | 2 | } |
|
117 | 6 | } |
|
118 | 6 | } |
|
119 | |||
120 | 441 | $union = $this->buildUnion($query->union, $params); |
|
121 | 441 | if ($union !== '') { |
|
122 | 8 | $sql = "($sql){$this->separator}$union"; |
|
123 | 8 | } |
|
124 | |||
125 | 441 | return [$sql, $params]; |
|
126 | } |
||
127 | |||
128 | /** |
||
129 | * Creates an INSERT SQL statement. |
||
130 | * For example, |
||
131 | * |
||
132 | * ```php |
||
133 | * $sql = $queryBuilder->insert('user', [ |
||
134 | * 'name' => 'Sam', |
||
135 | * 'age' => 30, |
||
136 | * ], $params); |
||
137 | * ``` |
||
138 | * |
||
139 | * The method will properly escape the table and column names. |
||
140 | * |
||
141 | * @param string $table the table that new rows will be inserted into. |
||
142 | * @param array $columns the column data (name => value) to be inserted into the table. |
||
143 | * @param array $params the binding parameters that will be generated by this method. |
||
144 | * They should be bound to the DB command later. |
||
145 | * @return string the INSERT SQL |
||
146 | */ |
||
147 | 69 | public function insert($table, $columns, &$params) |
|
175 | |||
176 | /** |
||
177 | * Generates a batch INSERT SQL statement. |
||
178 | * For example, |
||
179 | * |
||
180 | * ```php |
||
181 | * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [ |
||
182 | * ['Tom', 30], |
||
183 | * ['Jane', 20], |
||
184 | * ['Linda', 25], |
||
185 | * ]); |
||
186 | * ``` |
||
187 | * |
||
188 | * Note that the values in each row must match the corresponding column names. |
||
189 | * |
||
190 | * The method will properly escape the column names, and quote the values to be inserted. |
||
191 | * |
||
192 | * @param string $table the table that new rows will be inserted into. |
||
193 | * @param array $columns the column names |
||
194 | * @param array $rows the rows to be batch inserted into the table |
||
195 | * @return string the batch INSERT SQL statement |
||
196 | */ |
||
197 | 5 | public function batchInsert($table, $columns, $rows) |
|
198 | { |
||
199 | 5 | $schema = $this->db->getSchema(); |
|
200 | 5 | if (($tableSchema = $schema->getTableSchema($table)) !== null) { |
|
201 | 3 | $columnSchemas = $tableSchema->columns; |
|
202 | 3 | } else { |
|
203 | 2 | $columnSchemas = []; |
|
204 | } |
||
205 | |||
206 | 5 | $values = []; |
|
207 | 5 | foreach ($rows as $row) { |
|
208 | 5 | $vs = []; |
|
209 | 5 | foreach ($row as $i => $value) { |
|
210 | 5 | if (isset($columns[$i], $columnSchemas[$columns[$i]]) && !is_array($value)) { |
|
211 | 3 | $value = $columnSchemas[$columns[$i]]->dbTypecast($value); |
|
212 | 3 | } |
|
213 | 5 | if (is_string($value)) { |
|
214 | 5 | $value = $schema->quoteValue($value); |
|
215 | 5 | } elseif ($value === false) { |
|
216 | $value = 0; |
||
217 | 5 | } elseif ($value === null) { |
|
218 | 2 | $value = 'NULL'; |
|
219 | 2 | } |
|
220 | 5 | $vs[] = $value; |
|
221 | 5 | } |
|
222 | 5 | $values[] = '(' . implode(', ', $vs) . ')'; |
|
223 | 5 | } |
|
224 | |||
225 | 5 | foreach ($columns as $i => $name) { |
|
226 | 5 | $columns[$i] = $schema->quoteColumnName($name); |
|
227 | 5 | } |
|
228 | |||
229 | 5 | return 'INSERT INTO ' . $schema->quoteTableName($table) |
|
230 | 5 | . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values); |
|
231 | } |
||
232 | |||
233 | /** |
||
234 | * Creates an UPDATE SQL statement. |
||
235 | * For example, |
||
236 | * |
||
237 | * ```php |
||
238 | * $params = []; |
||
239 | * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params); |
||
240 | * ``` |
||
241 | * |
||
242 | * The method will properly escape the table and column names. |
||
243 | * |
||
244 | * @param string $table the table to be updated. |
||
245 | * @param array $columns the column data (name => value) to be updated. |
||
246 | * @param array|string $condition the condition that will be put in the WHERE part. Please |
||
247 | * refer to [[Query::where()]] on how to specify condition. |
||
248 | * @param array $params the binding parameters that will be modified by this method |
||
249 | * so that they can be bound to the DB command later. |
||
250 | * @return string the UPDATE SQL |
||
251 | */ |
||
252 | 61 | public function update($table, $columns, $condition, &$params) |
|
279 | |||
280 | /** |
||
281 | * Creates a DELETE SQL statement. |
||
282 | * For example, |
||
283 | * |
||
284 | * ```php |
||
285 | * $sql = $queryBuilder->delete('user', 'status = 0'); |
||
286 | * ``` |
||
287 | * |
||
288 | * The method will properly escape the table and column names. |
||
289 | * |
||
290 | * @param string $table the table where the data will be deleted from. |
||
291 | * @param array|string $condition the condition that will be put in the WHERE part. Please |
||
292 | * refer to [[Query::where()]] on how to specify condition. |
||
293 | * @param array $params the binding parameters that will be modified by this method |
||
294 | * so that they can be bound to the DB command later. |
||
295 | * @return string the DELETE SQL |
||
296 | */ |
||
297 | 99 | public function delete($table, $condition, &$params) |
|
304 | |||
305 | /** |
||
306 | * Builds a SQL statement for creating a new DB table. |
||
307 | * |
||
308 | * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'), |
||
309 | * where name stands for a column name which will be properly quoted by the method, and definition |
||
310 | * stands for the column type which can contain an abstract DB type. |
||
311 | * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one. |
||
312 | * |
||
313 | * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly |
||
314 | * inserted into the generated SQL. |
||
315 | * |
||
316 | * For example, |
||
317 | * |
||
318 | * ```php |
||
319 | * $sql = $queryBuilder->createTable('user', [ |
||
320 | * 'id' => 'pk', |
||
321 | * 'name' => 'string', |
||
322 | * 'age' => 'integer', |
||
323 | * ]); |
||
324 | * ``` |
||
325 | * |
||
326 | * @param string $table the name of the table to be created. The name will be properly quoted by the method. |
||
327 | * @param array $columns the columns (name => definition) in the new table. |
||
328 | * @param string $options additional SQL fragment that will be appended to the generated SQL. |
||
329 | * @return string the SQL statement for creating a new DB table. |
||
330 | */ |
||
331 | 40 | public function createTable($table, $columns, $options = null) |
|
345 | |||
346 | /** |
||
347 | * Builds a SQL statement for renaming a DB table. |
||
348 | * @param string $oldName the table to be renamed. The name will be properly quoted by the method. |
||
349 | * @param string $newName the new table name. The name will be properly quoted by the method. |
||
350 | * @return string the SQL statement for renaming a DB table. |
||
351 | */ |
||
352 | 1 | public function renameTable($oldName, $newName) |
|
356 | |||
357 | /** |
||
358 | * Builds a SQL statement for dropping a DB table. |
||
359 | * @param string $table the table to be dropped. The name will be properly quoted by the method. |
||
360 | * @return string the SQL statement for dropping a DB table. |
||
361 | */ |
||
362 | 7 | public function dropTable($table) |
|
366 | |||
367 | /** |
||
368 | * Builds a SQL statement for adding a primary key constraint to an existing table. |
||
369 | * @param string $name the name of the primary key constraint. |
||
370 | * @param string $table the table that the primary key constraint will be added to. |
||
371 | * @param string|array $columns comma separated string or array of columns that the primary key will consist of. |
||
372 | * @return string the SQL statement for adding a primary key constraint to an existing table. |
||
373 | */ |
||
374 | 2 | public function addPrimaryKey($name, $table, $columns) |
|
388 | |||
389 | /** |
||
390 | * Builds a SQL statement for removing a primary key constraint to an existing table. |
||
391 | * @param string $name the name of the primary key constraint to be removed. |
||
392 | * @param string $table the table that the primary key constraint will be removed from. |
||
393 | * @return string the SQL statement for removing a primary key constraint from an existing table. |
||
394 | */ |
||
395 | 1 | public function dropPrimaryKey($name, $table) |
|
400 | |||
401 | /** |
||
402 | * Builds a SQL statement for truncating a DB table. |
||
403 | * @param string $table the table to be truncated. The name will be properly quoted by the method. |
||
404 | * @return string the SQL statement for truncating a DB table. |
||
405 | */ |
||
406 | 5 | public function truncateTable($table) |
|
410 | |||
411 | /** |
||
412 | * Builds a SQL statement for adding a new DB column. |
||
413 | * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method. |
||
414 | * @param string $column the name of the new column. The name will be properly quoted by the method. |
||
415 | * @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any) |
||
416 | * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. |
||
417 | * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'. |
||
418 | * @return string the SQL statement for adding a new column. |
||
419 | */ |
||
420 | 4 | public function addColumn($table, $column, $type) |
|
426 | |||
427 | /** |
||
428 | * Builds a SQL statement for dropping a DB column. |
||
429 | * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method. |
||
430 | * @param string $column the name of the column to be dropped. The name will be properly quoted by the method. |
||
431 | * @return string the SQL statement for dropping a DB column. |
||
432 | */ |
||
433 | public function dropColumn($table, $column) |
||
438 | |||
439 | /** |
||
440 | * Builds a SQL statement for renaming a column. |
||
441 | * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method. |
||
442 | * @param string $oldName the old name of the column. The name will be properly quoted by the method. |
||
443 | * @param string $newName the new name of the column. The name will be properly quoted by the method. |
||
444 | * @return string the SQL statement for renaming a DB column. |
||
445 | */ |
||
446 | public function renameColumn($table, $oldName, $newName) |
||
452 | |||
453 | /** |
||
454 | * Builds a SQL statement for changing the definition of a column. |
||
455 | * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method. |
||
456 | * @param string $column the name of the column to be changed. The name will be properly quoted by the method. |
||
457 | * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract |
||
458 | * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept |
||
459 | * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' |
||
460 | * will become 'varchar(255) not null'. |
||
461 | * @return string the SQL statement for changing the definition of a column. |
||
462 | */ |
||
463 | 1 | public function alterColumn($table, $column, $type) |
|
470 | |||
471 | /** |
||
472 | * Builds a SQL statement for adding a foreign key constraint to an existing table. |
||
473 | * The method will properly quote the table and column names. |
||
474 | * @param string $name the name of the foreign key constraint. |
||
475 | * @param string $table the table that the foreign key constraint will be added to. |
||
476 | * @param string|array $columns the name of the column to that the constraint will be added on. |
||
477 | * If there are multiple columns, separate them with commas or use an array to represent them. |
||
478 | * @param string $refTable the table that the foreign key references to. |
||
479 | * @param string|array $refColumns the name of the column that the foreign key references to. |
||
480 | * If there are multiple columns, separate them with commas or use an array to represent them. |
||
481 | * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL |
||
482 | * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL |
||
483 | * @return string the SQL statement for adding a foreign key constraint to an existing table. |
||
484 | */ |
||
485 | public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null) |
||
501 | |||
502 | /** |
||
503 | * Builds a SQL statement for dropping a foreign key constraint. |
||
504 | * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method. |
||
505 | * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method. |
||
506 | * @return string the SQL statement for dropping a foreign key constraint. |
||
507 | */ |
||
508 | public function dropForeignKey($name, $table) |
||
513 | |||
514 | /** |
||
515 | * Builds a SQL statement for creating a new index. |
||
516 | * @param string $name the name of the index. The name will be properly quoted by the method. |
||
517 | * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method. |
||
518 | * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, |
||
519 | * separate them with commas or use an array to represent them. Each column name will be properly quoted |
||
520 | * by the method, unless a parenthesis is found in the name. |
||
521 | * @param boolean $unique whether to add UNIQUE constraint on the created index. |
||
522 | * @return string the SQL statement for creating a new index. |
||
523 | */ |
||
524 | public function createIndex($name, $table, $columns, $unique = false) |
||
531 | |||
532 | /** |
||
533 | * Builds a SQL statement for dropping an index. |
||
534 | * @param string $name the name of the index to be dropped. The name will be properly quoted by the method. |
||
535 | * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method. |
||
536 | * @return string the SQL statement for dropping an index. |
||
537 | */ |
||
538 | public function dropIndex($name, $table) |
||
542 | |||
543 | /** |
||
544 | * Creates a SQL statement for resetting the sequence value of a table's primary key. |
||
545 | * The sequence will be reset such that the primary key of the next new row inserted |
||
546 | * will have the specified value or 1. |
||
547 | * @param string $table the name of the table whose primary key sequence will be reset |
||
548 | * @param array|string $value the value for the primary key of the next new row inserted. If this is not set, |
||
549 | * the next new row's primary key will have a value 1. |
||
550 | * @return string the SQL statement for resetting sequence |
||
551 | * @throws NotSupportedException if this is not supported by the underlying DBMS |
||
552 | */ |
||
553 | public function resetSequence($table, $value = null) |
||
557 | |||
558 | /** |
||
559 | * Builds a SQL statement for enabling or disabling integrity check. |
||
560 | * @param boolean $check whether to turn on or off the integrity check. |
||
561 | * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. |
||
562 | * @param string $table the table name. Defaults to empty string, meaning that no table will be changed. |
||
563 | * @return string the SQL statement for checking integrity |
||
564 | * @throws NotSupportedException if this is not supported by the underlying DBMS |
||
565 | */ |
||
566 | public function checkIntegrity($check = true, $schema = '', $table = '') |
||
570 | |||
571 | /** |
||
572 | * Converts an abstract column type into a physical column type. |
||
573 | * The conversion is done using the type map specified in [[typeMap]]. |
||
574 | * The following abstract column types are supported (using MySQL as an example to explain the corresponding |
||
575 | * physical types): |
||
576 | * |
||
577 | * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY" |
||
578 | * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY" |
||
579 | * - `string`: string type, will be converted into "varchar(255)" |
||
580 | * - `text`: a long string type, will be converted into "text" |
||
581 | * - `smallint`: a small integer type, will be converted into "smallint(6)" |
||
582 | * - `integer`: integer type, will be converted into "int(11)" |
||
583 | * - `bigint`: a big integer type, will be converted into "bigint(20)" |
||
584 | * - `boolean`: boolean type, will be converted into "tinyint(1)" |
||
585 | * - `float``: float number type, will be converted into "float" |
||
586 | * - `decimal`: decimal number type, will be converted into "decimal" |
||
587 | * - `datetime`: datetime type, will be converted into "datetime" |
||
588 | * - `timestamp`: timestamp type, will be converted into "timestamp" |
||
589 | * - `time`: time type, will be converted into "time" |
||
590 | * - `date`: date type, will be converted into "date" |
||
591 | * - `money`: money type, will be converted into "decimal(19,4)" |
||
592 | * - `binary`: binary data type, will be converted into "blob" |
||
593 | * |
||
594 | * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only |
||
595 | * the first part will be converted, and the rest of the parts will be appended to the converted result. |
||
596 | * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'. |
||
597 | * |
||
598 | * For some of the abstract types you can also specify a length or precision constraint |
||
599 | * by appending it in round brackets directly to the type. |
||
600 | * For example `string(32)` will be converted into "varchar(32)" on a MySQL database. |
||
601 | * If the underlying DBMS does not support these kind of constraints for a type it will |
||
602 | * be ignored. |
||
603 | * |
||
604 | * If a type cannot be found in [[typeMap]], it will be returned without any change. |
||
605 | * @param string|ColumnSchemaBuilder $type abstract column type |
||
606 | * @return string physical column type. |
||
607 | */ |
||
608 | 44 | public function getColumnType($type) |
|
609 | { |
||
610 | 44 | if ($type instanceof ColumnSchemaBuilder) { |
|
611 | 3 | $type = $type->__toString(); |
|
612 | 3 | } |
|
613 | |||
614 | 44 | if (isset($this->typeMap[$type])) { |
|
615 | 43 | return $this->typeMap[$type]; |
|
616 | 27 | } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) { |
|
617 | 19 | if (isset($this->typeMap[$matches[1]])) { |
|
618 | 10 | return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3]; |
|
619 | } |
||
620 | 27 | } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) { |
|
621 | 18 | if (isset($this->typeMap[$matches[1]])) { |
|
622 | 15 | return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type); |
|
623 | } |
||
624 | 3 | } |
|
625 | |||
626 | 12 | return $type; |
|
627 | } |
||
628 | |||
629 | /** |
||
630 | * @param array $columns |
||
631 | * @param array $params the binding parameters to be populated |
||
632 | * @param boolean $distinct |
||
633 | * @param string $selectOption |
||
634 | * @return string the SELECT clause built from [[Query::$select]]. |
||
635 | */ |
||
636 | 630 | public function buildSelect($columns, &$params, $distinct = false, $selectOption = null) |
|
674 | |||
675 | /** |
||
676 | * @param array $tables |
||
677 | * @param array $params the binding parameters to be populated |
||
678 | * @return string the FROM clause built from [[Query::$from]]. |
||
679 | */ |
||
680 | 630 | public function buildFrom($tables, &$params) |
|
690 | |||
691 | /** |
||
692 | * @param array $joins |
||
693 | * @param array $params the binding parameters to be populated |
||
694 | * @return string the JOIN clause built from [[Query::$join]]. |
||
695 | * @throws Exception if the $joins parameter is not in proper format |
||
696 | */ |
||
697 | 630 | public function buildJoin($joins, &$params) |
|
722 | |||
723 | /** |
||
724 | * Quotes table names passed |
||
725 | * |
||
726 | * @param array $tables |
||
727 | * @param array $params |
||
728 | * @return array |
||
729 | */ |
||
730 | 402 | private function quoteTableNames($tables, &$params) |
|
751 | |||
752 | /** |
||
753 | * @param string|array $condition |
||
754 | * @param array $params the binding parameters to be populated |
||
755 | * @return string the WHERE clause built from [[Query::$where]]. |
||
756 | */ |
||
757 | 645 | public function buildWhere($condition, &$params) |
|
758 | { |
||
759 | 645 | $where = $this->buildCondition($condition, $params); |
|
760 | |||
761 | 645 | return $where === '' ? '' : 'WHERE ' . $where; |
|
762 | } |
||
763 | |||
764 | /** |
||
765 | * @param array $columns |
||
766 | * @return string the GROUP BY clause |
||
767 | */ |
||
768 | 630 | public function buildGroupBy($columns) |
|
769 | { |
||
770 | 630 | if (empty($columns)) { |
|
771 | 624 | return ''; |
|
772 | } |
||
773 | 9 | foreach ($columns as $i => $column) { |
|
774 | 9 | if ($column instanceof Expression) { |
|
775 | 3 | $columns[$i] = $column->expression; |
|
776 | 9 | } elseif (strpos($column, '(') === false) { |
|
777 | 9 | $columns[$i] = $this->db->quoteColumnName($column); |
|
778 | 9 | } |
|
779 | 9 | } |
|
780 | 9 | return 'GROUP BY ' . implode(', ', $columns); |
|
781 | } |
||
782 | |||
783 | /** |
||
784 | * @param string|array $condition |
||
785 | * @param array $params the binding parameters to be populated |
||
786 | * @return string the HAVING clause built from [[Query::$having]]. |
||
787 | */ |
||
788 | 630 | public function buildHaving($condition, &$params) |
|
794 | |||
795 | /** |
||
796 | * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL. |
||
797 | * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET) |
||
798 | * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter. |
||
799 | * @param integer $limit the limit number. See [[Query::limit]] for more details. |
||
800 | * @param integer $offset the offset number. See [[Query::offset]] for more details. |
||
801 | * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any) |
||
802 | */ |
||
803 | 630 | public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset) |
|
815 | |||
816 | /** |
||
817 | * @param array $columns |
||
818 | * @return string the ORDER BY clause built from [[Query::$orderBy]]. |
||
819 | */ |
||
820 | 630 | public function buildOrderBy($columns) |
|
821 | { |
||
822 | 630 | if (empty($columns)) { |
|
823 | 607 | return ''; |
|
824 | } |
||
825 | 119 | $orders = []; |
|
826 | 119 | foreach ($columns as $name => $direction) { |
|
827 | 119 | if ($direction instanceof Expression) { |
|
828 | 3 | $orders[] = $direction->expression; |
|
829 | 3 | } else { |
|
830 | 119 | $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : ''); |
|
831 | } |
||
832 | 119 | } |
|
833 | |||
834 | 119 | return 'ORDER BY ' . implode(', ', $orders); |
|
835 | } |
||
836 | |||
837 | /** |
||
838 | * @param integer $limit |
||
839 | * @param integer $offset |
||
840 | * @return string the LIMIT and OFFSET clauses |
||
841 | */ |
||
842 | 189 | public function buildLimit($limit, $offset) |
|
854 | |||
855 | /** |
||
856 | * Checks to see if the given limit is effective. |
||
857 | * @param mixed $limit the given limit |
||
858 | * @return boolean whether the limit is effective |
||
859 | */ |
||
860 | 630 | protected function hasLimit($limit) |
|
864 | |||
865 | /** |
||
866 | * Checks to see if the given offset is effective. |
||
867 | * @param mixed $offset the given offset |
||
868 | * @return boolean whether the offset is effective |
||
869 | */ |
||
870 | 630 | protected function hasOffset($offset) |
|
875 | |||
876 | /** |
||
877 | * @param array $unions |
||
878 | * @param array $params the binding parameters to be populated |
||
879 | * @return string the UNION clause built from [[Query::$union]]. |
||
880 | */ |
||
881 | 441 | public function buildUnion($unions, &$params) |
|
900 | |||
901 | /** |
||
902 | * Processes columns and properly quotes them if necessary. |
||
903 | * It will join all columns into a string with comma as separators. |
||
904 | * @param string|array $columns the columns to be processed |
||
905 | * @return string the processing result |
||
906 | */ |
||
907 | public function buildColumns($columns) |
||
926 | |||
927 | /** |
||
928 | * Parses the condition specification and generates the corresponding SQL expression. |
||
929 | * @param string|array|Expression $condition the condition specification. Please refer to [[Query::where()]] |
||
930 | * on how to specify a condition. |
||
931 | * @param array $params the binding parameters to be populated |
||
932 | * @return string the generated SQL expression |
||
933 | */ |
||
934 | 645 | public function buildCondition($condition, &$params) |
|
960 | |||
961 | /** |
||
962 | * Creates a condition based on column-value pairs. |
||
963 | * @param array $condition the condition specification. |
||
964 | * @param array $params the binding parameters to be populated |
||
965 | * @return string the generated SQL expression |
||
966 | */ |
||
967 | 300 | public function buildHashCondition($condition, &$params) |
|
994 | |||
995 | /** |
||
996 | * Connects two or more SQL expressions with the `AND` or `OR` operator. |
||
997 | * @param string $operator the operator to use for connecting the given operands |
||
998 | * @param array $operands the SQL expressions to connect. |
||
999 | * @param array $params the binding parameters to be populated |
||
1000 | * @return string the generated SQL expression |
||
1001 | */ |
||
1002 | 98 | public function buildAndCondition($operator, $operands, &$params) |
|
1003 | { |
||
1004 | 98 | $parts = []; |
|
1005 | 98 | foreach ($operands as $operand) { |
|
1006 | 98 | if (is_array($operand)) { |
|
1007 | 74 | $operand = $this->buildCondition($operand, $params); |
|
1008 | 74 | } |
|
1009 | 98 | if ($operand instanceof Expression) { |
|
1010 | 6 | foreach ($operand->params as $n => $v) { |
|
1011 | 6 | $params[$n] = $v; |
|
1012 | 6 | } |
|
1013 | 6 | $operand = $operand->expression; |
|
1014 | 6 | } |
|
1015 | 98 | if ($operand !== '') { |
|
1016 | 98 | $parts[] = $operand; |
|
1017 | 98 | } |
|
1018 | 98 | } |
|
1019 | 98 | if (!empty($parts)) { |
|
1020 | 98 | return '(' . implode(") $operator (", $parts) . ')'; |
|
1021 | } else { |
||
1022 | return ''; |
||
1023 | } |
||
1024 | } |
||
1025 | |||
1026 | /** |
||
1027 | * Inverts an SQL expressions with `NOT` operator. |
||
1028 | * @param string $operator the operator to use for connecting the given operands |
||
1029 | * @param array $operands the SQL expressions to connect. |
||
1030 | * @param array $params the binding parameters to be populated |
||
1031 | * @return string the generated SQL expression |
||
1032 | * @throws InvalidParamException if wrong number of operands have been given. |
||
1033 | */ |
||
1034 | 3 | public function buildNotCondition($operator, $operands, &$params) |
|
1035 | { |
||
1036 | 3 | if (count($operands) !== 1) { |
|
1037 | throw new InvalidParamException("Operator '$operator' requires exactly one operand."); |
||
1038 | } |
||
1039 | |||
1040 | 3 | $operand = reset($operands); |
|
1041 | 3 | if (is_array($operand)) { |
|
1042 | $operand = $this->buildCondition($operand, $params); |
||
1043 | } |
||
1044 | 3 | if ($operand === '') { |
|
1045 | return ''; |
||
1046 | } |
||
1047 | |||
1048 | 3 | return "$operator ($operand)"; |
|
1049 | } |
||
1050 | |||
1051 | /** |
||
1052 | * Creates an SQL expressions with the `BETWEEN` operator. |
||
1053 | * @param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`) |
||
1054 | * @param array $operands the first operand is the column name. The second and third operands |
||
1055 | * describe the interval that column value should be in. |
||
1056 | * @param array $params the binding parameters to be populated |
||
1057 | * @return string the generated SQL expression |
||
1058 | * @throws InvalidParamException if wrong number of operands have been given. |
||
1059 | */ |
||
1060 | 21 | public function buildBetweenCondition($operator, $operands, &$params) |
|
1061 | { |
||
1062 | 21 | if (!isset($operands[0], $operands[1], $operands[2])) { |
|
1063 | throw new InvalidParamException("Operator '$operator' requires three operands."); |
||
1064 | } |
||
1065 | |||
1066 | 21 | list($column, $value1, $value2) = $operands; |
|
1067 | |||
1068 | 21 | if (strpos($column, '(') === false) { |
|
1069 | 21 | $column = $this->db->quoteColumnName($column); |
|
1070 | 21 | } |
|
1071 | 21 | if ($value1 instanceof Expression) { |
|
1072 | 12 | foreach ($value1->params as $n => $v) { |
|
1073 | $params[$n] = $v; |
||
1074 | 12 | } |
|
1075 | 12 | $phName1 = $value1->expression; |
|
1076 | 12 | } else { |
|
1077 | 9 | $phName1 = self::PARAM_PREFIX . count($params); |
|
1078 | 9 | $params[$phName1] = $value1; |
|
1079 | } |
||
1080 | 21 | if ($value2 instanceof Expression) { |
|
1081 | 6 | foreach ($value2->params as $n => $v) { |
|
1082 | $params[$n] = $v; |
||
1083 | 6 | } |
|
1084 | 6 | $phName2 = $value2->expression; |
|
1085 | 6 | } else { |
|
1086 | 15 | $phName2 = self::PARAM_PREFIX . count($params); |
|
1087 | 15 | $params[$phName2] = $value2; |
|
1088 | } |
||
1089 | |||
1090 | 21 | return "$column $operator $phName1 AND $phName2"; |
|
1091 | } |
||
1092 | |||
1093 | /** |
||
1094 | * Creates an SQL expressions with the `IN` operator. |
||
1095 | * @param string $operator the operator to use (e.g. `IN` or `NOT IN`) |
||
1096 | * @param array $operands the first operand is the column name. If it is an array |
||
1097 | * a composite IN condition will be generated. |
||
1098 | * The second operand is an array of values that column value should be among. |
||
1099 | * If it is an empty array the generated expression will be a `false` value if |
||
1100 | * operator is `IN` and empty if operator is `NOT IN`. |
||
1101 | * @param array $params the binding parameters to be populated |
||
1102 | * @return string the generated SQL expression |
||
1103 | * @throws Exception if wrong number of operands have been given. |
||
1104 | */ |
||
1105 | 152 | public function buildInCondition($operator, $operands, &$params) |
|
1106 | { |
||
1107 | 152 | if (!isset($operands[0], $operands[1])) { |
|
1108 | throw new Exception("Operator '$operator' requires two operands."); |
||
1109 | } |
||
1110 | |||
1111 | 152 | list($column, $values) = $operands; |
|
1112 | |||
1113 | 152 | if ($values === [] || $column === []) { |
|
1114 | 15 | return $operator === 'IN' ? '0=1' : ''; |
|
1115 | } |
||
1116 | |||
1117 | 152 | if ($values instanceof Query) { |
|
1118 | 14 | return $this->buildSubqueryInCondition($operator, $column, $values, $params); |
|
1119 | } |
||
1120 | |||
1121 | 138 | $values = (array) $values; |
|
1122 | |||
1123 | 138 | if (count($column) > 1) { |
|
1124 | 9 | return $this->buildCompositeInCondition($operator, $column, $values, $params); |
|
1125 | } |
||
1126 | |||
1127 | 129 | if (is_array($column)) { |
|
1128 | 93 | $column = reset($column); |
|
1129 | 93 | } |
|
1130 | 129 | foreach ($values as $i => $value) { |
|
1131 | 129 | if (is_array($value)) { |
|
1132 | $value = isset($value[$column]) ? $value[$column] : null; |
||
1133 | } |
||
1134 | 129 | if ($value === null) { |
|
1135 | $values[$i] = 'NULL'; |
||
1136 | 129 | } elseif ($value instanceof Expression) { |
|
1137 | $values[$i] = $value->expression; |
||
1138 | foreach ($value->params as $n => $v) { |
||
1139 | $params[$n] = $v; |
||
1140 | } |
||
1141 | } else { |
||
1142 | 129 | $phName = self::PARAM_PREFIX . count($params); |
|
1143 | 129 | $params[$phName] = $value; |
|
1144 | 129 | $values[$i] = $phName; |
|
1145 | } |
||
1146 | 129 | } |
|
1147 | 129 | if (strpos($column, '(') === false) { |
|
1148 | 129 | $column = $this->db->quoteColumnName($column); |
|
1149 | 129 | } |
|
1150 | |||
1151 | 129 | if (count($values) > 1) { |
|
1152 | 111 | return "$column $operator (" . implode(', ', $values) . ')'; |
|
1153 | } else { |
||
1154 | 78 | $operator = $operator === 'IN' ? '=' : '<>'; |
|
1155 | 78 | return $column . $operator . reset($values); |
|
1156 | } |
||
1157 | } |
||
1158 | |||
1159 | /** |
||
1160 | * Builds SQL for IN condition |
||
1161 | * |
||
1162 | * @param string $operator |
||
1163 | * @param array $columns |
||
1164 | * @param Query $values |
||
1165 | * @param array $params |
||
1166 | * @return string SQL |
||
1167 | */ |
||
1168 | 14 | protected function buildSubqueryInCondition($operator, $columns, $values, &$params) |
|
1185 | |||
1186 | /** |
||
1187 | * Builds SQL for IN condition |
||
1188 | * |
||
1189 | * @param string $operator |
||
1190 | * @param array $columns |
||
1191 | * @param array $values |
||
1192 | * @param array $params |
||
1193 | * @return string SQL |
||
1194 | */ |
||
1195 | 6 | protected function buildCompositeInCondition($operator, $columns, $values, &$params) |
|
1219 | |||
1220 | /** |
||
1221 | * Creates an SQL expressions with the `LIKE` operator. |
||
1222 | * @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`) |
||
1223 | * @param array $operands an array of two or three operands |
||
1224 | * |
||
1225 | * - The first operand is the column name. |
||
1226 | * - The second operand is a single value or an array of values that column value |
||
1227 | * should be compared with. If it is an empty array the generated expression will |
||
1228 | * be a `false` value if operator is `LIKE` or `OR LIKE`, and empty if operator |
||
1229 | * is `NOT LIKE` or `OR NOT LIKE`. |
||
1230 | * - An optional third operand can also be provided to specify how to escape special characters |
||
1231 | * in the value(s). The operand should be an array of mappings from the special characters to their |
||
1232 | * escaped counterparts. If this operand is not provided, a default escape mapping will be used. |
||
1233 | * You may use `false` or an empty array to indicate the values are already escaped and no escape |
||
1234 | * should be applied. Note that when using an escape mapping (or the third operand is not provided), |
||
1235 | * the values will be automatically enclosed within a pair of percentage characters. |
||
1236 | * @param array $params the binding parameters to be populated |
||
1237 | * @return string the generated SQL expression |
||
1238 | * @throws InvalidParamException if wrong number of operands have been given. |
||
1239 | */ |
||
1240 | 72 | public function buildLikeCondition($operator, $operands, &$params) |
|
1286 | |||
1287 | /** |
||
1288 | * Creates an SQL expressions with the `EXISTS` operator. |
||
1289 | * @param string $operator the operator to use (e.g. `EXISTS` or `NOT EXISTS`) |
||
1290 | * @param array $operands contains only one element which is a [[Query]] object representing the sub-query. |
||
1291 | * @param array $params the binding parameters to be populated |
||
1292 | * @return string the generated SQL expression |
||
1293 | * @throws InvalidParamException if the operand is not a [[Query]] object. |
||
1294 | */ |
||
1295 | 18 | public function buildExistsCondition($operator, $operands, &$params) |
|
1304 | |||
1305 | /** |
||
1306 | * Creates an SQL expressions like `"column" operator value`. |
||
1307 | * @param string $operator the operator to use. Anything could be used e.g. `>`, `<=`, etc. |
||
1308 | * @param array $operands contains two column names. |
||
1309 | * @param array $params the binding parameters to be populated |
||
1310 | * @return string the generated SQL expression |
||
1311 | * @throws InvalidParamException if wrong number of operands have been given. |
||
1312 | */ |
||
1313 | 30 | public function buildSimpleCondition($operator, $operands, &$params) |
|
1341 | } |
||
1342 |