Passed
Push — master ( 4281e6...ce1733 )
by Alexander
03:46
created

QueryBuilder::insert()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 4
nop 3
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Query;
6
7
use Generator;
8
use JsonException;
9
use Yiisoft\Db\Connection\ConnectionInterface;
10
use Yiisoft\Db\Exception\Exception;
11
use Yiisoft\Db\Exception\InvalidConfigException;
12
use Yiisoft\Db\Query\Conditions\ConditionInterface;
13
use Yiisoft\Db\Constraint\Constraint;
14
use Yiisoft\Db\Constraint\ConstraintFinderInterface;
15
use Yiisoft\Db\Exception\InvalidArgumentException;
16
use Yiisoft\Db\Exception\NotSupportedException;
17
use Yiisoft\Db\Expression\Expression;
18
use Yiisoft\Db\Expression\ExpressionBuilder;
19
use Yiisoft\Db\Expression\ExpressionBuilderInterface;
20
use Yiisoft\Db\Expression\ExpressionInterface;
21
use Yiisoft\Db\Query\Conditions\HashCondition;
22
use Yiisoft\Db\Query\Conditions\SimpleCondition;
23
use Yiisoft\Db\Schema\ColumnSchemaBuilder;
24
use Yiisoft\Db\Schema\Schema;
25
use Yiisoft\Db\Pdo\PdoValue;
26
use Yiisoft\Db\Pdo\PdoValueBuilder;
27
use Yiisoft\Strings\NumericHelper;
28
29
use function array_combine;
30
use function array_diff;
31
use function array_filter;
32
use function array_keys;
33
use function array_map;
34
use function array_merge;
35
use function array_reverse;
36
use function array_shift;
37
use function array_unique;
38
use function array_values;
39
use function array_walk;
40
use function count;
41
use function ctype_digit;
42
use function get_class;
43
use function implode;
44
use function in_array;
45
use function is_array;
46
use function is_int;
47
use function is_object;
48
use function is_string;
49
use function is_subclass_of;
50
use function json_encode;
51
use function ltrim;
52
use function preg_match;
53
use function preg_replace;
54
use function preg_split;
55
use function reset;
56
use function strpos;
57
use function strtoupper;
58
use function strtr;
59
use function trim;
60
61
/**
62
 * QueryBuilder builds a SELECT SQL statement based on the specification given as a {@see Query} object.
63
 *
64
 * SQL statements are created from {@see Query} objects using the {@see build()}-method.
65
 *
66
 * QueryBuilder is also used by {@see Command} to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE.
67
 *
68
 * For more details and usage information on QueryBuilder:
69
 * {@see [guide article on query builders](guide:db-query-builder)}.
70
 *
71
 * @property string[] $conditionClasses Map of condition aliases to condition classes. This property is write-only.
72
 *
73
 * For example:
74
 * ```php
75
 *     ['LIKE' => \Yiisoft\Db\Condition\LikeCondition::class]
76
 * ```
77
 *
78
 * @property string[] $expressionBuilders Array of builders that should be merged with the pre-defined ones in
79
 * {@see expressionBuilders} property. This property is write-only.
80
 */
81
class QueryBuilder
82
{
83
    /**
84
     * The prefix for automatically generated query binding parameters.
85
     */
86
    public const PARAM_PREFIX = ':qp';
87
    protected ?ConnectionInterface $db = null;
88
    protected string $separator = ' ';
89
90
    /**
91
     * @var array the abstract column types mapped to physical column types.
92
     * This is mainly used to support creating/modifying tables using DB-independent data type specifications.
93
     * Child classes should override this property to declare supported type mappings.
94
     */
95
    protected array $typeMap = [];
96
97
    /**
98
     * @var array map of condition aliases to condition classes. For example:
99
     *
100
     * ```php
101
     * return [
102
     *     'LIKE' => \Yiisoft\Db\Condition\LikeCondition::class,
103
     * ];
104
     * ```
105
     *
106
     * This property is used by {@see createConditionFromArray} method.
107
     * See default condition classes list in {@see defaultConditionClasses()} method.
108
     *
109
     * In case you want to add custom conditions support, use the {@see setConditionClasses()} method.
110
     *
111
     * @see setConditonClasses()
112
     * @see defaultConditionClasses()
113
     */
114
    protected array $conditionClasses = [];
115
116
    /**
117
     * @var string[]|ExpressionBuilderInterface[] maps expression class to expression builder class.
118
     * For example:
119
     *
120
     * ```php
121
     * [
122
     *    Expression::class => ExpressionBuilder::class
123
     * ]
124
     * ```
125
     * This property is mainly used by {@see buildExpression()} to build SQL expressions form expression objects.
126
     * See default values in {@see defaultExpressionBuilders()} method.
127
     *
128
     * {@see setExpressionBuilders()}
129
     * {@see defaultExpressionBuilders()}
130
     */
131
    protected array $expressionBuilders = [];
132
133 1495
    public function __construct(ConnectionInterface $db)
134
    {
135 1495
        $this->db = $db;
136 1495
        $this->expressionBuilders = $this->defaultExpressionBuilders();
137 1495
        $this->conditionClasses = $this->defaultConditionClasses();
138 1495
    }
139
140
    /**
141
     * Contains array of default condition classes. Extend this method, if you want to change default condition classes
142
     * for the query builder.
143
     *
144
     * @return array
145
     *
146
     * See {@see conditionClasses} docs for details.
147
     */
148 1495
    protected function defaultConditionClasses(): array
149
    {
150
        return [
151 1495
            'NOT'         => Conditions\NotCondition::class,
152
            'AND'         => Conditions\AndCondition::class,
153
            'OR'          => Conditions\OrCondition::class,
154
            'BETWEEN'     => Conditions\BetweenCondition::class,
155
            'NOT BETWEEN' => Conditions\BetweenCondition::class,
156
            'IN'          => Conditions\InCondition::class,
157
            'NOT IN'      => Conditions\InCondition::class,
158
            'LIKE'        => Conditions\LikeCondition::class,
159
            'NOT LIKE'    => Conditions\LikeCondition::class,
160
            'OR LIKE'     => Conditions\LikeCondition::class,
161
            'OR NOT LIKE' => Conditions\LikeCondition::class,
162
            'EXISTS'      => Conditions\ExistsCondition::class,
163
            'NOT EXISTS'  => Conditions\ExistsCondition::class,
164
        ];
165
    }
166
167
    /**
168
     * Contains array of default expression builders. Extend this method and override it, if you want to change default
169
     * expression builders for this query builder.
170
     *
171
     * @return array
172
     *
173
     * See {@see expressionBuilders} docs for details.
174
     */
175 1495
    protected function defaultExpressionBuilders(): array
176
    {
177
        return [
178 1495
            Query::class                              => QueryExpressionBuilder::class,
179
            PdoValue::class                           => PdoValueBuilder::class,
180
            Expression::class                         => ExpressionBuilder::class,
181
            Conditions\ConjunctionCondition::class    => Conditions\ConjunctionConditionBuilder::class,
182
            Conditions\NotCondition::class            => Conditions\NotConditionBuilder::class,
183
            Conditions\AndCondition::class            => Conditions\ConjunctionConditionBuilder::class,
184
            Conditions\OrCondition::class             => Conditions\ConjunctionConditionBuilder::class,
185
            Conditions\BetweenCondition::class        => Conditions\BetweenConditionBuilder::class,
186
            Conditions\InCondition::class             => Conditions\InConditionBuilder::class,
187
            Conditions\LikeCondition::class           => Conditions\LikeConditionBuilder::class,
188
            Conditions\ExistsCondition::class         => Conditions\ExistsConditionBuilder::class,
189
            Conditions\SimpleCondition::class         => Conditions\SimpleConditionBuilder::class,
190
            Conditions\HashCondition::class           => Conditions\HashConditionBuilder::class,
191
            Conditions\BetweenColumnsCondition::class => Conditions\BetweenColumnsConditionBuilder::class,
192
        ];
193
    }
194
195
    /**
196
     * Setter for {@see expressionBuilders property.
197
     *
198
     * @param string[] $builders array of builders that should be merged with the pre-defined ones in property.
199
     *
200
     * See {@see expressionBuilders} docs for details.
201
     */
202
    public function setExpressionBuilders(array $builders): void
203
    {
204
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
205
    }
206
207
    /**
208
     * Setter for {@see conditionClasses} property.
209
     *
210
     * @param string[] $classes map of condition aliases to condition classes. For example:
211
     *
212
     * ```php
213
     * ['LIKE' => \Yiisoft\Db\Condition\LikeCondition::class]
214
     * ```
215
     *
216
     * See {@see conditionClasses} docs for details.
217
     */
218
    public function setConditionClasses(array $classes): void
219
    {
220
        $this->conditionClasses = array_merge($this->conditionClasses, $classes);
221
    }
222
223
    /**
224
     * Generates a SELECT SQL statement from a {@see Query} object.
225
     *
226
     * @param Query $query the {@see Query} object from which the SQL statement will be generated.
227
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
228
     * in the result with the additional parameters generated during the query building process.
229
     *
230
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
231
     *
232
     * @return array the generated SQL statement (the first array element) and the corresponding parameters to be bound
233
     * to the SQL statement (the second array element). The parameters returned include those provided in `$params`.
234
     */
235 888
    public function build(Query $query, array $params = []): array
236
    {
237 888
        $query = $query->prepare($this);
238
239 888
        $params = empty($params) ? $query->getParams() : array_merge($params, $query->getParams());
240
241
        $clauses = [
242 888
            $this->buildSelect($query->getSelect(), $params, $query->getDistinct(), $query->getSelectOption()),
243 888
            $this->buildFrom($query->getFrom(), $params),
244 888
            $this->buildJoin($query->getJoin(), $params),
245 888
            $this->buildWhere($query->getWhere(), $params),
246 888
            $this->buildGroupBy($query->getGroupBy(), $params),
247 888
            $this->buildHaving($query->getHaving(), $params),
248
        ];
249
250 888
        $sql = implode($this->separator, array_filter($clauses));
251
252 888
        $sql = $this->buildOrderByAndLimit($sql, $query->getOrderBy(), $query->getLimit(), $query->getOffset());
253
254 888
        if (!empty($query->getOrderBy())) {
255 123
            foreach ($query->getOrderBy() as $expression) {
256 123
                if ($expression instanceof ExpressionInterface) {
257 3
                    $this->buildExpression($expression, $params);
258
                }
259
            }
260
        }
261
262 888
        if (!empty($query->getGroupBy())) {
263 9
            foreach ($query->getGroupBy() as $expression) {
264 9
                if ($expression instanceof ExpressionInterface) {
265 3
                    $this->buildExpression($expression, $params);
266
                }
267
            }
268
        }
269
270 888
        $union = $this->buildUnion($query->getUnion(), $params);
271
272 888
        if ($union !== '') {
273 7
            $sql = "($sql){$this->separator}$union";
274
        }
275
276 888
        $with = $this->buildWithQueries($query->getWithQueries(), $params);
277
278 888
        if ($with !== '') {
279 6
            $sql = "$with{$this->separator}$sql";
280
        }
281
282 888
        return [$sql, $params];
283
    }
284
285
    /**
286
     * Builds given $expression.
287
     *
288
     * @param ExpressionInterface $expression the expression to be built
289
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
290
     * in the result with the additional parameters generated during the expression building process.
291
     *
292
     * @throws Exception|InvalidConfigException|NotSupportedException|InvalidArgumentException when $expression building
293
     * is not supported by this QueryBuilder.
294
     *
295
     * @return string the SQL statement that will not be neither quoted nor encoded before passing to DBMS.
296
     *
297
     * {@see ExpressionInterface}
298
     * {@see ExpressionBuilderInterface}
299
     * {@see expressionBuilders}
300
     */
301 1041
    public function buildExpression(ExpressionInterface $expression, array &$params = []): string
302
    {
303 1041
        $builder = $this->getExpressionBuilder($expression);
304
305 1041
        return (string) $builder->build($expression, $params);
306
    }
307
308
    /**
309
     * Gets object of {@see ExpressionBuilderInterface} that is suitable for $expression.
310
     *
311
     * Uses {@see expressionBuilders} array to find a suitable builder class.
312
     *
313
     * @param ExpressionInterface $expression
314
     *
315
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
316
     *
317
     * @return ExpressionBuilderInterface|QueryBuilder|string
318
     *
319
     * {@see expressionBuilders}
320
     */
321 1041
    public function getExpressionBuilder(ExpressionInterface $expression)
322
    {
323 1041
        $className = get_class($expression);
324
325 1041
        if (!isset($this->expressionBuilders[$className])) {
326
            foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
327
                if (is_subclass_of($expression, $expressionClass)) {
328
                    $this->expressionBuilders[$className] = $builderClass;
329
                    break;
330
                }
331
            }
332
333
            if (!isset($this->expressionBuilders[$className])) {
334
                throw new InvalidArgumentException(
335
                    'Expression of class ' . $className . ' can not be built in ' . get_class($this)
336
                );
337
            }
338
        }
339
340 1041
        if ($this->expressionBuilders[$className] === __CLASS__) {
341
            return $this;
342
        }
343
344 1041
        if (!is_object($this->expressionBuilders[$className])) {
0 ignored issues
show
introduced by
The condition is_object($this->expressionBuilders[$className]) is always false.
Loading history...
345 1041
            $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
346
        }
347
348 1041
        return $this->expressionBuilders[$className];
349
    }
