Passed
Push — master ( 7be875...4e97ca )
by Alexander
02:16
created

QueryBuilder::buildWhere()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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

333
        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...
334 101
            . (!empty($names) ? ' (' . \implode(', ', $names) . ')' : '')
335 101
            . (!empty($placeholders) ? ' VALUES (' . \implode(', ', $placeholders) . ')' : $values);
336
    }
337
338
    /**
339
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
340
     *
341
     * @param string $table the table that new rows will be inserted into.
342
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
343
     * {\Yiisoft\Db\Query\Query|Query} to perform INSERT INTO ... SELECT SQL statement.
344
     * @param array $params the binding parameters that will be generated by this method.
345
     * They should be bound to the DB command later.
346
     *
347
     * @throws Exception
348
     * @throws InvalidArgumentException
349
     * @throws InvalidConfigException
350
     * @throws NotSupportedException
351
     *
352
     * @return array array of column names, placeholders, values and params.
353
     */
354 125
    protected function prepareInsertValues(string $table, $columns, array $params = []): array
355
    {
356 125
        $schema = $this->db->getSchema();
357 125
        $tableSchema = $schema->getTableSchema($table);
358 125
        $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
359 125
        $names = [];
360 125
        $placeholders = [];
361 125
        $values = ' DEFAULT VALUES';
362
363 125
        if ($columns instanceof Query) {
364 42
            [$names, $values, $params] = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
365
        } else {
366 89
            foreach ($columns as $name => $value) {
367 89
                $names[] = $schema->quoteColumnName($name);
368 89
                $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
369
370 89
                if ($value instanceof ExpressionInterface) {
371 23
                    $placeholders[] = $this->buildExpression($value, $params);
372 88
                } elseif ($value instanceof Query) {
373
                    [$sql, $params] = $this->build($value, $params);
374
                    $placeholders[] = "($sql)";
375
                } else {
376 88
                    $placeholders[] = $this->bindParam($value, $params);
377
                }
378
            }
379
        }
380
381 116
        return [$names, $placeholders, $values, $params];
382
    }
383
384
    /**
385
     * Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
386
     *
387
     * @param Query $columns Object, which represents select query.
388
     * @param Schema $schema  Schema object to quote column name.
389
     * @param array $params  the parameters to be bound to the generated SQL statement. These parameters will
390
     * be included in the result with the additional parameters generated during the query building process.
391
     *
392
     * @return array array of column names, values and params.
393
     */
394 42
    protected function prepareInsertSelectSubQuery(Query $columns, Schema $schema, array $params = []): array
395
    {
396 42
        if (!\is_array($columns->getSelect()) || empty($columns->getSelect()) || \in_array('*', $columns->getSelect(), true)) {
397 9
            throw new \InvalidArgumentException('Expected select query object with enumerated (named) parameters');
398
        }
399
400 33
        [$values, $params] = $this->build($columns, $params);
401
402 33
        $names = [];
403 33
        $values = ' ' . $values;
404
405 33
        foreach ($columns->getSelect() as $title => $field) {
406 33
            if (\is_string($title)) {
407 33
                $names[] = $schema->quoteColumnName($title);
408
            } elseif (\preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) {
409
                $names[] = $schema->quoteColumnName($matches[2]);
410
            } else {
411
                $names[] = $schema->quoteColumnName($field);
412
            }
413
        }
414
415 33
        return [$names, $values, $params];
416
    }
417
418
    /**
419
     * Generates a batch INSERT SQL statement.
420
     *
421
     * For example,
422
     *
423
     * ```php
424
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
425
     *     ['Tom', 30],
426
     *     ['Jane', 20],
427
     *     ['Linda', 25],
428
     * ]);
429
     * ```
430
     *
431
     * Note that the values in each row must match the corresponding column names.
432
     *
433
     * The method will properly escape the column names, and quote the values to be inserted.
434
     *
435
     * @param string $table the table that new rows will be inserted into.
436
     * @param array $columns the column names.
437
     * @param array|Generator $rows the rows to be batch inserted into the table.
438
     * @param array $params the binding parameters. This parameter exists.
439
     *
440
     * @throws Exception
441
     * @throws InvalidArgumentException
442
     * @throws InvalidConfigException
443
     * @throws NotSupportedException
444
     *
445
     * @return string the batch INSERT SQL statement.
446
     */
