Test Failed
Pull Request — master (#251)
by Sergei
12:48 queued 06:30
created

DMLQueryBuilder   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 184
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 80
c 5
b 0
f 0
dl 0
loc 184
ccs 88
cts 88
cp 1
rs 10
wmc 28

5 Methods

Rating   Name   Duplication   Size   Complexity  
A insertWithReturningPks() 0 3 1
A batchInsert() 0 24 4
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 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
        $columns = $this->extractColumnNames($rows, $columns);
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

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

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...
38 21
        $values = $this->prepareBatchInsertValues($table, $rows, $columns, $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

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