Passed
Push — master ( 244aa0...c1114e )
by Wilmer
27:09 queued 12:07
created

QueryBuilder::batchInsert()   C

Complexity

Conditions 14
Paths 97

Size

Total Lines 52
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 33
nc 97
nop 4
dl 0
loc 52
rs 6.2666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql;
6
7
use PDO;
8
use Yiisoft\Db\Constraint\Constraint;
9
use Yiisoft\Db\Exception\Exception;
10
use Yiisoft\Db\Exception\InvalidArgumentException;
11
use Yiisoft\Db\Exception\InvalidConfigException;
12
use Yiisoft\Db\Exception\NotSupportedException;
13
use Yiisoft\Db\Expression\ArrayExpression;
14
use Yiisoft\Db\Expression\Expression;
15
use Yiisoft\Db\Expression\ExpressionInterface;
16
use Yiisoft\Db\Expression\JsonExpression;
17
use Yiisoft\Db\Pdo\PdoValue;
18
use Yiisoft\Db\Query\Conditions\LikeCondition;
19
use Yiisoft\Db\Query\Query;
20
use Yiisoft\Db\Query\QueryBuilder as AbstractQueryBuilder;
21
use Yiisoft\Strings\NumericHelper;
22
23
use function array_diff;
24
use function array_merge;
25
use function array_unshift;
26
use function count;
27
use function explode;
28
use function implode;
29
use function is_bool;
30
use function is_float;
31
use function is_string;
32
use function preg_match;
33
use function preg_replace;
34
use function reset;
35
use function strpos;
36
use function strrpos;
37
use function version_compare;
38
39
final class QueryBuilder extends AbstractQueryBuilder
40
{
41
    /**
42
     * Defines a UNIQUE index for {@see createIndex()}.
43
     */
44
    public const INDEX_UNIQUE = 'unique';
45
46
    /**
47
     * Defines a B-tree index for {@see createIndex()}.
48
     */
49
    public const INDEX_B_TREE = 'btree';
50
51
    /**
52
     * Defines a hash index for {@see createIndex()}.
53
     */
54
    public const INDEX_HASH = 'hash';
55
56
    /**
57
     * Defines a GiST index for {@see createIndex()}.
58
     */
59
    public const INDEX_GIST = 'gist';
60
61
    /**
62
     * Defines a GIN index for {@see createIndex()}.
63
     */
64
    public const INDEX_GIN = 'gin';
65
66
    /**
67
     * @var array mapping from abstract column types (keys) to physical column types (values).
68
     */
69
    protected array $typeMap = [
70
        Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
71
        Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
72
        Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
73
        Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
74
        Schema::TYPE_CHAR => 'char(1)',
75
        Schema::TYPE_STRING => 'varchar(255)',
76
        Schema::TYPE_TEXT => 'text',
77
        Schema::TYPE_TINYINT => 'smallint',
78
        Schema::TYPE_SMALLINT => 'smallint',
79
        Schema::TYPE_INTEGER => 'integer',
80
        Schema::TYPE_BIGINT => 'bigint',
81
        Schema::TYPE_FLOAT => 'double precision',
82
        Schema::TYPE_DOUBLE => 'double precision',
83
        Schema::TYPE_DECIMAL => 'numeric(10,0)',
84
        Schema::TYPE_DATETIME => 'timestamp(0)',
85
        Schema::TYPE_TIMESTAMP => 'timestamp(0)',
86
        Schema::TYPE_TIME => 'time(0)',
87
        Schema::TYPE_DATE => 'date',
88
        Schema::TYPE_BINARY => 'bytea',
89
        Schema::TYPE_BOOLEAN => 'boolean',
90
        Schema::TYPE_MONEY => 'numeric(19,4)',
91
        Schema::TYPE_JSON => 'jsonb',
92
    ];
93
94
    /**
95
     * Contains array of default condition classes. Extend this method, if you want to change default condition classes
96
     * for the query builder.
97
     *
98
     * @return array
99
     *
100
     * See {@see conditionClasses} docs for details.
101
     */
102
    protected function defaultConditionClasses(): array
103
    {
104
        return array_merge(parent::defaultConditionClasses(), [
105
            'ILIKE' => LikeCondition::class,
106
            'NOT ILIKE' => LikeCondition::class,
107
            'OR ILIKE' => LikeCondition::class,
108
            'OR NOT ILIKE' => LikeCondition::class,
109
        ]);
110
    }
111
112
    /**
113
     * Contains array of default expression builders. Extend this method and override it, if you want to change default
114
     * expression builders for this query builder.
115
     *
116
     * @return array
117
     *
118
     * See {@see ExpressionBuilder} docs for details.
119
     */
120
    protected function defaultExpressionBuilders(): array
121
    {
122
        return array_merge(parent::defaultExpressionBuilders(), [
123
            ArrayExpression::class => ArrayExpressionBuilder::class,
124
            JsonExpression::class => JsonExpressionBuilder::class,
125
        ]);
126
    }
127
128
    /**
129
     * Builds a SQL statement for creating a new index.
130
     *
131
     * @param string $name the name of the index. The name will be properly quoted by the method.
132
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by
133
     * the method.
134
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
135
     * separate them with commas or use an array to represent them. Each column name will be properly quoted by the
136
     * method, unless a parenthesis is found in the name.
137
     * @param bool|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or
138
     * {@see INDEX_UNIQUE} to create a unique index, `false` to make a non-unique index using the default index type, or
139
     * one of the following constants to specify the index method to use: {@see INDEX_B_TREE}, {@see INDEX_HASH},
140
     * {@see INDEX_GIST}, {@see INDEX_GIN}.
141
     *
142
     * @throws Exception
143
     * @throws InvalidArgumentException
144
     * @throws InvalidConfigException
145
     * @throws NotSupportedException
146
     *
147
     * @return string the SQL statement for creating a new index.
148
     *
149
     * {@see http://www.postgresql.org/docs/8.2/static/sql-createindex.html}
150
     */
151
    public function createIndex(string $name, string $table, $columns, bool $unique = false): string
152
    {
153
        if ($unique === self::INDEX_UNIQUE || $unique === true) {
154
            $index = false;
155
            $unique = true;
156
        } else {
157
            $index = $unique;
158
            $unique = false;
159
        }
160
161
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
162
            . $this->db->quoteTableName($name) . ' ON '
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

162
            . $this->db->/** @scrutinizer ignore-call */ quoteTableName($name) . ' ON '

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...
163
            . $this->db->quoteTableName($table)
164
            . ($index !== false ? " USING $index" : '')
0 ignored issues
show
introduced by
The condition $index !== false is always false.
Loading history...
165
            . ' (' . $this->buildColumns($columns) . ')';
166
    }
167
168
    /**
169
     * Builds a SQL statement for dropping an index.
170
     *
171
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
172
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
173
     *
174
     * @throws Exception
175
     * @throws InvalidConfigException
176
     * @throws NotSupportedException
177
     *
178
     * @return string the SQL statement for dropping an index.
179
     */
180
    public function dropIndex(string $name, string $table): string
181
    {
182
        if (strpos($table, '.') !== false && strpos($name, '.') === false) {
183
            if (strpos($table, '{{') !== false) {
184
                $table = preg_replace('/{{(.*?)}}/', '\1', $table);
185
                [$schema, $table] = explode('.', $table);
186
                if (strpos($schema, '%') === false) {
187
                    $name = $schema . '.' . $name;
188
                } else {
189
                    $name = '{{' . $schema . '.' . $name . '}}';
190
                }
191
            } else {
192
                [$schema] = explode('.', $table);
193
                $name = $schema . '.' . $name;
194
            }
195
        }
196
197
        return 'DROP INDEX ' . $this->db->quoteTableName($name);
198
    }
199
200
    /**
201
     * Builds a SQL statement for renaming a DB table.
202
     *
203
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
204
     * @param string $newName the new table name. The name will be properly quoted by the method.
205
     *
206
     * @throws Exception
207
     * @throws InvalidConfigException
208
     * @throws NotSupportedException
209
     *
210
     * @return string the SQL statement for renaming a DB table.
211
     */
212
    public function renameTable(string $oldName, string $newName): string
213
    {
214
        return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO '
215
            . $this->db->quoteTableName($newName);
216
    }
217
218
    /**
219
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
220
     *
221
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
222
     * or 1.
223
     *
224
     * @param string $tableName the name of the table whose primary key sequence will be reset.
225
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set, the next new
226
     * row's primary key will have a value 1.
227
     *
228
     * @throws Exception
229
     * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
230
     * @throws InvalidConfigException
231
     * @throws NotSupportedException
232
     *
233
     * @return string the SQL statement for resetting sequence.
234
     */
235
    public function resetSequence(string $tableName, $value = null): string
236
    {
237
        $table = $this->db->getTableSchema($tableName);
238
        if ($table !== null && $table->getSequenceName() !== null) {
239
            /**
240
             * {@see http://www.postgresql.org/docs/8.1/static/functions-sequence.html}
241
             */
242
            $sequence = $this->db->quoteTableName($table->getSequenceName());
243
            $tableName = $this->db->quoteTableName($tableName);
244
            if ($value === null) {
245
                $pk = $table->getPrimaryKey();
246
                $key = $this->db->quoteColumnName(reset($pk));
247
                $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
248
            } else {
249
                $value = (int) $value;
250
            }
251
252
            return "SELECT SETVAL('$sequence',$value,false)";
253
        }
254
255
        if ($table === null) {
256
            throw new InvalidArgumentException("Table not found: $tableName");
257
        }
258
259
        throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
260
    }
261
262
    /**
263
     * Builds a SQL statement for enabling or disabling integrity check.
264
     *
265
     * @param string $schema the schema of the tables.
266
     * @param string $table the table name.
267
     * @param bool $check whether to turn on or off the integrity check.
268
     *
269
     * @throws Exception
270
     * @throws InvalidConfigException
271
     * @throws NotSupportedException
272
     *
273
     * @return string the SQL statement for checking integrity.
274
     */
275
    public function checkIntegrity(string $schema = '', string $table = '', bool $check = true): string
276
    {
277
        $enable = $check ? 'ENABLE' : 'DISABLE';
278
        $schema = $schema ?: $this->db->getSchema()->getDefaultSchema();
279
        $tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema);
0 ignored issues
show
Bug introduced by
It seems like $schema can also be of type null; however, parameter $schema of Yiisoft\Db\Schema\Schema::getTableNames() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

279
        $tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames(/** @scrutinizer ignore-type */ $schema);
Loading history...
280
        $viewNames = $this->db->getSchema()->getViewNames($schema);
281
        $tableNames = array_diff($tableNames, $viewNames);
282
        $command = '';
283
284
        foreach ($tableNames as $tableName) {
285
            $tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
286
            $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
287
        }
288
289
        /* enable to have ability to alter several tables */
290
        $this->db->getMasterPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
291
292
        return $command;
293
    }