350
351
    /**
352
     * Creates an INSERT SQL statement.
353
     *
354
     * For example,.
355
     *
356
     * ```php
357
     * $sql = $queryBuilder->insert('user', [
358
     *     'name' => 'Sam',
359
     *     'age' => 30,
360
     * ], $params);
361
     * ```
362
     *
363
     * The method will properly escape the table and column names.
364
     *
365
     * @param string $table the table that new rows will be inserted into.
366
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
367
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement. Passing of {@see Query}.
368
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the
369
     * DB command later.
370
     *
371
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
372
     *
373
     * @return string the INSERT SQL.
374
     */
375 156
    public function insert(string $table, $columns, array &$params = []): string
376
    {
377 156
        [$names, $placeholders, $values, $params] = $this->prepareInsertValues($table, $columns, $params);
378
379 147
        return 'INSERT INTO ' . $this->db->quoteTableName($table)
0 ignored issues
show
Bug introduced by
The method quoteTableName() does not exist on Yiisoft\Db\Connection\ConnectionInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\Db\Connection\ConnectionInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

379
        return 'INSERT INTO ' . $this->db->/** @scrutinizer ignore-call */ quoteTableName($table)
Loading history...
Bug introduced by
The method quoteTableName() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

379
        return 'INSERT INTO ' . $this->db->/** @scrutinizer ignore-call */ quoteTableName($table)

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
380 147
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
381 147
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
382
    }
383
384
    /**
385
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
386
     *
387
     * @param string $table the table that new rows will be inserted into.
388
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
389
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement.
390
     * @param array $params the binding parameters that will be generated by this method.
391
     * They should be bound to the DB command later.
392
     *
393
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
394
     *
395
     * @return array array of column names, placeholders, values and params.
396
     */
397 225
    protected function prepareInsertValues(string $table, $columns, array $params = []): array
398
    {
399 225
        $schema = $this->db->getSchema();
400 225
        $tableSchema = $schema->getTableSchema($table);
401 225
        $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
402 225
        $names = [];
403 225
        $placeholders = [];
404 225
        $values = ' DEFAULT VALUES';
405
406 225
        if ($columns instanceof Query) {
407 56
            [$names, $values, $params] = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
408
        } else {
409 177
            foreach ($columns as $name => $value) {
410 173
                $names[] = $schema->quoteColumnName($name);
411 173
                $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
412
413 173
                if ($value instanceof ExpressionInterface) {
414 36
                    $placeholders[] = $this->buildExpression($value, $params);
415 167
                } elseif ($value instanceof Query) {
416
                    [$sql, $params] = $this->build($value, $params);
417
                    $placeholders[] = "($sql)";
418
                } else {
419 167
                    $placeholders[] = $this->bindParam($value, $params);
420
                }
421
            }
422
        }
423
424 213
        return [$names, $placeholders, $values, $params];
425
    }
426
427
    /**
428
     * Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
429
     *
430
     * @param Query $columns Object, which represents select query.
431
     * @param Schema $schema Schema object to quote column name.
432
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
433
     * in the result with the additional parameters generated during the query building process.
434
     *
435
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
436
     *
437
     * @return array array of column names, values and params.
438
     */
439 56
    protected function prepareInsertSelectSubQuery(Query $columns, Schema $schema, array $params = []): array
440
    {
441
        if (
442 56
            !is_array($columns->getSelect())
0 ignored issues
show
introduced by
The condition is_array($columns->getSelect()) is always true.
Loading history...
443 56
            || empty($columns->getSelect())
444 56
            || in_array('*', $columns->getSelect(), true)
445
        ) {
446 12
            throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
447
        }
448
449 44
        [$values, $params] = $this->build($columns, $params);
450
451 44
        $names = [];
452 44
        $values = ' ' . $values;
453
454 44
        foreach ($columns->getSelect() as $title => $field) {
455 44
            if (is_string($title)) {
456 44
                $names[] = $schema->quoteColumnName($title);
457
            } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_.]+)$/', $field, $matches)) {
