forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBuilder.php
More file actions
501 lines (410 loc) · 16.1 KB
/
Builder.php
File metadata and controls
501 lines (410 loc) · 16.1 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\OCI8;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\RawSql;
/**
* Builder for OCI8
*/
class Builder extends BaseBuilder
{
/**
* Identifier escape character
*
* @var string
*/
protected $escapeChar = '"';
/**
* ORDER BY random keyword
*
* @var array
*/
protected $randomKeyword = [
'"DBMS_RANDOM"."RANDOM"',
];
/**
* COUNT string
*
* @used-by CI_DB_driver::count_all()
* @used-by BaseBuilder::count_all_results()
*
* @var string
*/
protected $countString = 'SELECT COUNT(1) ';
/**
* A reference to the database connection.
*
* @var Connection
*/
protected $db;
/**
* Generates a platform-specific insert string from the supplied data.
*/
protected function _insertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$insertKeys = implode(', ', $keys);
$hasPrimaryKey = in_array('PRIMARY', array_column($this->db->getIndexData($table), 'type'), true);
// ORA-00001 measures
$sql = 'INSERT' . ($hasPrimaryKey ? '' : ' ALL') . ' INTO ' . $table . ' (' . $insertKeys . ")\n{:_table_:}";
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" FROM DUAL UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . " FROM DUAL\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific replace string from the supplied data
*/
protected function _replace(string $table, array $keys, array $values): string
{
$fieldNames = array_map(static fn ($columnName): string => trim($columnName, '"'), $keys);
$uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool {
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
return ($index->type === 'PRIMARY') && $hasAllFields;
});
$replaceableFields = array_filter($keys, static function ($columnName) use ($uniqueIndexes): bool {
foreach ($uniqueIndexes as $index) {
if (in_array(trim($columnName, '"'), $index->fields, true)) {
return false;
}
}
return true;
});
$sql = 'MERGE INTO ' . $table . "\n USING (SELECT ";
$sql .= implode(', ', array_map(static fn ($columnName, $value): string => $value . ' ' . $columnName, $keys, $values));
$sql .= ' FROM DUAL) "_replace" ON ( ';
$onList = [];
$onList[] = '1 != 1';
foreach ($uniqueIndexes as $index) {
$onList[] = '(' . implode(' AND ', array_map(static fn ($columnName): string => $table . '."' . $columnName . '" = "_replace"."' . $columnName . '"', $index->fields)) . ')';
}
$sql .= implode(' OR ', $onList) . ') WHEN MATCHED THEN UPDATE SET ';
$sql .= implode(', ', array_map(static fn ($columnName): string => $columnName . ' = "_replace".' . $columnName, $replaceableFields));
$sql .= ' WHEN NOT MATCHED THEN INSERT (' . implode(', ', $replaceableFields) . ') VALUES ';
return $sql . (' (' . implode(', ', array_map(static fn ($columnName): string => '"_replace".' . $columnName, $replaceableFields)) . ')');
}
/**
* Generates a platform-specific truncate string from the supplied data
*
* If the database does not support the truncate() command,
* then this method maps to 'DELETE FROM table'
*/
protected function _truncate(string $table): string
{
return 'TRUNCATE TABLE ' . $table;
}
/**
* Compiles a delete string and runs the query
*
* @param mixed $where
*
* @return mixed
*
* @throws DatabaseException
*/
public function delete($where = '', ?int $limit = null, bool $resetData = true)
{
if ($limit !== null && $limit !== 0) {
$this->QBLimit = $limit;
}
return parent::delete($where, null, $resetData);
}
/**
* Generates a platform-specific delete string from the supplied data
*/
protected function _delete(string $table): string
{
if ($this->QBLimit) {
$this->where('rownum <= ', $this->QBLimit, false);
$this->QBLimit = false;
}
return parent::_delete($table);
}
/**
* Generates a platform-specific update string from the supplied data
*/
protected function _update(string $table, array $values): string
{
$valStr = [];
foreach ($values as $key => $val) {
$valStr[] = $key . ' = ' . $val;
}
if ($this->QBLimit) {
$this->where('rownum <= ', $this->QBLimit, false);
}
return 'UPDATE ' . $this->compileIgnore('update') . $table . ' SET ' . implode(', ', $valStr)
. $this->compileWhereHaving('QBWhere')
. $this->compileOrderBy();
}
/**
* Generates a platform-specific LIMIT clause.
*/
protected function _limit(string $sql, bool $offsetIgnore = false): string
{
$offset = (int) ($offsetIgnore === false ? $this->QBOffset : 0);
// OFFSET-FETCH can be used only with the ORDER BY clause
if (empty($this->QBOrderBy)) {
$sql .= ' ORDER BY 1';
}
return $sql . ' OFFSET ' . $offset . ' ROWS FETCH NEXT ' . $this->QBLimit . ' ROWS ONLY';
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _updateBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch updates.');
}
return ''; // @codeCoverageIgnore
}
$updateFields = $this->QBOptions['updateFields'] ??
$this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ??
[];
$alias = $this->QBOptions['alias'] ?? '"_u"';
// Oracle doesn't support ignore on updates so we will use MERGE
$sql = 'MERGE INTO ' . $table . "\n";
$sql .= "USING (\n{:_table_:}";
$sql .= ') ' . $alias . "\n";
$sql .= 'ON (' . implode(
' AND ',
array_map(
static fn ($key, $value) => (
($value instanceof RawSql && is_string($key))
?
$table . '.' . $key . ' = ' . $value
:
(
$value instanceof RawSql
?
$value
:
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints,
),
) . ")\n";
$sql .= "WHEN MATCHED THEN UPDATE\n";
$sql .= "SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value): string => $table . '.' . $key . ($value instanceof RawSql ?
' = ' . $value :
' = ' . $alias . '.' . $value),
array_keys($updateFields),
$updateFields,
),
);
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)) . ' FROM DUAL',
$values,
),
) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific upsertBatch string from the supplied data
*
* @throws DatabaseException
*/
protected function _upsertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if (empty($constraints)) {
$fieldNames = array_map(static fn ($columnName): string => trim($columnName, '"'), $keys);
$uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool {
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
return ($index->type === 'PRIMARY' || $index->type === 'UNIQUE') && $hasAllFields;
});
// only take first index
foreach ($uniqueIndexes as $index) {
$constraints = $index->fields;
break;
}
$constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? [];
}
if (empty($constraints)) {
if ($this->db->DBDebug) {
throw new DatabaseException('No constraint found for upsert.');
}
return ''; // @codeCoverageIgnore
}
$alias = $this->QBOptions['alias'] ?? '"_upsert"';
$updateFields = $this->QBOptions['updateFields'] ?? $this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ?? [];
$sql = 'MERGE INTO ' . $table . "\nUSING (\n{:_table_:}";
$sql .= ") {$alias}\nON (";
$sql .= implode(
' AND ',
array_map(
static fn ($key, $value) => (
($value instanceof RawSql && is_string($key))
?
$table . '.' . $key . ' = ' . $value
:
(
$value instanceof RawSql
?
$value
:
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints,
),
) . ")\n";
$sql .= "WHEN MATCHED THEN UPDATE SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value): string => $key . ($value instanceof RawSql ?
" = {$value}" :
" = {$alias}.{$value}"),
array_keys($updateFields),
$updateFields,
),
);
$sql .= "\nWHEN NOT MATCHED THEN INSERT (" . implode(', ', $keys) . ")\nVALUES ";
$sql .= (' ('
. implode(', ', array_map(static fn ($columnName): string => "{$alias}.{$columnName}", $keys))
. ')');
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" FROM DUAL UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . " FROM DUAL\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _deleteBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch deletes.'); // @codeCoverageIgnore
}
return ''; // @codeCoverageIgnore
}
$alias = $this->QBOptions['alias'] ?? '_u';
$sql = 'DELETE ' . $table . "\n";
$sql .= "WHERE EXISTS (SELECT * FROM (\n{:_table_:}";
$sql .= ') ' . $alias . "\n";
$sql .= 'WHERE ' . implode(
' AND ',
array_map(
static fn ($key, $value) => (
$value instanceof RawSql ?
$value :
(
is_string($key) ?
$table . '.' . $key . ' = ' . $alias . '.' . $value :
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints,
),
);
// convert binds in where
foreach ($this->QBWhere as $key => $where) {
foreach ($this->binds as $field => $bind) {
$this->QBWhere[$key]['condition'] = str_replace(':' . $field . ':', $bind[0], $where['condition']);
}
}
$sql .= ' ' . str_replace(
'WHERE ',
'AND ',
$this->compileWhereHaving('QBWhere'),
) . ')';
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" FROM DUAL UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . " FROM DUAL\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Gets column names from a select query
*/
protected function fieldsFromQuery(string $sql): array
{
return $this->db->query('SELECT * FROM (' . $sql . ') "_u_" WHERE ROWNUM = 1')->getFieldNames();
}
}