447 26
    public function batchInsert(string $table, array $columns, $rows, array &$params = []): string
448
    {
449 26
        if (empty($rows)) {
450 2
            return '';
451
        }
452
453 25
        $schema = $this->db->getSchema();
454
455 25
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
456 25
            $columnSchemas = $tableSchema->getColumns();
457
        } else {
458
            $columnSchemas = [];
459
        }
460
461 25
        $values = [];
462
463 25
        foreach ($rows as $row) {
464 23
            $vs = [];
465 23
            foreach ($row as $i => $value) {
466 23
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
467 17
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
468
                }
469 23
                if (\is_string($value)) {
470 15
                    $value = $schema->quoteValue($value);
471 14
                } elseif (\is_float($value)) {
472
                    // ensure type cast always has . as decimal separator in all locales
473 2
                    $value = StringHelper::floatToString($value);
474 14
                } elseif ($value === false) {
475 6
                    $value = 0;
476 14
                } elseif ($value === null) {
477 8
                    $value = 'NULL';
478 8
                } elseif ($value instanceof ExpressionInterface) {
479 6
                    $value = $this->buildExpression($value, $params);
480
                }
481 23
                $vs[] = $value;
482
            }
483 23
            $values[] = '(' . \implode(', ', $vs) . ')';
484
        }
485
486 25
        if (empty($values)) {
487 2
            return '';
488
        }
489
490 23
        foreach ($columns as $i => $name) {
491 21
            $columns[$i] = $schema->quoteColumnName($name);
492
        }
493
494 23
        return 'INSERT INTO ' . $schema->quoteTableName($table)
495 23
            . ' (' . \implode(', ', $columns) . ') VALUES ' . \implode(', ', $values);
496
    }
497
498
    /**
499
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
500
     * constraints), or update them if they do.
501
     *
502
     * For example,
503
     *
504
     * ```php
505
     * $sql = $queryBuilder->upsert('pages', [
506
     *     'name' => 'Front page',
507
     *     'url' => 'http://example.com/', // url is unique
508
     *     'visits' => 0,
509
     * ], [
510
     *     'visits' => new \Yiisoft\Db\Expression('visits + 1'),
511
     * ], $params);
512
     * ```
513
     *
514
     * The method will properly escape the table and column names.
515
     *
516
     * @param string $table the table that new rows will be inserted into/updated in.
517
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance
518
     * of {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
519
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
520
     * If `true` is passed, the column data will be updated to match the insert column data.
521
     * If `false` is passed, no update will be performed if the column data already exists.
522
     * @param array $params the binding parameters that will be generated by this method.
523
     * They should be bound to the DB command later.
524
     *
525
     * @throws Exception
526
     * @throws InvalidConfigException
527
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
528
     *
529
     * @return string the resulting SQL.
530
     */
531
    public function upsert(string $table, $insertColumns, $updateColumns, array &$params): string
532
    {
533
        throw new NotSupportedException($this->db->getDriverName() . ' does not support upsert statements.');
534
    }
535
536
    /**
537
     * @param string $table
538
     * @param array|Query $insertColumns
539
     * @param array|bool $updateColumns
540
     * @param Constraint[] $constraints this parameter recieves a matched constraint list.
541
     * The constraints will be unique by their column names.
542
     *
543
     * @throws Exception
544
     * @throws InvalidConfigException
545
     * @throws NotSupportedException
546
     *
547
     * @return array
548
     */
549 54
    protected function prepareUpsertColumns(string $table, $insertColumns, $updateColumns, array &$constraints = []): array
550
    {
551 54
        if ($insertColumns instanceof Query) {
552 24
            [$insertNames] = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
553
        } else {
554 30
            $insertNames = \array_map([$this->db, 'quoteColumnName'], \array_keys($insertColumns));
555
        }
556
557 54
        $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
558 54
        $uniqueNames = \array_map([$this->db, 'quoteColumnName'], $uniqueNames);
559
560 54
        if ($updateColumns !== true) {
561 39
            return [$uniqueNames, $insertNames, null];
562
        }
563
564 15
        return [$uniqueNames, $insertNames, \array_diff($insertNames, $uniqueNames)];
565
    }
