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