-
-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathQuery.php
More file actions
108 lines (81 loc) · 2.59 KB
/
Query.php
File metadata and controls
108 lines (81 loc) · 2.59 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
<?php
declare(strict_types=1);
namespace Tempest\Database;
use Tempest\Database\Config\DatabaseDialect;
use Tempest\Support\Str\ImmutableString;
use function Tempest\Container\get;
/**
* A database query that can be executed.
*/
final class Query
{
use OnDatabase;
private Database $database {
get => get(Database::class, $this->onDatabase);
}
private DatabaseDialect $dialect {
get => $this->database->dialect;
}
public function __construct(
public string|QueryStatement $sql,
public array $bindings = [],
/** @var \Closure[] $executeAfter */
public array $executeAfter = [],
public ?string $primaryKeyColumn = null,
) {}
public function execute(mixed ...$bindings): ?PrimaryKey
{
$this->bindings = [...$this->bindings, ...$bindings];
$database = $this->database;
$query = $this->withBindings($bindings);
$database->execute($query);
// TODO: add support for "after" queries to attach hasMany relations
if (! $this->primaryKeyColumn) {
return null;
}
return isset($query->bindings[$this->primaryKeyColumn])
? new PrimaryKey($query->bindings[$this->primaryKeyColumn])
: $database->getLastInsertId();
}
public function fetch(mixed ...$bindings): array
{
return $this->database->fetch($this->withBindings($bindings));
}
public function fetchFirst(mixed ...$bindings): ?array
{
return $this->database->fetchFirst($this->withBindings($bindings));
}
/**
* Compile the query to a SQL statement without the bindings.
*/
public function compile(): ImmutableString
{
$sql = $this->sql;
$dialect = $this->dialect;
if ($sql instanceof QueryStatement) {
$sql = $sql->compile($dialect);
}
if ($dialect === DatabaseDialect::POSTGRESQL) {
$sql = str_replace('`', '"', $sql);
}
return new ImmutableString($sql);
}
/**
* Returns the SQL statement with bindings. This method may generate syntax errors, it is not recommended to use it other than for debugging.
*/
public function toRawSql(): ImmutableString
{
return $this->database->getRawSql($this);
}
public function append(string $append): self
{
$this->sql .= PHP_EOL . $append;
return $this;
}
public function withBindings(array $bindings): self
{
$clone = clone $this;
$clone->bindings = [...$clone->bindings, ...$bindings];
return $clone;
}
}