Passed
Pull Request — master (#163)
by Wilmer
14:01
created

QueryBuilder::dropForeignKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 0
cp 0
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 695
    protected function defaultConditionClasses(): array
113
    {
114
        return [
115 695
            '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 695
    protected function defaultExpressionBuilders(): array
140
    {
141
        return [
142 695
            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());
220
221 340
        if (!empty($query->getOrderBy())) {
222
            foreach ($query->getOrderBy() as $expression) {
223 340
                if ($expression instanceof ExpressionInterface) {
224 6
                    $this->buildExpression($expression, $params);
225
                }
226
            }
227 340
        }
228
229 340
        if (!empty($query->getGroupBy())) {
230 4
            foreach ($query->getGroupBy() as $expression) {
231
                if ($expression instanceof ExpressionInterface) {
232
                    $this->buildExpression($expression, $params);
233 340
                }
234
            }
235
        }
236
237
        $union = $this->buildUnion($query->getUnion(), $params);
238
239
        if ($union !== '') {
240
            $sql = "($sql){$this->separator}$union";
241
        }
242
243
        $with = $this->buildWithQueries($query->getWithQueries(), $params);
244
245
        if ($with !== '') {
246
            $sql = "$with{$this->separator}$sql";
247
        }
248
249
        return [$sql, $params];
250
    }
251 442
252
    /**
253 442
     * Builds given $expression.
254
     *
255 442
     * @param ExpressionInterface $expression the expression to be built
256
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
257
     * in the result with the additional parameters generated during the expression building process.
258
     *
259
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
260
     *
261
     * @return string the SQL statement that will not be neither quoted nor encoded before passing to DBMS
262
     *
263
     * {@see ExpressionInterface}
264
     * {@see ExpressionBuilderInterface}
265
     * {@see expressionBuilders}
266
     */
267
    public function buildExpression(ExpressionInterface $expression, array &$params = []): string
268
    {
269
        $builder = $this->getExpressionBuilder($expression);
270
271 442
        return $builder->build($expression, $params);
272
    }
273 442
274
    /**
275 442
     * Gets object of {@see ExpressionBuilderInterface} that is suitable for $expression.
276
     *
277
     * Uses {@see expressionBuilders} array to find a suitable builder class.
278
     *
279
     * @param ExpressionInterface $expression
280
     *
281
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
282
     *
283
     * @return ExpressionBuilderInterface
284
     *
285
     * {@see expressionBuilders}
286
     */
287
    public function getExpressionBuilder(ExpressionInterface $expression): ExpressionBuilderInterface
288
    {
289
        $className = \get_class($expression);
290 442
291
        if (!isset($this->expressionBuilders[$className])) {
292
            foreach (\array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
293
                if (\is_subclass_of($expression, $expressionClass)) {
294 442
                    $this->expressionBuilders[$className] = $builderClass;
295 442
                    break;
296
                }
297
            }
298 442
299
            if (!isset($this->expressionBuilders[$className])) {
300
                throw new InvalidArgumentException(
301
                    'Expression of class ' . $className . ' can not be built in ' . get_class($this)
302
                );
303
            }
304
        }
305
306
        if ($this->expressionBuilders[$className] === __CLASS__) {
307
            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...
308
        }
309
310
        if (!\is_object($this->expressionBuilders[$className])) {
0 ignored issues
show
introduced by
The condition is_object($this->expressionBuilders[$className]) is always false.
Loading history...
311
            $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
312
        }
313
314
        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...
315
    }
316
317
    /**
318
     * Creates an INSERT SQL statement.
319
     *
320
     * For example,.
321
     *
322
     * ```php
323
     * $sql = $queryBuilder->insert('user', [
324
     *     'name' => 'Sam',
325
     *     'age' => 30,
326
     * ], $params);
327
     * ```
328
     *
329 110
     * The method will properly escape the table and column names.
330
     *
331 110
     * @param string $table the table that new rows will be inserted into.
332
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance
333 101
     * of {@see \Yiisoft\Db\Query\Query|Query} to perform INSERT INTO ... SELECT SQL statement. Passing of
334 101
     * {@see \Yiisoft\Db\Query\Query|Query}.
335 101
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the
336
     * DB command later.
337
     *
338
     * @throws Exception
339
     * @throws InvalidArgumentException
340
     * @throws InvalidConfigException
341
     * @throws NotSupportedException
342
     *
343
     * @return string the INSERT SQL
344
     */
345
    public function insert(string $table, $columns, array &$params = []): string
346
    {
347
        [$names, $placeholders, $values, $params] = $this->prepareInsertValues($table, $columns, $params);
348
349
        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

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

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

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

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

1257
    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...
1258
    {
1259
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1260
    }
1261
1262
    /**
1263
     * Builds a SQL statement for enabling or disabling integrity check.
1264
     *
1265
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1266
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1267
     *
1268
     * @param bool $check whether to turn on or off the integrity check.
1269
     *
1270
     * @throws Exception
1271
     * @throws InvalidConfigException
1272
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
1273
     *
1274
     * @return string the SQL statement for checking integrity.
1275
     */
1276
    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

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

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

1772
            $sql = 'LIMIT ' . /** @scrutinizer ignore-type */ $limit;
Loading history...
1773 323
        }
1774
1775 323
        if ($this->hasOffset($offset)) {
1776
            $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

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

1868
        return \implode(', ', /** @scrutinizer ignore-type */ $columns);
Loading history...
1869 358
    }
1870 3
1871
    /**
1872
     * Parses the condition specification and generates the corresponding SQL expression.
1873 358
     *
1874
     * @param string|array|ExpressionInterface $condition the condition specification.
1875
     * Please refer to {@see Query::where()} on how to specify a condition.
1876 494
     * @param array $params the binding parameters to be populated
1877 379
     *
1878
     * @throws InvalidArgumentException
1879
     *
1880 480
     * @return string the generated SQL expression
1881
     */
1882
    public function buildCondition($condition, array &$params = []): string
1883
    {
1884
        if (\is_array($condition)) {
1885
            if (empty($condition)) {
1886
                return '';
1887
            }
1888
1889
            $condition = $this->createConditionFromArray($condition);
1890
        }
1891
1892
        if ($condition instanceof ExpressionInterface) {
1893
            return $this->buildExpression($condition, $params);
1894
        }
1895
1896 358
        return (string) $condition;
1897
    }
1898 358
1899 297
    /**
1900 297
     * Transforms $condition defined in array format (as described in {@see Query::where()} to instance of
1901
     *
1902
     * {@see \Yiisoft\Db\Condition\ConditionInterface|ConditionInterface} according to {@see conditionClasses}
1903 297
     * map.
1904
     *
1905
     * @param string|array $condition
1906
     * {@see conditionClasses}
1907 102
     *
1908
     * @throws InvalidArgumentException
1909
     *
1910
     * @return ConditionInterface
1911
     */
1912
    public function createConditionFromArray($condition): ConditionInterface
1913
    {
1914
        if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
1915
            $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

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