Test Failed
Pull Request — master (#233)
by Sergei
06:54
created

DMLQueryBuilder::upsert()   B

Complexity

Conditions 11
Paths 37

Size

Total Lines 75
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
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 39
cts 39
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 JsonException;
8
use Yiisoft\Db\Exception\Exception;
9
use Yiisoft\Db\Exception\InvalidArgumentException;
10
use Yiisoft\Db\Exception\InvalidConfigException;
11
use Yiisoft\Db\Exception\NotSupportedException;
12
use Yiisoft\Db\Expression\Expression;
13
use Yiisoft\Db\Expression\ExpressionInterface;
14
use Yiisoft\Db\Query\QueryInterface;
15
use Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder;
16
17
use function array_map;
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
     * @throws Exception
28
     * @throws InvalidArgumentException
29
     * @throws InvalidConfigException
30
     * @throws NotSupportedException
31
     */
32
    public function batchInsert(string $table, array $columns, iterable $rows, array &$params = []): string
33
    {
34
        if (empty($rows)) {
35
            return '';
36
        }
37 16
38
        $values = [];
39 16
        $columns = $this->getNormalizeColumnNames('', $columns);
40 1
        $columnSchemas = $this->schema->getTableSchema($table)?->getColumns() ?? [];
41
42
        foreach ($rows as $row) {
43 15
            $i = 0;
44 15
            $placeholders = [];
45
46
            foreach ($row as $value) {
47
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
48
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
49 15
                }
50 15
51
                if ($value instanceof ExpressionInterface) {
52
                    $placeholders[] = $this->queryBuilder->buildExpression($value, $params);
53 15
                } else {
54 14
                    $placeholders[] = $this->queryBuilder->bindParam($value, $params);
55 14
                }
56 14
57
                ++$i;
58 13
            }
59
            $values[] = '(' . implode(', ', $placeholders) . ')';
60
        }
61 14
62 3
        if (empty($values)) {
63
            return '';
64 14
        }
65
66
        $columns = array_map(
67 14
            [$this->quoter, 'quoteColumnName'],
68
            $columns,
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 72
        if ($tableSchema === null) {
203
            throw new InvalidArgumentException("Table not found: '$table'.");
204
        }
205
206
        $sequenceName = $tableSchema->getSequenceName();
207
208 72
        if ($sequenceName === null) {
209
            throw new InvalidArgumentException("There is not sequence associated with table '$table'.");
210 69
        }
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 69
    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