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

PgsqlQueryBuilder::normalizeTableRowData()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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

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

283
        $tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames(/** @scrutinizer ignore-type */ $schema);
Loading history...
284
        $viewNames = $this->db->getSchema()->getViewNames($schema);
285
        $tableNames = array_diff($tableNames, $viewNames);
286
        $command = '';
287
288
        foreach ($tableNames as $tableName) {
289
            $tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
290
            $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
291
        }
292
293
        /** enable to have ability to alter several tables */
294
        $this->db->getMasterPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
295
296
        return $command;
297
    }
298
299
    /**
300
     * Builds a SQL statement for truncating a DB table.
301
     *
302
     * Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default.
303
     *
304
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
305
     *
306
     * @throws Exception
307
     * @throws InvalidConfigException
308
     * @throws NotSupportedException
309
     *
310
     * @return string the SQL statement for truncating a DB table.
311
     */
312
    public function truncateTable(string $table): string
313
    {
314
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY';
315
    }
316
317
    /**
318
     * Builds a SQL statement for changing the definition of a column.
319
     *
320
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the
321
     * method.
322
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
323
     * @param string $type the new column type. The {@see getColumnType()} method will be invoked to convert abstract
324
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the
325
     * generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become
326
     * 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
327
     *
328
     * @throws Exception
329
     * @throws InvalidConfigException
330
     * @throws NotSupportedException
331
     *
332
     * @return string the SQL statement for changing the definition of a column.
333
     */
334
    public function alterColumn(string $table, string $column, $type): string
335
    {
336
        $columnName = $this->db->quoteColumnName($column);
337
        $tableName = $this->db->quoteTableName($table);
338
339
        /**
340
         * {@see https://github.com/yiisoft/yii2/issues/4492}
341
         * {@see http://www.postgresql.org/docs/9.1/static/sql-altertable.html}
342
         */
343
        if (preg_match('/^(DROP|SET|RESET)\s+/i', (string) $type)) {
344
            return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}";
345
        }
346
347
        $type = 'TYPE ' . $this->getColumnType($type);
348
        $multiAlterStatement = [];
349
        $constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
350
351
        if (preg_match('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', $type, $matches)) {
352
            $type = preg_replace('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', '', $type);
353
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}";
354
        } else {
355
            /* safe to drop default even if there was none in the first place */
356
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT";
357
        }
358
359
        $type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
360
361
        if ($count) {
362
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL";
363
        } else {
364
            /* remove additional null if any */
365
            $type = preg_replace('/\s+NULL/i', '', $type);
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 PgsqlSchema $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() === PgsqlSchema::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\Query\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