566
567
    /**
568
     * Returns all column names belonging to constraints enforcing uniqueness (`PRIMARY KEY`, `UNIQUE INDEX`, etc.)
569
     * for the named table removing constraints which did not cover the specified column list.
570
     *
571
     * The column list will be unique by column names.
572
     *
573
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
574
     * @param string[] $columns source column list.
575
     * @param Constraint[] $constraints this parameter optionally recieves a matched constraint list.
576
     * The constraints will be unique by their column names.
577
     *
578
     * @throws Exception
579
     * @throws InvalidConfigException
580
     * @throws NotSupportedException
581
     *
582
     * @return array column list.
583
     */
584 54
    private function getTableUniqueColumnNames(string $name, array $columns, array &$constraints = []): array
585
    {
586 54
        $schema = $this->db->getSchema();
587
588 54
        if (!$schema instanceof ConstraintFinderInterface) {
589
            return [];
590
        }
591
592 54
        $constraints = [];
593 54
        $primaryKey = $schema->getTablePrimaryKey($name);
594
595 54
        if ($primaryKey !== null) {
596 54
            $constraints[] = $primaryKey;
597
        }
598
599 54
        foreach ($schema->getTableIndexes($name) as $constraint) {
600 53
            if ($constraint->isUnique()) {
601 53
                $constraints[] = $constraint;
602
            }
603
        }
604
605 54
        $constraints = \array_merge($constraints, $schema->getTableUniques($name));
606
607
        // Remove duplicates
608 54
        $constraints = \array_combine(
609 54
            \array_map(
610 54
                static function ($constraint) {
611 54
                    $columns = $constraint->getColumnNames();
612 54
                    sort($columns, SORT_STRING);
613
614 54
                    return \json_encode($columns);
615
                },
616 54
                $constraints
617
            ),
618 54
            $constraints
619
        );
620
621 54
        $columnNames = [];
622
623
        // Remove all constraints which do not cover the specified column list
624 54
        $constraints = \array_values(
625 54
            \array_filter(
626 54
                $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

626
                /** @scrutinizer ignore-type */ $constraints,
Loading history...
627 54
                static function ($constraint) use ($schema, $columns, &$columnNames) {
628 54
                    $constraintColumnNames = \array_map([$schema, 'quoteColumnName'], $constraint->getColumnNames());
629 54
                    $result = !\array_diff($constraintColumnNames, $columns);
630
631 54
                    if ($result) {
632 45
                        $columnNames = \array_merge($columnNames, $constraintColumnNames);
633
                    }
634
635 54
                    return $result;
636 54
                }
637
            )
638
        );
639
640 54
        return \array_unique($columnNames);
641
    }
642
643
    /**
644
     * Creates an UPDATE SQL statement.
645
     *
646
     * For example,
647
     *
648
     * ```php
649
     * $params = [];
650
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
651
     * ```
652
     *
653
     * The method will properly escape the table and column names.
654
     *
655
     * @param string $table the table to be updated.
656
     * @param array $columns the column data (name => value) to be updated.
657
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
658
     * {@see Query::where()} on how to specify condition.
659
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
660
     * DB command later.
661
     *
662
     * @throws Exception
663
     * @throws InvalidArgumentException
664
     * @throws InvalidConfigException
665
     * @throws NotSupportedException
666
     *
667
     * @return string the UPDATE SQL.
668
     */
669 19
    public function update(string $table, array $columns, $condition, array &$params = []): string
670
    {
671 19
        [$lines, $params] = $this->prepareUpdateSets($table, $columns, $params);
672 19
        $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
673 19
        $where = $this->buildWhere($condition, $params);
674
675 19
        return ($where === '') ? $sql : ($sql . ' ' . $where);
676
    }
677
678
    /**
679
     * Prepares a `SET` parts for an `UPDATE` SQL statement.
680
     *
681
     * @param string $table the table to be updated.
682
     * @param array $columns the column data (name => value) to be updated.
683
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
684
     * DB command later.
685
     *
686
     * @throws Exception
687
     * @throws InvalidArgumentException
688
     * @throws InvalidConfigException
689
     * @throws NotSupportedException
690
     *
691
     * @return array an array `SET` parts for an `UPDATE` SQL statement (the first array element) and params (the second
692
     * array element).
693
     */
694 44
    protected function prepareUpdateSets(string $table, array $columns, array $params = []): array
