Skip to content

Commit 6a3f3c9

Browse files
committed
Add Postgres _deleteBatch()
1 parent 288ff93 commit 6a3f3c9

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

system/Database/Postgre/Builder.php

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,4 +400,85 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri
400400

401401
return str_replace('{:_table_:}', $data, $sql);
402402
}
403+
404+
/**
405+
* Generates a platform-specific batch update string from the supplied data
406+
*/
407+
protected function _deleteBatch(string $table, array $keys, array $values): string
408+
{
409+
$sql = $this->QBOptions['sql'] ?? '';
410+
411+
// if this is the first iteration of batch then we need to build skeleton sql
412+
if ($sql === '') {
413+
$constraints = $this->QBOptions['constraints'] ?? [];
414+
415+
if ($constraints === []) {
416+
if ($this->db->DBDebug) {
417+
throw new DatabaseException('You must specify a constraint to match on for batch deletes.'); // @codeCoverageIgnore
418+
}
419+
420+
return ''; // @codeCoverageIgnore
421+
}
422+
423+
$updateFields = $this->QBOptions['updateFields'] ??
424+
$this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ??
425+
[];
426+
427+
$alias = $this->QBOptions['alias'] ?? '_u';
428+
429+
$sql = 'DELETE FROM ' . $table . "\n";
430+
431+
$sql .= "USING (\n{:_table_:}";
432+
433+
$sql .= ') ' . $alias . "\n";
434+
435+
$sql .= 'WHERE ' . implode(
436+
' AND ',
437+
array_map(
438+
static fn ($key) => ($key instanceof RawSql ?
439+
$key :
440+
$table . '.' . $key . ' = ' . $alias . '.' . $key),
441+
$constraints
442+
)
443+
);
444+
445+
// convert binds in where
446+
foreach ($this->QBWhere as $key => $where) {
447+
foreach ($this->binds as $field => $bind) {
448+
$this->QBWhere[$key]['condition'] = str_replace(':' . $field . ':', $bind[0], $where['condition']);
449+
}
450+
}
451+
452+
// remove database prefix from alias in where
453+
$sql .= ' ' . str_replace(
454+
'WHERE ',
455+
' AND ',
456+
str_replace(
457+
$this->db->DBPrefix . trim($alias, $this->db->escapeChar),
458+
trim($alias, $this->db->escapeChar),
459+
$this->compileWhereHaving('QBWhere')
460+
)
461+
);
462+
463+
$this->QBOptions['sql'] = $sql;
464+
}
465+
466+
if (isset($this->QBOptions['fromQuery'])) {
467+
$data = $this->QBOptions['fromQuery'];
468+
} else {
469+
$data = implode(
470+
" UNION ALL\n",
471+
array_map(
472+
static fn ($value) => 'SELECT ' . implode(', ', array_map(
473+
static fn ($key, $index) => $index . ' ' . $key,
474+
$keys,
475+
$value
476+
)),
477+
$values
478+
)
479+
) . "\n";
480+
}
481+
482+
return str_replace('{:_table_:}', $data, $sql);
483+
}
403484
}

0 commit comments

Comments
 (0)