Test Failed
Pull Request — master (#142)
by Def
16:45 queued 09:23
created

DMLQueryBuilder::upsert()   C

Complexity

Conditions 13
Paths 109

Size

Total Lines 98
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 55
CRAP Score 13

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 52
c 1
b 0
f 0
nc 109
nop 4
dl 0
loc 98
ccs 55
cts 55
cp 1
crap 13
rs 6.5416

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
        $usingValues = null;
99 21
        $constraints = [];
100
101
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
102 34
            $table,
103 10
            $insertColumns,
104
            $updateColumns,
105
            $constraints
106 34
        );
107 34
108
        if (empty($uniqueNames)) {
109 34
            return $this->insert($table, $insertColumns, $params);
110 34
        }
111 34
112 34
        if ($updateNames === []) {
0 ignored issues
show
introduced by
The condition $updateNames === array() is always false.
Loading history...
113 34
            /** there are no columns to update */
114 34
            $updateColumns = false;
115
        }
116 34
117 2
        $onCondition = ['or'];
118
        $quotedTableName = $this->quoter->quoteTableName($table);
119
120 32
        foreach ($constraints as $constraint) {
121
            $columnNames = $constraint->getColumnNames() ?? [];
122 2
            $constraintCondition = ['and'];
123
            /** @psalm-var string[] $columnNames */
124
            foreach ($columnNames as $name) {
125 32
                $quotedName = $this->quoter->quoteColumnName($name);
126 32
                $constraintCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
127
            }
128 32
129 32
            $onCondition[] = $constraintCondition;
130 32
        }
131
132 32
        $on = $this->queryBuilder->buildCondition($onCondition, $params);
133 32
        /** @psalm-var string[] $placeholders */
134 32
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
135
136
        if (!empty($placeholders)) {
137 32
            $usingSelectValues = [];
138
            /** @psalm-var string[] $insertNames */
139
            foreach ($insertNames as $index => $name) {
140 32
                $usingSelectValues[$name] = new Expression($placeholders[$index]);
141
            }
142 32
143
            /** @psalm-var array $params */
144 32
            $usingValues = $this->queryBuilder->buildSelect($usingSelectValues, $params) . ' ' . $this->queryBuilder->buildFrom(['DUAL'], $params);
145 19
        }
146
147 19
        $insertValues = [];
148 19
        $mergeSql = 'MERGE INTO '
149
            . $this->quoter->quoteTableName($table)
150
            . ' '
151
            . 'USING (' . ($usingValues ?? ltrim((string) $values, ' '))
152 19
            . ') "EXCLUDED" '
153
            . "ON ($on)";
154
155 32
        /** @psalm-var string[] $insertNames */
156 32
        foreach ($insertNames as $name) {
157 32
            $quotedName = $this->quoter->quoteColumnName($name);
158 32
159 32
            if (strrpos($quotedName, '.') === false) {
160 32
                $quotedName = '"EXCLUDED".' . $quotedName;
161 32
            }
162
163
            $insertValues[] = $quotedName;
164 32
        }
165 32
166
        $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')' . ' VALUES (' . implode(', ', $insertValues) . ')';
167 32
168 32
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
169
            return "$mergeSql WHEN NOT MATCHED THEN $insertSql";
170
        }
171 32
172
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
173
            $updateColumns = [];
174 32
            /** @psalm-var string[] $updateNames */
175
            foreach ($updateNames as $name) {
176 32
                $quotedName = $this->quoter->quoteColumnName($name);
177 14
178
                if (strrpos($quotedName, '.') === false) {
179
                    $quotedName = '"EXCLUDED".' . $quotedName;
180 18
                }
181 8
                $updateColumns[$name] = new Expression($quotedName);
182
            }
183 8
        }
184 8
185
        /** @psalm-var string[] $updates */
186 8
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, (array) $params);
187 8
        $updateSql = 'UPDATE SET ' . implode(', ', $updates);
188
189 8
        return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql";
190
    }
191
192
    protected function prepareInsertValues(string $table, array|QueryInterface $columns, array $params = []): array
193
    {
194 18
        /**
195 18
         * @var array $names
196
         * @var array $placeholders
197 18
         */
198
        [$names, $placeholders, $values, $params] = parent::prepareInsertValues($table, $columns, $params);
199
200 66
        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...
201
            $tableSchema = $this->schema->getTableSchema($table);
202
203
            if ($tableSchema !== null) {
204
                $tableColumns = $tableSchema->getColumns();
205
                $columns = !empty($tableSchema->getPrimaryKey())
206 66
                    ? $tableSchema->getPrimaryKey() : [reset($tableColumns)->getName()];
207
                foreach ($columns as $name) {
208 63
                    /** @var mixed */
209 1
                    $names[] = $this->quoter->quoteColumnName($name);
210
                    $placeholders[] = 'DEFAULT';
211 1
                }
212 1
            }
213 1
        }
214 1
215 1
        return [$names, $placeholders, $values, $params];
216
    }
217 1
218 1
    /**
219
     * @throws InvalidArgumentException
220
     */
221
    public function resetSequence(string $tableName, int|string $value = null): string
222
    {
223 63
        $tableSchema = $this->schema->getTableSchema($tableName);
224
225
        if ($tableSchema === null) {
226
            throw new InvalidArgumentException("Table not found: '$tableName'.");
227
        }
228
229 4
        $sequenceName = $tableSchema->getSequenceName();
230
231 4
        if ($sequenceName === null) {
232
            throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
233 4
        }
234 1
235
        if ($value === null && count($tableSchema->getPrimaryKey()) > 1) {
236
            throw new InvalidArgumentException("Can't reset sequence for composite primary key in table: $tableName");
237 3
        }
238
239 3
        /**
240 1
         * Oracle needs at least many queries to reset sequence (see adding transactions and/or use alter method to
241
         * avoid grants issue?)
242
         */
243 2
        return 'declare
244 1
    lastSeq number' . ($value !== null ? (' := ' . $value) : '') . ';
245
begin' . ($value === null ? '
246
    SELECT MAX("' . $tableSchema->getPrimaryKey()[0] . '") + 1 INTO lastSeq FROM "' . $tableSchema->getName() . '";' : '') . '
247
    if lastSeq IS NULL then lastSeq := 1; end if;
248
    execute immediate \'DROP SEQUENCE "' . $sequenceName . '"\';
249
    execute immediate \'CREATE SEQUENCE "' . $sequenceName . '" START WITH \' || lastSeq || \' INCREMENT BY 1 NOMAXVALUE NOCACHE\';
250
end;';
251 1
    }
252
}
253