458
                $names[] = $schema->quoteColumnName($matches[2]);
459
            } else {
460
                $names[] = $schema->quoteColumnName($field);
461
            }
462
        }
463
464 44
        return [$names, $values, $params];
465
    }
466
467
    /**
468
     * Generates a batch INSERT SQL statement.
469
     *
470
     * For example,
471
     *
472
     * ```php
473
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
474
     *     ['Tom', 30],
475
     *     ['Jane', 20],
476
     *     ['Linda', 25],
477
     * ]);
478
     * ```
479
     *
480
     * Note that the values in each row must match the corresponding column names.
481
     *
482
     * The method will properly escape the column names, and quote the values to be inserted.
483
     *
484
     * @param string $table the table that new rows will be inserted into.
485
     * @param array $columns the column names.
486
     * @param array|Generator $rows the rows to be batch inserted into the table.
487
     * @param array $params the binding parameters. This parameter exists.
488
     *
489
     * @throws Exception|InvalidArgumentException
490
     *
491
     * @return string the batch INSERT SQL statement.
492
     */
493 40
    public function batchInsert(string $table, array $columns, $rows, array &$params = []): string
494
    {
495 40
        if (empty($rows)) {
496 4
            return '';
497
        }
498
499 38
        $schema = $this->db->getSchema();
500
501
502 38
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
503 38
            $columnSchemas = $tableSchema->getColumns();
504
        } else {
505
            $columnSchemas = [];
506
        }
507
508 38
        $values = [];
509
510 38
        foreach ($rows as $row) {
511 35
            $vs = [];
512 35
            foreach ($row as $i => $value) {
513 35
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
514 26
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
515
                }
516 35
                if (is_string($value)) {
517 23
                    $value = $schema->quoteValue($value);
518 21
                } elseif (is_float($value)) {
519
                    /* ensure type cast always has . as decimal separator in all locales */
520 2
                    $value = NumericHelper::normalize((string) $value);
521 21
                } elseif ($value === false) {
522 7
                    $value = 0;
523 21
                } elseif ($value === null) {
524 12
                    $value = 'NULL';
525 13
                } elseif ($value instanceof ExpressionInterface) {
526 9
                    $value = $this->buildExpression($value, $params);
527
                }
528 35
                $vs[] = $value;
529
            }
530 35
            $values[] = '(' . implode(', ', $vs) . ')';
531
        }
532
533 38
        if (empty($values)) {
534 3
            return '';
535
        }
536
537 35
        foreach ($columns as $i => $name) {
538 32
            $columns[$i] = $schema->quoteColumnName($name);
539
        }
540
541 35
        return 'INSERT INTO ' . $schema->quoteTableName($table)
542 35
            . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
543
    }
544
545
    /**
546
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
547
     * constraints), or update them if they do.
548
     *
549
     * For example,
550
     *
551
     * ```php
552
     * $sql = $queryBuilder->upsert('pages', [
553
     *     'name' => 'Front page',
554
     *     'url' => 'http://example.com/', // url is unique
555
     *     'visits' => 0,
556
     * ], [
557
     *     'visits' => new \Yiisoft\Db\Expression('visits + 1'),
558
     * ], $params);
559
     * ```
560
     *
561
     * The method will properly escape the table and column names.
562
     *
563
     * @param string $table the table that new rows will be inserted into/updated in.
564
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance
565
     * of {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
566
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
567
     * If `true` is passed, the column data will be updated to match the insert column data.
568
     * If `false` is passed, no update will be performed if the column data already exists.
569
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the DB
570
     * command later.
571
     *
572
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
573
     *
574
     * @return string the resulting SQL.
575
     */
576
    public function upsert(string $table, $insertColumns, $updateColumns, array &$params): string
577
    {
578
        throw new NotSupportedException($this->db->getDriverName() . ' does not support upsert statements.');
579
    }
580
581
    /**
582
     * @param string $table
583
     * @param array|Query $insertColumns
584
     * @param array|bool $updateColumns
585
     * @param Constraint[] $constraints this parameter recieves a matched constraint list.
586
     * The constraints will be unique by their column names.
587
     *
588
     * @throws Exception|JsonException
589
     *
590
     * @return array
591
     */
592 72
    protected function prepareUpsertColumns(string $table, $insertColumns, $updateColumns, array &$constraints = []): array
593
    {
594 72
        if ($insertColumns instanceof Query) {
595 32
            [$insertNames] = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
596
        } else {
597
            /** @psalm-suppress UndefinedMethod */
598 40
            $insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
599
        }
600
601 72
        $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
602
603
        /** @psalm-suppress UndefinedMethod */
604 72
        $uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
605
606 72
        if ($updateColumns !== true) {
607 52
            return [$uniqueNames, $insertNames, null];
608
        }
609
610 20
        return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)];
611
    }
612
613
    /**
614
     * Returns all column names belonging to constraints enforcing uniqueness (`PRIMARY KEY`, `UNIQUE INDEX`, etc.)
615
     * for the named table removing constraints which did not cover the specified column list.
616
     *
617
     * The column list will be unique by column names.
618
     *
619
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
620
     * @param string[] $columns source column list.
621
     * @param Constraint[] $constraints this parameter optionally recieves a matched constraint list. The constraints
622
     * will be unique by their column names.
623
     *
624
     * @throws JsonException
625
     *
626
     * @return array column list.
627
     */
628 72
    private function getTableUniqueColumnNames(string $name, array $columns, array &$constraints = []): array
629
    {
630 72
        $schema = $this->db->getSchema();
631
632 72
        if (!$schema instanceof ConstraintFinderInterface) {
633
            return [];
634
        }
635
636 72
        $constraints = [];
637 72
        $primaryKey = $schema->getTablePrimaryKey($name);
638
639 72
        if ($primaryKey !== null) {
640 71
            $constraints[] = $primaryKey;
641
        }
642
643 72
        foreach ($schema->getTableIndexes($name) as $constraint) {
644 71
            if ($constraint->isUnique()) {
645 71
                $constraints[] = $constraint;
646
            }
647
        }
648
649 72
        $constraints = array_merge($constraints, $schema->getTableUniques($name));
650
651
        /** Remove duplicates */
652 72
        $constraints = array_combine(
653 72
            array_map(
654 72
                static function ($constraint) {
655 72
                    $columns = $constraint->getColumnNames();
656 72
                    sort($columns, SORT_STRING);
657
658 72
                    return json_encode($columns, JSON_THROW_ON_ERROR);
659
                },
660 72
                $constraints
661
            ),
662 72
            $constraints
663
        );
664
665 72
        $columnNames = [];
666
667
        /** Remove all constraints which do not cover the specified column list */
668 72
        $constraints = array_values(
669 72
            array_filter(
670 72
                $constraints,
0 ignored issues
show
Bug introduced by
It seems like $constraints can also be of type false; however, parameter $input of array_filter() 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 ignore-type  annotation

670
                /** @scrutinizer ignore-type */ $constraints,
Loading history...
671 72
                static function ($constraint) use ($schema, $columns, &$columnNames) {
672
                    /** @psalm-suppress UndefinedClass, UndefinedMethod */
673 72
                    $constraintColumnNames = array_map([$schema, 'quoteColumnName'], $constraint->getColumnNames());
674 72
                    $result = !array_diff($constraintColumnNames, $columns);
675
676 72
                    if ($result) {
677 60
                        $columnNames = array_merge($columnNames, $constraintColumnNames);
678
                    }
679
680 72
                    return $result;
681 72
                }
682
            )
683
        );
684
685 72
        return array_unique($columnNames);
686
    }
687
688
    /**
689
     * Creates an UPDATE SQL statement.
690
     *
691
     * For example,
692
     *
693
     * ```php
694
     * $params = [];
695
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
696
     * ```
697
     *
698
     * The method will properly escape the table and column names.
699
     *
700
     * @param string $table the table to be updated.
701
     * @param array $columns the column data (name => value) to be updated.
702
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
703
     * {@see Query::where()} on how to specify condition.
704
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
705
     * DB command later.
706
     *
707
     * @throws Exception|InvalidArgumentException
708
     *
709
     * @return string the UPDATE SQL.
710
     */
711 79
    public function update(string $table, array $columns, $condition, array &$params = []): string
712
    {
713 79
        [$lines, $params] = $this->prepareUpdateSets($table, $columns, $params);
714 79
        $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
715 79
        $where = $this->buildWhere($condition, $params);
716
717 79
        return ($where === '') ? $sql : ($sql . ' ' . $where);
718
    }
