Test Failed
Push — change-visibility-abstractdmlq... ( 8490d3 )
by Wilmer
29:18 queued 22:35
created

DMLQueryBuilder   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 230
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 103
c 2
b 0
f 0
dl 0
loc 230
rs 9.52
wmc 36

5 Methods

Rating   Name   Duplication   Size   Complexity  
A insertWithReturningPks() 0 3 1
B batchInsert() 0 45 9
C upsert() 0 98 13
B resetSequence() 0 29 7
A prepareInsertValues() 0 24 6
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
    public function batchInsert(string $table, array $columns, iterable|Generator $rows, array &$params = []): string
38
    {
39
        if (empty($rows)) {
40
            return '';
41
        }
42
43
        if (($tableSchema = $this->schema->getTableSchema($table)) !== null) {
0 ignored issues
show
Bug introduced by
The property schema is declared private in Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder and cannot be accessed from this context.
Loading history...
44
            $columnSchemas = $tableSchema->getColumns();
45
        } else {
46
            $columnSchemas = [];
47
        }
48
49
        $mappedNames = $this->getNormalizeColumnNames($table, $columns);
50
        $values = [];
51
52
        /** @psalm-var array<array-key, array<array-key, string>> $rows */
53
        foreach ($rows as $row) {
54
            $placeholders = [];
55
            foreach ($row as $index => $value) {
56
                if (isset($columns[$index], $mappedNames[$columns[$index]], $columnSchemas[$mappedNames[$columns[$index]]])) {
57
                    /** @var mixed $value */
58
                    $value = $this->getTypecastValue($value, $columnSchemas[$mappedNames[$columns[$index]]]);
59
                }
60
61
                if ($value instanceof ExpressionInterface) {
62
                    $placeholders[] = $this->queryBuilder->buildExpression($value, $params);
0 ignored issues
show
Bug introduced by
The property queryBuilder is declared private in Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder and cannot be accessed from this context.
Loading history...
63
                } else {
64
                    $placeholders[] = $this->queryBuilder->bindParam($value, $params);
65
                }
66
            }
67
            $values[] = '(' . implode(', ', $placeholders) . ')';
68
        }
69
70
        if (empty($values)) {
71
            return '';
72
        }
73
74
        foreach ($columns as $i => $name) {
75
            $columns[$i] = $this->quoter->quoteColumnName($mappedNames[$name]);
0 ignored issues
show
Bug introduced by
The property quoter is declared private in Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder and cannot be accessed from this context.
Loading history...
76
        }
77
78
        $tableAndColumns = ' INTO ' . $this->quoter->quoteTableName($table)
79
            . ' (' . implode(', ', $columns) . ') VALUES ';
80
81
        return 'INSERT ALL ' . $tableAndColumns . implode($tableAndColumns, $values) . ' SELECT 1 FROM SYS.DUAL';
82
    }
83
84
    /**
85
     * @throws Exception
86
     * @throws NotSupportedException
87
     */
88
    public function insertWithReturningPks(string $table, QueryInterface|array $columns, array &$params = []): string
89
    {
90
        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
    public function upsert(
103
        string $table,
104
        QueryInterface|array $insertColumns,
105
        array|bool $updateColumns,
106
        array &$params = []
107
    ): string {
108
        $usingValues = null;
109
        $constraints = [];
110
111
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
112
            $table,
113
            $insertColumns,
114
            $updateColumns,
115
            $constraints
116
        );
117
118
        if (empty($uniqueNames)) {
119
            return $this->insert($table, $insertColumns, $params);
120
        }
121
122
        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
            $updateColumns = false;
125
        }
126
127
        $onCondition = ['or'];
128
        $quotedTableName = $this->quoter->quoteTableName($table);
0 ignored issues
show
Bug introduced by
The property quoter is declared private in Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder and cannot be accessed from this context.
Loading history...
129
130
        foreach ($constraints as $constraint) {
131
            $columnNames = $constraint->getColumnNames() ?? [];
132
            $constraintCondition = ['and'];
133
            /** @psalm-var string[] $columnNames */
134
            foreach ($columnNames as $name) {
135
                $quotedName = $this->quoter->quoteColumnName($name);
136
                $constraintCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
137
            }
138
139
            $onCondition[] = $constraintCondition;
140
        }
141
142
        $on = $this->queryBuilder->buildCondition($onCondition, $params);
