-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpsert.php
More file actions
64 lines (52 loc) · 2.22 KB
/
Upsert.php
File metadata and controls
64 lines (52 loc) · 2.22 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
<?php
namespace Utopia\Query\Builder\Trait;
use Utopia\Query\Builder\Statement;
use Utopia\Query\Exception\ValidationException;
trait Upsert
{
public function upsert(): Statement
{
$this->bindings = [];
$this->validateTable();
$this->validateRows('upsert');
$columns = $this->validateAndGetColumns();
if (empty($this->conflictKeys)) {
throw new ValidationException('No conflict keys specified. Call onConflict() before upsert().');
}
if (empty($this->conflictUpdateColumns)) {
throw new ValidationException('No conflict update columns specified. Call onConflict() with update columns before upsert().');
}
$rowColumns = $columns;
foreach ($this->conflictUpdateColumns as $col) {
if (! \in_array($col, $rowColumns, true)) {
throw new ValidationException("Conflict update column '{$col}' is not present in the row data.");
}
}
$wrappedColumns = \array_map(fn (string $col): string => $this->resolveAndWrap($col), $columns);
$rowPlaceholders = [];
foreach ($this->rows as $row) {
$placeholders = [];
foreach ($columns as $col) {
$this->addBinding($row[$col] ?? null);
if (isset($this->insertColumnExpressions[$col])) {
$placeholders[] = $this->insertColumnExpressions[$col];
foreach ($this->insertColumnExpressionBindings[$col] ?? [] as $extra) {
$this->addBinding($extra);
}
} else {
$placeholders[] = '?';
}
}
$rowPlaceholders[] = '(' . \implode(', ', $placeholders) . ')';
}
$tablePart = $this->quote($this->table);
if ($this->insertAlias !== '') {
$tablePart .= ' AS ' . $this->quote($this->insertAlias);
}
$sql = 'INSERT INTO ' . $tablePart
. ' (' . \implode(', ', $wrappedColumns) . ')'
. ' VALUES ' . \implode(', ', $rowPlaceholders);
$sql .= ' ' . $this->compileConflictClause();
return new Statement($sql, $this->bindings, executor: $this->executor);
}
}