Test Failed
Pull Request — master (#251)
by Alexander
35:01 queued 27:57
created

DMLQueryBuilder::batchInsert()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 14
c 2
b 0
f 0
nc 4
nop 4
dl 0
loc 26
ccs 16
cts 16
cp 1
crap 4
rs 9.7998
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\Query\QueryInterface;
14
use Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder;
15
16
use function array_map;
17
use function implode;
18
use function count;
19
20
/**
21
 * Implements a DML (Data Manipulation Language) SQL statements for Oracle Server.
22
 */
23
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
24
{
25
    /**
26
     * @throws Exception
27
     * @throws InvalidArgumentException
28
     * @throws InvalidConfigException
29
     * @throws NotSupportedException
30
     */
31
    public function batchInsert(string $table, array $columns, iterable $rows, array &$params = []): string
32 22
    {
33
        if (empty($rows)) {
34 22
            return '';
35 1
        }
36
37
        $columnSchemas = $this->schema->getTableSchema($table)?->getColumns() ?? [];
38 21
        $columns = $this->extractColumnNames($columns, $columnSchemas, $rows);
0 ignored issues
show
Bug introduced by
The method extractColumnNames() does not exist on Yiisoft\Db\Oracle\DMLQueryBuilder. ( Ignorable by Annotation )

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

38
        /** @scrutinizer ignore-call */ 
39
        $columns = $this->extractColumnNames($columns, $columnSchemas, $rows);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
39 21
        $values = $this->prepareBatchInsertValues($columns, $columnSchemas, $rows, $params);
0 ignored issues
show
Bug introduced by
The method prepareBatchInsertValues() does not exist on Yiisoft\Db\Oracle\DMLQueryBuilder. Did you maybe mean prepareInsertValues()? ( Ignorable by Annotation )

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

39
        /** @scrutinizer ignore-call */ 
40
        $values = $this->prepareBatchInsertValues($columns, $columnSchemas, $rows, $params);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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