Passed
Push — master ( 41bd5a...46e7ad )
by Wilmer
14:55 queued 08:18
created

DMLQueryBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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