719
720
    /**
721
     * Prepares a `SET` parts for an `UPDATE` SQL statement.
722
     *
723
     * @param string $table the table to be updated.
724
     * @param array $columns the column data (name => value) to be updated.
725
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
726
     * DB command later.
727
     *
728
     * @throws Exception|InvalidArgumentException
729
     *
730
     * @return array an array `SET` parts for an `UPDATE` SQL statement (the first array element) and params (the second
731
     * array element).
732
     */
733 114
    protected function prepareUpdateSets(string $table, array $columns, array $params = []): array
734
    {
735 114
        $tableSchema = $this->db->getTableSchema($table);
736
737 114
        $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
738
739 114
        $sets = [];
740
741 114
        foreach ($columns as $name => $value) {
742 114
            $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
743 114
            if ($value instanceof ExpressionInterface) {
744 58
                $placeholder = $this->buildExpression($value, $params);
745
            } else {
746 77
                $placeholder = $this->bindParam($value, $params);
747
            }
748
749 114
            $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
0 ignored issues
show
Bug introduced by
The method quoteColumnName() does not exist on Yiisoft\Db\Connection\ConnectionInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\Db\Connection\ConnectionInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

749
            $sets[] = $this->db->/** @scrutinizer ignore-call */ quoteColumnName($name) . '=' . $placeholder;
Loading history...
750
        }
751
752 114
        return [$sets, $params];
753
    }
754
755
    /**
756
     * Creates a DELETE SQL statement.
757
     *
758
     * For example,
759
     *
760
     * ```php
761
     * $sql = $queryBuilder->delete('user', 'status = 0');
762
     * ```
763
     *
764
     * The method will properly escape the table and column names.
765
     *
766
     * @param string $table the table where the data will be deleted from.
767
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
768
     * {@see Query::where()} on how to specify condition.
769
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
770
     * DB command later.
771
     *
772
     * @throws Exception|InvalidArgumentException
773
     *
774
     * @return string the DELETE SQL.
775
     */
776 33
    public function delete(string $table, $condition, array &$params): string
777
    {
778 33
        $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
779 33
        $where = $this->buildWhere($condition, $params);
780
781 33
        return ($where === '') ? $sql : ($sql . ' ' . $where);
782
    }
783
784
    /**
785
     * Builds a SQL statement for creating a new DB table.
786
     *
787
     * The columns in the new  table should be specified as name-definition pairs (e.g. 'name' => 'string'), where name
788
     * stands for a column name which will be properly quoted by the method, and definition stands for the column type
789
     * which can contain an abstract DB type.
790
     *
791
     * The {@see getColumnType()} method will be invoked to convert any abstract type into a physical one.
792
     *
793
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly inserted
794
     * into the generated SQL.
795
     *
796
     * For example,
797
     *
798
     * ```php
799
     * $sql = $queryBuilder->createTable('user', [
800
     *  'id' => 'pk',
801
     *  'name' => 'string',
802
     *  'age' => 'integer',
803
     * ]);
804
     * ```
805
     *
806
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
807
     * @param array $columns the columns (name => definition) in the new table.
808
     * @param string|null $options additional SQL fragment that will be appended to the generated SQL.
809
     *
810
     * @return string the SQL statement for creating a new DB table.
811
     */
812 43
    public function createTable(string $table, array $columns, ?string $options = null): string
813
    {
814 43
        $cols = [];
815 43
        foreach ($columns as $name => $type) {
816 43
            if (is_string($name)) {
817 43
                $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
818
            } else {
819 4
                $cols[] = "\t" . $type;
820
            }
821
        }
822
823 43
        $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
824
825 43
        return ($options === null) ? $sql : ($sql . ' ' . $options);
826
    }
827
828
    /**
829
     * Builds a SQL statement for renaming a DB table.
830
     *
831
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
832
     * @param string $newName the new table name. The name will be properly quoted by the method.
833
     *
834
     * @return string the SQL statement for renaming a DB table.
835
     */
836 2
    public function renameTable(string $oldName, string $newName): string
837
    {
838 2
        return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
839
    }
840
841
    /**
842
     * Builds a SQL statement for dropping a DB table.
843
     *
844
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
845
     *
846
     * @return string the SQL statement for dropping a DB table.
847
     */
848 5
    public function dropTable(string $table): string
849
    {
850 5
        return 'DROP TABLE ' . $this->db->quoteTableName($table);
851
    }
852
853
    /**
854
     * Builds a SQL statement for adding a primary key constraint to an existing table.
855
     *
856
     * @param string $name the name of the primary key constraint.
857
     * @param string $table the table that the primary key constraint will be added to.
858
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
859
     *
860
     * @return string the SQL statement for adding a primary key constraint to an existing table.
861
     */
862 8
    public function addPrimaryKey(string $name, string $table, $columns): string
863
    {
864 8
        if (is_string($columns)) {
865 6
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
866
        }
867
868 8
        foreach ($columns as $i => $col) {
869 8
            $columns[$i] = $this->db->quoteColumnName($col);
870
        }
871
872 8
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
873 8
            . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
874 8
            . implode(', ', $columns) . ')';
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false; 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 ignore-type  annotation

874
            . implode(', ', /** @scrutinizer ignore-type */ $columns) . ')';
Loading history...
875
    }
876
877
    /**
878
     * Builds a SQL statement for removing a primary key constraint to an existing table.
879
     *
880
     * @param string $name the name of the primary key constraint to be removed.
881
     * @param string $table the table that the primary key constraint will be removed from.
882
     *
883
     * @return string the SQL statement for removing a primary key constraint from an existing table.
884
     */
885 3
    public function dropPrimaryKey(string $name, string $table): string
886
    {
887 3
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
888 3
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
889
    }
890
891
    /**
892
     * Builds a SQL statement for truncating a DB table.
893
     *
894
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
895
     *
896
     * @return string the SQL statement for truncating a DB table.
897
     */
898 2
    public function truncateTable(string $table): string
899
    {
900 2
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
901
    }
902
903
    /**
904
     * Builds a SQL statement for adding a new DB column.
905
     *
906
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by
907
     * the method.
908
     * @param string $column the name of the new column. The name will be properly quoted by the method.
909
     * @param string $type the column type. The {@see getColumnType()} method will be invoked to convert abstract column
910
     * type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the
911
     * generated SQL.
912
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become
913
     * 'varchar(255) not null'.
914
     *
915
     * @return string the SQL statement for adding a new column.
916
     */
917 1
    public function addColumn(string $table, string $column, string $type): string
918
    {
919 1
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
920 1
            . ' ADD ' . $this->db->quoteColumnName($column) . ' '
921 1
            . $this->getColumnType($type);
922
    }
923
924
    /**
925
     * Builds a SQL statement for dropping a DB column.
926
     *
927
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
928
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
929
     *
930
     * @return string the SQL statement for dropping a DB column.
931
     */
932
    public function dropColumn(string $table, string $column): string
933
    {
934
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
935
            . ' DROP COLUMN ' . $this->db->quoteColumnName($column);
936
    }
937
938
    /**
939
     * Builds a SQL statement for renaming a column.
940
     *
941
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
942
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
943
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
944
     *
945
     * @return string the SQL statement for renaming a DB column.
946
     */
947
    public function renameColumn(string $table, string $oldName, string $newName): string
948
    {
949
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
950
            . ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
951
            . ' TO ' . $this->db->quoteColumnName($newName);
952
    }
953
954
    /**
955
     * Builds a SQL statement for changing the definition of a column.
956
     *
957
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the
958
     * method.
959
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
960
     * @param string $type the new column type. The {@see getColumnType()} method will be invoked to convert abstract
961
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
962
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
963
     * will become 'varchar(255) not null'.
964
     *
965
     * @return string the SQL statement for changing the definition of a column.
966
     */
967
    public function alterColumn(string $table, string $column, string $type): string
968
    {
969
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
970
            . $this->db->quoteColumnName($column) . ' '
971
            . $this->db->quoteColumnName($column) . ' '
972
            . $this->getColumnType($type);
973
    }
974
975
    /**
976
     * Builds a SQL statement for adding a foreign key constraint to an existing table. The method will properly quote
977
     * the table and column names.
978
     *
979
     * @param string $name the name of the foreign key constraint.
980
     * @param string $table the table that the foreign key constraint will be added to.
981
     * @param string|array $columns the name of the column to that the constraint will be added on. If there are
982
     * multiple columns, separate them with commas or use an array to represent them.
983
     * @param string $refTable the table that the foreign key references to.
984
     * @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple
985
     * columns, separate them with commas or use an array to represent them.
986
     * @param string|null $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION,
987
     * SET DEFAULT, SET NULL.
988
     * @param string|null $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION,
989
     * SET DEFAULT, SET NULL.
990
     *
991
     * @throws Exception|InvalidArgumentException
992
     *
993
     * @return string the SQL statement for adding a foreign key constraint to an existing table.
994
     */
