Passed
Push — temp ( 9bb6e0 )
by Wilmer
24:48 queued 12:24
created

DMLQueryBuilder   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 287
Duplicated Lines 0 %

Test Coverage

Coverage 91.04%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 66
dl 0
loc 287
ccs 61
cts 67
cp 0.9104
rs 10
c 2
b 0
f 0
wmc 29

9 Methods

Rating   Name   Duplication   Size   Complexity  
A insert() 0 3 1
A insertEx() 0 20 4
A __construct() 0 6 1
A newUpsert() 0 49 6
B normalizeTableRowData() 0 22 7
A upsert() 0 13 2
A resetSequence() 0 25 5
A update() 0 9 2
A truncateTable() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql;
6
7
use JsonException;
8
use PDO;
9
use Yiisoft\Db\Command\Param;
10
use Yiisoft\Db\Exception\Exception;
11
use Yiisoft\Db\Exception\InvalidArgumentException;
12
use Yiisoft\Db\Exception\InvalidConfigException;
13
use Yiisoft\Db\Exception\NotSupportedException;
14
use Yiisoft\Db\Expression\Expression;
15
use Yiisoft\Db\QueryBuilder\DMLQueryBuilder as AbstractDMLQueryBuilder;
16
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
17
use Yiisoft\Db\Query\Query;
18
use Yiisoft\Db\Query\QueryInterface;
19
use Yiisoft\Db\Schema\QuoterInterface;
20
use Yiisoft\Db\Schema\Schema;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Yiisoft\Db\Pgsql\Schema. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
21
use Yiisoft\Db\Schema\SchemaInterface;
22
23
use function implode;
24
use function is_array;
25
use function is_string;
26
use function reset;
27
28
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
29
{
30 422
    public function __construct(
31
        private QueryBuilderInterface $queryBuilder,
32
        private QuoterInterface $quoter,
33
        private SchemaInterface $schema
34
    ) {
35 422
        parent::__construct($queryBuilder, $quoter, $schema);
36
    }
37
38 1
    public function insertEx(string $table, QueryInterface|array $columns, array &$params = []): string
39
    {
40 1
        $sql = $this->insert($table, $columns, $params);
41
42 1
        $tableSchema = $this->schema->getTableSchema($table);
43
44 1
        $returnColumns = [];
45 1
        if ($tableSchema !== null) {
46 1
            $returnColumns = $tableSchema->getPrimaryKey();
47
        }
48
49 1
        if (!empty($returnColumns)) {
50 1
            $returning = [];
51 1
            foreach ($returnColumns as $name) {
52 1
                $returning[] = $this->quoter->quoteColumnName($name);
53
            }
54 1
            $sql .= ' RETURNING ' . implode(', ', $returning);
55
        }
56
57 1
        return $sql;
58
    }
59
60
    /**
61
     * Creates an INSERT SQL statement.
62
     *
63
     * For example,
64
     *
65
     * ```php
66
     * $sql = $queryBuilder->insert('user', [
67
     *     'name' => 'Sam',
68
     *     'age' => 30,
69
     * ], $params);
70
     * ```
71
     *
72
     * The method will properly escape the table and column names.
73
     *
74
     * @param string $table the table that new rows will be inserted into.
75
     * @param array|QueryInterface $columns the column data (name => value) to be inserted into the table or instance of
76
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement. Passing of {@see Query}.
77
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the
78
     * DB command later.
79
     *
80
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
81
     *
82
     * @return string the INSERT SQL
83
     *
84
     * @psalm-suppress UndefinedInterfaceMethod
85
     * @psalm-suppress MixedArgument
86
     */
87 50
    public function insert(string $table, QueryInterface|array $columns, array &$params = []): string
88
    {
89 50
        return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
90
    }
91
92
    /**
93
     * {@see upsert()} implementation for PostgresSQL 9.5 or higher.
94
     *
95
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
96
     */
97 18
    public function newUpsert(
98
        string $table,
99
        QueryInterface|array $insertColumns,
100
        bool|array|QueryInterface $updateColumns,
101
        array &$params = []
102
    ): string {
103 18
        $insertSql = $this->insert($table, $insertColumns, $params);
104
105
        /** @var array $uniqueNames */
106 18
        [$uniqueNames, , $updateNames] = $this->prepareUpsertColumns(
107
            $table,
108
            $insertColumns,
109
            $updateColumns,
110
        );
111
112 18
        if (empty($uniqueNames)) {
113 3
            return $insertSql;
114
        }
115
116 15
        if ($updateNames === []) {
0 ignored issues
show
introduced by
The condition $updateNames === array() is always false.
Loading history...
117
            /** there are no columns to update */
118
            $updateColumns = false;
119
        }
120
121 15
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
122 5
            return "$insertSql ON CONFLICT DO NOTHING";
123
        }
124
125 10
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
126 4
            $updateColumns = [];
127
128
            /** @var string $name */
129 4
            foreach ($updateNames as $name) {
130 4
                $updateColumns[$name] = new Expression(
131 4
                    'EXCLUDED.' . $this->quoter->quoteColumnName($name)
132
                );
133
            }
134
        }
