Completed
Push — master ( 01636a...5e01dd )
by Dmitry
70:16 queued 67:10
created

QueryBuilder::truncateTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db\pgsql;
9
10
use yii\base\InvalidArgumentException;
11
use yii\db\Constraint;
12
use yii\db\Expression;
13
use yii\db\ExpressionInterface;
14
use yii\db\Query;
15
use yii\db\PdoValue;
16
use yii\helpers\StringHelper;
17
18
/**
19
 * QueryBuilder is the query builder for PostgreSQL databases.
20
 *
21
 * @author Gevik Babakhani <[email protected]>
22
 * @since 2.0
23
 */
24
class QueryBuilder extends \yii\db\QueryBuilder
25
{
26
    /**
27
     * Defines a UNIQUE index for [[createIndex()]].
28
     * @since 2.0.6
29
     */
30
    const INDEX_UNIQUE = 'unique';
31
    /**
32
     * Defines a B-tree index for [[createIndex()]].
33
     * @since 2.0.6
34
     */
35
    const INDEX_B_TREE = 'btree';
36
    /**
37
     * Defines a hash index for [[createIndex()]].
38
     * @since 2.0.6
39
     */
40
    const INDEX_HASH = 'hash';
41
    /**
42
     * Defines a GiST index for [[createIndex()]].
43
     * @since 2.0.6
44
     */
45
    const INDEX_GIST = 'gist';
46
    /**
47
     * Defines a GIN index for [[createIndex()]].
48
     * @since 2.0.6
49
     */
50
    const INDEX_GIN = 'gin';
51
52
    /**
53
     * @var array mapping from abstract column types (keys) to physical column types (values).
54
     */
55
    public $typeMap = [
56
        Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
57
        Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
58
        Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
59
        Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
60
        Schema::TYPE_CHAR => 'char(1)',
61
        Schema::TYPE_STRING => 'varchar(255)',
62
        Schema::TYPE_TEXT => 'text',
63
        Schema::TYPE_TINYINT => 'smallint',
64
        Schema::TYPE_SMALLINT => 'smallint',
65
        Schema::TYPE_INTEGER => 'integer',
66
        Schema::TYPE_BIGINT => 'bigint',
67
        Schema::TYPE_FLOAT => 'double precision',
68
        Schema::TYPE_DOUBLE => 'double precision',
69
        Schema::TYPE_DECIMAL => 'numeric(10,0)',
70
        Schema::TYPE_DATETIME => 'timestamp(0)',
71
        Schema::TYPE_TIMESTAMP => 'timestamp(0)',
72
        Schema::TYPE_TIME => 'time(0)',
73
        Schema::TYPE_DATE => 'date',
74
        Schema::TYPE_BINARY => 'bytea',
75
        Schema::TYPE_BOOLEAN => 'boolean',
76
        Schema::TYPE_MONEY => 'numeric(19,4)',
77
        Schema::TYPE_JSON => 'jsonb',
78
    ];
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 528
    protected function defaultConditionClasses()
84
    {
85 528
        return array_merge(parent::defaultConditionClasses(), [
86 528
            'ILIKE' => 'yii\db\conditions\LikeCondition',
87
            'NOT ILIKE' => 'yii\db\conditions\LikeCondition',
88
            'OR ILIKE' => 'yii\db\conditions\LikeCondition',
89
            'OR NOT ILIKE' => 'yii\db\conditions\LikeCondition',
90
        ]);
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96 528
    protected function defaultExpressionBuilders()
97
    {
98 528
        return array_merge(parent::defaultExpressionBuilders(), [
99 528
            'yii\db\ArrayExpression' => 'yii\db\pgsql\ArrayExpressionBuilder',
100
            'yii\db\JsonExpression' => 'yii\db\pgsql\JsonExpressionBuilder',
101
        ]);
102
    }
103
104
    /**
105
     * Builds a SQL statement for creating a new index.
106
     * @param string $name the name of the index. The name will be properly quoted by the method.
107
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
108
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
109
     * separate them with commas or use an array to represent them. Each column name will be properly quoted
110
     * by the method, unless a parenthesis is found in the name.
111
     * @param bool|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or [[INDEX_UNIQUE]] to create
112
     * a unique index, `false` to make a non-unique index using the default index type, or one of the following constants to specify
113
     * the index method to use: [[INDEX_B_TREE]], [[INDEX_HASH]], [[INDEX_GIST]], [[INDEX_GIN]].
114
     * @return string the SQL statement for creating a new index.
115
     * @see http://www.postgresql.org/docs/8.2/static/sql-createindex.html
116
     */
117 6
    public function createIndex($name, $table, $columns, $unique = false)
118
    {
119 6
        if ($unique === self::INDEX_UNIQUE || $unique === true) {
120 4
            $index = false;
121 4
            $unique = true;
122
        } else {
123 3
            $index = $unique;
124 3
            $unique = false;
125
        }
126
127 6
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') .
128 6
        $this->db->quoteTableName($name) . ' ON ' .
129 6
        $this->db->quoteTableName($table) .
130 6
        ($index !== false ? " USING $index" : '') .
131 6
        ' (' . $this->buildColumns($columns) . ')';
132
    }
133
134
    /**
135
     * Builds a SQL statement for dropping an index.
136
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
137
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
138
     * @return string the SQL statement for dropping an index.
139
     */
140 2
    public function dropIndex($name, $table)
141
    {
142 2
        return 'DROP INDEX ' . $this->db->quoteTableName($name);
143
    }
144
145
    /**
146
     * Builds a SQL statement for renaming a DB table.
147
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
148
     * @param string $newName the new table name. The name will be properly quoted by the method.
149
     * @return string the SQL statement for renaming a DB table.
150
     */
151 1
    public function renameTable($oldName, $newName)
152
    {
153 1
        return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO ' . $this->db->quoteTableName($newName);
154
    }
155
156
    /**
157
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
158
     * The sequence will be reset such that the primary key of the next new row inserted
159
     * will have the specified value or 1.
160
     * @param string $tableName the name of the table whose primary key sequence will be reset
161
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
162
     * the next new row's primary key will have a value 1.
163
     * @return string the SQL statement for resetting sequence
164
     * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
165
     */
166 5
    public function resetSequence($tableName, $value = null)
167
    {
168 5
        $table = $this->db->getTableSchema($tableName);
169 5
        if ($table !== null && $table->sequenceName !== null) {
170
            // c.f. http://www.postgresql.org/docs/8.1/static/functions-sequence.html
171 5
            $sequence = $this->db->quoteTableName($table->sequenceName);
172 5
            $tableName = $this->db->quoteTableName($tableName);
173 5
            if ($value === null) {
174 1
                $key = $this->db->quoteColumnName(reset($table->primaryKey));
0 ignored issues
show
Security Bug introduced by
It seems like reset($table->primaryKey) targeting reset() can also be of type false; however, yii\db\Connection::quoteColumnName() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
175 1
                $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
176
            } else {
177 5
                $value = (int) $value;
178
            }
179
180 5
            return "SELECT SETVAL('$sequence',$value,false)";
181
        } elseif ($table === null) {
182
            throw new InvalidArgumentException("Table not found: $tableName");
183
        }
184
185
        throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
186
    }
187
188
    /**
189
     * Builds a SQL statement for enabling or disabling integrity check.
190
     * @param bool $check whether to turn on or off the integrity check.
191
     * @param string $schema the schema of the tables.
192
     * @param string $table the table name.
193
     * @return string the SQL statement for checking integrity
194
     */
195
    public function checkIntegrity($check = true, $schema = '', $table = '')
196
    {
197
        $enable = $check ? 'ENABLE' : 'DISABLE';
198
        $schema = $schema ?: $this->db->getSchema()->defaultSchema;
199
        $tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema);
200
        $viewNames = $this->db->getSchema()->getViewNames($schema);
0 ignored issues
show
Documentation Bug introduced by
The method getViewNames does not exist on object<yii\db\Schema>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
201
        $tableNames = array_diff($tableNames, $viewNames);
202
        $command = '';
203
204
        foreach ($tableNames as $tableName) {
205
            $tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
206
            $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
207
        }
208
209
        // enable to have ability to alter several tables
210
        $this->db->getMasterPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
211
212
        return $command;
213
    }
214
215
    /**
216
     * Builds a SQL statement for truncating a DB table.
217
     * Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default.
218
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
219
     * @return string the SQL statement for truncating a DB table.
220
     */
221 1
    public function truncateTable($table)
222
    {
223 1
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY';
224
    }
225
226
    /**
227
     * Builds a SQL statement for changing the definition of a column.
228
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
229
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
230
     * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
231
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
232
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
233
     * will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
234
     * @return string the SQL statement for changing the definition of a column.
235
     */
236 2
    public function alterColumn($table, $column, $type)
237
    {
238
        // https://github.com/yiisoft/yii2/issues/4492
239
        // http://www.postgresql.org/docs/9.1/static/sql-altertable.html
240 2
        if (!preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
241 2
            $type = 'TYPE ' . $this->getColumnType($type);
242
        }
243
244 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ALTER COLUMN '
245 2
            . $this->db->quoteColumnName($column) . ' ' . $type;
246
    }
247
248
    /**
249
     * {@inheritdoc}
250
     */
251 189
    public function insert($table, $columns, &$params)
252
    {
253 189
        return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
254
    }
255
256
    /**
257
     * @inheritdoc
258
     * @see https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT
259
     * @see https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291
260
     */
261 22
    public function upsert($table, $insertColumns, $updateColumns, &$params)
262
    {
263 22
        $insertColumns = $this->normalizeTableRowData($table, $insertColumns);
264 22
        if (!is_bool($updateColumns)) {
265 7
            $updateColumns = $this->normalizeTableRowData($table, $updateColumns);
266
        }
267 22
        if (version_compare($this->db->getServerVersion(), '9.5', '<')) {
268
            return $this->oldUpsert($table, $insertColumns, $updateColumns, $params);
269
        }
270
271 22
        return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
272
    }
273
274
    /**
275
     * [[upsert()]] implementation for PostgreSQL 9.5 or higher.
276
     * @param string $table
277
     * @param array|Query $insertColumns
278
     * @param array|bool $updateColumns
279
     * @param array $params
280
     * @return string
281
     */
282 22
    private function newUpsert($table, $insertColumns, $updateColumns, &$params)
283
    {
284 22
        $insertSql = $this->insert($table, $insertColumns, $params);
285 22
        list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
286 22
        if (empty($uniqueNames)) {
287 3
            return $insertSql;
288
        }
289
290 19
        if ($updateColumns === false) {
291 4
            return "$insertSql ON CONFLICT DO NOTHING";
292
        }
293
294 15
        if ($updateColumns === true) {
295 9
            $updateColumns = [];
296 9
            foreach ($updateNames as $name) {
297 9
                $updateColumns[$name] = new Expression('EXCLUDED.' . $this->db->quoteColumnName($name));
298
            }
299
        }
300 15
        list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
301 15
        return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET ' . implode(', ', $updates);
302
    }
303
304
    /**
305
     * [[upsert()]] implementation for PostgreSQL older than 9.5.
306
     * @param string $table
307
     * @param array|Query $insertColumns
308
     * @param array|bool $updateColumns
309
     * @param array $params
310
     * @return string
311
     */
312
    private function oldUpsert($table, $insertColumns, $updateColumns, &$params)
313
    {
314
        /** @var Constraint[] $constraints */
315
        list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
316
        if (empty($uniqueNames)) {
317
            return $this->insert($table, $insertColumns, $params);
318
        }
319
320
        /** @var Schema $schema */
321
        $schema = $this->db->getSchema();
322
        if (!$insertColumns instanceof Query) {
323
            $tableSchema = $schema->getTableSchema($table);
324
            $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
325
            foreach ($insertColumns as $name => $value) {
326
                // NULLs and numeric values must be type hinted in order to be used in SET assigments
327
                // NVM, let's cast them all
328
                if (isset($columnSchemas[$name])) {
329
                    $phName = self::PARAM_PREFIX . count($params);
330
                    $params[$phName] = $value;
331
                    $insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->dbType})");
332
                }
333
            }
334
        }
