Passed
Push — master ( be06f7...c027e3 )
by Wilmer
08:58 queued 06:59
created

QueryBuilder::hasLimit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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

382
        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...
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

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

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

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

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

1101
            . implode(', ', /** @scrutinizer ignore-type */ $columns) . ')';
Loading history...
1102
    }
1103
1104
    /**
1105
     * Creates a SQL command for dropping an unique constraint.
1106
     *
1107
     * @param string $name the name of the unique constraint to be dropped. The name will be properly quoted by the
1108
     * method.
1109
     * @param string $table the table whose unique constraint is to be dropped. The name will be properly quoted by the
1110
     * method.
1111
     *
1112
     * @return string the SQL statement for dropping an unique constraint.
1113
     */
1114 4
    public function dropUnique(string $name, string $table): string
1115
    {
1116 4
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1117 4
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1118
    }
1119
1120
    /**
1121
     * Creates a SQL command for adding a check constraint to an existing table.
1122
     *
1123
     * @param string $name the name of the check constraint. The name will be properly quoted by the method.
1124
     * @param string $table the table that the check constraint will be added to. The name will be properly quoted by
1125
     * the method.
1126
     * @param string $expression the SQL of the `CHECK` constraint.
1127
     *
1128
     * @return string the SQL statement for adding a check constraint to an existing table.
1129
     */
1130 4
    public function addCheck(string $name, string $table, string $expression): string
1131
    {
1132 4
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1133 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

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

1213
    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...
1214
    {
1215
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1216
    }
1217
1218
    /**
1219
     * Builds a SQL statement for enabling or disabling integrity check.
1220
     *
1221
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1222
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1223
     *
1224
     * @param bool $check whether to turn on or off the integrity check.
1225
     *
1226
     * @throws Exception
1227
     * @throws InvalidConfigException
1228
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
1229
     *
1230
     * @return string the SQL statement for checking integrity.
1231
     */
1232
    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

1232
    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...
1233
    {
1234
        throw new NotSupportedException(
1235
            $this->db->getDriverName() . ' does not support enabling/disabling integrity check.'
1236
        );
1237
    }
1238
1239
    /**
1240
     * Builds a SQL command for adding comment to column.
1241
     *
1242
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1243
     * method.
1244
     * @param string $column the name of the column to be commented. The column 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 column.
1249
     */
1250 1
    public function addCommentOnColumn(string $table, string $column, string $comment): string
1251
    {
1252 1
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column)
1253 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

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

1603
                $params = array_merge($params, $column->/** @scrutinizer ignore-call */ getParams());
Loading history...
1604 12
            } elseif (strpos($column, '(') === false) {
1605 12
                $columns[$i] = $this->db->quoteColumnName($column);
1606
            }
1607
        }
1608
1609 12
        return 'GROUP BY ' . implode(', ', $columns);
1610
    }
1611
1612
    /**
1613
     * @param string|array $condition
1614
     * @param array $params the binding parameters to be populated.
1615
     *
1616
     * @throws InvalidArgumentException
1617
     *
1618
     * @return string the HAVING clause built from {@see Query::$having}.
1619
     */
1620 1132
    public function buildHaving($condition, array &$params = []): string
1621
    {
1622 1132
        $having = $this->buildCondition($condition, $params);
1623
1624 1132
        return ($having === '') ? '' : ('HAVING ' . $having);
1625
    }
1626
1627
    /**
1628
     * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
1629
     *
1630
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET).
1631
     * @param array $orderBy the order by columns. See {@see Query::orderBy} for more details on how to specify this
1632
     * parameter.
1633
     * @param int|object|null $limit the limit number. See {@see Query::limit} for more details.
1634
     * @param int|object|null $offset the offset number. See {@see Query::offset} for more details.
1635
     * @param array $params the binding parameters to be populated.
1636
     *
1637
     * @throws Exception
1638
     * @throws InvalidArgumentException
1639
     *
1640
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any).
1641
     */
1642 864
    public function buildOrderByAndLimit(
1643
        string $sql,
1644
        array $orderBy,
1645
        $limit,
1646
        $offset,
1647
        array &$params = []
1648
    ): string {
1649 864
        $orderBy = $this->buildOrderBy($orderBy, $params);
1650 864
        if ($orderBy !== '') {
1651 111
            $sql .= $this->separator . $orderBy;
1652
        }
1653 864
        $limit = $this->buildLimit($limit, $offset);
1654 864
        if ($limit !== '') {
1655 36
            $sql .= $this->separator . $limit;
1656
        }
1657
1658 864
        return $sql;
1659
    }
1660
1661
    /**
1662
     * @param array $columns
1663
     * @param array $params the binding parameters to be populated
1664
     *
1665
     * @throws Exception
1666
     * @throws InvalidArgumentException
1667
     *
1668
     * @return string the ORDER BY clause built from {@see Query::$orderBy}.
1669
     */
