Passed
Push — add-more-tests ( 149556...e75ca0 )
by Wilmer
18:22 queued 12:10
created

DMLQueryBuilder::upsert()   F

Complexity

Conditions 15
Paths 436

Size

Total Lines 106
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 58
CRAP Score 15

Importance

Changes 0
Metric Value
cc 15
eloc 56
nc 436
nop 4
dl 0
loc 106
ccs 58
cts 58
cp 1
crap 15
rs 2.5333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Oracle;
6
7
use Generator;
8
use JsonException;
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\Expression;
14
use Yiisoft\Db\Expression\ExpressionInterface;
15
use Yiisoft\Db\QueryBuilder\DMLQueryBuilder as AbstractDMLQueryBuilder;
16
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
17
use Yiisoft\Db\Query\QueryInterface;
18
use Yiisoft\Db\Schema\QuoterInterface;
19
use Yiisoft\Db\Schema\SchemaInterface;
20
21
use function implode;
22
use function ltrim;
23
use function strrpos;
24
use function count;
25
use function reset;
26
27
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
28
{
29 479
    public function __construct(
30
        private QueryBuilderInterface $queryBuilder,
31
        private QuoterInterface $quoter,
32
        private SchemaInterface $schema
33
    ) {
34 479
        parent::__construct($queryBuilder, $quoter, $schema);
35
    }
36
37
    /**
38
     * @psalm-suppress MixedArrayOffset
39
     */
40 15
    public function batchInsert(string $table, array $columns, iterable|Generator $rows, array &$params = []): string
41
    {
42 15
        if (empty($rows)) {
43 1
            return '';
44
        }
45
46 14
        if (($tableSchema = $this->schema->getTableSchema($table)) !== null) {
47 14
            $columnSchemas = $tableSchema->getColumns();
48
        } else {
49
            $columnSchemas = [];
50
        }
51
52 14
        $mappedNames = $this->getNormalizeColumnNames($table, $columns);
53 14
        $values = [];
54
55
        /** @psalm-var array<array-key, array<array-key, string>> $rows */
56 14
        foreach ($rows as $row) {
57 14
            $placeholders = [];
58 14
            foreach ($row as $index => $value) {
59 14
                if (isset($columns[$index], $mappedNames[$columns[$index]], $columnSchemas[$mappedNames[$columns[$index]]])) {
60
                    /** @var mixed $value */
61 13
                    $value = $this->getTypecastValue($value, $columnSchemas[$mappedNames[$columns[$index]]]);
62
                }
63
64 14
                if ($value instanceof ExpressionInterface) {
65 3
                    $placeholders[] = $this->queryBuilder->buildExpression($value, $params);
66
                } else {
67 14
                    $placeholders[] = $this->queryBuilder->bindParam($value, $params);
68
                }
69
            }
70 14
            $values[] = '(' . implode(', ', $placeholders) . ')';
71
        }
72
73 14
        if (empty($values)) {
74
            return '';
75
        }
76
77 14
        foreach ($columns as $i => $name) {
78 13
            $columns[$i] = $this->quoter->quoteColumnName($mappedNames[$name]);
79
        }
80
81 14
        $tableAndColumns = ' INTO ' . $this->quoter->quoteTableName($table)
82 14
            . ' (' . implode(', ', $columns) . ') VALUES ';
83
84 14
        return 'INSERT ALL ' . $tableAndColumns . implode($tableAndColumns, $values) . ' SELECT 1 FROM SYS.DUAL';
85
    }
86
87
    /**
88
     * @link https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606
89
     *
90
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
91
     */
92 34
    public function upsert(
93
        string $table,
94
        QueryInterface|array $insertColumns,
95
        array|bool $updateColumns,
96
        array &$params = []
97
    ): string {
98 34
        if (!$insertColumns instanceof QueryInterface) {
0 ignored issues
show
introduced by
$insertColumns is never a sub-type of Yiisoft\Db\Query\QueryInterface.
Loading history...
99 21
            $insertColumns = $this->normalizeColumnNames($table, $insertColumns);
100
        }
101
102 34
        if (!is_bool($updateColumns)) {
0 ignored issues
show
introduced by
The condition is_bool($updateColumns) is always false.
Loading history...
103 10
            $updateColumns = $this->normalizeColumnNames($table, $updateColumns);
104
        }
105
106 34
        $usingValues = null;
107 34
        $constraints = [];
108
109 34
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
110 34
            $table,
111 34
            $insertColumns,
112 34
            $updateColumns,
113 34
            $constraints
114 34
        );
115
116 34
        if (empty($uniqueNames)) {
117 2
            return $this->insert($table, $insertColumns, $params);
118
        }
119
120 32
        if ($updateNames === []) {
0 ignored issues
show
introduced by
The condition $updateNames === array() is always false.
Loading history...
121
            /** there are no columns to update */
122 2
            $updateColumns = false;
123
        }
124
125 32
        $onCondition = ['or'];
126 32
        $quotedTableName = $this->quoter->quoteTableName($table);
127
128 32
        foreach ($constraints as $constraint) {
129 32
            $columnNames = $constraint->getColumnNames() ?? [];
130 32
            $constraintCondition = ['and'];
131
            /** @psalm-var string[] $columnNames */
132 32
            foreach ($columnNames as $name) {
133 32
                $quotedName = $this->quoter->quoteColumnName($name);
134 32
                $constraintCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
135
            }
136
137 32
            $onCondition[] = $constraintCondition;
138
        }
139
140 32
        $on = $this->queryBuilder->buildCondition($onCondition, $params);
141
        /** @psalm-var string[] $placeholders */
142 32
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
143
144 32
        if (!empty($placeholders)) {
145 19
            $usingSelectValues = [];
146
            /** @psalm-var string[] $insertNames */
147 19
            foreach ($insertNames as $index => $name) {
148 19
                $usingSelectValues[$name] = new Expression($placeholders[$index]);
149
            }
150
151
            /** @psalm-var array $params */
152 19
            $usingValues = $this->queryBuilder->buildSelect($usingSelectValues, $params) . ' ' . $this->queryBuilder->buildFrom(['DUAL'], $params);
153
        }
154
155 32
        $insertValues = [];
156 32
        $mergeSql = 'MERGE INTO '
157 32
            . $this->quoter->quoteTableName($table)
158 32
            . ' '
159 32
            . 'USING (' . ($usingValues ?? ltrim((string) $values, ' '))
160 32
            . ') "EXCLUDED" '
161 32
            . "ON ($on)";
162
163
        /** @psalm-var string[] $insertNames */
164 32
        foreach ($insertNames as $name) {
165 32
            $quotedName = $this->quoter->quoteColumnName($name);
166
167 32
            if (strrpos($quotedName, '.') === false) {
168 32
                $quotedName = '"EXCLUDED".' . $quotedName;
169
            }
170
171 32
            $insertValues[] = $quotedName;
172
        }
173
174 32
        $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')' . ' VALUES (' . implode(', ', $insertValues) . ')';
175
176 32
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
177 14
            return "$mergeSql WHEN NOT MATCHED THEN $insertSql";
178
        }