335
        list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
336
        $updateCondition = ['or'];
337
        $insertCondition = ['or'];
338
        $quotedTableName = $schema->quoteTableName($table);
339
        foreach ($constraints as $constraint) {
340
            $constraintUpdateCondition = ['and'];
341
            $constraintInsertCondition = ['and'];
342
            foreach ($constraint->columnNames as $name) {
0 ignored issues
show
Bug introduced by
The expression $constraint->columnNames of type array<integer,string>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
343
                $quotedName = $schema->quoteColumnName($name);
344
                $constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
345
                $constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName";
346
            }
347
            $updateCondition[] = $constraintUpdateCondition;
348
            $insertCondition[] = $constraintInsertCondition;
349
        }
350
        $withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames)
351
            . ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')';
352
        if ($updateColumns === false) {
353
            $selectSubQuery = (new Query())
354
                ->select(new Expression('1'))
355
                ->from($table)
356
                ->where($updateCondition);
357
            $insertSelectSubQuery = (new Query())
358
                ->select($insertNames)
359
                ->from('EXCLUDED')
360
                ->where(['not exists', $selectSubQuery]);
361
            $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
362
            return "$withSql $insertSql";
363
        }
364
365
        if ($updateColumns === true) {
366
            $updateColumns = [];
367
            foreach ($updateNames as $name) {
368
                $quotedName = $this->db->quoteColumnName($name);
369
                if (strrpos($quotedName, '.') === false) {
370
                    $quotedName = '"EXCLUDED".' . $quotedName;
371
                }
372
                $updateColumns[$name] = new Expression($quotedName);
373
            }
374
        }