0 ignored issues
show
Bug introduced by
The property queryBuilder is declared private in Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder and cannot be accessed from this context.
Loading history...
143
        /** @psalm-var string[] $placeholders */
144
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
145
146
        if (!empty($placeholders)) {
147
            $usingSelectValues = [];
148
            /** @psalm-var string[] $insertNames */
149
            foreach ($insertNames as $index => $name) {
150
                $usingSelectValues[$name] = new Expression($placeholders[$index]);
151
            }
152
153
            /** @psalm-var array $params */
154
            $usingValues = $this->queryBuilder->buildSelect($usingSelectValues, $params) . ' ' . $this->queryBuilder->buildFrom(['DUAL'], $params);
155
        }
156
157
        $insertValues = [];
158
        $mergeSql = 'MERGE INTO '
159
            . $this->quoter->quoteTableName($table)
160
            . ' '
161
            . 'USING (' . ($usingValues ?? ltrim((string) $values, ' '))
162
            . ') "EXCLUDED" '
163
            . "ON ($on)";
164
165
        /** @psalm-var string[] $insertNames */
166
        foreach ($insertNames as $name) {
167
            $quotedName = $this->quoter->quoteColumnName($name);
168
169
            if (strrpos($quotedName, '.') === false) {
170
                $quotedName = '"EXCLUDED".' . $quotedName;
171
            }
172
173
            $insertValues[] = $quotedName;
174
        }
175
176
        $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')' . ' VALUES (' . implode(', ', $insertValues) . ')';
177
178
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
179
            return "$mergeSql WHEN NOT MATCHED THEN $insertSql";
180
        }
181
182
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
183
            $updateColumns = [];
184
            /** @psalm-var string[] $updateNames */
185
            foreach ($updateNames as $name) {
186
                $quotedName = $this->quoter->quoteColumnName($name);
187
188
                if (strrpos($quotedName, '.') === false) {
189
                    $quotedName = '"EXCLUDED".' . $quotedName;
190
                }
191
                $updateColumns[$name] = new Expression($quotedName);
192
            }
193
        }
194
195
        /** @psalm-var string[] $updates */
196
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, (array) $params);
197
        $updateSql = 'UPDATE SET ' . implode(', ', $updates);
198
199
        return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql";
200
    }
201
202
    protected function prepareInsertValues(string $table, array|QueryInterface $columns, array $params = []): array
203
    {
204
        /**
205
         * @var array $names
206
         * @var array $placeholders
207
         */
208
        [$names, $placeholders, $values, $params] = parent::prepareInsertValues($table, $columns, $params);
209
210
        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
            $tableSchema = $this->schema->getTableSchema($table);
0 ignored issues
show
Bug introduced by
The property schema is declared private in Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder and cannot be accessed from this context.
Loading history...
212
213
            if ($tableSchema !== null) {
214
                $tableColumns = $tableSchema->getColumns();
215
                $columns = !empty($tableSchema->getPrimaryKey())
216
                    ? $tableSchema->getPrimaryKey() : [reset($tableColumns)->getName()];
217
                foreach ($columns as $name) {
218
                    /** @psalm-var mixed */
219
                    $names[] = $this->quoter->quoteColumnName($name);
0 ignored issues
show
Bug introduced by
The property quoter is declared private in Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder and cannot be accessed from this context.
Loading history...
220
                    $placeholders[] = 'DEFAULT';
221
                }
222
            }
223
        }
224
225
        return [$names, $placeholders, $values, $params];
226
    }
227
228
    public function resetSequence(string $tableName, int|string $value = null): string
229
    {
230
        $tableSchema = $this->schema->getTableSchema($tableName);
0 ignored issues
show
Bug introduced by
The property schema is declared private in Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder and cannot be accessed from this context.
Loading history...
231
232
        if ($tableSchema === null) {
233
            throw new InvalidArgumentException("Table not found: '$tableName'.");
234
        }
235
236
        $sequenceName = $tableSchema->getSequenceName();
237
238
        if ($sequenceName === null) {
239
            throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
240
        }
241
242
        if ($value === null && count($tableSchema->getPrimaryKey()) > 1) {
243
            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
        return 'declare
251
    lastSeq number' . ($value !== null ? (' := ' . $value) : '') . ';
252
begin' . ($value === null ? '
253
    SELECT MAX("' . $tableSchema->getPrimaryKey()[0] . '") + 1 INTO lastSeq FROM "' . $tableSchema->getName() . '";' : '') . '
254
    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
    }
259
}
260