695
    {
696 44
        $tableSchema = $this->db->getTableSchema($table);
697
698 44
        $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
699
700 44
        $sets = [];
701
702 44
        foreach ($columns as $name => $value) {
703 44
            $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
704 44
            if ($value instanceof ExpressionInterface) {
705 35
                $placeholder = $this->buildExpression($value, $params);
706
            } else {
707 24
                $placeholder = $this->bindParam($value, $params);
708
            }
709
710 44
            $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
711
        }
712
713 44
        return [$sets, $params];
714
    }
715
716
    /**
717
     * Creates a DELETE SQL statement.
718
     *
719
     * For example,
720
     *
721
     * ```php
722
     * $sql = $queryBuilder->delete('user', 'status = 0');
723
     * ```
724
     *
725
     * The method will properly escape the table and column names.
726
     *
727
     * @param string $table the table where the data will be deleted from.
728
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
729
     * {@see Query::where()} on how to specify condition.
730
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
731
     * DB command later.
732
     *
733
     * @throws Exception
734
     * @throws InvalidArgumentException
735
     * @throws InvalidConfigException
736
     * @throws NotSupportedException
737
     *
738
     * @return string the DELETE SQL.
739
     */
740 7
    public function delete(string $table, $condition, array &$params): string
741
    {
742 7
        $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
743 7
        $where = $this->buildWhere($condition, $params);
744
745 7
        return ($where === '') ? $sql : ($sql . ' ' . $where);
746
    }
747
748
    /**
749
     * Builds a SQL statement for creating a new DB table.
750
     *
751
     * The columns in the new  table should be specified as name-definition pairs (e.g. 'name' => 'string'), where name
752
     * stands for a column name which will be properly quoted by the method, and definition stands for the column type
753
     * which can contain an abstract DB type.
754
     *
755
     * The {@see getColumnType()} method will be invoked to convert any abstract type into a physical one.
756
     *
757
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly inserted
758
     * into the generated SQL.
759
     *
760
     * For example,
761
     *
762
     * ```php
763
     * $sql = $queryBuilder->createTable('user', [
764
     *  'id' => 'pk',
765
     *  'name' => 'string',
766
     *  'age' => 'integer',
767
     * ]);
768
     * ```
769
     *
770
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
771
     * @param array $columns the columns (name => definition) in the new table.
772
     * @param string|null $options additional SQL fragment that will be appended to the generated SQL.
773
     *
774
     * @throws Exception
775
     * @throws InvalidConfigException
776
     * @throws NotSupportedException
777
     *
778
     * @return string the SQL statement for creating a new DB table.
779
     */
780 36
    public function createTable(string $table, array $columns, ?string $options = null): string
781
    {
782 36
        $cols = [];
783 36
        foreach ($columns as $name => $type) {
784 36
            if (\is_string($name)) {
785 36
                $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
786
            } else {
787 3
                $cols[] = "\t" . $type;
788
            }
789
        }
790
791 36
        $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . \implode(",\n", $cols) . "\n)";
792
793 36
        return ($options === null) ? $sql : ($sql . ' ' . $options);
794
    }
795
796
    /**
797
     * Builds a SQL statement for renaming a DB table.
798
     *
799
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
800
     * @param string $newName the new table name. The name will be properly quoted by the method.
801
     *
802
     * @throws Exception
803
     * @throws InvalidConfigException
804
     * @throws NotSupportedException
805
     *
806
     * @return string the SQL statement for renaming a DB table.
807
     */
808 2
    public function renameTable(string $oldName, string $newName): string
809
    {
810 2
        return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
811
    }
812
813
    /**
814
     * Builds a SQL statement for dropping a DB table.
815
     *
816
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
817
     *
818
     * @throws Exception
819
     * @throws InvalidConfigException
820
     * @throws NotSupportedException
821
     *
822
     * @return string the SQL statement for dropping a DB table.
823
     */
824 9
    public function dropTable($table): string
825
    {
826 9
        return 'DROP TABLE ' . $this->db->quoteTableName($table);
827
    }
828
829
    /**
830
     * Builds a SQL statement for adding a primary key constraint to an existing table.
831
     *
832
     * @param string $name the name of the primary key constraint.
833
     * @param string $table the table that the primary key constraint will be added to.
834
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
835
     *
836
     * @throws Exception
837
     * @throws InvalidConfigException
838
     * @throws NotSupportedException
839
     *
840
     * @return string the SQL statement for adding a primary key constraint to an existing table.
841
     */
842 6
    public function addPrimaryKey(string $name, string $table, $columns): string
