-
-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathIsDatabaseModel.php
More file actions
392 lines (331 loc) · 10.7 KB
/
IsDatabaseModel.php
File metadata and controls
392 lines (331 loc) · 10.7 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
<?php
declare(strict_types=1);
namespace Tempest\Database;
use Tempest\Database\Builder\QueryBuilders\CountQueryBuilder;
use Tempest\Database\Builder\QueryBuilders\InsertQueryBuilder;
use Tempest\Database\Builder\QueryBuilders\QueryBuilder;
use Tempest\Database\Builder\QueryBuilders\SelectQueryBuilder;
use Tempest\Database\Exceptions\RelationWasMissing;
use Tempest\Database\Exceptions\ValueWasMissing;
use Tempest\Reflection\PropertyReflector;
use Tempest\Router\IsBindingValue;
use Tempest\Validation\SkipValidation;
use UnitEnum;
use function Tempest\Support\arr;
use function Tempest\Support\str;
trait IsDatabaseModel
{
#[IsBindingValue, SkipValidation]
public PrimaryKey $id;
#[SkipValidation, Virtual]
private null|string|UnitEnum $onDatabase = null;
/**
* Returns a query builder targeting the specified database connection.
*
* @return QueryBuilder<self>
*/
public static function on(null|string|UnitEnum $databaseTag): QueryBuilder
{
return self::queryBuilder()->onDatabase(databaseTag: $databaseTag);
}
/**
* Targets a specific database connection for this model instance.
*/
public function onDatabase(null|string|UnitEnum $databaseTag): self
{
$clone = clone $this;
$clone->onDatabase = $databaseTag;
return $clone;
}
/** @return QueryBuilder<self> */
protected static function queryBuilder(): QueryBuilder
{
return query(self::class);
}
/**
* Returns a builder for selecting records using this model's table.
*
* @return SelectQueryBuilder<self>
*/
public static function select(): SelectQueryBuilder
{
return self::queryBuilder()->select();
}
/**
* Returns a builder for inserting records using this model's table.
*
* @return InsertQueryBuilder<self>
*/
public static function insert(): InsertQueryBuilder
{
return self::queryBuilder()->insert();
}
/**
* Returns a builder for counting records using this model's table.
*
* @return CountQueryBuilder<self>
*/
public static function count(): CountQueryBuilder
{
return self::queryBuilder()->count();
}
/**
* Executes an aggregate query and returns the sum of the given column.
*/
public static function sum(string $column): int|float
{
return self::queryBuilder()->sum(column: $column);
}
/**
* Executes an aggregate query and returns the average of the given column.
*/
public static function avg(string $column): float
{
return self::queryBuilder()->avg(column: $column);
}
/**
* Executes an aggregate query and returns the maximum value of the given column.
*/
public static function max(string $column): mixed
{
return self::queryBuilder()->max(column: $column);
}
/**
* Executes an aggregate query and returns the minimum value of the given column.
*/
public static function min(string $column): mixed
{
return self::queryBuilder()->min(column: $column);
}
/**
* Creates a new instance of this model without persisting it to the database.
*/
public static function new(mixed ...$params): self
{
return self::queryBuilder()->new(...$params);
}
/**
* Finds a model instance by its ID.
*/
public static function findById(string|int|PrimaryKey $id): ?self
{
return self::get($id);
}
/**
* Finds a model instance by its ID. Use through {@see \Tempest\Router\Bindable}.
*/
public static function resolve(string $input): ?self
{
return self::queryBuilder()->resolve($input);
}
/**
* Gets a model instance by its ID, optionally loading the given relationships.
*/
public static function get(string|int|PrimaryKey $id, array $relations = []): ?self
{
return self::queryBuilder()->get($id, $relations);
}
/**
* Gets all records from the model's table.
*
* @return self[]
*/
public static function all(array $relations = []): array
{
return self::queryBuilder()->all($relations);
}
/**
* Finds records based on their columns.
*
* **Example**
* ```php
* MagicUser::find(name: 'Frieren');
* ```
*
* @return SelectQueryBuilder<self>
*/
public static function find(mixed ...$conditions): SelectQueryBuilder
{
return self::queryBuilder()->find(...$conditions);
}
/**
* Creates a new model instance and persists it to the database.
*
* **Example**
* ```php
* MagicUser::create(name: 'Frieren', kind: Kind::ELF);
* ```
*
* @return self
*/
public static function create(mixed ...$params): self
{
return self::queryBuilder()->create(...$params);
}
/**
* Finds an existing model instance or creates a new one if it doesn't exist, without persisting it to the database.
*
* **Example**
* ```php
* $model = MagicUser::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 self
*/
public static function findOrNew(array $find, array $update): self
{
return self::queryBuilder()->findOrNew($find, $update);
}
/**
* Finds an existing model instance or creates a new one if it doesn't exist, and persists it to the database.
*
* **Example**
* ```php
* $model = MagicUser::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.
*/
public static function updateOrCreate(array $find, array $update): self
{
return self::queryBuilder()->updateOrCreate($find, $update);
}
/**
* Refreshes the model instance with the latest data from the database.
*/
public function refresh(): self
{
$model = inspect($this);
$loadedRelations = $model
->getRelations()
->filter($model->isRelationLoaded(...));
$primaryKeyProperty = $model->getPrimaryKeyProperty();
$primaryKeyValue = $primaryKeyProperty->getValue($this);
$new = self::queryBuilder()
->onDatabase($this->onDatabase)
->select()
->with(...$loadedRelations->map(fn (Relation $relation) => $relation->name))
->get($primaryKeyValue);
foreach ($loadedRelations as $relation) {
$relation->property->setValue(
object: $this,
value: $relation->property->getValue($new),
);
}
foreach ($model->getValueFields() as $property) {
$property->setValue(
object: $this,
value: $property->getValue($new),
);
}
return $this;
}
/**
* Loads the specified relations on the model instance.
*/
public function load(string ...$relations): self
{
$model = inspect($this);
$primaryKeyProperty = $model->getPrimaryKeyProperty();
$primaryKeyValue = $primaryKeyProperty->getValue($this);
$new = self::queryBuilder()
->onDatabase($this->onDatabase)
->get($primaryKeyValue, $relations);
$fieldsToUpdate = arr($relations)
->map(fn (string $relation) => str($relation)->before('.')->toString())
->unique();
foreach ($fieldsToUpdate as $fieldToUpdate) {
$this->{$fieldToUpdate} = $new->{$fieldToUpdate};
}
return $this;
}
/**
* Saves the model to the database. If the model has no primary key, this method always inserts.
*/
public function save(): self
{
$model = inspect($this);
$model->validate(...inspect($this)->getPropertyValues());
// Models without primary keys always insert
if (! $model->hasPrimaryKey()) {
query($this::class)
->onDatabase($this->onDatabase)
->insert($this)
->execute();
return $this;
}
$primaryKeyProperty = $model->getPrimaryKeyProperty();
$isInitialized = $primaryKeyProperty->isInitialized($this);
$primaryKeyValue = $isInitialized ? $primaryKeyProperty->getValue($this) : null;
// If there is a primary key property but it's not set, we insert the model
// to generate the id and populate the model instance with it
if ($primaryKeyValue === null) {
$id = query($this::class)
->onDatabase($this->onDatabase)
->insert($this)
->execute();
if (! $model->hasUuidPrimaryKey()) {
$primaryKeyProperty->setValue($this, $id);
}
return $this;
}
// Is the model was already saved, we update it
query($this)
->onDatabase($this->onDatabase)
->update(...inspect($this)->getPropertyValues())
->execute();
return $this;
}
/**
* Updates the specified columns and persist the model to the database.
*/
public function update(mixed ...$params): self
{
$model = inspect($this);
$model->validate(...$params);
query($this)
->onDatabase($this->onDatabase)
->update(...$params)
->whereField($model->getPrimaryKey(), $model->getPrimaryKeyValue())
->execute();
foreach ($params as $key => $value) {
$this->{$key} = $value;
}
return $this;
}
/**
* Deletes this model from the database.
*/
public function delete(): void
{
query($this)
->onDatabase($this->onDatabase)
->delete()
->build()
->execute();
}
public function __get(string $name): mixed
{
$property = PropertyReflector::fromParts($this, $name);
if ($property->hasAttribute(Lazy::class)) {
$this->load($name);
return $property->getValue($this);
}
if (inspect(model: $this)->isRelation(name: $name)) {
throw new RelationWasMissing($this, $name);
}
if ($property->getType()->isBuiltIn()) {
throw new ValueWasMissing($this, $name);
}
throw new RelationWasMissing($this, $name);
}
}