995 9
    public function addForeignKey(
996
        string $name,
997
        string $table,
998
        $columns,
999
        string $refTable,
1000
        $refColumns,
1001
        ?string $delete = null,
1002
        ?string $update = null
1003
    ): string {
1004 9
        $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
1005 9
            . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
1006 9
            . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
1007 9
            . ' REFERENCES ' . $this->db->quoteTableName($refTable)
1008 9
            . ' (' . $this->buildColumns($refColumns) . ')';
1009
1010 9
        if ($delete !== null) {
1011 6
            $sql .= ' ON DELETE ' . $delete;
1012
        }
1013
1014 9
        if ($update !== null) {
1015 6
            $sql .= ' ON UPDATE ' . $update;
1016
        }
1017
1018 9
        return $sql;
1019
    }
1020
1021
    /**
1022
     * Builds a SQL statement for dropping a foreign key constraint.
1023
     *
1024
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by
1025
     * the method.
1026
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
1027
     *
1028
     * @return string the SQL statement for dropping a foreign key constraint.
1029
     */
1030 4
    public function dropForeignKey(string $name, string $table): string
1031
    {
1032 4
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1033 4
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1034
    }
1035
1036
    /**
1037
     * Builds a SQL statement for creating a new index.
1038
     *
1039
     * @param string $name the name of the index. The name will be properly quoted by the method.
1040
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by
1041
     * the method.
1042
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
1043
     * separate them with commas or use an array to represent them. Each column name will be properly quoted by the
1044
     * method, unless a parenthesis is found in the name.
1045
     * @param bool $unique whether to add UNIQUE constraint on the created index.
1046
     *
1047
     * @throws Exception|InvalidArgumentException
1048
     *
1049
     * @return string the SQL statement for creating a new index.
1050
     */
1051 5
    public function createIndex(string $name, string $table, $columns, bool $unique = false): string
1052
    {
1053 5
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
1054 5
            . $this->db->quoteTableName($name) . ' ON '
1055 5
            . $this->db->quoteTableName($table)
1056 5
            . ' (' . $this->buildColumns($columns) . ')';
1057
    }
1058
1059
    /**
1060
     * Builds a SQL statement for dropping an index.
1061
     *
1062
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
1063
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
1064
     *
1065
     * @return string the SQL statement for dropping an index.
1066
     */
1067 6
    public function dropIndex(string $name, string $table): string
1068
    {
1069 6
        return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
1070
    }
1071
1072
    /**
1073
     * Creates a SQL command for adding an unique constraint to an existing table.
1074
     *
1075
     * @param string $name the name of the unique constraint. The name will be properly quoted by the method.
1076
     * @param string $table the table that the unique constraint will be added to. The name will be properly quoted by
1077
     * the method.
1078
     * @param string|array $columns the name of the column to that the constraint will be added on. If there are
1079
     * multiple columns, separate them with commas. The name will be properly quoted by the method.
1080
     *
1081
     * @return string the SQL statement for adding an unique constraint to an existing table.
1082
     */
1083 9
    public function addUnique(string $name, string $table, $columns): string
1084
    {
1085 9
        if (is_string($columns)) {
1086 6
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1087
        }
1088 9
        foreach ($columns as $i => $col) {
1089 9
            $columns[$i] = $this->db->quoteColumnName($col);
1090
        }
1091
1092 9
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1093 9
            . $this->db->quoteColumnName($name) . ' UNIQUE ('
1094 9
            . implode(', ', $columns) . ')';
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false; 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 ignore-type  annotation

1094
            . implode(', ', /** @scrutinizer ignore-type */ $columns) . ')';
Loading history...
1095
    }
1096
1097
    /**
1098
     * Creates a SQL command for dropping an unique constraint.
1099
     *
1100
     * @param string $name the name of the unique constraint to be dropped. The name will be properly quoted by the
1101
     * method.
1102
     * @param string $table the table whose unique constraint is to be dropped. The name will be properly quoted by the
1103
     * method.
1104
     *
1105
     * @return string the SQL statement for dropping an unique constraint.
1106
     */
1107 4
    public function dropUnique(string $name, string $table): string
1108
    {
1109 4
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1110 4
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1111
    }
1112
1113
    /**
1114
     * Creates a SQL command for adding a check constraint to an existing table.
1115
     *
1116
     * @param string $name the name of the check constraint. The name will be properly quoted by the method.
1117
     * @param string $table the table that the check constraint will be added to. The name will be properly quoted by
1118
     * the method.
1119
     * @param string $expression the SQL of the `CHECK` constraint.
1120
     *
1121
     * @return string the SQL statement for adding a check constraint to an existing table.
1122
     */
1123 4
    public function addCheck(string $name, string $table, string $expression): string
1124
    {
1125 4
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1126 4
            . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
0 ignored issues
show
Bug introduced by
The method quoteSql() does not exist on Yiisoft\Db\Connection\ConnectionInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\Db\Connection\ConnectionInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1126
            . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->/** @scrutinizer ignore-call */ quoteSql($expression) . ')';
Loading history...
1127
    }
1128
1129
    /**
1130
     * Creates a SQL command for dropping a check constraint.
1131
     *
1132
     * @param string $name the name of the check constraint to be dropped. The name will be properly quoted by the
1133
     * method.
1134
     * @param string $table the table whose check constraint is to be dropped. The name will be properly quoted by the
1135
     * method.
1136
     *
1137
     * @return string the SQL statement for dropping a check constraint.
1138
     */
1139 4
    public function dropCheck(string $name, string $table): string
1140
    {
1141 4
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1142 4
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1143
    }
1144
1145
    /**
1146
     * Creates a SQL command for adding a default value constraint to an existing table.
1147
     *
1148
     * @param string $name the name of the default value constraint.
1149
     * The name will be properly quoted by the method.
1150
     * @param string $table the table that the default value constraint will be added to.
1151
     * The name will be properly quoted by the method.
1152
     * @param string $column the name of the column to that the constraint will be added on.
1153
     * The name will be properly quoted by the method.
1154
     * @param mixed $value default value.
1155
     *
1156
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1157
     *
1158
     * @return string the SQL statement for adding a default value constraint to an existing table.
1159
     */
1160
    public function addDefaultValue(string $name, string $table, string $column, $value): string
1161
    {
1162
        throw new NotSupportedException(
1163
            $this->db->getDriverName() . ' does not support adding default value constraints.'
1164
        );
1165
    }
1166
1167
    /**
1168
     * Creates a SQL command for dropping a default value constraint.
1169
     *
1170
     * @param string $name the name of the default value constraint to be dropped.
1171
     * The name will be properly quoted by the method.
1172
     * @param string $table the table whose default value constraint is to be dropped.
1173
     * The name will be properly quoted by the method.
1174
     *
1175
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1176
     *
1177
     * @return string the SQL statement for dropping a default value constraint.
1178
     */
1179
    public function dropDefaultValue(string $name, string $table): string
1180
    {
1181
        throw new NotSupportedException(
1182
            $this->db->getDriverName() . ' does not support dropping default value constraints.'
1183
        );
1184
    }
1185
1186
    /**
1187
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
1188
     *
1189
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
1190
     * or 1.
1191
     *
1192
     * @param string $tableName the name of the table whose primary key sequence will be reset.
1193
     * @param array|string|null $value the value for the primary key of the next new row inserted. If this is not set,
1194
     * the next new row's primary key will have a value 1.
1195
     *
1196
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1197
     *
1198
     * @return string the SQL statement for resetting sequence.
1199
     */
1200
    public function resetSequence(string $tableName, $value = null): string
0 ignored issues
show
Unused Code introduced by
The parameter $tableName 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 ignore-unused  annotation

1200
    public function resetSequence(/** @scrutinizer ignore-unused */ string $tableName, $value = null): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1201
    {
1202
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1203
    }
1204
1205
    /**
1206
     * Builds a SQL statement for enabling or disabling integrity check.
1207
     *
1208
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1209
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1210
     *
1211
     * @param bool $check whether to turn on or off the integrity check.
1212
     *
1213
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1214
     *
1215
     * @return string the SQL statement for checking integrity.
1216
     */
1217
    public function checkIntegrity(string $schema = '', string $table = '', bool $check = true): string