1670 1132
    public function buildOrderBy(array $columns, array &$params = []): string
1671
    {
1672 1132
        if (empty($columns)) {
1673 1088
            return '';
1674
        }
1675
1676 148
        $orders = [];
1677
1678 148
        foreach ($columns as $name => $direction) {
1679 148
            if ($direction instanceof ExpressionInterface) {
1680 4
                $orders[] = $this->buildExpression($direction);
1681 4
                $params = array_merge($params, $direction->getParams());
1682
            } else {
1683 148
                $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
1684
            }
1685
        }
1686
1687 148
        return 'ORDER BY ' . implode(', ', $orders);
1688
    }
1689
1690
    /**
1691
     * @param int|object|null $limit
1692
     * @param int|object|null $offset
1693
     *
1694
     * @return string the LIMIT and OFFSET clauses.
1695
     */
1696 321
    public function buildLimit($limit, $offset): string
1697
    {
1698 321
        $sql = '';
1699
1700 321
        if ($this->hasLimit($limit)) {
1701 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

1701
            $sql = 'LIMIT ' . /** @scrutinizer ignore-type */ $limit;
Loading history...
1702
        }
1703
1704 321
        if ($this->hasOffset($offset)) {
1705 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

1705
            $sql .= ' OFFSET ' . /** @scrutinizer ignore-type */ $offset;
Loading history...
1706
        }
1707
1708 321
        return ltrim($sql);
1709
    }
1710
1711
    /**
1712
     * Checks to see if the given limit is effective.
1713
     *
1714
     * @param mixed $limit the given limit.
1715
     *
1716
     * @return bool whether the limit is effective.
1717
     */
1718 854
    protected function hasLimit($limit): bool
1719
    {
1720 854
        return ($limit instanceof ExpressionInterface) || ctype_digit((string) $limit);
1721
    }
1722
1723
    /**
1724
     * Checks to see if the given offset is effective.
1725
     *
1726
     * @param mixed $offset the given offset.
1727
     *
1728
     * @return bool whether the offset is effective.
1729
     */
1730 854
    protected function hasOffset($offset): bool
1731
    {
1732 854
        return ($offset instanceof ExpressionInterface) || (ctype_digit((string)$offset) && (string)$offset !== '0');
1733
    }
1734
1735
    /**
1736
     * @param array $unions
1737
     * @param array $params the binding parameters to be populated
1738
     *
1739
     * @throws Exception
1740
     * @throws InvalidArgumentException
1741
     * @throws InvalidConfigException
1742
     * @throws NotSupportedException
1743
     *
1744
     * @return string the UNION clause built from {@see Query::$union}.
1745
     */
1746 867
    public function buildUnion(array $unions, array &$params): string
1747
    {
1748 867
        if (empty($unions)) {
1749 867
            return '';
1750
        }
1751
1752 7
        $result = '';
1753
1754 7
        foreach ($unions as $i => $union) {
1755 7
            $query = $union['query'];
1756 7
            if ($query instanceof Query) {
1757 7
                [$unions[$i]['query'], $params] = $this->build($query, $params);
1758
            }
1759
1760 7
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
1761
        }
1762
1763 7
        return trim($result);
1764
    }
1765
1766
    /**
1767
     * Processes columns and properly quotes them if necessary.
1768
     *
1769
     * It will join all columns into a string with comma as separators.
1770
     *
1771
     * @param string|array $columns the columns to be processed.
1772
     *
1773
     * @throws InvalidArgumentException
1774
     * @throws Exception
1775
     *
1776
     * @return string the processing result.
1777
     */
1778 31
    public function buildColumns($columns): string
1779
    {
1780 31
        if (!is_array($columns)) {
1781 23
            if (strpos($columns, '(') !== false) {
1782
                return $columns;
1783
            }
1784
1785 23
            $rawColumns = $columns;
1786 23
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1787
1788 23
            if ($columns === false) {
1789
                throw new InvalidArgumentException("$rawColumns is not valid columns.");
1790
            }
1791
        }
1792 31
        foreach ($columns as $i => $column) {
1793 31
            if ($column instanceof ExpressionInterface) {
1794
                $columns[$i] = $this->buildExpression($column);
1795 31
            } elseif (strpos($column, '(') === false) {
1796 31
                $columns[$i] = $this->db->quoteColumnName($column);
1797
            }
1798
        }
1799
1800 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

1800
        return implode(', ', /** @scrutinizer ignore-type */ $columns);
Loading history...
1801
    }
1802
1803
    /**
1804
     * Parses the condition specification and generates the corresponding SQL expression.
1805
     *
1806
     * @param string|array|ExpressionInterface $condition the condition specification.
1807
     * Please refer to {@see Query::where()} on how to specify a condition.
1808
     * @param array $params the binding parameters to be populated.
1809
     *
1810
     * @throws InvalidArgumentException
1811
     *
1812
     * @return string the generated SQL expression.
1813
     */