294
295
    /**
296
     * Builds a SQL statement for truncating a DB table.
297
     *
298
     * Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default.
299
     *
300
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
301
     *
302
     * @throws Exception
303
     * @throws InvalidConfigException
304
     * @throws NotSupportedException
305
     *
306
     * @return string the SQL statement for truncating a DB table.
307
     */
308
    public function truncateTable(string $table): string
309
    {
310
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY';
311
    }
312
313
    /**
314
     * Builds a SQL statement for changing the definition of a column.
315
     *
316
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the
317
     * method.
318
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
319
     * @param string $type the new column type. The {@see getColumnType()} method will be invoked to convert abstract
320
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the
321
     * generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become
322
     * 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
323
     *
324
     * @throws Exception
325
     * @throws InvalidConfigException
326
     * @throws NotSupportedException
327
     *
328
     * @return string the SQL statement for changing the definition of a column.
329
     */
330
    public function alterColumn(string $table, string $column, $type): string
331
    {
332
        $columnName = $this->db->quoteColumnName($column);
333
        $tableName = $this->db->quoteTableName($table);
334
335
        /**
336
         * {@see https://github.com/yiisoft/yii2/issues/4492}
337
         * {@see http://www.postgresql.org/docs/9.1/static/sql-altertable.html}
338
         */
339
        if (preg_match('/^(DROP|SET|RESET)\s+/i', (string) $type)) {
340
            return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}";
341
        }