843
    {
844 6
        if (\is_string($columns)) {
845 4
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
846
        }
847
848 6
        foreach ($columns as $i => $col) {
849 6
            $columns[$i] = $this->db->quoteColumnName($col);
850
        }
851
852 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
853 6
            . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
854 6
            . \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

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

1116
            . implode(', ', /** @scrutinizer ignore-type */ $columns) . ')';
Loading history...
1117
    }
1118
1119
    /**
1120
     * Creates a SQL command for dropping an unique constraint.
1121
     *
1122
     * @param string $name the name of the unique constraint to be dropped. The name will be properly quoted by the
1123
     * method.
1124
     * @param string $table the table whose unique constraint is to be dropped. The name will be properly quoted by the
1125
     * method.
1126
     *
1127
     * @throws Exception
1128
     * @throws InvalidConfigException
1129
     * @throws NotSupportedException
1130
     *
1131
     * @return string the SQL statement for dropping an unique constraint.
1132
     */
1133 2
    public function dropUnique(string $name, string $table): string
1134
    {
1135 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1136 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1137
    }
1138
1139
    /**
1140
     * Creates a SQL command for adding a check constraint to an existing table.
1141
     *
1142
     * @param string $name the name of the check constraint.
1143
     * The name will be properly quoted by the method.
1144
     * @param string $table the table that the check constraint will be added to.
1145
     * The name will be properly quoted by the method.
1146
     * @param string $expression the SQL of the `CHECK` constraint.
1147
     *
1148
     * @throws Exception
1149
     * @throws InvalidConfigException
1150
     * @throws NotSupportedException
1151
     *
1152
     * @return string the SQL statement for adding a check constraint to an existing table.
1153
     */
1154 2
    public function addCheck(string $name, string $table, string $expression): string
1155
    {
1156 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1157 2
            . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
1158
    }
1159
1160
    /**
1161
     * Creates a SQL command for dropping a check constraint.
1162
     *
1163
     * @param string $name the name of the check constraint to be dropped.
1164
     * The name will be properly quoted by the method.
1165
     * @param string $table the table whose check constraint is to be dropped.
1166
     * The name will be properly quoted by the method.
1167
     *
1168
     * @throws Exception
1169
     * @throws InvalidConfigException
1170
     * @throws NotSupportedException
1171
     *
1172
     * @return string the SQL statement for dropping a check constraint.
1173
     */
1174 2
    public function dropCheck(string $name, string $table): string
1175
    {
1176 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1177 2
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1178
    }
1179
1180
    /**
1181
     * Creates a SQL command for adding a default value constraint to an existing table.
1182
     *
1183
     * @param string $name the name of the default value constraint.
1184
     * The name will be properly quoted by the method.
1185
     * @param string $table the table that the default value constraint will be added to.
1186
     * The name will be properly quoted by the method.
1187
     * @param string $column the name of the column to that the constraint will be added on.
1188
     * The name will be properly quoted by the method.
1189
     * @param mixed $value default value.
1190
     *
1191
     * @throws Exception
1192
     * @throws InvalidConfigException
1193
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
1194
     *
1195
     * @return string the SQL statement for adding a default value constraint to an existing table.
1196
     */
1197
    public function addDefaultValue(string $name, string $table, string $column, $value): string
1198
    {
1199
        throw new NotSupportedException(
1200
            $this->db->getDriverName() . ' does not support adding default value constraints.'
1201
        );
1202
    }
1203
1204
    /**
1205
     * Creates a SQL command for dropping a default value constraint.
1206
     *
1207
     * @param string $name the name of the default value constraint to be dropped.
1208
     * The name will be properly quoted by the method.
1209
     * @param string $table the table whose default value constraint is to be dropped.
1210
     * The name will be properly quoted by the method.
1211
     *
1212
     * @throws Exception
1213
     * @throws InvalidConfigException
1214
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
1215
     *
1216
     * @return string the SQL statement for dropping a default value constraint.
1217
     */
1218
    public function dropDefaultValue(string $name, string $table): string
1219
    {
1220
        throw new NotSupportedException(
1221
            $this->db->getDriverName() . ' does not support dropping default value constraints.'
1222
        );
1223
    }
1224
1225
    /**
1226
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
1227
     *
1228
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
1229
     * or 1.
1230
     *
1231
     * @param string $tableName the name of the table whose primary key sequence will be reset.
1232
     * @param array|string $value the value for the primary key of the next new row inserted. If this is not set, the
1233
     * next new row's primary key will have a value 1.
1234
     *
1235
     * @throws Exception
1236
     * @throws InvalidConfigException
1237
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
1238
     *
1239
     * @return string the SQL statement for resetting sequence.
1240
     */