0 ignored issues
show
Unused Code introduced by
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 ignore-unused  annotation

1217
    public function checkIntegrity(string $schema = '', string $table = '', /** @scrutinizer ignore-unused */ bool $check = true): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1218
    {
1219
        throw new NotSupportedException(
1220
            $this->db->getDriverName() . ' does not support enabling/disabling integrity check.'
1221
        );
1222
    }
1223
1224
    /**
1225
     * Builds a SQL command for adding comment to column.
1226
     *
1227
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1228
     * method.
1229
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the
1230
     * method.
1231
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1232
     *
1233
     * @return string the SQL statement for adding comment on column.
1234
     */
1235 1
    public function addCommentOnColumn(string $table, string $column, string $comment): string
1236
    {
1237 1
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column)
1238 1
            . ' IS ' . $this->db->quoteValue($comment);
0 ignored issues
show
Bug introduced by
The method quoteValue() does not exist on Yiisoft\Db\Connection\ConnectionInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\Db\Connection\ConnectionInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1238
            . ' IS ' . $this->db->/** @scrutinizer ignore-call */ quoteValue($comment);
Loading history...
1239
    }
1240
1241
    /**
1242
     * Builds a SQL command for adding comment to table.
1243
     *
1244
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1245
     * method.
1246
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1247
     *
1248
     * @return string the SQL statement for adding comment on table.
1249
     */
1250 1
    public function addCommentOnTable(string $table, string $comment): string
1251
    {
1252 1
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
1253
    }
1254
1255
    /**
1256
     * Builds a SQL command for adding comment to column.
1257
     *
1258
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1259
     * method.
1260
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the
1261
     * method.
1262
     *
1263
     * @return string the SQL statement for adding comment on column.
1264
     */
1265 1
    public function dropCommentFromColumn(string $table, string $column): string
1266
    {
1267 1
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column)
1268 1
            . ' IS NULL';
1269
    }
1270
1271
    /**
1272
     * Builds a SQL command for adding comment to table.
1273
     *
1274
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1275
     * method.
1276
     *
1277
     * @return string the SQL statement for adding comment on column.
1278
     */
1279 1
    public function dropCommentFromTable(string $table): string
1280
    {
1281 1
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
1282
    }
1283
1284
    /**
1285
     * Creates a SQL View.
1286
     *
1287
     * @param string $viewName the name of the view to be created.
1288
     * @param string|Query $subQuery the select statement which defines the view.
1289
     *
1290
     * This can be either a string or a {@see Query} object.
1291
     *
1292
     * @throws Exception|InvalidConfigException|NotSupportedException
1293
     *
1294
     * @return string the `CREATE VIEW` SQL statement.
1295
     */
1296 4
    public function createView(string $viewName, $subQuery): string
1297
    {
1298 4
        if ($subQuery instanceof Query) {
1299 4
            [$rawQuery, $params] = $this->build($subQuery);
1300 4
            array_walk(
1301
                $params,
1302 4
                function (&$param) {
1303 4
                    $param = $this->db->quoteValue($param);
1304 4
                }
1305
            );
1306 4
            $subQuery = strtr($rawQuery, $params);
1307
        }
1308
1309 4
        return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery;
1310
    }
1311
1312
    /**
1313
     * Drops a SQL View.
1314
     *
1315
     * @param string $viewName the name of the view to be dropped.
1316
     *
1317
     * @return string the `DROP VIEW` SQL statement.
1318
     */
1319 4
    public function dropView(string $viewName): string
1320
    {
1321 4
        return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
1322
    }
1323
1324
    /**
1325
     * Converts an abstract column type into a physical column type.
1326
     *
1327
     * The conversion is done using the type map specified in {@see typeMap}.
1328
     * The following abstract column types are supported (using MySQL as an example to explain the corresponding
1329
     * physical types):
1330
     *
1331
     * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY
1332
     *    KEY"
1333
     * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT
1334
     *    PRIMARY KEY"
1335
     * - `upk`: an unsigned auto-incremental primary key type, will be converted into "int(10) UNSIGNED NOT NULL
1336
     *    AUTO_INCREMENT PRIMARY KEY"
1337
     * - `char`: char type, will be converted into "char(1)"
1338
     * - `string`: string type, will be converted into "varchar(255)"
1339
     * - `text`: a long string type, will be converted into "text"
1340
     * - `smallint`: a small integer type, will be converted into "smallint(6)"
1341
     * - `integer`: integer type, will be converted into "int(11)"
1342
     * - `bigint`: a big integer type, will be converted into "bigint(20)"
1343
     * - `boolean`: boolean type, will be converted into "tinyint(1)"
1344
     * - `float``: float number type, will be converted into "float"
1345
     * - `decimal`: decimal number type, will be converted into "decimal"
1346
     * - `datetime`: datetime type, will be converted into "datetime"
1347
     * - `timestamp`: timestamp type, will be converted into "timestamp"
1348
     * - `time`: time type, will be converted into "time"
1349
     * - `date`: date type, will be converted into "date"
1350
     * - `money`: money type, will be converted into "decimal(19,4)"
1351
     * - `binary`: binary data type, will be converted into "blob"
1352
     *
1353
     * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only the first
1354
     * part will be converted, and the rest of the parts will be appended to the converted result.
1355
     *
1356
     * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
1357
     *
1358
     * For some of the abstract types you can also specify a length or precision constraint by appending it in round
1359
     * brackets directly to the type.
1360
     *
1361
     * For example `string(32)` will be converted into "varchar(32)" on a MySQL database. If the underlying DBMS does
1362
     * not support these kind of constraints for a type it will be ignored.
1363
     *
1364
     * If a type cannot be found in {@see typeMap}, it will be returned without any change.
1365
     *
1366
     * @param string|ColumnSchemaBuilder $type abstract column type.
1367
     *
1368
     * @return string physical column type.
1369
     */
1370 48
    public function getColumnType($type): string
1371
    {
1372 48
        if ($type instanceof ColumnSchemaBuilder) {
1373 9
            $type = $type->__toString();
1374
        }
1375
1376 48
        if (isset($this->typeMap[$type])) {
1377 28
            return $this->typeMap[$type];
1378
        }
1379
1380 32
        if (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
1381 17
            if (isset($this->typeMap[$matches[1]])) {
1382 14
                return preg_replace(
1383
                    '/\(.+\)/',
1384 14
                    '(' . $matches[2] . ')',
1385 14
                    $this->typeMap[$matches[1]]
1386 17
                ) . $matches[3];
1387
            }
1388 26
        } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
1389 26
            if (isset($this->typeMap[$matches[1]])) {
1390 26
                return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
1391
            }
1392
        }
1393
1394 4
        return $type;
1395
    }
1396
1397
    /**
1398
     * @param array $columns
1399
     * @param array $params the binding parameters to be populated.
1400
     * @param bool|null $distinct
1401
     * @param string|null $selectOption
1402
     *
1403
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
1404
     *
1405
     * @return string the SELECT clause built from {@see Query::$select}.
1406
     */
1407 1160
    public function buildSelect(
1408
        array $columns,
1409
        array &$params,
1410
        ?bool $distinct = false,
1411
        string $selectOption = null
1412
    ): string {
1413 1160
        $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
1414
1415 1160
        if ($selectOption !== null) {
1416
            $select .= ' ' . $selectOption;
1417
        }
1418
1419 1160
        if (empty($columns)) {
1420 982
            return $select . ' *';
1421
        }
1422
1423 321
        foreach ($columns as $i => $column) {
1424 321
            if ($column instanceof ExpressionInterface) {
1425 56
                if (is_int($i)) {
1426 8
                    $columns[$i] = $this->buildExpression($column, $params);
1427
                } else {
1428 56
                    $columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
1429
                }
1430 309
            } elseif ($column instanceof Query) {
1431
                [$sql, $params] = $this->build($column, $params);
1432
                $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
1433 309
            } elseif (is_string($i) && $i !== $column) {
1434 16
                if (strpos($column, '(') === false) {
1435 12
                    $column = $this->db->quoteColumnName($column);
1436
                }
1437 16
                $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
1438 305
            } elseif (strpos($column, '(') === false) {
1439 227
                if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_.]+)$/', $column, $matches)) {
1440
                    $columns[$i] = $this->db->quoteColumnName(
1441
                        $matches[1]
1442
                    ) . ' AS ' . $this->db->quoteColumnName($matches[2]);
1443
                } else {
1444 227
                    $columns[$i] = $this->db->quoteColumnName($column);
1445
                }
1446
            }
1447
        }
1448
1449 321
        return $select . ' ' . implode(', ', $columns);
1450
    }