135
136
        /**
137
         * @var array $updateColumns
138
         *
139
         * @psalm-var string[] $uniqueNames
140
         * @psalm-var string[] $updates
141
         */
142 10
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
143
144
        return $insertSql
145 10
            . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET ' . implode(', ', $updates);
146
    }
147
148
    /**
149
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
150
     *
151
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
152
     * or 1.
153
     *
154
     * @param string $tableName the name of the table whose primary key sequence will be reset.
155
     * @param int|string|null $value the value for the primary key of the next new row inserted. If this is not set, the
156
     * next new row's primary key will have a value 1.
157
     *
158
     * @throws Exception|InvalidArgumentException if the table does not exist or there is no sequence
159
     * associated with the table.
160
     *
161
     * @return string the SQL statement for resetting sequence.
162
     */
163 2
    public function resetSequence(string $tableName, int|string $value = null): string
164
    {
165 2
        $table = $this->schema->getTableSchema($tableName);
166
167 2
        if ($table !== null && ($sequence = $table->getSequenceName()) !== null) {
168
            /**
169
             * {@see http://www.postgresql.org/docs/8.1/static/functions-sequence.html}
170
             */
171 2
            $sequence = $this->quoter->quoteTableName($sequence);
172 2
            $tableName = $this->quoter->quoteTableName($tableName);
173
174 2
            if ($value === null) {
175 2
                $pk = $table->getPrimaryKey();
176 2
                $key = $this->quoter->quoteColumnName(reset($pk));
177 2
                $value = "(SELECT COALESCE(MAX($key),0) FROM $tableName)+1";
178
            }
179
180 2
            return "SELECT SETVAL('$sequence',$value,false)";
181
        }
182
183
        if ($table === null) {
184
            throw new InvalidArgumentException("Table not found: $tableName");
185
        }
186
187
        throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
188
    }
189
190
    public function truncateTable(string $table): string
191
    {
192
        return 'TRUNCATE TABLE ' . $this->quoter->quoteTableName($table) . ' RESTART IDENTITY';
193
    }
194
195
    /**
196
     * Creates an UPDATE SQL statement.
197
     *
198
     * For example,
199
     *
200
     * ```php
201
     * $params = [];
202
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
203
     * ```
204
     *
205
     * The method will properly escape the table and column names.
206
     *
207
     * @param string $table the table to be updated.
208
     * @param array $columns the column data (name => value) to be updated.
209
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
210
     * {@see Query::where()} on how to specify condition.
211
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
212
     * DB command later.
213
     *
214
     * @return string the UPDATE SQL.
215
     *
216
     * @psalm-suppress UndefinedInterfaceMethod
217
     */