1241
    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

1241
    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...
1242
    {
1243
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1244
    }
1245
1246
    /**
1247
     * Builds a SQL statement for enabling or disabling integrity check.
1248
     *
1249
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1250
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1251
     *
1252
     * @param bool $check whether to turn on or off the integrity check.
1253
     *
1254
     * @throws Exception
1255
     * @throws InvalidConfigException
1256
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
1257
     *
1258
     * @return string the SQL statement for checking integrity.
1259
     */
1260
    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

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

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

1654
                $params = \array_merge($params, $column->/** @scrutinizer ignore-call */ getParams());
Loading history...
1655 6
            } elseif (\strpos($column, '(') === false) {
1656 6
                $columns[$i] = $this->db->quoteColumnName($column);
1657
            }
1658
        }
1659
1660 6
        return 'GROUP BY ' . \implode(', ', $columns);
1661
    }
1662
1663
    /**
1664
     * @param string|array $condition
1665
     * @param array $params the binding parameters to be populated
1666
     *
1667
     * @throws InvalidArgumentException
1668
     *
1669
     * @return string the HAVING clause built from {@see Query::$having}.
1670
     */
1671 476
    public function buildHaving($condition, array &$params = []): string
1672
    {
1673 476
        $having = $this->buildCondition($condition, $params);
1674
1675 476
        return ($having === '') ? '' : ('HAVING ' . $having);
1676
    }
1677
1678
    /**
1679
     * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
1680
     *
1681
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
1682
     * @param array $orderBy the order by columns. See {@see Query::orderBy} for more details on how to specify this
1683
     * parameter.
1684
     * @param int|object|null $limit the limit number. See {@see Query::limit} for more details.
1685
     * @param int|object|null $offset the offset number. See {@see Query::offset} for more details.
1686
     * @param array $params the binding parameters to be populated
1687
     *
1688
     * @throws Exception
1689
     * @throws InvalidArgumentException
1690
     * @throws InvalidConfigException
1691
     * @throws NotSupportedException
1692
     *
1693
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any).
1694
     */
1695 476
    public function buildOrderByAndLimit(
1696
        string $sql,
1697
        array $orderBy,
1698
        $limit,
1699
        $offset,
1700
        array &$params = []
1701
    ): string {
1702 476
        $orderBy = $this->buildOrderBy($orderBy, $params);
1703 476
        if ($orderBy !== '') {
1704 15
            $sql .= $this->separator . $orderBy;
1705
        }
1706 476
        $limit = $this->buildLimit($limit, $offset);
1707 476
        if ($limit !== '') {
1708 26
            $sql .= $this->separator . $limit;
1709
        }
1710
1711 476
        return $sql;
1712
    }
1713
1714
    /**
1715
     * @param array $columns
1716
     * @param array $params the binding parameters to be populated
1717
     *
1718
     * @throws Exception
1719
     * @throws InvalidArgumentException
1720
     * @throws InvalidConfigException
1721
     * @throws NotSupportedException
1722
     *
1723
     * @return string the ORDER BY clause built from {@see Query::$orderBy}.
1724
     */
1725 476
    public function buildOrderBy(array $columns, array &$params = []): string
1726
    {
1727 476
        if (empty($columns)) {
1728 464
            return '';
1729
        }
1730
1731 15
        $orders = [];
1732
1733 15
        foreach ($columns as $name => $direction) {
1734 15
            if ($direction instanceof ExpressionInterface) {
1735 3
                $orders[] = $this->buildExpression($direction);
1736 3
                $params = \array_merge($params, $direction->getParams());
1737
            } else {
1738 15
                $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
1739
            }
1740
        }
1741
1742 15
        return 'ORDER BY ' . \implode(', ', $orders);
1743
    }
1744
1745
    /**
1746
     * @param int|object|null $limit
1747
     * @param int|object|null $offset
1748
     *
1749
     * @return string the LIMIT and OFFSET clauses
1750
     */
1751 187
    public function buildLimit($limit, $offset): string