1451
1452
    /**
1453
     * @param array|null $tables
1454
     * @param array $params the binding parameters to be populated.
1455
     *
1456
     * @throws Exception|InvalidConfigException|NotSupportedException
1457
     *
1458
     * @return string the FROM clause built from {@see Query::$from}.
1459
     */
1460 1176
    public function buildFrom(?array $tables, array &$params): string
1461
    {
1462 1176
        if (empty($tables)) {
1463 545
            return '';
1464
        }
1465
1466 681
        $tables = $this->quoteTableNames($tables, $params);
1467
1468 681
        return 'FROM ' . implode(', ', $tables);
1469
    }
1470
1471
    /**
1472
     * @param array $joins
1473
     * @param array $params the binding parameters to be populated.
1474
     *
1475
     * @throws Exception if the $joins parameter is not in proper format.
1476
     *
1477
     * @return string the JOIN clause built from {@see Query::$join}.
1478
     */
1479 1160
    public function buildJoin(array $joins, array &$params): string
1480
    {
1481 1160
        if (empty($joins)) {
1482 1156
            return '';
1483
        }
1484
1485 60
        foreach ($joins as $i => $join) {
1486 60
            if (!is_array($join) || !isset($join[0], $join[1])) {
1487
                throw new Exception(
1488
                    'A join clause must be specified as an array of join type, join table, and optionally join '
1489
                    . 'condition.'
1490
                );
1491
            }
1492
1493
            /* 0:join type, 1:join table, 2:on-condition (optional) */
1494 60
            [$joinType, $table] = $join;
1495
1496 60
            $tables = $this->quoteTableNames((array) $table, $params);
1497 60
            $table = reset($tables);
1498 60
            $joins[$i] = "$joinType $table";
1499
1500 60
            if (isset($join[2])) {
1501 60
                $condition = $this->buildCondition($join[2], $params);
1502 60
                if ($condition !== '') {
1503 60
                    $joins[$i] .= ' ON ' . $condition;
1504
                }
1505
            }
1506
        }
1507
1508 60
        return implode($this->separator, $joins);
1509
    }
1510
1511
    /**
1512
     * Quotes table names passed.
1513
     *
1514
     * @param array $tables
1515
     * @param array $params
1516
     *
1517
     * @throws Exception|InvalidConfigException|NotSupportedException
1518
     *
1519
     * @return array
1520
     */
1521 681
    private function quoteTableNames(array $tables, array &$params): array
1522
    {
1523 681
        foreach ($tables as $i => $table) {
1524 681
            if ($table instanceof Query) {
1525 13
                [$sql, $params] = $this->build($table, $params);
1526 13
                $tables[$i] = "($sql) " . $this->db->quoteTableName((string) $i);
1527 681
            } elseif (is_string($i)) {
1528 60
                if (strpos($table, '(') === false) {
1529 44
                    $table = $this->db->quoteTableName($table);
1530
                }
1531 60
                $tables[$i] = "$table " . $this->db->quoteTableName($i);
1532 641
            } elseif (is_string($table)) {
1533 632
                if (strpos($table, '(') === false) {
1534 632
                    if ($tableWithAlias = $this->extractAlias($table)) { // with alias
1535 36
                        $tables[$i] = $this->db->quoteTableName($tableWithAlias[1]) . ' '
1536 36
                            . $this->db->quoteTableName($tableWithAlias[2]);
1537
                    } else {
1538 600
                        $tables[$i] = $this->db->quoteTableName($table);
1539
                    }
1540
                }
1541
            }
1542
        }
1543
1544 681
        return $tables;
1545
    }
1546
1547
    /**
1548
     * @param string|array $condition
1549
     * @param array $params the binding parameters to be populated.
1550
     *
1551
     * @throws InvalidArgumentException
1552
     *
1553
     * @return string the WHERE clause built from {@see Query::$where}.
1554
     */
1555 1182
    public function buildWhere($condition, array &$params = []): string
1556
    {
1557 1182
        $where = $this->buildCondition($condition, $params);
1558
1559 1182
        return ($where === '') ? '' : ('WHERE ' . $where);
1560
    }
1561
1562
    /**
1563
     * @param array $columns
1564
     * @param array $params the binding parameters to be populated
1565
     *
1566
     * @throws Exception|InvalidArgumentException
1567
     *
1568
     * @return string the GROUP BY clause
1569
     */
1570 1160
    public function buildGroupBy(array $columns, array &$params = []): string
1571
    {
1572 1160
        if (empty($columns)) {
1573 1152
            return '';
1574
        }
1575 12
        foreach ($columns as $i => $column) {
1576 12
            if ($column instanceof ExpressionInterface) {
1577 4
                $columns[$i] = $this->buildExpression($column);
1578 4
                $params = array_merge($params, $column->getParams());
0 ignored issues
show
Bug introduced by
The method getParams() does not exist on Yiisoft\Db\Expression\ExpressionInterface. It seems like you code against a sub-type of Yiisoft\Db\Expression\ExpressionInterface such as Yiisoft\Db\Expression\Expression or Yiisoft\Db\Query\Query. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1578
                $params = array_merge($params, $column->/** @scrutinizer ignore-call */ getParams());
Loading history...
1579 12
            } elseif (strpos($column, '(') === false) {
1580 12
                $columns[$i] = $this->db->quoteColumnName($column);
1581
            }
1582
        }
1583
1584 12
        return 'GROUP BY ' . implode(', ', $columns);
1585
    }
1586
1587
    /**
1588
     * @param string|array $condition
1589
     * @param array $params the binding parameters to be populated.
1590
     *
1591
     * @throws InvalidArgumentException
1592
     *
1593
     * @return string the HAVING clause built from {@see Query::$having}.
1594
     */
1595 1160
    public function buildHaving($condition, array &$params = []): string
1596
    {
1597 1160
        $having = $this->buildCondition($condition, $params);
1598
1599 1160
        return ($having === '') ? '' : ('HAVING ' . $having);
1600
    }
1601
1602
    /**
1603
     * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
1604
     *
1605
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET).
1606
     * @param array $orderBy the order by columns. See {@see Query::orderBy} for more details on how to specify this
1607
     * parameter.
1608
     * @param int|object|null $limit the limit number. See {@see Query::limit} for more details.
1609
     * @param int|object|null $offset the offset number. See {@see Query::offset} for more details.
1610
     * @param array $params the binding parameters to be populated.
1611
     *
1612
     * @throws Exception|InvalidArgumentException
1613
     *
1614
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any).
1615
     */
1616 894
    public function buildOrderByAndLimit(
1617
        string $sql,
1618
        array $orderBy,
1619
        $limit,
1620
        $offset,
1621
        array &$params = []
1622
    ): string {
1623 894
        $orderBy = $this->buildOrderBy($orderBy, $params);
1624 894
        if ($orderBy !== '') {
1625 126
            $sql .= $this->separator . $orderBy;
1626
        }
1627 894
        $limit = $this->buildLimit($limit, $offset);
1628 894
        if ($limit !== '') {
1629 36
            $sql .= $this->separator . $limit;
1630
        }
1631
1632 894
        return $sql;
1633
    }
1634
1635
    /**
1636
     * @param array $columns
1637
     * @param array $params the binding parameters to be populated
1638
     *
1639
     * @throws Exception|InvalidArgumentException
1640
     *
1641
     * @return string the ORDER BY clause built from {@see Query::$orderBy}.
1642
     */
1643 1172
    public function buildOrderBy(array $columns, array &$params = []): string
1644
    {
1645 1172
        if (empty($columns)) {
1646 1120
            return '';
1647
        }
1648
1649 168
        $orders = [];
1650
1651 168
        foreach ($columns as $name => $direction) {
1652 168
            if ($direction instanceof ExpressionInterface) {
1653 4
                $orders[] = $this->buildExpression($direction);
1654 4
                $params = array_merge($params, $direction->getParams());
1655
            } else {
1656 168
                $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
1657
            }
1658
        }
1659
1660 168
        return 'ORDER BY ' . implode(', ', $orders);
1661
    }
1662
1663
    /**
1664
     * @param int|object|null $limit
1665
     * @param int|object|null $offset
1666
     *
1667
     * @return string the LIMIT and OFFSET clauses.
1668
     */
1669 331
    public function buildLimit($limit, $offset): string
1670
    {
1671 331
        $sql = '';
1672
1673 331
        if ($this->hasLimit($limit)) {
1674 11
            $sql = 'LIMIT ' . $limit;
0 ignored issues
show
Bug introduced by
Are you sure $limit of type integer|null|object can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1674
            $sql = 'LIMIT ' . /** @scrutinizer ignore-type */ $limit;
Loading history...
1675
        }
1676
1677 331
        if ($this->hasOffset($offset)) {
1678 3
            $sql .= ' OFFSET ' . $offset;
0 ignored issues
show
Bug introduced by
Are you sure $offset of type integer|null|object can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1678
            $sql .= ' OFFSET ' . /** @scrutinizer ignore-type */ $offset;
Loading history...
1679
        }
1680
1681 331
        return ltrim($sql);
1682
    }
