Test Setup Failed
Pull Request — master (#233)
by
unknown
02:46
created

DMLQueryBuilder   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 203
Duplicated Lines 0 %

Test Coverage

Coverage 98.91%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 90
c 4
b 0
f 0
dl 0
loc 203
ccs 91
cts 92
cp 0.9891
rs 9.84
wmc 32

5 Methods

Rating   Name   Duplication   Size   Complexity  
A insertWithReturningPks() 0 3 1
B batchInsert() 0 41 8
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 implode;
19
use function count;
20
21
/**
22
 * Implements a DML (Data Manipulation Language) SQL statements for Oracle Server.
23
 */
24
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
25
{
26
    /**
27
     * @psalm-suppress MixedArrayOffset
28
     *
29
     * @throws Exception
30
     * @throws InvalidArgumentException
31
     * @throws InvalidConfigException
32
     * @throws NotSupportedException
33
     */
34
    public function batchInsert(string $table, array $columns, iterable|Generator $rows, array &$params = []): string
35
    {
36
        if (empty($rows)) {
37 16
            return '';
38
        }
39 16
40 1
        $values = [];
41
        $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

41
        /** @scrutinizer ignore-call */ 
42
        $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

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