179
180 18
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
181 8
            $updateColumns = [];
182
            /** @psalm-var string[] $updateNames */
183 8
            foreach ($updateNames as $name) {
184 8
                $quotedName = $this->quoter->quoteColumnName($name);
185
186 8
                if (strrpos($quotedName, '.') === false) {
187 8
                    $quotedName = '"EXCLUDED".' . $quotedName;
188
                }
189 8
                $updateColumns[$name] = new Expression($quotedName);
190
            }
191
        }
192
193
        /** @psalm-var string[] $updates */
194 18
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, (array) $params);
195 18
        $updateSql = 'UPDATE SET ' . implode(', ', $updates);
196
197 18
        return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql";
198
    }
199
200 66
    protected function prepareInsertValues(string $table, array|QueryInterface $columns, array $params = []): array
201
    {
202
        /**
203
         * @var array $names
204
         * @var array $placeholders
205
         */
206 66
        [$names, $placeholders, $values, $params] = parent::prepareInsertValues($table, $columns, $params);
207
208 63
        if (!$columns instanceof QueryInterface && empty($names)) {
0 ignored issues
show
introduced by
$columns is never a sub-type of Yiisoft\Db\Query\QueryInterface.
Loading history...
209 1
            $tableSchema = $this->schema->getTableSchema($table);
210
211 1
            if ($tableSchema !== null) {
212 1
                $tableColumns = $tableSchema->getColumns();
213 1
                $columns = !empty($tableSchema->getPrimaryKey())
214 1
                    ? $tableSchema->getPrimaryKey() : [reset($tableColumns)->getName()];
215 1
                foreach ($columns as $name) {
216
                    /** @var mixed */
217 1
                    $names[] = $this->quoter->quoteColumnName($name);
218 1
                    $placeholders[] = 'DEFAULT';
219
                }
220
            }
221
        }
222
223 63
        return [$names, $placeholders, $values, $params];
224
    }
225
226
    /**
227
     * @throws InvalidArgumentException
228
     */
229 4
    public function resetSequence(string $tableName, int|string $value = null): string
230
    {
231 4
        $tableSchema = $this->schema->getTableSchema($tableName);
232
233 4
        if ($tableSchema === null) {
234 1
            throw new InvalidArgumentException("Table not found: '$tableName'.");
235
        }
236
237 3
        $sequenceName = $tableSchema->getSequenceName();
238
239 3
        if ($sequenceName === null) {
240 1
            throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
241
        }
242
243 2
        if ($value === null && count($tableSchema->getPrimaryKey()) > 1) {
244 1
            throw new InvalidArgumentException("Can't reset sequence for composite primary key in table: $tableName");
245
        }
246
247
        /**
248
         * Oracle needs at least many queries to reset sequence (see adding transactions and/or use alter method to
249
         * avoid grants issue?)
250
         */
251 1
        return 'declare
252 1
    lastSeq number' . ($value !== null ? (' := ' . $value) : '') . ';
253 1
begin' . ($value === null ? '
254 1
    SELECT MAX("' . $tableSchema->getPrimaryKey()[0] . '") + 1 INTO lastSeq FROM "' . $tableSchema->getName() . '";' : '') . '
255
    if lastSeq IS NULL then lastSeq := 1; end if;
256 1
    execute immediate \'DROP SEQUENCE "' . $sequenceName . '"\';
257 1
    execute immediate \'CREATE SEQUENCE "' . $sequenceName . '" START WITH \' || lastSeq || \' INCREMENT BY 1 NOMAXVALUE NOCACHE\';
258 1
end;';
259
    }
260
}
261