1683
1684
    /**
1685
     * Checks to see if the given limit is effective.
1686
     *
1687
     * @param mixed $limit the given limit.
1688
     *
1689
     * @return bool whether the limit is effective.
1690
     */
1691 884
    protected function hasLimit($limit): bool
1692
    {
1693 884
        return ($limit instanceof ExpressionInterface) || ctype_digit((string) $limit);
1694
    }
1695
1696
    /**
1697
     * Checks to see if the given offset is effective.
1698
     *
1699
     * @param mixed $offset the given offset.
1700
     *
1701
     * @return bool whether the offset is effective.
1702
     */
1703 884
    protected function hasOffset($offset): bool
1704
    {
1705 884
        return ($offset instanceof ExpressionInterface) || (ctype_digit((string)$offset) && (string)$offset !== '0');
1706
    }
1707
1708
    /**
1709
     * @param array $unions
1710
     * @param array $params the binding parameters to be populated
1711
     *
1712
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
1713
     *
1714
     * @return string the UNION clause built from {@see Query::$union}.
1715
     */
1716 888
    public function buildUnion(array $unions, array &$params): string
1717
    {
1718 888
        if (empty($unions)) {
1719 888
            return '';
1720
        }
1721
1722 7
        $result = '';
1723
1724 7
        foreach ($unions as $i => $union) {
1725 7
            $query = $union['query'];
1726 7
            if ($query instanceof Query) {
1727 7
                [$unions[$i]['query'], $params] = $this->build($query, $params);
1728
            }
1729
1730 7
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
1731
        }
1732
1733 7
        return trim($result);
1734
    }
1735
1736
    /**
1737
     * Processes columns and properly quotes them if necessary.
1738
     *
1739
     * It will join all columns into a string with comma as separators.
1740
     *
1741
     * @param string|array $columns the columns to be processed.
1742
     *
1743
     * @throws InvalidArgumentException|Exception
1744
     *
1745
     * @return string the processing result.
1746
     */
1747 31
    public function buildColumns($columns): string
1748
    {
1749 31
        if (!is_array($columns)) {
1750 23
            if (strpos($columns, '(') !== false) {
1751
                return $columns;
1752
            }
1753
1754 23
            $rawColumns = $columns;
1755 23
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1756
1757 23
            if ($columns === false) {
1758
                throw new InvalidArgumentException("$rawColumns is not valid columns.");
1759
            }
1760
        }
1761 31
        foreach ($columns as $i => $column) {
1762 31
            if ($column instanceof ExpressionInterface) {
1763
                $columns[$i] = $this->buildExpression($column);
1764 31
            } elseif (strpos($column, '(') === false) {
1765 31
                $columns[$i] = $this->db->quoteColumnName($column);
1766
            }
1767
        }
1768
1769 31
        return implode(', ', $columns);
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false and 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 ignore-type  annotation

1769
        return implode(', ', /** @scrutinizer ignore-type */ $columns);
Loading history...
1770
    }
1771
1772
    /**
1773
     * Parses the condition specification and generates the corresponding SQL expression.
1774
     *
1775
     * @param string|array|ExpressionInterface $condition the condition specification.
1776
     * Please refer to {@see Query::where()} on how to specify a condition.
1777
     * @param array $params the binding parameters to be populated.
1778
     *
1779
     * @throws InvalidArgumentException
1780
     *
1781
     * @return array|string the generated SQL expression.
1782
     */
1783 1186
    public function buildCondition($condition, array &$params = [])
1784
    {
1785 1186
        if (is_array($condition)) {
1786 880
            if (empty($condition)) {
1787 4
                return '';
1788
            }
1789
1790 880
            $condition = $this->createConditionFromArray($condition);
1791
        }
1792
1793 1186
        if ($condition instanceof ExpressionInterface) {
1794 964
            return $this->buildExpression($condition, $params);
1795
        }
1796
1797 1165
        return (string) $condition;
1798
    }
1799
1800
    /**
1801
     * Transforms $condition defined in array format (as described in {@see Query::where()} to instance of
1802
     *
1803
     * @param string|array $condition.
1804
     *
1805
     * @throws InvalidArgumentException
1806
     *
1807
     * @return ConditionInterface
1808
     *
1809
     * {@see ConditionInterface|ConditionInterface} according to {@see conditionClasses} map.
1810
     */
1811 880
    public function createConditionFromArray($condition): ConditionInterface
1812
    {
1813
        /** operator format: operator, operand 1, operand 2, ... */
1814 880
        if (isset($condition[0])) {
1815 637
            $operator = strtoupper(array_shift($condition));
1816
1817 637
            $className = $this->conditionClasses[$operator] ?? SimpleCondition::class;
1818
1819
            /** @var ConditionInterface $className */
1820 637
            return $className::fromArrayDefinition($operator, $condition);
1821
        }
1822
1823
        /** hash format: 'column1' => 'value1', 'column2' => 'value2', ... */
1824 455
        return new HashCondition($condition);
1825
    }
1826
1827
    /**
1828
     * Creates a SELECT EXISTS() SQL statement.
1829
     *
1830
     * @param string $rawSql the subquery in a raw form to select from.
1831
     *
1832
     * @return string the SELECT EXISTS() SQL statement.
1833
     */
1834 9
    public function selectExists(string $rawSql): string
1835
    {
1836 9
        return 'SELECT EXISTS(' . $rawSql . ')';
1837
    }
1838
1839
    /**
1840
     * Helper method to add $value to $params array using {@see PARAM_PREFIX}.
1841
     *
1842
     * @param string|int|null $value
1843
     * @param array $params passed by reference.
1844
     *
1845
     * @return string the placeholder name in $params array.
1846
     */
1847 888
    public function bindParam($value, array &$params = []): string
1848
    {
1849 888
        $phName = self::PARAM_PREFIX . count($params);
1850 888
        $params[$phName] = $value;
1851
1852 888
        return $phName;
1853
    }
1854
1855
    /**
1856
     * Extracts table alias if there is one or returns false.
1857
     *
1858
     * @param $table
1859
     *
1860
     * @return bool|array
1861
     */
1862 632
    protected function extractAlias($table)
1863
    {
1864 632
        if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
1865 36
            return $matches;
1866
        }
1867
1868 600
        return false;
1869
    }
1870
1871
    public function buildWith($withs, &$params): string
1872
    {
1873
        if (empty($withs)) {
1874
            return '';
1875
        }
1876
1877
        $recursive = false;
1878
        $result = [];
1879
1880
        foreach ($withs as $i => $with) {
1881
            if ($with['recursive']) {
1882
                $recursive = true;
1883
            }
1884
1885
            $query = $with['query'];
1886
1887
            if ($query instanceof Query) {
1888
                [$with['query'], $params] = $this->build($query, $params);
1889
            }
1890
1891
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
1892
        }
1893
1894
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result);
1895
    }
1896
1897 1160
    public function buildWithQueries($withs, &$params): string
1898
    {
1899 1160
        if (empty($withs)) {
1900 1160
            return '';
1901
        }
1902
1903 8
        $recursive = false;
1904 8
        $result = [];
1905
1906 8
        foreach ($withs as $i => $with) {
1907 8
            if ($with['recursive']) {
1908 4
                $recursive = true;
1909
            }
1910
1911 8
            $query = $with['query'];
1912 8
            if ($query instanceof Query) {
1913 8
                [$with['query'], $params] = $this->build($query, $params);
1914
            }
1915
1916 8
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
1917
        }
1918
1919 8
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result);
1920
    }
1921
1922
    /**
1923
     * @return ConnectionInterface|null the database connection.
1924
     */
1925 889
    public function getDb(): ConnectionInterface
1926
    {
1927 889
        return $this->db;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->db could return the type null which is incompatible with the type-hinted return Yiisoft\Db\Connection\ConnectionInterface. Consider adding an additional type-check to rule them out.
Loading history...
1928
    }
1929
1930
    /**
1931
     * @param string the separator between different fragments of a SQL statement.
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\the was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1932
     *
1933
     * Defaults to an empty space. This is mainly used by {@see build()} when generating a SQL statement.
1934
     */
1935 4
    public function setSeparator(string $separator): void
1936
    {
1937 4
        $this->separator = $separator;
1938 4
    }
1939
}
1940