Passed
Pull Request — master (#32)
by Wilmer
29:12 queued 14:12
created

PgsqlQueryBuilder::renameTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
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\StringHelper;
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 PgsqlQueryBuilder extends QueryBuilder
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
        PgsqlSchema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
74
        PgsqlSchema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
75
        PgsqlSchema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
76
        PgsqlSchema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
77
        PgsqlSchema::TYPE_CHAR => 'char(1)',
78
        PgsqlSchema::TYPE_STRING => 'varchar(255)',
79
        PgsqlSchema::TYPE_TEXT => 'text',
80
        PgsqlSchema::TYPE_TINYINT => 'smallint',
81
        PgsqlSchema::TYPE_SMALLINT => 'smallint',
82
        PgsqlSchema::TYPE_INTEGER => 'integer',
83
        PgsqlSchema::TYPE_BIGINT => 'bigint',
84
        PgsqlSchema::TYPE_FLOAT => 'double precision',
85
        PgsqlSchema::TYPE_DOUBLE => 'double precision',
86
        PgsqlSchema::TYPE_DECIMAL => 'numeric(10,0)',
87
        PgsqlSchema::TYPE_DATETIME => 'timestamp(0)',
88
        PgsqlSchema::TYPE_TIMESTAMP => 'timestamp(0)',
89
        PgsqlSchema::TYPE_TIME => 'time(0)',
90
        PgsqlSchema::TYPE_DATE => 'date',
91
        PgsqlSchema::TYPE_BINARY => 'bytea',
92
        PgsqlSchema::TYPE_BOOLEAN => 'boolean',
93
        PgsqlSchema::TYPE_MONEY => 'numeric(19,4)',
94
        PgsqlSchema::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
            /* safe to drop not null even if there was none in the first place */
366
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL";
367
        }
368
369
        if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
370
            $type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
371
            $multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})";
372
        }
373
374
        $type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
375
376
        if ($count) {
377
            $multiAlterStatement[] = "ADD UNIQUE ({$columnName})";
378
        }
379
380
        /* add what's left at the beginning */
381
        array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}");
382
383
        return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
384
    }
385
386
    /**
387
     * Creates an INSERT SQL statement.
388
     *
389
     * For example,.
390
     *
391
     * ```php
392
     * $sql = $queryBuilder->insert('user', [
393
     *     'name' => 'Sam',
394
     *     'age' => 30,
395
     * ], $params);
396
     * ```
397
     *
398
     * The method will properly escape the table and column names.
399
     *
400
     * @param string $table the table that new rows will be inserted into.
401
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
402
     * {@see Query|Query} to perform INSERT INTO ... SELECT SQL statement. Passing of
403
     * {@see Query|Query}.
404
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the
405
     * DB command later.
406
     *
407
     * @throws Exception
408
     * @throws InvalidArgumentException
409
     * @throws InvalidConfigException
410
     * @throws NotSupportedException
411
     *
412
     * @return string the INSERT SQL
413
     */
414
    public function insert(string $table, $columns, array &$params = []): string
415
    {
416
        return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
417
    }
418
419
    /**
420
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
421
     * constraints), or update them if they do.
422
     *
423
     * For example,
424
     *
425
     * ```php
426
     * $sql = $queryBuilder->upsert('pages', [
427
     *     'name' => 'Front page',
428
     *     'url' => 'http://example.com/', // url is unique
429
     *     'visits' => 0,
430
     * ], [
431
     *     'visits' => new \Yiisoft\Db\Expression('visits + 1'),
432
     * ], $params);
433
     * ```
434
     *
435
     * The method will properly escape the table and column names.
436
     *
437
     * @param string $table the table that new rows will be inserted into/updated in.
438
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance of
439
     * {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
440
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
441
     * If `true` is passed, the column data will be updated to match the insert column data.
442
     * If `false` is passed, no update will be performed if the column data already exists.
443
     * @param array $params the binding parameters that will be generated by this method.
444
     * They should be bound to the DB command later.
445
     *
446
     * @throws Exception
447
     * @throws InvalidConfigException
448
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
449
     *
450
     * @return string the resulting SQL.
451
     *
452
     * {@see https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT}
453
     * {@see https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291}
454
     */
455
    public function upsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
456
    {
457
        $insertColumns = $this->normalizeTableRowData($table, $insertColumns);
458
459
        if (!is_bool($updateColumns)) {
460
            $updateColumns = $this->normalizeTableRowData($table, $updateColumns);
461
        }
462
        if (version_compare($this->db->getServerVersion(), '9.5', '<')) {
463
            return $this->oldUpsert($table, $insertColumns, $updateColumns, $params);
464
        }
465
466
        return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
467
    }
