1 | <?php |
||||||
2 | /** |
||||||
3 | * @link https://www.yiiframework.com/ |
||||||
4 | * @copyright Copyright (c) 2008 Yii Software LLC |
||||||
5 | * @license https://www.yiiframework.com/license/ |
||||||
6 | */ |
||||||
7 | |||||||
8 | namespace yii\db; |
||||||
9 | |||||||
10 | use yii\base\InvalidArgumentException; |
||||||
11 | use yii\base\NotSupportedException; |
||||||
12 | use yii\db\conditions\ConditionInterface; |
||||||
13 | use yii\db\conditions\HashCondition; |
||||||
14 | use yii\helpers\StringHelper; |
||||||
15 | |||||||
16 | /** |
||||||
17 | * QueryBuilder builds a SELECT SQL statement based on the specification given as a [[Query]] object. |
||||||
18 | * |
||||||
19 | * SQL statements are created from [[Query]] objects using the [[build()]]-method. |
||||||
20 | * |
||||||
21 | * QueryBuilder is also used by [[Command]] to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE. |
||||||
22 | * |
||||||
23 | * For more details and usage information on QueryBuilder, see the [guide article on query builders](guide:db-query-builder). |
||||||
24 | * |
||||||
25 | * @property-write string[] $conditionClasses Map of condition aliases to condition classes. For example: |
||||||
26 | * ```php ['LIKE' => yii\db\condition\LikeCondition::class] ``` . |
||||||
27 | * @property-write string[] $expressionBuilders Array of builders that should be merged with the pre-defined |
||||||
28 | * ones in [[expressionBuilders]] property. |
||||||
29 | * |
||||||
30 | * @author Qiang Xue <[email protected]> |
||||||
31 | * @since 2.0 |
||||||
32 | */ |
||||||
33 | class QueryBuilder extends \yii\base\BaseObject |
||||||
34 | { |
||||||
35 | /** |
||||||
36 | * The prefix for automatically generated query binding parameters. |
||||||
37 | */ |
||||||
38 | const PARAM_PREFIX = ':qp'; |
||||||
39 | |||||||
40 | /** |
||||||
41 | * @var Connection the database connection. |
||||||
42 | */ |
||||||
43 | public $db; |
||||||
44 | /** |
||||||
45 | * @var string the separator between different fragments of a SQL statement. |
||||||
46 | * Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement. |
||||||
47 | */ |
||||||
48 | public $separator = ' '; |
||||||
49 | /** |
||||||
50 | * @var array the abstract column types mapped to physical column types. |
||||||
51 | * This is mainly used to support creating/modifying tables using DB-independent data type specifications. |
||||||
52 | * Child classes should override this property to declare supported type mappings. |
||||||
53 | */ |
||||||
54 | public $typeMap = []; |
||||||
55 | |||||||
56 | /** |
||||||
57 | * @var array map of condition aliases to condition classes. For example: |
||||||
58 | * |
||||||
59 | * ```php |
||||||
60 | * return [ |
||||||
61 | * 'LIKE' => yii\db\condition\LikeCondition::class, |
||||||
62 | * ]; |
||||||
63 | * ``` |
||||||
64 | * |
||||||
65 | * This property is used by [[createConditionFromArray]] method. |
||||||
66 | * See default condition classes list in [[defaultConditionClasses()]] method. |
||||||
67 | * |
||||||
68 | * In case you want to add custom conditions support, use the [[setConditionClasses()]] method. |
||||||
69 | * |
||||||
70 | * @see setConditionClasses() |
||||||
71 | * @see defaultConditionClasses() |
||||||
72 | * @since 2.0.14 |
||||||
73 | */ |
||||||
74 | protected $conditionClasses = []; |
||||||
75 | /** |
||||||
76 | * @var string[]|ExpressionBuilderInterface[] maps expression class to expression builder class. |
||||||
77 | * For example: |
||||||
78 | * |
||||||
79 | * ```php |
||||||
80 | * [ |
||||||
81 | * yii\db\Expression::class => yii\db\ExpressionBuilder::class |
||||||
82 | * ] |
||||||
83 | * ``` |
||||||
84 | * This property is mainly used by [[buildExpression()]] to build SQL expressions form expression objects. |
||||||
85 | * See default values in [[defaultExpressionBuilders()]] method. |
||||||
86 | * |
||||||
87 | * |
||||||
88 | * To override existing builders or add custom, use [[setExpressionBuilder()]] method. New items will be added |
||||||
89 | * to the end of this array. |
||||||
90 | * |
||||||
91 | * To find a builder, [[buildExpression()]] will check the expression class for its exact presence in this map. |
||||||
92 | * In case it is NOT present, the array will be iterated in reverse direction, checking whether the expression |
||||||
93 | * extends the class, defined in this map. |
||||||
94 | * |
||||||
95 | * @see setExpressionBuilders() |
||||||
96 | * @see defaultExpressionBuilders() |
||||||
97 | * @since 2.0.14 |
||||||
98 | */ |
||||||
99 | protected $expressionBuilders = []; |
||||||
100 | |||||||
101 | |||||||
102 | /** |
||||||
103 | * Constructor. |
||||||
104 | * @param Connection $connection the database connection. |
||||||
105 | * @param array $config name-value pairs that will be used to initialize the object properties |
||||||
106 | */ |
||||||
107 | 83 | public function __construct($connection, $config = []) |
|||||
108 | { |
||||||
109 | 83 | $this->db = $connection; |
|||||
110 | 83 | parent::__construct($config); |
|||||
111 | } |
||||||
112 | |||||||
113 | /** |
||||||
114 | * {@inheritdoc} |
||||||
115 | */ |
||||||
116 | 83 | public function init() |
|||||
117 | { |
||||||
118 | 83 | parent::init(); |
|||||
119 | |||||||
120 | 83 | $this->expressionBuilders = array_merge($this->defaultExpressionBuilders(), $this->expressionBuilders); |
|||||
0 ignored issues
–
show
introduced
by
![]() |
|||||||
121 | 83 | $this->conditionClasses = array_merge($this->defaultConditionClasses(), $this->conditionClasses); |
|||||
0 ignored issues
–
show
|
|||||||
122 | } |
||||||
123 | |||||||
124 | /** |
||||||
125 | * Contains array of default condition classes. Extend this method, if you want to change |
||||||
126 | * default condition classes for the query builder. See [[conditionClasses]] docs for details. |
||||||
127 | * |
||||||
128 | * @return array |
||||||
129 | * @see conditionClasses |
||||||
130 | * @since 2.0.14 |
||||||
131 | */ |
||||||
132 | 83 | protected function defaultConditionClasses() |
|||||
133 | { |
||||||
134 | 83 | return [ |
|||||
135 | 83 | 'NOT' => 'yii\db\conditions\NotCondition', |
|||||
136 | 83 | 'AND' => 'yii\db\conditions\AndCondition', |
|||||
137 | 83 | 'OR' => 'yii\db\conditions\OrCondition', |
|||||
138 | 83 | 'BETWEEN' => 'yii\db\conditions\BetweenCondition', |
|||||
139 | 83 | 'NOT BETWEEN' => 'yii\db\conditions\BetweenCondition', |
|||||
140 | 83 | 'IN' => 'yii\db\conditions\InCondition', |
|||||
141 | 83 | 'NOT IN' => 'yii\db\conditions\InCondition', |
|||||
142 | 83 | 'LIKE' => 'yii\db\conditions\LikeCondition', |
|||||
143 | 83 | 'NOT LIKE' => 'yii\db\conditions\LikeCondition', |
|||||
144 | 83 | 'OR LIKE' => 'yii\db\conditions\LikeCondition', |
|||||
145 | 83 | 'OR NOT LIKE' => 'yii\db\conditions\LikeCondition', |
|||||
146 | 83 | 'EXISTS' => 'yii\db\conditions\ExistsCondition', |
|||||
147 | 83 | 'NOT EXISTS' => 'yii\db\conditions\ExistsCondition', |
|||||
148 | 83 | ]; |
|||||
149 | } |
||||||
150 | |||||||
151 | /** |
||||||
152 | * Contains array of default expression builders. Extend this method and override it, if you want to change |
||||||
153 | * default expression builders for this query builder. See [[expressionBuilders]] docs for details. |
||||||
154 | * |
||||||
155 | * @return array |
||||||
156 | * @see expressionBuilders |
||||||
157 | * @since 2.0.14 |
||||||
158 | */ |
||||||
159 | 83 | protected function defaultExpressionBuilders() |
|||||
160 | { |
||||||
161 | 83 | return [ |
|||||
162 | 83 | 'yii\db\Query' => 'yii\db\QueryExpressionBuilder', |
|||||
163 | 83 | 'yii\db\PdoValue' => 'yii\db\PdoValueBuilder', |
|||||
164 | 83 | 'yii\db\Expression' => 'yii\db\ExpressionBuilder', |
|||||
165 | 83 | 'yii\db\conditions\ConjunctionCondition' => 'yii\db\conditions\ConjunctionConditionBuilder', |
|||||
166 | 83 | 'yii\db\conditions\NotCondition' => 'yii\db\conditions\NotConditionBuilder', |
|||||
167 | 83 | 'yii\db\conditions\AndCondition' => 'yii\db\conditions\ConjunctionConditionBuilder', |
|||||
168 | 83 | 'yii\db\conditions\OrCondition' => 'yii\db\conditions\ConjunctionConditionBuilder', |
|||||
169 | 83 | 'yii\db\conditions\BetweenCondition' => 'yii\db\conditions\BetweenConditionBuilder', |
|||||
170 | 83 | 'yii\db\conditions\InCondition' => 'yii\db\conditions\InConditionBuilder', |
|||||
171 | 83 | 'yii\db\conditions\LikeCondition' => 'yii\db\conditions\LikeConditionBuilder', |
|||||
172 | 83 | 'yii\db\conditions\ExistsCondition' => 'yii\db\conditions\ExistsConditionBuilder', |
|||||
173 | 83 | 'yii\db\conditions\SimpleCondition' => 'yii\db\conditions\SimpleConditionBuilder', |
|||||
174 | 83 | 'yii\db\conditions\HashCondition' => 'yii\db\conditions\HashConditionBuilder', |
|||||
175 | 83 | 'yii\db\conditions\BetweenColumnsCondition' => 'yii\db\conditions\BetweenColumnsConditionBuilder', |
|||||
176 | 83 | ]; |
|||||
177 | } |
||||||
178 | |||||||
179 | /** |
||||||
180 | * Setter for [[expressionBuilders]] property. |
||||||
181 | * |
||||||
182 | * @param string[] $builders array of builders that should be merged with the pre-defined ones |
||||||
183 | * in [[expressionBuilders]] property. |
||||||
184 | * @since 2.0.14 |
||||||
185 | * @see expressionBuilders |
||||||
186 | */ |
||||||
187 | public function setExpressionBuilders($builders) |
||||||
188 | { |
||||||
189 | $this->expressionBuilders = array_merge($this->expressionBuilders, $builders); |
||||||
0 ignored issues
–
show
|
|||||||
190 | } |
||||||
191 | |||||||
192 | /** |
||||||
193 | * Setter for [[conditionClasses]] property. |
||||||
194 | * |
||||||
195 | * @param string[] $classes map of condition aliases to condition classes. For example: |
||||||
196 | * |
||||||
197 | * ```php |
||||||
198 | * ['LIKE' => yii\db\condition\LikeCondition::class] |
||||||
199 | * ``` |
||||||
200 | * |
||||||
201 | * @since 2.0.14.2 |
||||||
202 | * @see conditionClasses |
||||||
203 | */ |
||||||
204 | public function setConditionClasses($classes) |
||||||
205 | { |
||||||
206 | $this->conditionClasses = array_merge($this->conditionClasses, $classes); |
||||||
0 ignored issues
–
show
|
|||||||
207 | } |
||||||
208 | |||||||
209 | /** |
||||||
210 | * Generates a SELECT SQL statement from a [[Query]] object. |
||||||
211 | * |
||||||
212 | * @param Query $query the [[Query]] object from which the SQL statement will be generated. |
||||||
213 | * @param array $params the parameters to be bound to the generated SQL statement. These parameters will |
||||||
214 | * be included in the result with the additional parameters generated during the query building process. |
||||||
215 | * @return array the generated SQL statement (the first array element) and the corresponding |
||||||
216 | * parameters to be bound to the SQL statement (the second array element). The parameters returned |
||||||
217 | * include those provided in `$params`. |
||||||
218 | */ |
||||||
219 | public function build($query, $params = []) |
||||||
220 | { |
||||||
221 | $query = $query->prepare($this); |
||||||
222 | |||||||
223 | $params = empty($params) ? $query->params : array_merge($params, $query->params); |
||||||
0 ignored issues
–
show
It seems like
$query->params can also be of type null ; however, parameter $arrays of array_merge() does only seem to accept array , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
224 | |||||||
225 | $clauses = [ |
||||||
226 | $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption), |
||||||
227 | $this->buildFrom($query->from, $params), |
||||||
228 | $this->buildJoin($query->join, $params), |
||||||
229 | $this->buildWhere($query->where, $params), |
||||||
0 ignored issues
–
show
It seems like
$query->where can also be of type yii\db\ExpressionInterface ; however, parameter $condition of yii\db\QueryBuilder::buildWhere() does only seem to accept array|string , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
230 | $this->buildGroupBy($query->groupBy), |
||||||
231 | $this->buildHaving($query->having, $params), |
||||||
0 ignored issues
–
show
It seems like
$query->having can also be of type yii\db\ExpressionInterface ; however, parameter $condition of yii\db\QueryBuilder::buildHaving() does only seem to accept array|string , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
232 | ]; |
||||||
233 | |||||||
234 | $sql = implode($this->separator, array_filter($clauses)); |
||||||
235 | $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset); |
||||||
0 ignored issues
–
show
It seems like
$query->limit can also be of type yii\db\ExpressionInterface ; however, parameter $limit of yii\db\QueryBuilder::buildOrderByAndLimit() does only seem to accept integer , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() It seems like
$query->offset can also be of type yii\db\ExpressionInterface ; however, parameter $offset of yii\db\QueryBuilder::buildOrderByAndLimit() does only seem to accept integer , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
236 | |||||||
237 | if (!empty($query->orderBy)) { |
||||||
238 | foreach ($query->orderBy as $expression) { |
||||||
239 | if ($expression instanceof ExpressionInterface) { |
||||||
240 | $this->buildExpression($expression, $params); |
||||||
241 | } |
||||||
242 | } |
||||||
243 | } |
||||||
244 | if (!empty($query->groupBy)) { |
||||||
245 | foreach ($query->groupBy as $expression) { |
||||||
246 | if ($expression instanceof ExpressionInterface) { |
||||||
247 | $this->buildExpression($expression, $params); |
||||||
248 | } |
||||||
249 | } |
||||||
250 | } |
||||||
251 | |||||||
252 | $union = $this->buildUnion($query->union, $params); |
||||||
253 | if ($union !== '') { |
||||||
254 | $sql = "($sql){$this->separator}$union"; |
||||||
255 | } |
||||||
256 | |||||||
257 | $with = $this->buildWithQueries($query->withQueries, $params); |
||||||
258 | if ($with !== '') { |
||||||
259 | $sql = "$with{$this->separator}$sql"; |
||||||
260 | } |
||||||
261 | |||||||
262 | return [$sql, $params]; |
||||||
263 | } |
||||||
264 | |||||||
265 | /** |
||||||
266 | * Builds given $expression |
||||||
267 | * |
||||||
268 | * @param ExpressionInterface $expression the expression to be built |
||||||
269 | * @param array $params the parameters to be bound to the generated SQL statement. These parameters will |
||||||
270 | * be included in the result with the additional parameters generated during the expression building process. |
||||||
271 | * @return string the SQL statement that will not be neither quoted nor encoded before passing to DBMS |
||||||
272 | * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder. |
||||||
273 | * @see ExpressionBuilderInterface |
||||||
274 | * @see expressionBuilders |
||||||
275 | * @since 2.0.14 |
||||||
276 | * @see ExpressionInterface |
||||||
277 | */ |
||||||
278 | 28 | public function buildExpression(ExpressionInterface $expression, &$params = []) |
|||||
279 | { |
||||||
280 | 28 | $builder = $this->getExpressionBuilder($expression); |
|||||
281 | |||||||
282 | 28 | return $builder->build($expression, $params); |
|||||
283 | } |
||||||
284 | |||||||
285 | /** |
||||||
286 | * Gets object of [[ExpressionBuilderInterface]] that is suitable for $expression. |
||||||
287 | * Uses [[expressionBuilders]] array to find a suitable builder class. |
||||||
288 | * |
||||||
289 | * @param ExpressionInterface $expression |
||||||
290 | * @return ExpressionBuilderInterface |
||||||
291 | * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder. |
||||||
292 | * @since 2.0.14 |
||||||
293 | * @see expressionBuilders |
||||||
294 | */ |
||||||
295 | 28 | public function getExpressionBuilder(ExpressionInterface $expression) |
|||||
296 | { |
||||||
297 | 28 | $className = get_class($expression); |
|||||
298 | |||||||
299 | 28 | if (!isset($this->expressionBuilders[$className])) { |
|||||
0 ignored issues
–
show
|
|||||||
300 | foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) { |
||||||
301 | if (is_subclass_of($expression, $expressionClass)) { |
||||||
302 | $this->expressionBuilders[$className] = $builderClass; |
||||||
303 | break; |
||||||
304 | } |
||||||
305 | } |
||||||
306 | |||||||
307 | if (!isset($this->expressionBuilders[$className])) { |
||||||
308 | throw new InvalidArgumentException('Expression of class ' . $className . ' can not be built in ' . get_class($this)); |
||||||
309 | } |
||||||
310 | } |
||||||
311 | |||||||
312 | 28 | if ($this->expressionBuilders[$className] === __CLASS__) { |
|||||
313 | return $this; |
||||||
314 | } |
||||||
315 | |||||||
316 | 28 | if (!is_object($this->expressionBuilders[$className])) { |
|||||
0 ignored issues
–
show
|
|||||||
317 | 28 | $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this); |
|||||
318 | } |
||||||
319 | |||||||
320 | 28 | return $this->expressionBuilders[$className]; |
|||||
0 ignored issues
–
show
|
|||||||
321 | } |
||||||
322 | |||||||
323 | /** |
||||||
324 | * Creates an INSERT SQL statement. |
||||||
325 | * For example, |
||||||
326 | * ```php |
||||||
327 | * $sql = $queryBuilder->insert('user', [ |
||||||
328 | * 'name' => 'Sam', |
||||||
329 | * 'age' => 30, |
||||||
330 | * ], $params); |
||||||
331 | * ``` |
||||||
332 | * The method will properly escape the table and column names. |
||||||
333 | * |
||||||
334 | * @param string $table the table that new rows will be inserted into. |
||||||
335 | * @param array|Query $columns the column data (name => value) to be inserted into the table or instance |
||||||
336 | * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement. |
||||||
337 | * Passing of [[yii\db\Query|Query]] is available since version 2.0.11. |
||||||
338 | * @param array $params the binding parameters that will be generated by this method. |
||||||
339 | * They should be bound to the DB command later. |
||||||
340 | * @return string the INSERT SQL |
||||||
341 | */ |
||||||
342 | 32 | public function insert($table, $columns, &$params) |
|||||
343 | { |
||||||
344 | 32 | list($names, $placeholders, $values, $params) = $this->prepareInsertValues($table, $columns, $params); |
|||||
345 | 32 | return 'INSERT INTO ' . $this->db->quoteTableName($table) |
|||||
346 | 32 | . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '') |
|||||
347 | 32 | . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values); |
|||||
348 | } |
||||||
349 | |||||||
350 | /** |
||||||
351 | * Prepares a `VALUES` part for an `INSERT` SQL statement. |
||||||
352 | * |
||||||
353 | * @param string $table the table that new rows will be inserted into. |
||||||
354 | * @param array|Query $columns the column data (name => value) to be inserted into the table or instance |
||||||
355 | * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement. |
||||||
356 | * @param array $params the binding parameters that will be generated by this method. |
||||||
357 | * They should be bound to the DB command later. |
||||||
358 | * @return array array of column names, placeholders, values and params. |
||||||
359 | * @since 2.0.14 |
||||||
360 | */ |
||||||
361 | 32 | protected function prepareInsertValues($table, $columns, $params = []) |
|||||
362 | { |
||||||
363 | 32 | $schema = $this->db->getSchema(); |
|||||
364 | 32 | $tableSchema = $schema->getTableSchema($table); |
|||||
365 | 32 | $columnSchemas = $tableSchema !== null ? $tableSchema->columns : []; |
|||||
366 | 32 | $names = []; |
|||||
367 | 32 | $placeholders = []; |
|||||
368 | 32 | $values = ' DEFAULT VALUES'; |
|||||
369 | 32 | if ($columns instanceof Query) { |
|||||
370 | list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params); |
||||||
371 | } else { |
||||||
372 | 32 | foreach ($columns as $name => $value) { |
|||||
373 | 31 | $names[] = $schema->quoteColumnName($name); |
|||||
374 | 31 | $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value; |
|||||
375 | |||||||
376 | 31 | if ($value instanceof ExpressionInterface) { |
|||||
377 | 3 | $placeholders[] = $this->buildExpression($value, $params); |
|||||
378 | 28 | } elseif ($value instanceof \yii\db\Query) { |
|||||
379 | list($sql, $params) = $this->build($value, $params); |
||||||
380 | $placeholders[] = "($sql)"; |
||||||
381 | } else { |
||||||
382 | 28 | $placeholders[] = $this->bindParam($value, $params); |
|||||
383 | } |
||||||
384 | } |
||||||
385 | } |
||||||
386 | 32 | return [$names, $placeholders, $values, $params]; |
|||||
387 | } |
||||||
388 | |||||||
389 | /** |
||||||
390 | * Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement. |
||||||
391 | * |
||||||
392 | * @param Query $columns Object, which represents select query. |
||||||
393 | * @param \yii\db\Schema $schema Schema object to quote column name. |
||||||
394 | * @param array $params the parameters to be bound to the generated SQL statement. These parameters will |
||||||
395 | * be included in the result with the additional parameters generated during the query building process. |
||||||
396 | * @return array array of column names, values and params. |
||||||
397 | * @throws InvalidArgumentException if query's select does not contain named parameters only. |
||||||
398 | * @since 2.0.11 |
||||||
399 | */ |
||||||
400 | protected function prepareInsertSelectSubQuery($columns, $schema, $params = []) |
||||||
401 | { |
||||||
402 | if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) { |
||||||
403 | throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters'); |
||||||
404 | } |
||||||
405 | |||||||
406 | list($values, $params) = $this->build($columns, $params); |
||||||
407 | $names = []; |
||||||
408 | $values = ' ' . $values; |
||||||
409 | foreach ($columns->select as $title => $field) { |
||||||
410 | if (is_string($title)) { |
||||||
411 | $names[] = $schema->quoteColumnName($title); |
||||||
412 | } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) { |
||||||
413 | $names[] = $schema->quoteColumnName($matches[2]); |
||||||
414 | } else { |
||||||
415 | $names[] = $schema->quoteColumnName($field); |
||||||
416 | } |
||||||
417 | } |
||||||
418 | |||||||
419 | return [$names, $values, $params]; |
||||||
420 | } |
||||||
421 | |||||||
422 | /** |
||||||
423 | * Generates a batch INSERT SQL statement. |
||||||
424 | * |
||||||
425 | * For example, |
||||||
426 | * |
||||||
427 | * ```php |
||||||
428 | * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [ |
||||||
429 | * ['Tom', 30], |
||||||
430 | * ['Jane', 20], |
||||||
431 | * ['Linda', 25], |
||||||
432 | * ]); |
||||||
433 | * ``` |
||||||
434 | * |
||||||
435 | * Note that the values in each row must match the corresponding column names. |
||||||
436 | * |
||||||
437 | * The method will properly escape the column names, and quote the values to be inserted. |
||||||
438 | * |
||||||
439 | * @param string $table the table that new rows will be inserted into. |
||||||
440 | * @param array $columns the column names |
||||||
441 | * @param array|\Generator $rows the rows to be batch inserted into the table |
||||||
442 | * @param array $params the binding parameters. This parameter exists since 2.0.14 |
||||||
443 | * @return string the batch INSERT SQL statement |
||||||
444 | */ |
||||||
445 | public function batchInsert($table, $columns, $rows, &$params = []) |
||||||
446 | { |
||||||
447 | if (empty($rows)) { |
||||||
448 | return ''; |
||||||
449 | } |
||||||
450 | |||||||
451 | $schema = $this->db->getSchema(); |
||||||
452 | if (($tableSchema = $schema->getTableSchema($table)) !== null) { |
||||||
453 | $columnSchemas = $tableSchema->columns; |
||||||
454 | } else { |
||||||
455 | $columnSchemas = []; |
||||||
456 | } |
||||||
457 | |||||||
458 | $values = []; |
||||||
459 | foreach ($rows as $row) { |
||||||
460 | $vs = []; |
||||||
461 | foreach ($row as $i => $value) { |
||||||
462 | if (isset($columns[$i], $columnSchemas[$columns[$i]])) { |
||||||
463 | $value = $columnSchemas[$columns[$i]]->dbTypecast($value); |
||||||
464 | } |
||||||
465 | if (is_string($value)) { |
||||||
466 | $value = $schema->quoteValue($value); |
||||||
467 | } elseif (is_float($value)) { |
||||||
468 | // ensure type cast always has . as decimal separator in all locales |
||||||
469 | $value = StringHelper::floatToString($value); |
||||||
470 | } elseif ($value === false) { |
||||||
471 | $value = 0; |
||||||
472 | } elseif ($value === null) { |
||||||
473 | $value = 'NULL'; |
||||||
474 | } elseif ($value instanceof ExpressionInterface) { |
||||||
475 | $value = $this->buildExpression($value, $params); |
||||||
476 | } |
||||||
477 | $vs[] = $value; |
||||||
478 | } |
||||||
479 | $values[] = '(' . implode(', ', $vs) . ')'; |
||||||
480 | } |
||||||
481 | if (empty($values)) { |
||||||
482 | return ''; |
||||||
483 | } |
||||||
484 | |||||||
485 | foreach ($columns as $i => $name) { |
||||||
486 | $columns[$i] = $schema->quoteColumnName($name); |
||||||
487 | } |
||||||
488 | |||||||
489 | return 'INSERT INTO ' . $schema->quoteTableName($table) |
||||||
490 | . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values); |
||||||
491 | } |
||||||
492 | |||||||
493 | /** |
||||||
494 | * Creates an SQL statement to insert rows into a database table if |
||||||
495 | * they do not already exist (matching unique constraints), |
||||||
496 | * or update them if they do. |
||||||
497 | * |
||||||
498 | * For example, |
||||||
499 | * |
||||||
500 | * ```php |
||||||
501 | * $sql = $queryBuilder->upsert('pages', [ |
||||||
502 | * 'name' => 'Front page', |
||||||
503 | * 'url' => 'https://example.com/', // url is unique |
||||||
504 | * 'visits' => 0, |
||||||
505 | * ], [ |
||||||
506 | * 'visits' => new \yii\db\Expression('visits + 1'), |
||||||
507 | * ], $params); |
||||||
508 | * ``` |
||||||
509 | * |
||||||
510 | * The method will properly escape the table and column names. |
||||||
511 | * |
||||||
512 | * @param string $table the table that new rows will be inserted into/updated in. |
||||||
513 | * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance |
||||||
514 | * of [[Query]] to perform `INSERT INTO ... SELECT` SQL statement. |
||||||
515 | * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist. |
||||||
516 | * If `true` is passed, the column data will be updated to match the insert column data. |
||||||
517 | * If `false` is passed, no update will be performed if the column data already exists. |
||||||
518 | * @param array $params the binding parameters that will be generated by this method. |
||||||
519 | * They should be bound to the DB command later. |
||||||
520 | * @return string the resulting SQL. |
||||||
521 | * @throws NotSupportedException if this is not supported by the underlying DBMS. |
||||||
522 | * @since 2.0.14 |
||||||
523 | */ |
||||||
524 | public function upsert($table, $insertColumns, $updateColumns, &$params) |
||||||
525 | { |
||||||
526 | throw new NotSupportedException($this->db->getDriverName() . ' does not support upsert statements.'); |
||||||
527 | } |
||||||
528 | |||||||
529 | /** |
||||||
530 | * @param string $table |
||||||
531 | * @param array|Query $insertColumns |
||||||
532 | * @param array|bool $updateColumns |
||||||
533 | * @param Constraint[] $constraints this parameter recieves a matched constraint list. |
||||||
534 | * The constraints will be unique by their column names. |
||||||
535 | * @return array |
||||||
536 | * @since 2.0.14 |
||||||
537 | */ |
||||||
538 | protected function prepareUpsertColumns($table, $insertColumns, $updateColumns, &$constraints = []) |
||||||
539 | { |
||||||
540 | if ($insertColumns instanceof Query) { |
||||||
541 | list($insertNames) = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema()); |
||||||
542 | } else { |
||||||
543 | $insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns)); |
||||||
544 | } |
||||||
545 | $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints); |
||||||
546 | $uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames); |
||||||
547 | if ($updateColumns !== true) { |
||||||
548 | return [$uniqueNames, $insertNames, null]; |
||||||
549 | } |
||||||
550 | |||||||
551 | return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)]; |
||||||
552 | } |
||||||
553 | |||||||
554 | /** |
||||||
555 | * Returns all column names belonging to constraints enforcing uniqueness (`PRIMARY KEY`, `UNIQUE INDEX`, etc.) |
||||||
556 | * for the named table removing constraints which did not cover the specified column list. |
||||||
557 | * The column list will be unique by column names. |
||||||
558 | * |
||||||
559 | * @param string $name table name. The table name may contain schema name if any. Do not quote the table name. |
||||||
560 | * @param string[] $columns source column list. |
||||||
561 | * @param Constraint[] $constraints this parameter optionally recieves a matched constraint list. |
||||||
562 | * The constraints will be unique by their column names. |
||||||
563 | * @return string[] column list. |
||||||
564 | */ |
||||||
565 | private function getTableUniqueColumnNames($name, $columns, &$constraints = []) |
||||||
566 | { |
||||||
567 | $schema = $this->db->getSchema(); |
||||||
568 | if (!$schema instanceof ConstraintFinderInterface) { |
||||||
569 | return []; |
||||||
570 | } |
||||||
571 | |||||||
572 | $constraints = []; |
||||||
573 | $primaryKey = $schema->getTablePrimaryKey($name); |
||||||
0 ignored issues
–
show
The method
getTablePrimaryKey() does not exist on yii\db\Schema . Since you implemented __call , consider adding a @method annotation.
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
574 | if ($primaryKey !== null) { |
||||||
575 | $constraints[] = $primaryKey; |
||||||
576 | } |
||||||
577 | foreach ($schema->getTableIndexes($name) as $constraint) { |
||||||
0 ignored issues
–
show
The method
getTableIndexes() does not exist on yii\db\Schema . Since you implemented __call , consider adding a @method annotation.
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
578 | if ($constraint->isUnique) { |
||||||
579 | $constraints[] = $constraint; |
||||||
580 | } |
||||||
581 | } |
||||||
582 | $constraints = array_merge($constraints, $schema->getTableUniques($name)); |
||||||
0 ignored issues
–
show
The method
getTableUniques() does not exist on yii\db\Schema . Since you implemented __call , consider adding a @method annotation.
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
583 | // Remove duplicates |
||||||
584 | $constraints = array_combine(array_map(function (Constraint $constraint) { |
||||||
585 | $columns = $constraint->columnNames; |
||||||
586 | sort($columns, SORT_STRING); |
||||||
0 ignored issues
–
show
It seems like
$columns can also be of type null ; however, parameter $array of sort() does only seem to accept array , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
587 | return json_encode($columns); |
||||||
588 | }, $constraints), $constraints); |
||||||
589 | $columnNames = []; |
||||||
590 | // Remove all constraints which do not cover the specified column list |
||||||
591 | $constraints = array_values(array_filter($constraints, function (Constraint $constraint) use ($schema, $columns, &$columnNames) { |
||||||
592 | $constraintColumnNames = array_map([$schema, 'quoteColumnName'], $constraint->columnNames); |
||||||
0 ignored issues
–
show
It seems like
$constraint->columnNames can also be of type null ; however, parameter $array of array_map() does only seem to accept array , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
593 | $result = !array_diff($constraintColumnNames, $columns); |
||||||
594 | if ($result) { |
||||||
595 | $columnNames = array_merge($columnNames, $constraintColumnNames); |
||||||
596 | } |
||||||
597 | return $result; |
||||||
598 | })); |
||||||
599 | return array_unique($columnNames); |
||||||
600 | } |
||||||
601 | |||||||
602 | /** |
||||||
603 | * Creates an UPDATE SQL statement. |
||||||
604 | * |
||||||
605 | * For example, |
||||||
606 | * |
||||||
607 | * ```php |
||||||
608 | * $params = []; |
||||||
609 | * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params); |
||||||
610 | * ``` |
||||||
611 | * |
||||||
612 | * The method will properly escape the table and column names. |
||||||
613 | * |
||||||
614 | * @param string $table the table to be updated. |
||||||
615 | * @param array $columns the column data (name => value) to be updated. |
||||||
616 | * @param array|string $condition the condition that will be put in the WHERE part. Please |
||||||
617 | * refer to [[Query::where()]] on how to specify condition. |
||||||
618 | * @param array $params the binding parameters that will be modified by this method |
||||||
619 | * so that they can be bound to the DB command later. |
||||||
620 | * @return string the UPDATE SQL |
||||||
621 | */ |
||||||
622 | 11 | public function update($table, $columns, $condition, &$params) |
|||||
623 | { |
||||||
624 | 11 | list($lines, $params) = $this->prepareUpdateSets($table, $columns, $params); |
|||||
625 | 11 | $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines); |
|||||
626 | 11 | $where = $this->buildWhere($condition, $params); |
|||||
627 | 11 | return $where === '' ? $sql : $sql . ' ' . $where; |
|||||
628 | } |
||||||
629 | |||||||
630 | /** |
||||||
631 | * Prepares a `SET` parts for an `UPDATE` SQL statement. |
||||||
632 | * @param string $table the table to be updated. |
||||||
633 | * @param array $columns the column data (name => value) to be updated. |
||||||
634 | * @param array $params the binding parameters that will be modified by this method |
||||||
635 | * so that they can be bound to the DB command later. |
||||||
636 | * @return array an array `SET` parts for an `UPDATE` SQL statement (the first array element) and params (the second array element). |
||||||
637 | * @since 2.0.14 |
||||||
638 | */ |
||||||
639 | 11 | protected function prepareUpdateSets($table, $columns, $params = []) |
|||||
640 | { |
||||||
641 | 11 | $tableSchema = $this->db->getTableSchema($table); |
|||||
642 | 11 | $columnSchemas = $tableSchema !== null ? $tableSchema->columns : []; |
|||||
643 | 11 | $sets = []; |
|||||
644 | 11 | foreach ($columns as $name => $value) { |
|||||
645 | 11 | $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value; |
|||||
646 | 11 | if ($value instanceof ExpressionInterface) { |
|||||
647 | $placeholder = $this->buildExpression($value, $params); |
||||||
648 | } else { |
||||||
649 | 11 | $placeholder = $this->bindParam($value, $params); |
|||||
650 | } |
||||||
651 | |||||||
652 | 11 | $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder; |
|||||
653 | } |
||||||
654 | 11 | return [$sets, $params]; |
|||||
655 | } |
||||||
656 | |||||||
657 | /** |
||||||
658 | * Creates a DELETE SQL statement. |
||||||
659 | * |
||||||
660 | * For example, |
||||||
661 | * |
||||||
662 | * ```php |
||||||
663 | * $sql = $queryBuilder->delete('user', 'status = 0'); |
||||||
664 | * ``` |
||||||
665 | * |
||||||
666 | * The method will properly escape the table and column names. |
||||||
667 | * |
||||||
668 | * @param string $table the table where the data will be deleted from. |
||||||
669 | * @param array|string $condition the condition that will be put in the WHERE part. Please |
||||||
670 | * refer to [[Query::where()]] on how to specify condition. |
||||||
671 | * @param array $params the binding parameters that will be modified by this method |
||||||
672 | * so that they can be bound to the DB command later. |
||||||
673 | * @return string the DELETE SQL |
||||||
674 | */ |
||||||
675 | 3 | public function delete($table, $condition, &$params) |
|||||
676 | { |
||||||
677 | 3 | $sql = 'DELETE FROM ' . $this->db->quoteTableName($table); |
|||||
678 | 3 | $where = $this->buildWhere($condition, $params); |
|||||
679 | |||||||
680 | 3 | return $where === '' ? $sql : $sql . ' ' . $where; |
|||||
681 | } |
||||||
682 | |||||||
683 | /** |
||||||
684 | * Builds a SQL statement for creating a new DB table. |
||||||
685 | * |
||||||
686 | * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'), |
||||||
687 | * where name stands for a column name which will be properly quoted by the method, and definition |
||||||
688 | * stands for the column type which must contain an abstract DB type. |
||||||
689 | * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one. |
||||||
690 | * |
||||||
691 | * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly |
||||||
692 | * inserted into the generated SQL. |
||||||
693 | * |
||||||
694 | * For example, |
||||||
695 | * |
||||||
696 | * ```php |
||||||
697 | * $sql = $queryBuilder->createTable('user', [ |
||||||
698 | * 'id' => 'pk', |
||||||
699 | * 'name' => 'string', |
||||||
700 | * 'age' => 'integer', |
||||||
701 | * 'column_name double precision null default null', # definition only example |
||||||
702 | * ]); |
||||||
703 | * ``` |
||||||
704 | * |
||||||
705 | * @param string $table the name of the table to be created. The name will be properly quoted by the method. |
||||||
706 | * @param array $columns the columns (name => definition) in the new table. |
||||||
707 | * @param string|null $options additional SQL fragment that will be appended to the generated SQL. |
||||||
708 | * @return string the SQL statement for creating a new DB table. |
||||||
709 | */ |
||||||
710 | 72 | public function createTable($table, $columns, $options = null) |
|||||
711 | { |
||||||
712 | 72 | $cols = []; |
|||||
713 | 72 | foreach ($columns as $name => $type) { |
|||||
714 | 72 | if (is_string($name)) { |
|||||
715 | 72 | $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type); |
|||||
716 | } else { |
||||||
717 | $cols[] = "\t" . $type; |
||||||
718 | } |
||||||
719 | } |
||||||
720 | 72 | $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)"; |
|||||
721 | |||||||
722 | 72 | return $options === null ? $sql : $sql . ' ' . $options; |
|||||
723 | } |
||||||
724 | |||||||
725 | /** |
||||||
726 | * Builds a SQL statement for renaming a DB table. |
||||||
727 | * @param string $oldName the table to be renamed. The name will be properly quoted by the method. |
||||||
728 | * @param string $newName the new table name. The name will be properly quoted by the method. |
||||||
729 | * @return string the SQL statement for renaming a DB table. |
||||||
730 | */ |
||||||
731 | public function renameTable($oldName, $newName) |
||||||
732 | { |
||||||
733 | return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName); |
||||||
734 | } |
||||||
735 | |||||||
736 | /** |
||||||
737 | * Builds a SQL statement for dropping a DB table. |
||||||
738 | * @param string $table the table to be dropped. The name will be properly quoted by the method. |
||||||
739 | * @return string the SQL statement for dropping a DB table. |
||||||
740 | */ |
||||||
741 | public function dropTable($table) |
||||||
742 | { |
||||||
743 | return 'DROP TABLE ' . $this->db->quoteTableName($table); |
||||||
744 | } |
||||||
745 | |||||||
746 | /** |
||||||
747 | * Builds a SQL statement for adding a primary key constraint to an existing table. |
||||||
748 | * @param string $name the name of the primary key constraint. |
||||||
749 | * @param string $table the table that the primary key constraint will be added to. |
||||||
750 | * @param string|array $columns comma separated string or array of columns that the primary key will consist of. |
||||||
751 | * @return string the SQL statement for adding a primary key constraint to an existing table. |
||||||
752 | */ |
||||||
753 | public function addPrimaryKey($name, $table, $columns) |
||||||
754 | { |
||||||
755 | if (is_string($columns)) { |
||||||
756 | $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY); |
||||||
757 | } |
||||||
758 | |||||||
759 | foreach ($columns as $i => $col) { |
||||||
760 | $columns[$i] = $this->db->quoteColumnName($col); |
||||||
761 | } |
||||||
762 | |||||||
763 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT ' |
||||||
764 | . $this->db->quoteColumnName($name) . ' PRIMARY KEY (' |
||||||
765 | . implode(', ', $columns) . ')'; |
||||||
766 | } |
||||||
767 | |||||||
768 | /** |
||||||
769 | * Builds a SQL statement for removing a primary key constraint to an existing table. |
||||||
770 | * @param string $name the name of the primary key constraint to be removed. |
||||||
771 | * @param string $table the table that the primary key constraint will be removed from. |
||||||
772 | * @return string the SQL statement for removing a primary key constraint from an existing table. |
||||||
773 | */ |
||||||
774 | public function dropPrimaryKey($name, $table) |
||||||
775 | { |
||||||
776 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) |
||||||
777 | . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name); |
||||||
778 | } |
||||||
779 | |||||||
780 | /** |
||||||
781 | * Builds a SQL statement for truncating a DB table. |
||||||
782 | * @param string $table the table to be truncated. The name will be properly quoted by the method. |
||||||
783 | * @return string the SQL statement for truncating a DB table. |
||||||
784 | */ |
||||||
785 | public function truncateTable($table) |
||||||
786 | { |
||||||
787 | return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table); |
||||||
788 | } |
||||||
789 | |||||||
790 | /** |
||||||
791 | * Builds a SQL statement for adding a new DB column. |
||||||
792 | * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method. |
||||||
793 | * @param string $column the name of the new column. The name will be properly quoted by the method. |
||||||
794 | * @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any) |
||||||
795 | * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. |
||||||
796 | * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'. |
||||||
797 | * @return string the SQL statement for adding a new column. |
||||||
798 | */ |
||||||
799 | public function addColumn($table, $column, $type) |
||||||
800 | { |
||||||
801 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) |
||||||
802 | . ' ADD ' . $this->db->quoteColumnName($column) . ' ' |
||||||
803 | . $this->getColumnType($type); |
||||||
804 | } |
||||||
805 | |||||||
806 | /** |
||||||
807 | * Builds a SQL statement for dropping a DB column. |
||||||
808 | * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method. |
||||||
809 | * @param string $column the name of the column to be dropped. The name will be properly quoted by the method. |
||||||
810 | * @return string the SQL statement for dropping a DB column. |
||||||
811 | */ |
||||||
812 | public function dropColumn($table, $column) |
||||||
813 | { |
||||||
814 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) |
||||||
815 | . ' DROP COLUMN ' . $this->db->quoteColumnName($column); |
||||||
816 | } |
||||||
817 | |||||||
818 | /** |
||||||
819 | * Builds a SQL statement for renaming a column. |
||||||
820 | * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method. |
||||||
821 | * @param string $oldName the old name of the column. The name will be properly quoted by the method. |
||||||
822 | * @param string $newName the new name of the column. The name will be properly quoted by the method. |
||||||
823 | * @return string the SQL statement for renaming a DB column. |
||||||
824 | */ |
||||||
825 | public function renameColumn($table, $oldName, $newName) |
||||||
826 | { |
||||||
827 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) |
||||||
828 | . ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName) |
||||||
829 | . ' TO ' . $this->db->quoteColumnName($newName); |
||||||
830 | } |
||||||
831 | |||||||
832 | /** |
||||||
833 | * Builds a SQL statement for changing the definition of a column. |
||||||
834 | * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method. |
||||||
835 | * @param string $column the name of the column to be changed. The name will be properly quoted by the method. |
||||||
836 | * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract |
||||||
837 | * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept |
||||||
838 | * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' |
||||||
839 | * will become 'varchar(255) not null'. |
||||||
840 | * @return string the SQL statement for changing the definition of a column. |
||||||
841 | */ |
||||||
842 | public function alterColumn($table, $column, $type) |
||||||
843 | { |
||||||
844 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE ' |
||||||
845 | . $this->db->quoteColumnName($column) . ' ' |
||||||
846 | . $this->db->quoteColumnName($column) . ' ' |
||||||
847 | . $this->getColumnType($type); |
||||||
848 | } |
||||||
849 | |||||||
850 | /** |
||||||
851 | * Builds a SQL statement for adding a foreign key constraint to an existing table. |
||||||
852 | * The method will properly quote the table and column names. |
||||||
853 | * @param string $name the name of the foreign key constraint. |
||||||
854 | * @param string $table the table that the foreign key constraint will be added to. |
||||||
855 | * @param string|array $columns the name of the column to that the constraint will be added on. |
||||||
856 | * If there are multiple columns, separate them with commas or use an array to represent them. |
||||||
857 | * @param string $refTable the table that the foreign key references to. |
||||||
858 | * @param string|array $refColumns the name of the column that the foreign key references to. |
||||||
859 | * If there are multiple columns, separate them with commas or use an array to represent them. |
||||||
860 | * @param string|null $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL |
||||||
861 | * @param string|null $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL |
||||||
862 | * @return string the SQL statement for adding a foreign key constraint to an existing table. |
||||||
863 | */ |
||||||
864 | public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null) |
||||||
865 | { |
||||||
866 | $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) |
||||||
867 | . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name) |
||||||
868 | . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')' |
||||||
869 | . ' REFERENCES ' . $this->db->quoteTableName($refTable) |
||||||
870 | . ' (' . $this->buildColumns($refColumns) . ')'; |
||||||
871 | if ($delete !== null) { |
||||||
872 | $sql .= ' ON DELETE ' . $delete; |
||||||
873 | } |
||||||
874 | if ($update !== null) { |
||||||
875 | $sql .= ' ON UPDATE ' . $update; |
||||||
876 | } |
||||||
877 | |||||||
878 | return $sql; |
||||||
879 | } |
||||||
880 | |||||||
881 | /** |
||||||
882 | * Builds a SQL statement for dropping a foreign key constraint. |
||||||
883 | * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method. |
||||||
884 | * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method. |
||||||
885 | * @return string the SQL statement for dropping a foreign key constraint. |
||||||
886 | */ |
||||||
887 | public function dropForeignKey($name, $table) |
||||||
888 | { |
||||||
889 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) |
||||||
890 | . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name); |
||||||
891 | } |
||||||
892 | |||||||
893 | /** |
||||||
894 | * Builds a SQL statement for creating a new index. |
||||||
895 | * @param string $name the name of the index. The name will be properly quoted by the method. |
||||||
896 | * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method. |
||||||
897 | * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, |
||||||
898 | * separate them with commas or use an array to represent them. Each column name will be properly quoted |
||||||
899 | * by the method, unless a parenthesis is found in the name. |
||||||
900 | * @param bool $unique whether to add UNIQUE constraint on the created index. |
||||||
901 | * @return string the SQL statement for creating a new index. |
||||||
902 | */ |
||||||
903 | public function createIndex($name, $table, $columns, $unique = false) |
||||||
904 | { |
||||||
905 | return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') |
||||||
906 | . $this->db->quoteTableName($name) . ' ON ' |
||||||
907 | . $this->db->quoteTableName($table) |
||||||
908 | . ' (' . $this->buildColumns($columns) . ')'; |
||||||
909 | } |
||||||
910 | |||||||
911 | /** |
||||||
912 | * Builds a SQL statement for dropping an index. |
||||||
913 | * @param string $name the name of the index to be dropped. The name will be properly quoted by the method. |
||||||
914 | * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method. |
||||||
915 | * @return string the SQL statement for dropping an index. |
||||||
916 | */ |
||||||
917 | public function dropIndex($name, $table) |
||||||
918 | { |
||||||
919 | return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table); |
||||||
920 | } |
||||||
921 | |||||||
922 | /** |
||||||
923 | * Creates a SQL command for adding an unique constraint to an existing table. |
||||||
924 | * @param string $name the name of the unique constraint. |
||||||
925 | * The name will be properly quoted by the method. |
||||||
926 | * @param string $table the table that the unique constraint will be added to. |
||||||
927 | * The name will be properly quoted by the method. |
||||||
928 | * @param string|array $columns the name of the column to that the constraint will be added on. |
||||||
929 | * If there are multiple columns, separate them with commas. |
||||||
930 | * The name will be properly quoted by the method. |
||||||
931 | * @return string the SQL statement for adding an unique constraint to an existing table. |
||||||
932 | * @since 2.0.13 |
||||||
933 | */ |
||||||
934 | public function addUnique($name, $table, $columns) |
||||||
935 | { |
||||||
936 | if (is_string($columns)) { |
||||||
937 | $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY); |
||||||
938 | } |
||||||
939 | foreach ($columns as $i => $col) { |
||||||
940 | $columns[$i] = $this->db->quoteColumnName($col); |
||||||
941 | } |
||||||
942 | |||||||
943 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT ' |
||||||
944 | . $this->db->quoteColumnName($name) . ' UNIQUE (' |
||||||
945 | . implode(', ', $columns) . ')'; |
||||||
946 | } |
||||||
947 | |||||||
948 | /** |
||||||
949 | * Creates a SQL command for dropping an unique constraint. |
||||||
950 | * @param string $name the name of the unique constraint to be dropped. |
||||||
951 | * The name will be properly quoted by the method. |
||||||
952 | * @param string $table the table whose unique constraint is to be dropped. |
||||||
953 | * The name will be properly quoted by the method. |
||||||
954 | * @return string the SQL statement for dropping an unique constraint. |
||||||
955 | * @since 2.0.13 |
||||||
956 | */ |
||||||
957 | public function dropUnique($name, $table) |
||||||
958 | { |
||||||
959 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) |
||||||
960 | . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name); |
||||||
961 | } |
||||||
962 | |||||||
963 | /** |
||||||
964 | * Creates a SQL command for adding a check constraint to an existing table. |
||||||
965 | * @param string $name the name of the check constraint. |
||||||
966 | * The name will be properly quoted by the method. |
||||||
967 | * @param string $table the table that the check constraint will be added to. |
||||||
968 | * The name will be properly quoted by the method. |
||||||
969 | * @param string $expression the SQL of the `CHECK` constraint. |
||||||
970 | * @return string the SQL statement for adding a check constraint to an existing table. |
||||||
971 | * @since 2.0.13 |
||||||
972 | */ |
||||||
973 | public function addCheck($name, $table, $expression) |
||||||
974 | { |
||||||
975 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT ' |
||||||
976 | . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')'; |
||||||
977 | } |
||||||
978 | |||||||
979 | /** |
||||||
980 | * Creates a SQL command for dropping a check constraint. |
||||||
981 | * @param string $name the name of the check constraint to be dropped. |
||||||
982 | * The name will be properly quoted by the method. |
||||||
983 | * @param string $table the table whose check constraint is to be dropped. |
||||||
984 | * The name will be properly quoted by the method. |
||||||
985 | * @return string the SQL statement for dropping a check constraint. |
||||||
986 | * @since 2.0.13 |
||||||
987 | */ |
||||||
988 | public function dropCheck($name, $table) |
||||||
989 | { |
||||||
990 | return 'ALTER TABLE ' . $this->db->quoteTableName($table) |
||||||
991 | . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name); |
||||||
992 | } |
||||||
993 | |||||||
994 | /** |
||||||
995 | * Creates a SQL command for adding a default value constraint to an existing table. |
||||||
996 | * @param string $name the name of the default value constraint. |
||||||
997 | * The name will be properly quoted by the method. |
||||||
998 | * @param string $table the table that the default value constraint will be added to. |
||||||
999 | * The name will be properly quoted by the method. |
||||||
1000 | * @param string $column the name of the column to that the constraint will be added on. |
||||||
1001 | * The name will be properly quoted by the method. |
||||||
1002 | * @param mixed $value default value. |
||||||
1003 | * @return string the SQL statement for adding a default value constraint to an existing table. |
||||||
1004 | * @throws NotSupportedException if this is not supported by the underlying DBMS. |
||||||
1005 | * @since 2.0.13 |
||||||
1006 | */ |
||||||
1007 | public function addDefaultValue($name, $table, $column, $value) |
||||||
1008 | { |
||||||
1009 | throw new NotSupportedException($this->db->getDriverName() . ' does not support adding default value constraints.'); |
||||||
1010 | } |
||||||
1011 | |||||||
1012 | /** |
||||||
1013 | * Creates a SQL command for dropping a default value constraint. |
||||||
1014 | * @param string $name the name of the default value constraint to be dropped. |
||||||
1015 | * The name will be properly quoted by the method. |
||||||
1016 | * @param string $table the table whose default value constraint is to be dropped. |
||||||
1017 | * The name will be properly quoted by the method. |
||||||
1018 | * @return string the SQL statement for dropping a default value constraint. |
||||||
1019 | * @throws NotSupportedException if this is not supported by the underlying DBMS. |
||||||
1020 | * @since 2.0.13 |
||||||
1021 | */ |
||||||
1022 | public function dropDefaultValue($name, $table) |
||||||
1023 | { |
||||||
1024 | throw new NotSupportedException($this->db->getDriverName() . ' does not support dropping default value constraints.'); |
||||||
1025 | } |
||||||
1026 | |||||||
1027 | /** |
||||||
1028 | * Creates a SQL statement for resetting the sequence value of a table's primary key. |
||||||
1029 | * The sequence will be reset such that the primary key of the next new row inserted |
||||||
1030 | * will have the specified value or the maximum existing value +1. |
||||||
1031 | * @param string $table the name of the table whose primary key sequence will be reset |
||||||
1032 | * @param array|string|null $value the value for the primary key of the next new row inserted. If this is not set, |
||||||
1033 | * the next new row's primary key will have the maximum existing value +1. |
||||||
1034 | * @return string the SQL statement for resetting sequence |
||||||
1035 | * @throws NotSupportedException if this is not supported by the underlying DBMS |
||||||
1036 | */ |
||||||
1037 | public function resetSequence($table, $value = null) |
||||||
0 ignored issues
–
show
The parameter
$table is not used and could be removed.
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
This check looks for parameters that have been defined for a function or method, but which are not used in the method body. ![]() |
|||||||
1038 | { |
||||||
1039 | throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.'); |
||||||
1040 | } |
||||||
1041 | |||||||
1042 | /** |
||||||
1043 | * Execute a SQL statement for resetting the sequence value of a table's primary key. |
||||||
1044 | * Reason for execute is that some databases (Oracle) need several queries to do so. |
||||||
1045 | * The sequence is reset such that the primary key of the next new row inserted |
||||||
1046 | * will have the specified value or the maximum existing value +1. |
||||||
1047 | * @param string $table the name of the table whose primary key sequence is reset |
||||||
1048 | * @param array|string|null $value the value for the primary key of the next new row inserted. If this is not set, |
||||||
1049 | * the next new row's primary key will have the maximum existing value +1. |
||||||
1050 | * @throws NotSupportedException if this is not supported by the underlying DBMS |
||||||
1051 | * @since 2.0.16 |
||||||
1052 | */ |
||||||
1053 | public function executeResetSequence($table, $value = null) |
||||||
1054 | { |
||||||
1055 | $this->db->createCommand()->resetSequence($table, $value)->execute(); |
||||||
1056 | } |
||||||
1057 | |||||||
1058 | /** |
||||||
1059 | * Builds a SQL statement for enabling or disabling integrity check. |
||||||
1060 | * @param bool $check whether to turn on or off the integrity check. |
||||||
1061 | * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. |
||||||
1062 | * @param string $table the table name. Defaults to empty string, meaning that no table will be changed. |
||||||
1063 | * @return string the SQL statement for checking integrity |
||||||
1064 | * @throws NotSupportedException if this is not supported by the underlying DBMS |
||||||
1065 | */ |
||||||
1066 | public function checkIntegrity($check = true, $schema = '', $table = '') |
||||||
0 ignored issues
–
show
The parameter
$check is not used and could be removed.
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
This check looks for parameters that have been defined for a function or method, but which are not used in the method body. ![]() |
|||||||
1067 | { |
||||||
1068 | throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.'); |
||||||
1069 | } |
||||||
1070 | |||||||
1071 | /** |
||||||
1072 | * Builds a SQL command for adding comment to column. |
||||||
1073 | * |
||||||
1074 | * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method. |
||||||
1075 | * @param string $column the name of the column to be commented. The column name will be properly quoted by the method. |
||||||
1076 | * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method. |
||||||
1077 | * @return string the SQL statement for adding comment on column |
||||||
1078 | * @since 2.0.8 |
||||||
1079 | */ |
||||||
1080 | public function addCommentOnColumn($table, $column, $comment) |
||||||
1081 | { |
||||||
1082 | return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment); |
||||||
1083 | } |
||||||
1084 | |||||||
1085 | /** |
||||||
1086 | * Builds a SQL command for adding comment to table. |
||||||
1087 | * |
||||||
1088 | * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method. |
||||||
1089 | * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method. |
||||||
1090 | * @return string the SQL statement for adding comment on table |
||||||
1091 | * @since 2.0.8 |
||||||
1092 | */ |
||||||
1093 | public function addCommentOnTable($table, $comment) |
||||||
1094 | { |
||||||
1095 | return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment); |
||||||
1096 | } |
||||||
1097 | |||||||
1098 | /** |
||||||
1099 | * Builds a SQL command for adding comment to column. |
||||||
1100 | * |
||||||
1101 | * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method. |
||||||
1102 | * @param string $column the name of the column to be commented. The column name will be properly quoted by the method. |
||||||
1103 | * @return string the SQL statement for adding comment on column |
||||||
1104 | * @since 2.0.8 |
||||||
1105 | */ |
||||||
1106 | public function dropCommentFromColumn($table, $column) |
||||||
1107 | { |
||||||
1108 | return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS NULL'; |
||||||
1109 | } |
||||||
1110 | |||||||
1111 | /** |
||||||
1112 | * Builds a SQL command for adding comment to table. |
||||||
1113 | * |
||||||
1114 | * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method. |
||||||
1115 | * @return string the SQL statement for adding comment on column |
||||||
1116 | * @since 2.0.8 |
||||||
1117 | */ |
||||||
1118 | public function dropCommentFromTable($table) |
||||||
1119 | { |
||||||
1120 | return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL'; |
||||||
1121 | } |
||||||
1122 | |||||||
1123 | /** |
||||||
1124 | * Creates a SQL View. |
||||||
1125 | * |
||||||
1126 | * @param string $viewName the name of the view to be created. |
||||||
1127 | * @param string|Query $subQuery the select statement which defines the view. |
||||||
1128 | * This can be either a string or a [[Query]] object. |
||||||
1129 | * @return string the `CREATE VIEW` SQL statement. |
||||||
1130 | * @since 2.0.14 |
||||||
1131 | */ |
||||||
1132 | public function createView($viewName, $subQuery) |
||||||
1133 | { |
||||||
1134 | if ($subQuery instanceof Query) { |
||||||
1135 | list($rawQuery, $params) = $this->build($subQuery); |
||||||
1136 | array_walk( |
||||||
1137 | $params, |
||||||
1138 | function (&$param) { |
||||||
1139 | $param = $this->db->quoteValue($param); |
||||||
1140 | } |
||||||
1141 | ); |
||||||
1142 | $subQuery = strtr($rawQuery, $params); |
||||||
1143 | } |
||||||
1144 | |||||||
1145 | return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery; |
||||||
1146 | } |
||||||
1147 | |||||||
1148 | /** |
||||||
1149 | * Drops a SQL View. |
||||||
1150 | * |
||||||
1151 | * @param string $viewName the name of the view to be dropped. |
||||||
1152 | * @return string the `DROP VIEW` SQL statement. |
||||||
1153 | * @since 2.0.14 |
||||||
1154 | */ |
||||||
1155 | public function dropView($viewName) |
||||||
1156 | { |
||||||
1157 | return 'DROP VIEW ' . $this->db->quoteTableName($viewName); |
||||||
1158 | } |
||||||
1159 | |||||||
1160 | /** |
||||||
1161 | * Converts an abstract column type into a physical column type. |
||||||
1162 | * |
||||||
1163 | * The conversion is done using the type map specified in [[typeMap]]. |
||||||
1164 | * The following abstract column types are supported (using MySQL as an example to explain the corresponding |
||||||
1165 | * physical types): |
||||||
1166 | * |
||||||
1167 | * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY" |
||||||
1168 | * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY" |
||||||
1169 | * - `upk`: an unsigned auto-incremental primary key type, will be converted into "int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY" |
||||||
1170 | * - `char`: char type, will be converted into "char(1)" |
||||||
1171 | * - `string`: string type, will be converted into "varchar(255)" |
||||||
1172 | * - `text`: a long string type, will be converted into "text" |
||||||
1173 | * - `smallint`: a small integer type, will be converted into "smallint(6)" |
||||||
1174 | * - `integer`: integer type, will be converted into "int(11)" |
||||||
1175 | * - `bigint`: a big integer type, will be converted into "bigint(20)" |
||||||
1176 | * - `boolean`: boolean type, will be converted into "tinyint(1)" |
||||||
1177 | * - `float``: float number type, will be converted into "float" |
||||||
1178 | * - `decimal`: decimal number type, will be converted into "decimal" |
||||||
1179 | * - `datetime`: datetime type, will be converted into "datetime" |
||||||
1180 | * - `timestamp`: timestamp type, will be converted into "timestamp" |
||||||
1181 | * - `time`: time type, will be converted into "time" |
||||||
1182 | * - `date`: date type, will be converted into "date" |
||||||
1183 | * - `money`: money type, will be converted into "decimal(19,4)" |
||||||
1184 | * - `binary`: binary data type, will be converted into "blob" |
||||||
1185 | * |
||||||
1186 | * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only |
||||||
1187 | * the first part will be converted, and the rest of the parts will be appended to the converted result. |
||||||
1188 | * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'. |
||||||
1189 | * |
||||||
1190 | * For some of the abstract types you can also specify a length or precision constraint |
||||||
1191 | * by appending it in round brackets directly to the type. |
||||||
1192 | * For example `string(32)` will be converted into "varchar(32)" on a MySQL database. |
||||||
1193 | * If the underlying DBMS does not support these kind of constraints for a type it will |
||||||
1194 | * be ignored. |
||||||
1195 | * |
||||||
1196 | * If a type cannot be found in [[typeMap]], it will be returned without any change. |
||||||
1197 | * @param string|ColumnSchemaBuilder $type abstract column type |
||||||
1198 | * @return string physical column type. |
||||||
1199 | */ |
||||||
1200 | 72 | public function getColumnType($type) |
|||||
1201 | { |
||||||
1202 | 72 | if ($type instanceof ColumnSchemaBuilder) { |
|||||
1203 | $type = $type->__toString(); |
||||||
1204 | } |
||||||
1205 | |||||||
1206 | 72 | if (isset($this->typeMap[$type])) { |
|||||
1207 | 72 | return $this->typeMap[$type]; |
|||||
1208 | 15 | } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) { |
|||||
1209 | if (isset($this->typeMap[$matches[1]])) { |
||||||
1210 | return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3]; |
||||||
1211 | } |
||||||
1212 | 15 | } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) { |
|||||
1213 | 15 | if (isset($this->typeMap[$matches[1]])) { |
|||||
1214 | 15 | return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type); |
|||||
1215 | } |
||||||
1216 | } |
||||||
1217 | |||||||
1218 | return $type; |
||||||
1219 | } |
||||||
1220 | |||||||
1221 | /** |
||||||
1222 | * @param array $columns |
||||||
1223 | * @param array $params the binding parameters to be populated |
||||||
1224 | * @param bool $distinct |
||||||
1225 | * @param string|null $selectOption |
||||||
1226 | * @return string the SELECT clause built from [[Query::$select]]. |
||||||
1227 | */ |
||||||
1228 | 27 | public function buildSelect($columns, &$params, $distinct = false, $selectOption = null) |
|||||
1229 | { |
||||||
1230 | 27 | $select = $distinct ? 'SELECT DISTINCT' : 'SELECT'; |
|||||
1231 | 27 | if ($selectOption !== null) { |
|||||
1232 | $select .= ' ' . $selectOption; |
||||||
1233 | } |
||||||
1234 | |||||||
1235 | 27 | if (empty($columns)) { |
|||||
1236 | 15 | return $select . ' *'; |
|||||
1237 | } |
||||||
1238 | |||||||
1239 | 16 | foreach ($columns as $i => $column) { |
|||||
1240 | 16 | if ($column instanceof ExpressionInterface) { |
|||||
1241 | if (is_int($i)) { |
||||||
1242 | $columns[$i] = $this->buildExpression($column, $params); |
||||||
1243 | } else { |
||||||
1244 | $columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i); |
||||||
1245 | } |
||||||
1246 | 16 | } elseif ($column instanceof Query) { |
|||||
1247 | list($sql, $params) = $this->build($column, $params); |
||||||
1248 | $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i); |
||||||
1249 | 16 | } elseif (is_string($i) && $i !== $column) { |
|||||
1250 | if (strpos($column, '(') === false) { |
||||||
1251 | $column = $this->db->quoteColumnName($column); |
||||||
1252 | } |
||||||
1253 | $columns[$i] = "$column AS " . $this->db->quoteColumnName($i); |
||||||
1254 | 16 | } elseif (strpos($column, '(') === false) { |
|||||
1255 | 4 | if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) { |
|||||
1256 | $columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]); |
||||||
1257 | } else { |
||||||
1258 | 4 | $columns[$i] = $this->db->quoteColumnName($column); |
|||||
1259 | } |
||||||
1260 | } |
||||||
1261 | } |
||||||
1262 | |||||||
1263 | 16 | return $select . ' ' . implode(', ', $columns); |
|||||
1264 | } |
||||||
1265 | |||||||
1266 | /** |
||||||
1267 | * @param array $tables |
||||||
1268 | * @param array $params the binding parameters to be populated |
||||||
1269 | * @return string the FROM clause built from [[Query::$from]]. |
||||||
1270 | */ |
||||||
1271 | 27 | public function buildFrom($tables, &$params) |
|||||
1272 | { |
||||||
1273 | 27 | if (empty($tables)) { |
|||||
1274 | return ''; |
||||||
1275 | } |
||||||
1276 | |||||||
1277 | 27 | $tables = $this->quoteTableNames($tables, $params); |
|||||
1278 | |||||||
1279 | 27 | return 'FROM ' . implode(', ', $tables); |
|||||
1280 | } |
||||||
1281 | |||||||
1282 | /** |
||||||
1283 | * @param array $joins |
||||||
1284 | * @param array $params the binding parameters to be populated |
||||||
1285 | * @return string the JOIN clause built from [[Query::$join]]. |
||||||
1286 | * @throws Exception if the $joins parameter is not in proper format |
||||||
1287 | */ |
||||||
1288 | 27 | public function buildJoin($joins, &$params) |
|||||
1289 | { |
||||||
1290 | 27 | if (empty($joins)) { |
|||||
1291 | 27 | return ''; |
|||||
1292 | } |
||||||
1293 | |||||||
1294 | foreach ($joins as $i => $join) { |
||||||
1295 | if (!is_array($join) || !isset($join[0], $join[1])) { |
||||||
1296 | throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.'); |
||||||
1297 | } |
||||||
1298 | // 0:join type, 1:join table, 2:on-condition (optional) |
||||||
1299 | list($joinType, $table) = $join; |
||||||
1300 | $tables = $this->quoteTableNames((array)$table, $params); |
||||||
1301 | $table = reset($tables); |
||||||
1302 | $joins[$i] = "$joinType $table"; |
||||||
1303 | if (isset($join[2])) { |
||||||
1304 | $condition = $this->buildCondition($join[2], $params); |
||||||
1305 | if ($condition !== '') { |
||||||
1306 | $joins[$i] .= ' ON ' . $condition; |
||||||
1307 | } |
||||||
1308 | } |
||||||
1309 | } |
||||||
1310 | |||||||
1311 | return implode($this->separator, $joins); |
||||||
1312 | } |
||||||
1313 | |||||||
1314 | /** |
||||||
1315 | * Quotes table names passed. |
||||||
1316 | * |
||||||
1317 | * @param array $tables |
||||||
1318 | * @param array $params |
||||||
1319 | * @return array |
||||||
1320 | */ |
||||||
1321 | 27 | private function quoteTableNames($tables, &$params) |
|||||
1322 | { |
||||||
1323 | 27 | foreach ($tables as $i => $table) { |
|||||
1324 | 27 | if ($table instanceof Query) { |
|||||
1325 | list($sql, $params) = $this->build($table, $params); |
||||||
1326 | $tables[$i] = "($sql) " . $this->db->quoteTableName($i); |
||||||
1327 | 27 | } elseif (is_string($i)) { |
|||||
1328 | 11 | if (strpos($table, '(') === false) { |
|||||
1329 | $table = $this->db->quoteTableName($table); |
||||||
1330 | } |
||||||
1331 | 11 | $tables[$i] = "$table " . $this->db->quoteTableName($i); |
|||||
1332 | 16 | } elseif (strpos($table, '(') === false) { |
|||||
1333 | 16 | if ($tableWithAlias = $this->extractAlias($table)) { // with alias |
|||||
1334 | $tables[$i] = $this->db->quoteTableName($tableWithAlias[1]) . ' ' . $this->db->quoteTableName($tableWithAlias[2]); |
||||||
1335 | } else { |
||||||
1336 | 16 | $tables[$i] = $this->db->quoteTableName($table); |
|||||
1337 | } |
||||||
1338 | } |
||||||
1339 | } |
||||||
1340 | |||||||
1341 | 27 | return $tables; |
|||||
1342 | } |
||||||
1343 | |||||||
1344 | /** |
||||||
1345 | * @param string|array $condition |
||||||
1346 | * @param array $params the binding parameters to be populated |
||||||
1347 | * @return string the WHERE clause built from [[Query::$where]]. |
||||||
1348 | */ |
||||||
1349 | 33 | public function buildWhere($condition, &$params) |
|||||
1350 | { |
||||||
1351 | 33 | $where = $this->buildCondition($condition, $params); |
|||||
1352 | |||||||
1353 | 33 | return $where === '' ? '' : 'WHERE ' . $where; |
|||||
1354 | } |
||||||
1355 | |||||||
1356 | /** |
||||||
1357 | * @param array $columns |
||||||
1358 | * @return string the GROUP BY clause |
||||||
1359 | */ |
||||||
1360 | 27 | public function buildGroupBy($columns) |
|||||
1361 | { |
||||||
1362 | 27 | if (empty($columns)) { |
|||||
1363 | 27 | return ''; |
|||||
1364 | } |
||||||
1365 | foreach ($columns as $i => $column) { |
||||||
1366 | if ($column instanceof ExpressionInterface) { |
||||||
1367 | $columns[$i] = $this->buildExpression($column); |
||||||
1368 | } elseif (strpos($column, '(') === false) { |
||||||
1369 | $columns[$i] = $this->db->quoteColumnName($column); |
||||||
1370 | } |
||||||
1371 | } |
||||||
1372 | |||||||
1373 | return 'GROUP BY ' . implode(', ', $columns); |
||||||
1374 | } |
||||||
1375 | |||||||
1376 | /** |
||||||
1377 | * @param string|array $condition |
||||||
1378 | * @param array $params the binding parameters to be populated |
||||||
1379 | * @return string the HAVING clause built from [[Query::$having]]. |
||||||
1380 | */ |
||||||
1381 | 27 | public function buildHaving($condition, &$params) |
|||||
1382 | { |
||||||
1383 | 27 | $having = $this->buildCondition($condition, $params); |
|||||
1384 | |||||||
1385 | 27 | return $having === '' ? '' : 'HAVING ' . $having; |
|||||
1386 | } |
||||||
1387 | |||||||
1388 | /** |
||||||
1389 | * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL. |
||||||
1390 | * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET) |
||||||
1391 | * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter. |
||||||
1392 | * @param int $limit the limit number. See [[Query::limit]] for more details. |
||||||
1393 | * @param int $offset the offset number. See [[Query::offset]] for more details. |
||||||
1394 | * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any) |
||||||
1395 | */ |
||||||
1396 | 27 | public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset) |
|||||
1397 | { |
||||||
1398 | 27 | $orderBy = $this->buildOrderBy($orderBy); |
|||||
1399 | 27 | if ($orderBy !== '') { |
|||||
1400 | 9 | $sql .= $this->separator . $orderBy; |
|||||
1401 | } |
||||||
1402 | 27 | $limit = $this->buildLimit($limit, $offset); |
|||||
1403 | 27 | if ($limit !== '') { |
|||||
1404 | 13 | $sql .= $this->separator . $limit; |
|||||
1405 | } |
||||||
1406 | |||||||
1407 | 27 | return $sql; |
|||||
1408 | } |
||||||
1409 | |||||||
1410 | /** |
||||||
1411 | * @param array $columns |
||||||
1412 | * @return string the ORDER BY clause built from [[Query::$orderBy]]. |
||||||
1413 | */ |
||||||
1414 | 27 | public function buildOrderBy($columns) |
|||||
1415 | { |
||||||
1416 | 27 | if (empty($columns)) { |
|||||
1417 | 26 | return ''; |
|||||
1418 | } |
||||||
1419 | 9 | $orders = []; |
|||||
1420 | 9 | foreach ($columns as $name => $direction) { |
|||||
1421 | 9 | if ($direction instanceof ExpressionInterface) { |
|||||
1422 | 8 | $orders[] = $this->buildExpression($direction); |
|||||
1423 | } else { |
||||||
1424 | 9 | $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : ''); |
|||||
1425 | } |
||||||
1426 | } |
||||||
1427 | |||||||
1428 | 9 | return 'ORDER BY ' . implode(', ', $orders); |
|||||
1429 | } |
||||||
1430 | |||||||
1431 | /** |
||||||
1432 | * @param int $limit |
||||||
1433 | * @param int $offset |
||||||
1434 | * @return string the LIMIT and OFFSET clauses |
||||||
1435 | */ |
||||||
1436 | public function buildLimit($limit, $offset) |
||||||
1437 | { |
||||||
1438 | $sql = ''; |
||||||
1439 | if ($this->hasLimit($limit)) { |
||||||
1440 | $sql = 'LIMIT ' . $limit; |
||||||
1441 | } |
||||||
1442 | if ($this->hasOffset($offset)) { |
||||||
1443 | $sql .= ' OFFSET ' . $offset; |
||||||
1444 | } |
||||||
1445 | |||||||
1446 | return ltrim($sql); |
||||||
1447 | } |
||||||
1448 | |||||||
1449 | /** |
||||||
1450 | * Checks to see if the given limit is effective. |
||||||
1451 | * @param mixed $limit the given limit |
||||||
1452 | * @return bool whether the limit is effective |
||||||
1453 | */ |
||||||
1454 | 27 | protected function hasLimit($limit) |
|||||
1455 | { |
||||||
1456 | 27 | return ($limit instanceof ExpressionInterface) || ctype_digit((string)$limit); |
|||||
1457 | } |
||||||
1458 | |||||||
1459 | /** |
||||||
1460 | * Checks to see if the given offset is effective. |
||||||
1461 | * @param mixed $offset the given offset |
||||||
1462 | * @return bool whether the offset is effective |
||||||
1463 | */ |
||||||
1464 | 27 | protected function hasOffset($offset) |
|||||
1465 | { |
||||||
1466 | 27 | return ($offset instanceof ExpressionInterface) || ctype_digit((string)$offset) && (string)$offset !== '0'; |
|||||
1467 | } |
||||||
1468 | |||||||
1469 | /** |
||||||
1470 | * @param array $unions |
||||||
1471 | * @param array $params the binding parameters to be populated |
||||||
1472 | * @return string the UNION clause built from [[Query::$union]]. |
||||||
1473 | */ |
||||||
1474 | public function buildUnion($unions, &$params) |
||||||
1475 | { |
||||||
1476 | if (empty($unions)) { |
||||||
1477 | return ''; |
||||||
1478 | } |
||||||
1479 | |||||||
1480 | $result = ''; |
||||||
1481 | |||||||
1482 | foreach ($unions as $i => $union) { |
||||||
1483 | $query = $union['query']; |
||||||
1484 | if ($query instanceof Query) { |
||||||
1485 | list($unions[$i]['query'], $params) = $this->build($query, $params); |
||||||
1486 | } |
||||||
1487 | |||||||
1488 | $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) '; |
||||||
1489 | } |
||||||
1490 | |||||||
1491 | return trim($result); |
||||||
1492 | } |
||||||
1493 | |||||||
1494 | /** |
||||||
1495 | * @param array $withs of configurations for each WITH query |
||||||
1496 | * @param array $params the binding parameters to be populated |
||||||
1497 | * @return string compiled WITH prefix of query including nested queries |
||||||
1498 | * @see Query::withQuery() |
||||||
1499 | * @since 2.0.35 |
||||||
1500 | */ |
||||||
1501 | 27 | public function buildWithQueries($withs, &$params) |
|||||
1502 | { |
||||||
1503 | 27 | if (empty($withs)) { |
|||||
1504 | 27 | return ''; |
|||||
1505 | } |
||||||
1506 | |||||||
1507 | $recursive = false; |
||||||
1508 | $result = []; |
||||||
1509 | |||||||
1510 | foreach ($withs as $i => $with) { |
||||||
1511 | if ($with['recursive']) { |
||||||
1512 | $recursive = true; |
||||||
1513 | } |
||||||
1514 | |||||||
1515 | $query = $with['query']; |
||||||
1516 | if ($query instanceof Query) { |
||||||
1517 | list($with['query'], $params) = $this->build($query, $params); |
||||||
1518 | } |
||||||
1519 | |||||||
1520 | $result[] = $with['alias'] . ' AS (' . $with['query'] . ')'; |
||||||
1521 | } |
||||||
1522 | |||||||
1523 | return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result); |
||||||
1524 | } |
||||||
1525 | |||||||
1526 | /** |
||||||
1527 | * Processes columns and properly quotes them if necessary. |
||||||
1528 | * It will join all columns into a string with comma as separators. |
||||||
1529 | * @param string|array $columns the columns to be processed |
||||||
1530 | * @return string the processing result |
||||||
1531 | */ |
||||||
1532 | public function buildColumns($columns) |
||||||
1533 | { |
||||||
1534 | if (!is_array($columns)) { |
||||||
1535 | if (strpos($columns, '(') !== false) { |
||||||
1536 | return $columns; |
||||||
1537 | } |
||||||
1538 | |||||||
1539 | $rawColumns = $columns; |
||||||
1540 | $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY); |
||||||
1541 | if ($columns === false) { |
||||||
1542 | throw new InvalidArgumentException("$rawColumns is not valid columns."); |
||||||
1543 | } |
||||||
1544 | } |
||||||
1545 | foreach ($columns as $i => $column) { |
||||||
1546 | if ($column instanceof ExpressionInterface) { |
||||||
1547 | $columns[$i] = $this->buildExpression($column); |
||||||
1548 | } elseif (strpos($column, '(') === false) { |
||||||
1549 | $columns[$i] = $this->db->quoteColumnName($column); |
||||||
1550 | } |
||||||
1551 | } |
||||||
1552 | |||||||
1553 | return implode(', ', $columns); |
||||||
0 ignored issues
–
show
It seems like
$columns can also be of type string ; however, parameter $pieces of implode() does only seem to accept array , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
1554 | } |
||||||
1555 | |||||||
1556 | /** |
||||||
1557 | * Parses the condition specification and generates the corresponding SQL expression. |
||||||
1558 | * @param string|array|ExpressionInterface $condition the condition specification. Please refer to [[Query::where()]] |
||||||
1559 | * on how to specify a condition. |
||||||
1560 | * @param array $params the binding parameters to be populated |
||||||
1561 | * @return string the generated SQL expression |
||||||
1562 | */ |
||||||
1563 | 33 | public function buildCondition($condition, &$params) |
|||||
1564 | { |
||||||
1565 | 33 | if (is_array($condition)) { |
|||||
1566 | 19 | if (empty($condition)) { |
|||||
1567 | return ''; |
||||||
1568 | } |
||||||
1569 | |||||||
1570 | 19 | $condition = $this->createConditionFromArray($condition); |
|||||
1571 | } |
||||||
1572 | |||||||
1573 | 33 | if ($condition instanceof ExpressionInterface) { |
|||||
1574 | 19 | return $this->buildExpression($condition, $params); |
|||||
1575 | } |
||||||
1576 | |||||||
1577 | 27 | return (string)$condition; |
|||||
1578 | } |
||||||
1579 | |||||||
1580 | /** |
||||||
1581 | * Transforms $condition defined in array format (as described in [[Query::where()]] |
||||||
1582 | * to instance of [[yii\db\condition\ConditionInterface|ConditionInterface]] according to |
||||||
1583 | * [[conditionClasses]] map. |
||||||
1584 | * |
||||||
1585 | * @param string|array $condition |
||||||
1586 | * @return ConditionInterface |
||||||
1587 | * @see conditionClasses |
||||||
1588 | * @since 2.0.14 |
||||||
1589 | */ |
||||||
1590 | 19 | public function createConditionFromArray($condition) |
|||||
1591 | { |
||||||
1592 | 19 | if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ... |
|||||
1593 | 7 | $operator = strtoupper(array_shift($condition)); |
|||||
0 ignored issues
–
show
It seems like
$condition can also be of type string ; however, parameter $array of array_shift() does only seem to accept array , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
1594 | 7 | if (isset($this->conditionClasses[$operator])) { |
|||||
0 ignored issues
–
show
|
|||||||
1595 | 7 | $className = $this->conditionClasses[$operator]; |
|||||
1596 | } else { |
||||||
1597 | $className = 'yii\db\conditions\SimpleCondition'; |
||||||
1598 | } |
||||||
1599 | /** @var ConditionInterface $className */ |
||||||
1600 | 7 | return $className::fromArrayDefinition($operator, $condition); |
|||||
1601 | } |
||||||
1602 | |||||||
1603 | // hash format: 'column1' => 'value1', 'column2' => 'value2', ... |
||||||
1604 | 18 | return new HashCondition($condition); |
|||||
1605 | } |
||||||
1606 | |||||||
1607 | /** |
||||||
1608 | * Creates a SELECT EXISTS() SQL statement. |
||||||
1609 | * @param string $rawSql the subquery in a raw form to select from. |
||||||
1610 | * @return string the SELECT EXISTS() SQL statement. |
||||||
1611 | * @since 2.0.8 |
||||||
1612 | */ |
||||||
1613 | 7 | public function selectExists($rawSql) |
|||||
1614 | { |
||||||
1615 | 7 | return 'SELECT EXISTS(' . $rawSql . ')'; |
|||||
1616 | } |
||||||
1617 | |||||||
1618 | /** |
||||||
1619 | * Helper method to add $value to $params array using [[PARAM_PREFIX]]. |
||||||
1620 | * |
||||||
1621 | * @param string|null $value |
||||||
1622 | * @param array $params passed by reference |
||||||
1623 | * @return string the placeholder name in $params array |
||||||
1624 | * |
||||||
1625 | * @since 2.0.14 |
||||||
1626 | */ |
||||||
1627 | 31 | public function bindParam($value, &$params) |
|||||
1628 | { |
||||||
1629 | 31 | $phName = self::PARAM_PREFIX . count($params); |
|||||
1630 | 31 | $params[$phName] = $value; |
|||||
1631 | |||||||
1632 | 31 | return $phName; |
|||||
1633 | } |
||||||
1634 | |||||||
1635 | /** |
||||||
1636 | * Extracts table alias if there is one or returns false |
||||||
1637 | * @param $table |
||||||
1638 | * @return bool|array |
||||||
1639 | * @since 2.0.24 |
||||||
1640 | */ |
||||||
1641 | 16 | protected function extractAlias($table) |
|||||
1642 | { |
||||||
1643 | 16 | if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) { |
|||||
1644 | return $matches; |
||||||
1645 | } |
||||||
1646 | |||||||
1647 | 16 | return false; |
|||||
1648 | } |
||||||
1649 | } |
||||||
1650 |