Passed
Push — master ( 245d3e...5ecee2 )
by Sergei
34:20 queued 27:49
created

DMLQueryBuilder::upsert()   B

Complexity

Conditions 11
Paths 37

Size

Total Lines 75
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

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