375
        list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
376
        $updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates)
377
            . ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params)
378
            . ' RETURNING ' . $this->db->quoteTableName($table) .'.*';
379
        $selectUpsertSubQuery = (new Query())
380
            ->select(new Expression('1'))
381
            ->from('upsert')
382
            ->where($insertCondition);
383
        $insertSelectSubQuery = (new Query())
384
            ->select($insertNames)
385
            ->from('EXCLUDED')
386
            ->where(['not exists', $selectUpsertSubQuery]);
387
        $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
388
        return "$withSql, \"upsert\" AS ($updateSql) $insertSql";
389
    }
390
391
    /**
392
     * {@inheritdoc}
393
     */
394 39
    public function update($table, $columns, $condition, &$params)
395
    {
396 39
        return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
0 ignored issues
show
Bug introduced by
It seems like $this->normalizeTableRowData($table, $columns) targeting yii\db\pgsql\QueryBuilder::normalizeTableRowData() can also be of type object<yii\db\Query>; however, yii\db\QueryBuilder::update() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
397
    }
398
399
    /**
400
     * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
401
     *
402
     * @param string $table the table that data will be saved into.
403
     * @param array|Query $columns the column data (name => value) to be saved into the table or instance
404
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
405
     * Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
406
     * @return array normalized columns
407
     * @since 2.0.9
408
     */