342
343
        $type = 'TYPE ' . $this->getColumnType($type);
344
        $multiAlterStatement = [];
345
        $constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
346
347
        if (preg_match('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', $type, $matches)) {
348
            $type = preg_replace('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', '', $type);
349
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}";
350
        } else {
351
            /* safe to drop default even if there was none in the first place */
352
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT";
353
        }
354
355
        $type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
356
357
        if ($count) {
358
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL";
359
        } else {
360
            /* remove additional null if any */
361
            $type = preg_replace('/\s+NULL/i', '', $type);
362
363
            /* safe to drop not null even if there was none in the first place */
364
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL";
365
        }
366
367
        if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
368
            $type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
369
            $multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})";
370
        }
371
372
        $type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
373
374
        if ($count) {
375
            $multiAlterStatement[] = "ADD UNIQUE ({$columnName})";
376
        }
377
378
        /* add what's left at the beginning */
379
        array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}");
380
381
        return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
382
    }
383
384
    /**
385
     * Creates an INSERT SQL statement.
386
     *
387
     * For example,.
388
     *
389
     * ```php
390
     * $sql = $queryBuilder->insert('user', [
391
     *     'name' => 'Sam',
392
     *     'age' => 30,
393
     * ], $params);
394
     * ```
395
     *
396
     * The method will properly escape the table and column names.
397
     *
398
     * @param string $table the table that new rows will be inserted into.
399
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
400
     * {@see Query|Query} to perform INSERT INTO ... SELECT SQL statement. Passing of
401
     * {@see Query|Query}.
402
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the
403
     * DB command later.
404
     *
405
     * @throws Exception
406
     * @throws InvalidArgumentException
407
     * @throws InvalidConfigException
408
     * @throws NotSupportedException
409
     *
410
     * @return string the INSERT SQL
411
     */
