-
-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathQueryBuilder.php
More file actions
426 lines (376 loc) · 11.2 KB
/
QueryBuilder.php
File metadata and controls
426 lines (376 loc) · 11.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
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
<?php
namespace Tempest\Database\Builder\QueryBuilders;
use Tempest\Database\Exceptions\ModelDidNotHavePrimaryColumn;
use Tempest\Database\OnDatabase;
use Tempest\Database\PrimaryKey;
use Tempest\Mapper\SerializerFactory;
use Tempest\Reflection\PropertyReflector;
use function Tempest\Container\get;
use function Tempest\Database\inspect;
use function Tempest\Database\query;
use function Tempest\Mapper\make;
use function Tempest\Support\arr;
/** @template TModel */
final class QueryBuilder
{
use OnDatabase;
/** @var QueryScope[] */
private array $scopes = [];
/** @param class-string<TModel>|TModel|string $model */
public function __construct(
private readonly string|object $model,
) {}
/**
* Adds a scope that will be applied to any query builder created from this instance.
*
* @return self<TModel>
*/
public function scope(QueryScope $scope): self
{
$this->scopes[] = $scope;
return $this;
}
/**
* Creates a `SELECT` query builder for retrieving records from the database.
*
* **Example**
* ```php
* query(User::class)
* ->select('id', 'username', 'email')
* ->execute();
* ```
*
* @return SelectQueryBuilder<TModel>
*/
public function select(string ...$columns): SelectQueryBuilder
{
return new SelectQueryBuilder(
model: $this->model,
fields: $columns !== [] ? arr($columns)->unique() : null,
)
->onDatabase(databaseTag: $this->onDatabase)
->applyScopes(scopes: $this->scopes);
}
/**
* Creates an `INSERT` query builder for adding new records to the database.
*
* **Example**
* ```php
* query(User::class)
* ->insert(username: 'Frieren')
* ->execute();
* ```
*
* @return InsertQueryBuilder<TModel>
*/
public function insert(mixed ...$values): InsertQueryBuilder
{
if (! array_is_list($values)) {
$values = [$values];
}
return new InsertQueryBuilder(
model: $this->model,
rows: $values,
serializerFactory: get(SerializerFactory::class),
)->onDatabase($this->onDatabase);
}
/**
* Creates an `UPDATE` query builder for modifying existing records in the database.
*
* **Example**
* ```php
* query(User::class)
* ->update(is_admin: true)
* ->whereIn('id', [1, 2, 3])
* ->execute();
* ```
*
* @return UpdateQueryBuilder<TModel>
*/
public function update(mixed ...$values): UpdateQueryBuilder
{
return new UpdateQueryBuilder(
model: $this->model,
values: $values,
serializerFactory: get(SerializerFactory::class),
)
->onDatabase(databaseTag: $this->onDatabase)
->applyScopes(scopes: $this->scopes);
}
/**
* Creates a `DELETE` query builder for removing records from the database.
*
* **Example**
* ```php
* query(User::class)
* ->delete()
* ->where(name: 'Frieren')
* ->execute();
* ```
*
* @return DeleteQueryBuilder<TModel>
*/
public function delete(): DeleteQueryBuilder
{
return new DeleteQueryBuilder(model: $this->model)
->onDatabase(databaseTag: $this->onDatabase)
->applyScopes(scopes: $this->scopes);
}
/**
* Creates a `COUNT` query builder for counting records in the database.
*
* **Example**
* ```php
* query(User::class)->count()->execute();
* ```
*
* @return CountQueryBuilder<TModel>
*/
public function count(?string $column = null): CountQueryBuilder
{
return new CountQueryBuilder(
model: $this->model,
column: $column,
)
->onDatabase(databaseTag: $this->onDatabase)
->applyScopes(scopes: $this->scopes);
}
/**
* Executes an aggregate query and returns the sum of the given column.
*
* **Example**
* ```php
* query(User::class)->sum('price');
* ```
*/
public function sum(string $column): int|float
{
return $this->select()->onDatabase(databaseTag: $this->onDatabase)->sum(column: $column);
}
/**
* Executes an aggregate query and returns the average of the given column.
*
* **Example**
* ```php
* query(User::class)->avg('price');
* ```
*/
public function avg(string $column): float
{
return $this->select()->onDatabase(databaseTag: $this->onDatabase)->avg(column: $column);
}
/**
* Executes an aggregate query and returns the maximum value of the given column.
*
* **Example**
* ```php
* query(User::class)->max('price');
* ```
*/
public function max(string $column): mixed
{
return $this->select()->onDatabase(databaseTag: $this->onDatabase)->max(column: $column);
}
/**
* Executes an aggregate query and returns the minimum value of the given column.
*
* **Example**
* ```php
* query(User::class)->min('price');
* ```
*/
public function min(string $column): mixed
{
return $this->select()->onDatabase(databaseTag: $this->onDatabase)->min(column: $column);
}
/**
* Creates a new instance of this model without persisting it to the database.
*
* **Example**
* ```php
* query(User::class)->new(name: 'Frieren');
* ```
*
* @return TModel|object<TModel>
*/
public function new(mixed ...$params): object
{
return make($this->model)->from($params);
}
/**
* Finds a model instance by its ID.
*
* **Example**
* ```php
* query(User::class)->findById(1);
* ```
*
* @return TModel|object<TModel>|null
*/
public function findById(string|int|PrimaryKey $id): ?object
{
if (! inspect($this->model)->hasPrimaryKey()) {
throw ModelDidNotHavePrimaryColumn::neededForMethod($this->model, 'findById');
}
return $this->get($id);
}
/**
* Finds a model instance by its ID.
*
* **Example**
* ```php
* query(User::class)->resolve(1);
* ```
*
* @return TModel|object<TModel>|null
*/
public function resolve(string|int|PrimaryKey $id): ?object
{
if (! inspect($this->model)->hasPrimaryKey()) {
throw ModelDidNotHavePrimaryColumn::neededForMethod($this->model, 'resolve');
}
return $this->get($id);
}
/**
* Gets a model instance by its ID, optionally loading the given relationships.
*
* **Example**
* ```php
* query(User::class)->get(1);
* ```
*
* @return TModel|object<TModel>|null
*/
public function get(string|int|PrimaryKey $id, array $relations = []): ?object
{
if (! inspect($this->model)->hasPrimaryKey()) {
throw ModelDidNotHavePrimaryColumn::neededForMethod($this->model, 'get');
}
$id = match (true) {
$id instanceof PrimaryKey => $id,
default => new PrimaryKey($id),
};
return $this
->select()
->with(...$relations)
->get($id);
}
/**
* Gets all records from the model's table.
*
* @return TModel[]
*/
public function all(array $relations = []): array
{
return $this
->select()
->with(...$relations)
->all();
}
/**
* Finds records based on their columns.
*
* **Example**
* ```php
* query(User::class)->find(name: 'Frieren');
* ```
*
* @return SelectQueryBuilder<TModel>
*/
public function find(mixed ...$conditions): SelectQueryBuilder
{
$query = $this->select();
foreach ($conditions as $field => $value) {
$query->whereField($field, $value);
}
return $query;
}
/**
* Creates a new model instance and persists it to the database.
*
* **Example**
* ```php
* query(User::class)->create(name: 'Frieren', kind: Kind::ELF);
* ```
*
* @return TModel|object<TModel>
*/
public function create(mixed ...$params): object
{
inspect($this->model)->validate(...$params);
$model = $this->new(...$params);
$id = $this->insert($model)->execute();
$inspector = inspect($this->model);
$primaryKeyProperty = $inspector->getPrimaryKeyProperty();
if ($id instanceof PrimaryKey && $primaryKeyProperty instanceof PropertyReflector) {
$primaryKeyName = $primaryKeyProperty->getName();
if (! $inspector->hasUuidPrimaryKey() || $model->{$primaryKeyName} === null) {
$model->{$primaryKeyName} = new PrimaryKey($id);
}
}
return $model;
}
/**
* Finds an existing model instance or creates a new one if it doesn't exist, without persisting it to the database.
*
* **Example**
* ```php
* $model = query(User::class)->findOrNew(
* find: ['name' => 'Frieren'],
* update: ['kind' => Kind::ELF],
* );
* ```
*
* @param array<string,mixed> $find Properties to search for in the existing model.
* @param array<string,mixed> $update Properties to update or set on the model if it is found or created.
* @return TModel|object<TModel>
*/
public function findOrNew(array $find, array $update): object
{
$existing = $this->select();
foreach ($find as $key => $value) {
$existing = $existing->whereField($key, $value);
}
$model = $existing->first() ?? $this->new(...$find);
foreach ($update as $key => $value) {
$model->{$key} = $value;
}
return $model;
}
/**
* Finds an existing model instance or creates a new one if it doesn't exist, and persists it to the database.
*
* **Example**
* ```php
* $model = query(User::class)->updateOrCreate(
* find: ['name' => 'Frieren'],
* update: ['kind' => Kind::ELF],
* );
* ```
*
* @param array<string,mixed> $find Properties to search for in the existing model.
* @param array<string,mixed> $update Properties to update or set on the model if it is found or created.
* @return TModel|object<TModel>
*/
public function updateOrCreate(array $find, array $update): object
{
$inspector = inspect($this->model);
if (! $inspector->hasPrimaryKey()) {
throw ModelDidNotHavePrimaryColumn::neededForMethod($this->model, 'updateOrCreate');
}
$model = $this->findOrNew($find, $update);
$primaryKeyProperty = $inspector->getPrimaryKeyProperty();
$primaryKeyName = $primaryKeyProperty->getName();
if (! isset($model->{$primaryKeyName})) {
return $this->create(...array_merge($find, $update));
}
query($model)
->onDatabase($this->onDatabase)
->update(...$update)
->execute();
foreach ($update as $key => $value) {
$model->{$key} = $value;
}
return $model;
}
}