468
469
    /**
470
     * {@see upsert()} implementation for PostgreSQL 9.5 or higher.
471
     *
472
     * @param string $table
473
     * @param array|Query $insertColumns
474
     * @param array|bool $updateColumns
475
     * @param array $params
476
     *
477
     * @throws Exception
478
     * @throws InvalidArgumentException
479
     * @throws InvalidConfigException
480
     * @throws NotSupportedException
481
     *
482
     * @return string
483
     */
484
    private function newUpsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
485
    {
486
        $insertSql = $this->insert($table, $insertColumns, $params);
487
        [$uniqueNames, , $updateNames] = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
488
489
        if (empty($uniqueNames)) {
490
            return $insertSql;
491
        }
492
493
        if ($updateNames === []) {
494
            /** there are no columns to update */
495
            $updateColumns = false;
496
        }
497
498
        if ($updateColumns === false) {
499
            return "$insertSql ON CONFLICT DO NOTHING";
500
        }
501
502
        if ($updateColumns === true) {
503
            $updateColumns = [];
504
            foreach ($updateNames as $name) {
505
                $updateColumns[$name] = new Expression('EXCLUDED.' . $this->db->quoteColumnName($name));
506
            }
507
        }
508
509
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
510
511
        return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET '
512
            . implode(', ', $updates);
513
    }
514
515
    /**
516
     * {@see upsert()} implementation for PostgreSQL older than 9.5.
517
     *
518
     * @param string $table
519
     * @param array|Query $insertColumns
520
     * @param array|bool $updateColumns
521
     * @param array $params
522
     *
523
     * @throws Exception
524
     * @throws InvalidArgumentException
525
     * @throws InvalidConfigException
526
     * @throws NotSupportedException
527
     *
528
     * @return string
529
     */
530
    private function oldUpsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
531
    {
532
        /** @var Constraint[] $constraints */
533
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
534
            $table,
535
            $insertColumns,
536
            $updateColumns,
537
            $constraints
538
        );
539
540
        if (empty($uniqueNames)) {
541
            return $this->insert($table, $insertColumns, $params);
542
        }
543
544
        if ($updateNames === []) {
545
            /** there are no columns to update */
546
            $updateColumns = false;
547
        }
548
549
        /** @var PgsqlSchema $schema */
550
        $schema = $this->db->getSchema();
551
552
        if (!$insertColumns instanceof Query) {
553
            $tableSchema = $schema->getTableSchema($table);
554
            $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
555
            foreach ($insertColumns as $name => $value) {
556
                /**
557
                 * NULLs and numeric values must be type hinted in order to be used in SET assigments NVM, let's cast
558
                 * them all
559
                 */
560
                if (isset($columnSchemas[$name])) {
561
                    $phName = self::PARAM_PREFIX . count($params);
562
                    $params[$phName] = $value;
563
                    $insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->getDbType()})");
564
                }
565
            }
566
        }
567
568
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
569
        $updateCondition = ['or'];
570
        $insertCondition = ['or'];
571
        $quotedTableName = $schema->quoteTableName($table);
572
573
        foreach ($constraints as $constraint) {
574
            $constraintUpdateCondition = ['and'];
575
            $constraintInsertCondition = ['and'];
576
            foreach ($constraint->getColumnNames() as $name) {
577
                $quotedName = $schema->quoteColumnName($name);
578
                $constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
579
                $constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName";
580
            }
581
            $updateCondition[] = $constraintUpdateCondition;
582
            $insertCondition[] = $constraintInsertCondition;
583
        }
584
585
        $withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames) . ') AS ('
586
            . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')';
587
588
        if ($updateColumns === false) {
589
            $selectSubQuery = (new Query($this->db))
590
                ->select(new Expression('1'))
591
                ->from($table)
592
                ->where($updateCondition);
593
            $insertSelectSubQuery = (new Query($this->db))
594
                ->select($insertNames)
595
                ->from('EXCLUDED')
596
                ->where(['not exists', $selectSubQuery]);
597
            $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
598
599
            return "$withSql $insertSql";
600
        }
601
602
        if ($updateColumns === true) {
603
            $updateColumns = [];
604
            foreach ($updateNames as $name) {
605
                $quotedName = $this->db->quoteColumnName($name);
606
                if (strrpos($quotedName, '.') === false) {
607
                    $quotedName = '"EXCLUDED".' . $quotedName;
608
                }
609
                $updateColumns[$name] = new Expression($quotedName);
610
            }
611
        }
612
613
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
614
615
        $updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates)
616
            . ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params)
617
            . ' RETURNING ' . $this->db->quoteTableName($table) . '.*';
618
619
        $selectUpsertSubQuery = (new Query($this->db))
620
            ->select(new Expression('1'))
621
            ->from('upsert')
622
            ->where($insertCondition);