412
    public function insert(string $table, $columns, array &$params = []): string
413
    {
414
        return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
415
    }
416
417
    /**
418
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
419
     * constraints), or update them if they do.
420
     *
421
     * For example,
422
     *
423
     * ```php
424
     * $sql = $queryBuilder->upsert('pages', [
425
     *     'name' => 'Front page',
426
     *     'url' => 'http://example.com/', // url is unique
427
     *     'visits' => 0,
428
     * ], [
429
     *     'visits' => new \Yiisoft\Db\Expression('visits + 1'),
430
     * ], $params);
431
     * ```
432
     *
433
     * The method will properly escape the table and column names.
434
     *
435
     * @param string $table the table that new rows will be inserted into/updated in.
436
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance of
437
     * {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
438
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
439
     * If `true` is passed, the column data will be updated to match the insert column data.
440
     * If `false` is passed, no update will be performed if the column data already exists.
441
     * @param array $params the binding parameters that will be generated by this method.
442
     * They should be bound to the DB command later.
443
     *
444
     * @throws Exception
445
     * @throws InvalidConfigException
446
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
447
     *
448
     * @return string the resulting SQL.
449
     *
450
     * {@see https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT}
451
     * {@see https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291}
452
     */
453
    public function upsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
454
    {
455
        $insertColumns = $this->normalizeTableRowData($table, $insertColumns);
456
457
        if (!is_bool($updateColumns)) {
458
            $updateColumns = $this->normalizeTableRowData($table, $updateColumns);
459
        }
460
        if (version_compare($this->db->getServerVersion(), '9.5', '<')) {
461
            return $this->oldUpsert($table, $insertColumns, $updateColumns, $params);
462
        }
463
464
        return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
465
    }
466
467
    /**
468
     * {@see upsert()} implementation for PostgreSQL 9.5 or higher.
469
     *
470
     * @param string $table
471
     * @param array|Query $insertColumns
472
     * @param array|bool $updateColumns
473
     * @param array $params
474
     *
475
     * @throws Exception
476
     * @throws InvalidArgumentException
477
     * @throws InvalidConfigException
478
     * @throws NotSupportedException
479
     *
480
     * @return string
481
     */
482
    private function newUpsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
483
    {
484
        $insertSql = $this->insert($table, $insertColumns, $params);
485
        [$uniqueNames, , $updateNames] = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
486
487
        if (empty($uniqueNames)) {
488
            return $insertSql;
489
        }
490
491
        if ($updateNames === []) {
492
            /* there are no columns to update */
493
            $updateColumns = false;
494
        }
495
496
        if ($updateColumns === false) {
497
            return "$insertSql ON CONFLICT DO NOTHING";
498
        }
499
500
        if ($updateColumns === true) {
501
            $updateColumns = [];
502
            foreach ($updateNames as $name) {
503
                $updateColumns[$name] = new Expression('EXCLUDED.' . $this->db->quoteColumnName($name));
504
            }
505
        }
506
507
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
508
509
        return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET '
510
            . implode(', ', $updates);
511
    }
