Test Failed
Pull Request — master (#233)
by Sergei
19:07 queued 02:48
created

DMLQueryBuilder   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 207
Duplicated Lines 0 %

Test Coverage

Coverage 98.94%

Importance

Changes 6
Bugs 0 Features 0
Metric Value
eloc 93
c 6
b 0
f 0
dl 0
loc 207
ccs 93
cts 94
cp 0.9894
rs 9.92
wmc 31

5 Methods

Rating   Name   Duplication   Size   Complexity  
A insertWithReturningPks() 0 3 1
B batchInsert() 0 45 7
B upsert() 0 75 11
B resetSequence() 0 29 7
A prepareInsertValues() 0 24 5
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 array_map;
19
use function implode;
20
use function count;
21
22
/**
23
 * Implements a DML (Data Manipulation Language) SQL statements for Oracle Server.
24
 */
25
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
26
{
27
    /**
28
     * @psalm-suppress MixedArrayOffset
29
     *
30
     * @throws Exception
31
     * @throws InvalidArgumentException
32
     * @throws InvalidConfigException
33
     * @throws NotSupportedException
34
     */
35
    public function batchInsert(string $table, array $columns, iterable|Generator $rows, array &$params = []): string
36
    {
37 16
        if (empty($rows)) {
38
            return '';
39 16
        }
40 1
41
        $values = [];
42
        $columns = $this->getNormalizeColumnNames($columns);
0 ignored issues
show
Bug introduced by
The call to Yiisoft\Db\QueryBuilder\...tNormalizeColumnNames() has too few arguments starting with columns. ( Ignorable by Annotation )

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

42
        /** @scrutinizer ignore-call */ 
43
        $columns = $this->getNormalizeColumnNames($columns);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
Bug introduced by
$columns of type array is incompatible with the type string expected by parameter $table of Yiisoft\Db\QueryBuilder\...tNormalizeColumnNames(). ( Ignorable by Annotation )

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

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