623
624
        $insertSelectSubQuery = (new Query($this->db))
625
            ->select($insertNames)
626
            ->from('EXCLUDED')
627
            ->where(['not exists', $selectUpsertSubQuery]);
628
629
        $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
630
631
        return "$withSql, \"upsert\" AS ($updateSql) $insertSql";
632
    }
633
634
    /**
635
     * Creates an UPDATE SQL statement.
636
     *
637
     * For example,
638
     *
639
     * ```php
640
     * $params = [];
641
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
642
     * ```
643
     *
644
     * The method will properly escape the table and column names.
645
     *
646
     * @param string $table the table to be updated.
647
     * @param array $columns the column data (name => value) to be updated.
648
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
649
     * {@see Query::where()} on how to specify condition.
650
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
651
     * DB command later.
652
     *
653
     * @throws Exception
654
     * @throws InvalidArgumentException
655
     * @throws InvalidConfigException
656
     * @throws NotSupportedException
657
     *
658
     * @return string the UPDATE SQL.
659
     */
660
    public function update(string $table, array $columns, $condition, array &$params = []): string
661
    {
662
        return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
663
    }
664
665
    /**
666
     * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
667
     *
668
     * @param string $table the table that data will be saved into.
669
     * @param array|Query $columns the column data (name => value) to be saved into the table or instance of
670
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement. Passing of
671
     * {@see Query}.
672
     *
673
     * @throws Exception
674
     * @throws InvalidConfigException
675
     * @throws NotSupportedException
676
     *
677
     * @return array|object normalized columns
678
     */
679
    private function normalizeTableRowData(string $table, $columns)
680
    {
681
        if ($columns instanceof Query) {
682
            return $columns;
683
        }
684
685
        if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
686
            $columnSchemas = $tableSchema->getColumns();
687
            foreach ($columns as $name => $value) {
688
                if (
689
                    isset($columnSchemas[$name]) &&
690
                    $columnSchemas[$name]->getType() === PgsqlSchema::TYPE_BINARY &&
691
                    is_string($value)
692
                ) {
693
                    /** explicitly setup PDO param type for binary column */
694
                    $columns[$name] = new PdoValue($value, PDO::PARAM_LOB);
695
                }
696
            }
697
        }
698
699
        return $columns;
700
    }
701
702
    /**
703
     * Generates a batch INSERT SQL statement.
704
     *
705
     * For example,
706
     *
707
     * ```php
708
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
709
     *     ['Tom', 30],
710
     *     ['Jane', 20],
711
     *     ['Linda', 25],
712
     * ]);
713
     * ```
714
     *
715
     * Note that the values in each row must match the corresponding column names.
716
     *
717
     * The method will properly escape the column names, and quote the values to be inserted.
718
     *
719
     * @param string $table the table that new rows will be inserted into.
720
     * @param array $columns the column names.
721
     * @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...
722
     * @param array $params the binding parameters. This parameter exists.
723
     *
724
     * @throws Exception
725
     * @throws InvalidArgumentException
726
     * @throws InvalidConfigException
727
     * @throws NotSupportedException
728
     *
729
     * @return string the batch INSERT SQL statement.
730
     */
731
    public function batchInsert(string $table, array $columns, $rows, array &$params = []): string
732
    {
733
        if (empty($rows)) {
734
            return '';
735
        }
736
737
        $schema = $this->db->getSchema();
738
739
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
740
            $columnSchemas = $tableSchema->getColumns();
741
        } else {
742
            $columnSchemas = [];
743
        }
744
745
        $values = [];
746
        foreach ($rows as $row) {
747
            $vs = [];
748
            foreach ($row as $i => $value) {
749
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
750
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
751
                }
752
753
                if (is_string($value)) {
754
                    $value = $schema->quoteValue($value);
755
                } elseif (is_float($value)) {
756
                    /* ensure type cast always has . as decimal separator in all locales */
757
                    $value = StringHelper::floatToString($value);
758
                } elseif ($value === true) {
759
                    $value = 'TRUE';
760
                } elseif ($value === false) {
761
                    $value = 'FALSE';
762
                } elseif ($value === null) {
763
                    $value = 'NULL';
764
                } elseif ($value instanceof ExpressionInterface) {
765
                    $value = $this->buildExpression($value, $params);
766
                }
767
768
                $vs[] = $value;
769
            }
770
            $values[] = '(' . implode(', ', $vs) . ')';
771
        }
772
773
        if (empty($values)) {
774
            return '';
775
        }
776
777
        foreach ($columns as $i => $name) {
778
            $columns[$i] = $schema->quoteColumnName($name);
779
        }
780
781
        return 'INSERT INTO ' . $schema->quoteTableName($table)
782
            . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
783
    }
784
}
785