512
513
    /**
514
     * {@see upsert()} implementation for PostgreSQL older than 9.5.
515
     *
516
     * @param string $table
517
     * @param array|Query $insertColumns
518
     * @param array|bool $updateColumns
519
     * @param array $params
520
     *
521
     * @throws Exception
522
     * @throws InvalidArgumentException
523
     * @throws InvalidConfigException
524
     * @throws NotSupportedException
525
     *
526
     * @return string
527
     */
528
    private function oldUpsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
529
    {
530
        /** @var Constraint[] $constraints */
531
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
532
            $table,
533
            $insertColumns,
534
            $updateColumns,
535
            $constraints
536
        );
537
538
        if (empty($uniqueNames)) {
539
            return $this->insert($table, $insertColumns, $params);
540
        }
541
542
        if ($updateNames === []) {
543
            /* there are no columns to update */
544
            $updateColumns = false;
545
        }
546
547
        /** @var Schema $schema */
548
        $schema = $this->db->getSchema();
549
550
        if (!$insertColumns instanceof Query) {
551
            $tableSchema = $schema->getTableSchema($table);
552
            $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
553
            foreach ($insertColumns as $name => $value) {
554
                /**
555
                 * NULLs and numeric values must be type hinted in order to be used in SET assigments NVM, let's cast
556
                 * them all
557
                 */
558
                if (isset($columnSchemas[$name])) {
559
                    $phName = self::PARAM_PREFIX . count($params);
560
                    $params[$phName] = $value;
561
                    $insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->getDbType()})");
562
                }
563
            }
564
        }
565
566
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
567
        $updateCondition = ['or'];
568
        $insertCondition = ['or'];
569
        $quotedTableName = $schema->quoteTableName($table);
570
571
        foreach ($constraints as $constraint) {
572
            $constraintUpdateCondition = ['and'];
573
            $constraintInsertCondition = ['and'];
574
            foreach ($constraint->getColumnNames() as $name) {
575
                $quotedName = $schema->quoteColumnName($name);
576
                $constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
577
                $constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName";
578
            }
579
            $updateCondition[] = $constraintUpdateCondition;
580
            $insertCondition[] = $constraintInsertCondition;
581
        }
582
583
        $withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames) . ') AS ('
584
            . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')';
585
586
        if ($updateColumns === false) {
587
            $selectSubQuery = (new Query($this->db))
588
                ->select(new Expression('1'))
589
                ->from($table)
590
                ->where($updateCondition);
591
            $insertSelectSubQuery = (new Query($this->db))
592
                ->select($insertNames)
593
                ->from('EXCLUDED')
594
                ->where(['not exists', $selectSubQuery]);
595
            $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
596
597
            return "$withSql $insertSql";
598
        }
599
600
        if ($updateColumns === true) {
601
            $updateColumns = [];
602
            foreach ($updateNames as $name) {
603
                $quotedName = $this->db->quoteColumnName($name);
604
                if (strrpos($quotedName, '.') === false) {
605
                    $quotedName = '"EXCLUDED".' . $quotedName;
606
                }
607
                $updateColumns[$name] = new Expression($quotedName);
608
            }
609
        }
610
611
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
612
613
        $updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates)
614
            . ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params)
615
            . ' RETURNING ' . $this->db->quoteTableName($table) . '.*';
616
617
        $selectUpsertSubQuery = (new Query($this->db))
618
            ->select(new Expression('1'))
619
            ->from('upsert')
620
            ->where($insertCondition);
621
622
        $insertSelectSubQuery = (new Query($this->db))
623
            ->select($insertNames)
624
            ->from('EXCLUDED')
625
            ->where(['not exists', $selectUpsertSubQuery]);
626
627
        $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
628
629
        return "$withSql, \"upsert\" AS ($updateSql) $insertSql";
630
    }