1752
    {
1753 187
        $sql = '';
1754
1755 187
        if ($this->hasLimit($limit)) {
1756 9
            $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

1756
            $sql = 'LIMIT ' . /** @scrutinizer ignore-type */ $limit;
Loading history...
1757
        }
1758
1759 187
        if ($this->hasOffset($offset)) {
1760 1
            $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

1760
            $sql .= ' OFFSET ' . /** @scrutinizer ignore-type */ $offset;
Loading history...
1761
        }
1762
1763 187
        return ltrim($sql);
1764
    }
1765
1766
    /**
1767
     * Checks to see if the given limit is effective.
1768
     *
1769
     * @param mixed $limit the given limit
1770
     *
1771
     * @return bool whether the limit is effective
1772
     */
1773 323
    protected function hasLimit($limit): bool
1774
    {
1775 323
        return ($limit instanceof ExpressionInterface) || \ctype_digit((string) $limit);
1776
    }
1777
1778
    /**
1779
     * Checks to see if the given offset is effective.
1780
     *
1781
     * @param mixed $offset the given offset
1782
     *
1783
     * @return bool whether the offset is effective
1784
     */
1785 323
    protected function hasOffset($offset): bool
1786
    {
1787 323
        return ($offset instanceof ExpressionInterface) || (\ctype_digit((string)$offset) && (string)$offset !== '0');
1788
    }
1789
1790
    /**
1791
     * @param array $unions
1792
     * @param array $params the binding parameters to be populated
1793
     *
1794
     * @return string the UNION clause built from {@see Query::$union}.
1795
     */
1796 340
    public function buildUnion(array $unions, array &$params): string
1797
    {
1798 340
        if (empty($unions)) {
1799 340
            return '';
1800
        }
1801
1802 6
        $result = '';
1803
1804 6
        foreach ($unions as $i => $union) {
1805 6
            $query = $union['query'];
1806 6
            if ($query instanceof Query) {
1807 6
                [$unions[$i]['query'], $params] = $this->build($query, $params);
1808
            }
1809
1810 6
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
1811
        }
1812
1813 6
        return \trim($result);
1814
    }
1815
1816
    /**
1817
     * Processes columns and properly quotes them if necessary.
1818
     *
1819
     * It will join all columns into a string with comma as separators.
1820
     *
1821
     * @param string|array $columns the columns to be processed
1822
     *
1823
     * @throws InvalidArgumentException
1824
     * @throws NotSupportedException
1825
     * @throws Exception
1826
     * @throws InvalidConfigException
1827
     *
1828
     * @return string the processing result
1829
     */
1830 28
    public function buildColumns($columns): string
1831
    {
1832 28
        if (!\is_array($columns)) {
1833 22
            if (\strpos($columns, '(') !== false) {
1834
                return $columns;
1835
            }
1836
1837 22
            $rawColumns = $columns;
1838 22
            $columns = \preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1839
1840 22
            if ($columns === false) {
1841
                throw new InvalidArgumentException("$rawColumns is not valid columns.");
1842
            }
1843
        }
1844 28
        foreach ($columns as $i => $column) {
1845 28
            if ($column instanceof ExpressionInterface) {
1846
                $columns[$i] = $this->buildExpression($column);
1847 28
            } elseif (\strpos($column, '(') === false) {
1848 28
                $columns[$i] = $this->db->quoteColumnName($column);
1849
            }
1850
        }
1851
1852 28
        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

1852
        return \implode(', ', /** @scrutinizer ignore-type */ $columns);
Loading history...
1853
    }
1854
1855
    /**
1856
     * Parses the condition specification and generates the corresponding SQL expression.
1857
     *
1858
     * @param string|array|ExpressionInterface $condition the condition specification.
1859
     * Please refer to {@see Query::where()} on how to specify a condition.
1860
     * @param array $params the binding parameters to be populated
1861
     *
1862
     * @throws InvalidArgumentException
1863
     *
1864
     * @return string the generated SQL expression
1865
     */
1866 494
    public function buildCondition($condition, array &$params = []): string
1867
    {
1868 494
        if (\is_array($condition)) {
1869 358
            if (empty($condition)) {
1870 3
                return '';
1871
            }
1872
1873 358
            $condition = $this->createConditionFromArray($condition);
1874
        }
1875
1876 494
        if ($condition instanceof ExpressionInterface) {
1877 379
            return $this->buildExpression($condition, $params);
1878
        }
1879
1880 480
        return (string) $condition;
1881
    }