409 201
    private function normalizeTableRowData($table, $columns)
410
    {
411 201
        if ($columns instanceof Query) {
412 14
            return $columns;
413
        }
414
415 193
        if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
416 193
            $columnSchemas = $tableSchema->columns;
417 193
            foreach ($columns as $name => $value) {
418 192
                if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && is_string($value)) {
419 192
                    $columns[$name] = new PdoValue($value, \PDO::PARAM_LOB); // explicitly setup PDO param type for binary column
420
                }
421
            }
422
        }
423
424 193
        return $columns;
425
    }
426
427
    /**
428
     * {@inheritdoc}
429
     */
430 19
    public function batchInsert($table, $columns, $rows, &$params = [])
431
    {
432 19
        if (empty($rows)) {
433 2
            return '';
434
        }
435
436 18
        $schema = $this->db->getSchema();
437 18
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
438 12
            $columnSchemas = $tableSchema->columns;
439
        } else {
440 6
            $columnSchemas = [];
441
        }
442
443 18
        $values = [];
444 18
        foreach ($rows as $row) {
445 17
            $vs = [];
446 17
            foreach ($row as $i => $value) {
447 17
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
448 9
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
449
                }
450 17
                if (is_string($value)) {
451 8
                    $value = $schema->quoteValue($value);
452 12
                } elseif (is_float($value)) {
453
                    // ensure type cast always has . as decimal separator in all locales
454 1
                    $value = StringHelper::floatToString($value);
455 12
                } elseif ($value === true) {
456 4
                    $value = 'TRUE';
457 12
                } elseif ($value === false) {
458 7
                    $value = 'FALSE';
459 9
                } elseif ($value === null) {
460 4
                    $value = 'NULL';
461 6
                } elseif ($value instanceof ExpressionInterface) {
462 5
                    $value = $this->buildExpression($value, $params);
463
                }
464 17
                $vs[] = $value;
465
            }
466 17
            $values[] = '(' . implode(', ', $vs) . ')';
467
        }
468 18
        if (empty($values)) {
469 1
            return '';
470
        }
471
472 17
        foreach ($columns as $i => $name) {
473 16
            $columns[$i] = $schema->quoteColumnName($name);
474
        }
475
476 17
        return 'INSERT INTO ' . $schema->quoteTableName($table)
477 17
        . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
478
    }
479
}
480