631
632
    /**
633
     * Creates an UPDATE SQL statement.
634
     *
635
     * For example,
636
     *
637
     * ```php
638
     * $params = [];
639
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
640
     * ```
641
     *
642
     * The method will properly escape the table and column names.
643
     *
644
     * @param string $table the table to be updated.
645
     * @param array $columns the column data (name => value) to be updated.
646
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
647
     * {@see Query::where()} on how to specify condition.
648
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
649
     * DB command later.
650
     *
651
     * @throws Exception
652
     * @throws InvalidArgumentException
653
     * @throws InvalidConfigException
654
     * @throws NotSupportedException
655
     *
656
     * @return string the UPDATE SQL.
657
     */
658
    public function update(string $table, array $columns, $condition, array &$params = []): string
659
    {
660
        return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
661
    }
662
663
    /**
664
     * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
665
     *
666
     * @param string $table the table that data will be saved into.
667
     * @param array|Query $columns the column data (name => value) to be saved into the table or instance of
668
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement. Passing of
669
     * {@see Query}.
670
     *
671
     * @throws Exception
672
     * @throws InvalidConfigException
673
     * @throws NotSupportedException
674
     *
675
     * @return array|object normalized columns
676
     */
677
    private function normalizeTableRowData(string $table, $columns)
678
    {
679
        if ($columns instanceof Query) {
680
            return $columns;
681
        }
682
683
        if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
684
            $columnSchemas = $tableSchema->getColumns();
685
            foreach ($columns as $name => $value) {
686
                if (
687
                    isset($columnSchemas[$name]) &&
688
                    $columnSchemas[$name]->getType() === Schema::TYPE_BINARY &&
689
                    is_string($value)
690
                ) {
691
                    /* explicitly setup PDO param type for binary column */
692
                    $columns[$name] = new PdoValue($value, PDO::PARAM_LOB);
693
                }
694
            }
695
        }
696
697
        return $columns;
698
    }
699
700
    /**
701
     * Generates a batch INSERT SQL statement.
702
     *
703
     * For example,
704
     *
705
     * ```php
706
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
707
     *     ['Tom', 30],
708
     *     ['Jane', 20],
709
     *     ['Linda', 25],
710
     * ]);
711
     * ```
712
     *
713
     * Note that the values in each row must match the corresponding column names.
714
     *
715
     * The method will properly escape the column names, and quote the values to be inserted.
716
     *
717
     * @param string $table the table that new rows will be inserted into.
718
     * @param array $columns the column names.
719
     * @param array|Generator $rows the rows to be batch inserted into the table.
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Pgsql\Generator was not found. Did you mean Generator? If so, make sure to prefix the type with \.
Loading history...
720
     * @param array $params the binding parameters. This parameter exists.
721
     *
722
     * @throws Exception
723
     * @throws InvalidArgumentException
724
     * @throws InvalidConfigException
725
     * @throws NotSupportedException
726
     *
727
     * @return string the batch INSERT SQL statement.
728
     */
729
    public function batchInsert(string $table, array $columns, $rows, array &$params = []): string
730
    {
731
        if (empty($rows)) {
732
            return '';
733
        }
734
735
        $schema = $this->db->getSchema();
736
737
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
738
            $columnSchemas = $tableSchema->getColumns();
739
        } else {
740
            $columnSchemas = [];
741
        }
742
743
        $values = [];
744
        foreach ($rows as $row) {
745
            $vs = [];
746
            foreach ($row as $i => $value) {
747
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
748
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
749
                }
750
751
                if (is_string($value)) {
752
                    $value = $schema->quoteValue($value);
753
                } elseif (is_float($value)) {
754
                    /* ensure type cast always has . as decimal separator in all locales */
755
                    $value = NumericHelper::normalize($value);
756
                } elseif ($value === true) {
757
                    $value = 'TRUE';
758
                } elseif ($value === false) {
759
                    $value = 'FALSE';
760
                } elseif ($value === null) {
761
                    $value = 'NULL';
762
                } elseif ($value instanceof ExpressionInterface) {
763
                    $value = $this->buildExpression($value, $params);
764
                }
765
766
                $vs[] = $value;
767
            }
768
            $values[] = '(' . implode(', ', $vs) . ')';
769
        }
770
771
        if (empty($values)) {
772
            return '';
773
        }
774
775
        foreach ($columns as $i => $name) {
776
            $columns[$i] = $schema->quoteColumnName($name);
777
        }
778
779
        return 'INSERT INTO ' . $schema->quoteTableName($table)
780
            . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
781
    }
782
}
783