Test Failed
Pull Request — master (#233)
by Sergei
06:57 queued 52s
created

DMLQueryBuilder::upsert()   B

Complexity

Conditions 11
Paths 37

Size

Total Lines 75
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 40
CRAP Score 11

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 39
c 1
b 0
f 0
nc 37
nop 4
dl 0
loc 75
ccs 40
cts 40
cp 1
crap 11
rs 7.3166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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