218 4
    public function update(string $table, array $columns, array|string $condition, array &$params = []): string
219
    {
220 4
        $normalizeTableRowData = $this->normalizeTableRowData($table, $columns);
221
222 4
        return parent::update(
223
            $table,
224 4
            is_array($normalizeTableRowData) ? $normalizeTableRowData : [],
0 ignored issues
show
introduced by
The condition is_array($normalizeTableRowData) is always true.
Loading history...
225
            $condition,
226
            $params,
227
        );
228
    }
229
230
    /**
231
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
232
     * constraints), or update them if they do.
233
     *
234
     * For example,
235
     *
236
     * ```php
237
     * $sql = $queryBuilder->upsert('pages', [
238
     *     'name' => 'Front page',
239
     *     'url' => 'http://example.com/', // url is unique
240
     *     'visits' => 0,
241
     * ], [
242
     *     'visits' => new \Yiisoft\Db\Expression('visits + 1'),
243
     * ], $params);
244
     * ```
245
     *
246
     * The method will properly escape the table and column names.
247
     *
248
     * @param string $table the table that new rows will be inserted into/updated in.
249
     * @param array|QueryInterface $insertColumns the column data (name => value) to be inserted into the table or
250
     * instance of {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
251
     * @param array|bool|QueryInterface $updateColumns the column data (name => value) to be updated if they already
252
     * exist.
253
     * If `true` is passed, the column data will be updated to match the insert column data.
254
     * If `false` is passed, no update will be performed if the column data already exists.
255
     * @param array $params the binding parameters that will be generated by this method.
256
     * They should be bound to the DB command later.
257
     *
258
     * @throws Exception|InvalidConfigException|JsonException|NotSupportedException if this is not supported by the
259
     * underlying DBMS.
260
     *
261
     * @return string the resulting SQL.
262
     *
263
     * @link https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT
264
     * @link https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291
265
     *
266
     * @psalm-suppress UndefinedInterfaceMethod
267
     */
268 18
    public function upsert(
269
        string $table,
270
        QueryInterface|array $insertColumns,
271
        $updateColumns,
272
        array &$params = []
273
    ): string {
274 18
        $insertColumns = $this->normalizeTableRowData($table, $insertColumns);
275
276 18
        if (!is_bool($updateColumns)) {
277 7
            $updateColumns = $this->normalizeTableRowData($table, $updateColumns);
278
        }
279
280 18
        return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
281
    }
282
283
    /**
284
     * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
285
     *
286
     * @param string $table the table that data will be saved into.
287
     * @param array|QueryInterface $columns the column data (name => value) to be saved into the table or instance of
288
     * {@see QueryInterface} to perform INSERT INTO ... SELECT SQL statement. Passing of
289
     * {@see QueryInterface}.
290
     *
291
     * @return array|QueryInterface normalized columns.
292
     */
293 52
    private function normalizeTableRowData(string $table, QueryInterface|array $columns): QueryInterface|array
294
    {
295 52
        if ($columns instanceof QueryInterface) {
0 ignored issues
show
introduced by
$columns is never a sub-type of Yiisoft\Db\Query\QueryInterface.
Loading history...
296 14
            return $columns;
297
        }
298
299 44
        if (($tableSchema = $this->schema->getTableSchema($table)) !== null) {
300 44
            $columnSchemas = $tableSchema->getColumns();
301
            /** @var mixed $value */
302 44
            foreach ($columns as $name => $value) {
303
                if (
304 44
                    isset($columnSchemas[$name]) &&
305 44
                    $columnSchemas[$name]->getType() === Schema::TYPE_BINARY &&
306 44
                    is_string($value)
307
                ) {
308
                    /** explicitly setup PDO param type for binary column */
309 3
                    $columns[$name] = new Param($value, PDO::PARAM_LOB);
310
                }
311
            }
312
        }
313
314 44
        return $columns;
315
    }
316
}
317