Test Failed
Pull Request — master (#93)
by Def
60:00 queued 28:25
created

DMLQueryBuilder::batchInsert()   B

Complexity

Conditions 9
Paths 37

Size

Total Lines 45
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 9.0058

Importance

Changes 0
Metric Value
cc 9
eloc 24
nc 37
nop 4
dl 0
loc 45
ccs 23
cts 24
cp 0.9583
crap 9.0058
rs 8.0555
c 0
b 0
f 0
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
    public function __construct(
30
        private QueryBuilderInterface $queryBuilder,
31 347
        private QuoterInterface $quoter,
32
        private SchemaInterface $schema
33
    ) {
34
        parent::__construct($queryBuilder, $quoter, $schema);
35
    }
36 347
37
    /**
38
     * @psalm-suppress MixedArrayOffset
39
     */
40
    public function batchInsert(string $table, array $columns, iterable|Generator $rows, array &$params = []): string
41
    {
42 15
        if (empty($rows)) {
43
            return '';
44 15
        }
45 2
46
        if (($tableSchema = $this->schema->getTableSchema($table)) !== null) {
47
            $columnSchemas = $tableSchema->getColumns();
48 14
        } else {
49
            $columnSchemas = [];
50 14
        }
51 14
52
        $values = [];
53
54
        /** @psalm-var array<array-key, array<array-key, string>> $rows */
55
        foreach ($rows as $row) {
56 14
            $placeholders = [];
57
            foreach ($row as $index => $value) {
58
                if (isset($columns[$index], $columnSchemas[$columns[$index]])) {
59 14
                    /** @var mixed $value */
60 14
                    $value = $this->getTypecastValue($value, $columnSchemas[$columns[$index]]);
0 ignored issues
show
Bug introduced by
The method getTypecastValue() does not exist on Yiisoft\Db\Oracle\DMLQueryBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

60
                    /** @scrutinizer ignore-call */ 
61
                    $value = $this->getTypecastValue($value, $columnSchemas[$columns[$index]]);

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