Passed
Pull Request — master (#32)
by Wilmer
14:54
created

QueryBuilder::oldUpsert()   C

Complexity

Conditions 14
Paths 109

Size

Total Lines 102
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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