1882
1883
    /**
1884
     * Transforms $condition defined in array format (as described in {@see Query::where()} to instance of
1885
     *
1886
     * {@see \Yiisoft\Db\Condition\ConditionInterface|ConditionInterface} according to {@see conditionClasses}
1887
     * map.
1888
     *
1889
     * @param string|array $condition
1890
     * {@see conditionClasses}
1891
     *
1892
     * @throws InvalidArgumentException
1893
     *
1894
     * @return ConditionInterface
1895
     */
1896 358
    public function createConditionFromArray($condition): ConditionInterface
1897
    {
1898 358
        if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
1899 297
            $operator = \strtoupper(\array_shift($condition));
0 ignored issues
show
Bug introduced by
It seems like $condition can also be of type string; however, parameter $array of array_shift() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

1899
            $operator = \strtoupper(\array_shift(/** @scrutinizer ignore-type */ $condition));
Loading history...
1900
            $className = $this->conditionClasses[$operator] ?? SimpleCondition::class;
1901
1902
            /* @var ConditionInterface $className */
1903 297
            return $className::fromArrayDefinition($operator, $condition);
1904
        }
1905
1906
        // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
1907 102
        return new HashCondition($condition);
1908
    }
1909
1910
    /**
1911
     * Creates a SELECT EXISTS() SQL statement.
1912
     *
1913
     * @param string $rawSql the subquery in a raw form to select from.
1914
     *
1915
     * @return string the SELECT EXISTS() SQL statement.
1916
     */
1917 3
    public function selectExists(string $rawSql): string
1918
    {
1919 3
        return 'SELECT EXISTS(' . $rawSql . ')';
1920
    }
1921
1922
    /**
1923
     * Helper method to add $value to $params array using {@see PARAM_PREFIX}.
1924
     *
1925
     * @param string|int|null $value
1926
     * @param array $params passed by reference
1927
     *
1928
     * @return string the placeholder name in $params array
1929
     */
1930 334
    public function bindParam($value, array &$params = []): string
1931
    {
1932 334
        $phName = self::PARAM_PREFIX . \count($params);
1933 334
        $params[$phName] = $value;
1934
1935 334
        return $phName;
1936
    }
1937
1938
    /**
1939
     * Extracts table alias if there is one or returns false
1940
     *
1941
     * @param $table
1942
     *
1943
     * @return bool|array
1944
     */
1945 159
    protected function extractAlias($table)
1946
    {
1947 159
        if (\preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
1948 18
            return $matches;
1949
        }
1950
1951 144
        return false;
1952
    }
1953
1954
    public function buildWith($withs, &$params): string
1955
    {
1956
        if (empty($withs)) {
1957
            return '';
1958
        }
1959
1960
        $recursive = false;
1961
        $result = [];
1962
1963
        foreach ($withs as $i => $with) {
1964
            if ($with['recursive']) {
1965
                $recursive = true;
1966
            }
1967
1968
            $query = $with['query'];
1969
1970
            if ($query instanceof Query) {
1971
                [$with['query'], $params] = $this->build($query, $params);
1972
            }
1973
1974
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
1975
        }
1976
1977
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . \implode(', ', $result);
1978
    }
1979
1980 476
    public function buildWithQueries($withs, &$params): string
1981
    {
1982 476
        if (empty($withs)) {
1983 476
            return '';
1984
        }
1985
1986 6
        $recursive = false;
1987 6
        $result = [];
1988
1989 6
        foreach ($withs as $i => $with) {
1990 6
            if ($with['recursive']) {
1991 3
                $recursive = true;
1992
            }
1993
1994 6
            $query = $with['query'];
1995 6
            if ($query instanceof Query) {
1996 6
                [$with['query'], $params] = $this->build($query, $params);
1997
            }
1998
1999 6
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
2000
        }
2001
2002 6
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . \implode(', ', $result);
2003
    }
2004
2005
    /**
2006
     * @return Connection|null the database connection.
2007
     */
2008 298
    public function getDb(): ?Connection
2009
    {
2010 298
        return $this->db;
2011
    }
2012
2013
    /**
2014
     * @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...
2015
     *
2016
     * Defaults to an empty space. This is mainly used by {@see build()} when generating a SQL statement.
2017
     *
2018
     * @return void
2019
     */
2020
    public function setSeparator(string $separator): void
2021
    {
2022
        $this->separator = $separator;
2023
    }
2024
}
2025