forked from tempestphp/tempest-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertStatement.php
More file actions
69 lines (55 loc) · 2 KB
/
InsertStatement.php
File metadata and controls
69 lines (55 loc) · 2 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
<?php
namespace Tempest\Database\QueryStatements;
use Tempest\Database\Builder\TableDefinition;
use Tempest\Database\Config\DatabaseDialect;
use Tempest\Database\Exceptions\InsertColumnsMismatched;
use Tempest\Database\QueryStatement;
use Tempest\Support\Arr\ImmutableArray;
use function Tempest\Support\arr;
final class InsertStatement implements QueryStatement
{
public function __construct(
public readonly TableDefinition $table,
/** @var ImmutableArray<array-key, array|ImmutableArray> */
public ImmutableArray $entries = new ImmutableArray(),
) {}
public function addEntry(array|ImmutableArray $entry): self
{
$this->entries[] = $entry;
return $this;
}
public function compile(DatabaseDialect $dialect): string
{
$columns = arr($this->entries->first())->keys();
$entryPlaceholders = $this->entries
->map(function (array|ImmutableArray $row) use ($columns) {
$row = arr($row);
$rowColumns = $row->keys();
if (! $columns->equals($rowColumns)) {
throw new InsertColumnsMismatched($columns, $rowColumns);
}
return sprintf(
'(%s)',
$row->map(fn () => '?')->implode(', '),
);
})
->implode(', ');
if ($columns->isEmpty()) {
$sql = match ($dialect) {
DatabaseDialect::MYSQL => sprintf('INSERT INTO %s () VALUES ()', $this->table),
default => sprintf('INSERT INTO %s DEFAULT VALUES', $this->table),
};
} else {
$sql = sprintf(
'INSERT INTO %s (%s) VALUES %s',
$this->table,
$columns->map($dialect->quoteIdentifier(...))->implode(', '),
$entryPlaceholders,
);
}
if ($dialect === DatabaseDialect::POSTGRESQL) {
$sql .= ' RETURNING *';
}
return $sql;
}
}