1814 1158
    public function buildCondition($condition, array &$params = []): string
1815
    {
1816 1158
        if (is_array($condition)) {
1817 868
            if (empty($condition)) {
1818 4
                return '';
1819
            }
1820
1821 868
            $condition = $this->createConditionFromArray($condition);
1822
        }
1823
1824 1158
        if ($condition instanceof ExpressionInterface) {
1825 952
            return $this->buildExpression($condition, $params);
1826
        }
1827
1828 1137
        return (string) $condition;
1829
    }
1830
1831
    /**
1832
     * Transforms $condition defined in array format (as described in {@see Query::where()} to instance of
1833
     *
1834
     * @param string|array $condition.
1835
     *
1836
     * @throws InvalidArgumentException
1837
     *
1838
     * @return ConditionInterface
1839
     *
1840
     * {@see ConditionInterface|ConditionInterface} according to {@see conditionClasses} map.
1841
     */
1842 868
    public function createConditionFromArray($condition): ConditionInterface
1843
    {
1844
        /* operator format: operator, operand 1, operand 2, ... */
1845 868
        if (isset($condition[0])) {
1846 625
            $operator = strtoupper(array_shift($condition));
1847
1848 625
            if (isset($this->conditionClasses[$operator])) {
1849 528
                $className = $this->conditionClasses[$operator];
1850
            } else {
1851 109
                $className = SimpleCondition::class;
1852
            }
1853
1854
            /** @var ConditionInterface $className */
1855 625
            return $className::fromArrayDefinition($operator, $condition);
1856
        }
1857
1858
        /* hash format: 'column1' => 'value1', 'column2' => 'value2', ... */
1859 443
        return new HashCondition($condition);
1860
    }
1861
1862
    /**
1863
     * Creates a SELECT EXISTS() SQL statement.
1864
     *
1865
     * @param string $rawSql the subquery in a raw form to select from.
1866
     *
1867
     * @return string the SELECT EXISTS() SQL statement.
1868
     */
1869 9
    public function selectExists(string $rawSql): string
1870
    {
1871 9
        return 'SELECT EXISTS(' . $rawSql . ')';
1872
    }
1873
1874
    /**
1875
     * Helper method to add $value to $params array using {@see PARAM_PREFIX}.
1876
     *
1877
     * @param string|int|null $value
1878
     * @param array $params passed by reference.
1879
     *
1880
     * @return string the placeholder name in $params array.
1881
     */
1882 876
    public function bindParam($value, array &$params = []): string
1883
    {
1884 876
        $phName = self::PARAM_PREFIX . count($params);
1885 876
        $params[$phName] = $value;
1886
1887 876
        return $phName;
1888
    }
1889
1890
    /**
1891
     * Extracts table alias if there is one or returns false.
1892
     *
1893
     * @param $table
1894
     *
1895
     * @return bool|array
1896
     */
1897 612
    protected function extractAlias($table)
1898
    {
1899 612
        if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
1900 36
            return $matches;
1901
        }
1902
1903 580
        return false;
1904
    }
1905
1906
    public function buildWith($withs, &$params): string
1907
    {
1908
        if (empty($withs)) {
1909
            return '';
1910
        }
1911
1912
        $recursive = false;
1913
        $result = [];
1914
1915
        foreach ($withs as $i => $with) {
1916
            if ($with['recursive']) {
1917
                $recursive = true;
1918
            }
1919
1920
            $query = $with['query'];
1921
1922
            if ($query instanceof Query) {
1923
                [$with['query'], $params] = $this->build($query, $params);
1924
            }
1925
1926
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
1927
        }
1928
1929
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result);
1930
    }
1931
1932 1132
    public function buildWithQueries($withs, &$params): string
1933
    {
1934 1132
        if (empty($withs)) {
1935 1132
            return '';
1936
        }
1937
1938 8
        $recursive = false;
1939 8
        $result = [];
1940
1941 8
        foreach ($withs as $i => $with) {
1942 8
            if ($with['recursive']) {
1943 4
                $recursive = true;
1944
            }
1945
1946 8
            $query = $with['query'];
1947 8
            if ($query instanceof Query) {
1948 8
                [$with['query'], $params] = $this->build($query, $params);
1949
            }
1950
1951 8
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
1952
        }
1953
1954 8
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result);
1955
    }
1956
1957
    /**
1958
     * @return ConnectionInterface|null the database connection.
1959
     */
1960 877
    public function getDb(): ?ConnectionInterface
1961
    {
1962 877
        return $this->db;
1963
    }
1964
1965
    /**
1966
     * @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...
1967
     *
1968
     * Defaults to an empty space. This is mainly used by {@see build()} when generating a SQL statement.
1969
     */
1970 4
    public function setSeparator(string $separator): void
1971
    {
1972 4
        $this->separator = $separator;
1973 4
    }
1974
}
1975