-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
index.ts
2165 lines (1885 loc) · 57.9 KB
/
index.ts
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { DateTime } from 'luxon'
import equal from 'fast-deep-equal'
import Hooks from '@poppinss/hooks'
import lodash from '@poppinss/utils/lodash'
import { Exception, defineStaticProperty } from '@poppinss/utils'
import { QueryClientContract, TransactionClientContract } from '../../types/database.js'
import {
LucidRow,
CacheNode,
LucidModel,
CherryPick,
EventsList,
ModelObject,
HooksHandler,
ModelOptions,
ColumnOptions,
ComputedOptions,
AdapterContract,
CherryPickFields,
ModelColumnOptions,
ModelKeysContract,
ModelAssignOptions,
ModelAdapterOptions,
ModelRelationOptions,
ModelQueryBuilderContract,
ModelPaginatorContract,
QueryScopeCallback,
QueryScope,
} from '../../types/model.js'
import {
ModelRelations,
RelationOptions,
RelationshipsContract,
ThroughRelationOptions,
ManyToManyRelationOptions,
} from '../../types/relations.js'
import * as errors from '../../errors.js'
import { Preloader } from '../preloader/index.js'
import { proxyHandler } from './proxy_handler.js'
import { ModelKeys } from '../model_keys/index.js'
import { HasOne } from '../relations/has_one/index.js'
import { HasMany } from '../relations/has_many/index.js'
import { BelongsTo } from '../relations/belongs_to/index.js'
import { ManyToMany } from '../relations/many_to_many/index.js'
import { HasManyThrough } from '../relations/has_many_through/index.js'
import { CamelCaseNamingStrategy } from '../naming_strategies/camel_case.js'
import { LazyLoadAggregates } from '../relations/aggregates_loader/lazy_load.js'
import {
isObject,
collectValues,
ensureRelation,
managedTransaction,
normalizeCherryPickObject,
} from '../../utils/index.js'
const MANY_RELATIONS = ['hasMany', 'manyToMany', 'hasManyThrough']
const DATE_TIME_TYPES = {
date: 'date',
datetime: 'datetime',
}
function StaticImplements<T>() {
return (_t: T) => {}
}
/**
* Abstract class to define fully fledged data models
*/
@StaticImplements<LucidModel>()
class BaseModelImpl implements LucidRow {
/**
* The adapter to be used for persisting and fetching data.
*
* NOTE: Adapter is a singleton and share among all the models, unless
* a user wants to swap the adapter for a given model
*/
static $adapter: AdapterContract
/**
* Define an adapter to use for interacting with
* the database
*/
static useAdapter(adapter: AdapterContract) {
this.$adapter = adapter
}
/**
* Naming strategy for model properties
*/
static namingStrategy = new CamelCaseNamingStrategy()
/**
* Primary key is required to build relationships across models
*/
static primaryKey: string
/**
* Whether the model has been booted. Booting the model initializes its
* static properties. Base models must not be initialized.
*/
static booted: boolean
/**
* Query scopes defined on the model
*/
static $queryScopes: any = {}
/**
* A set of properties marked as computed. Computed properties are included in
* the `toJSON` result, else they behave the same way as any other instance
* property.
*/
static $computedDefinitions: Map<string, ComputedOptions>
/**
* Columns makes it easier to define extra props on the model
* and distinguish them with the attributes to be sent
* over to the adapter
*/
static $columnsDefinitions: Map<string, ModelColumnOptions>
/**
* Registered relationships for the given model
*/
static $relationsDefinitions: Map<string, RelationshipsContract>
/**
* The name of database table. It is auto generated from the model name, unless
* specified
*/
static table: string
/**
* Self assign the primary instead of relying on the database to
* return it back
*/
static selfAssignPrimaryKey: boolean
/**
* A custom connection to use for queries. The connection defined on
* query builder is preferred over the model connection
*/
static connection?: string
/**
* Storing model hooks
*/
static $hooks: Hooks<any>
/**
* Keys mappings to make the lookups easy
*/
static $keys: {
attributesToColumns: ModelKeysContract
attributesToSerialized: ModelKeysContract
columnsToAttributes: ModelKeysContract
columnsToSerialized: ModelKeysContract
serializedToColumns: ModelKeysContract
serializedToAttributes: ModelKeysContract
}
/**
* Creates a new model instance with payload and adapter options
*/
private static newUpWithOptions(
payload: any,
options?: ModelAdapterOptions,
allowExtraProperties?: boolean
) {
const row = new this()
row.merge(payload, allowExtraProperties)
/**
* Pass client options to the newly created row. If row was found
* the query builder will set the same options.
*/
row.$setOptionsAndTrx(options)
return row
}
/**
* Helper method for `fetchOrNewUpMany`, `fetchOrCreateMany` and `createOrUpdate`
* many.
*/
private static newUpIfMissing(
rowObjects: ModelObject[],
existingRows: BaseModelImpl[],
keys: string[],
mergeAttribute: boolean,
options?: ModelAdapterOptions,
allowExtraProperties?: boolean
) {
/**
* Return existing or create missing rows in the same order as the original
* array
*/
return rowObjects.map((rowObject: any) => {
const existingRow = existingRows.find((one: any) => {
/* eslint-disable-next-line eqeqeq */
return keys.every((key) => one[key] == rowObject[key])
})
/**
* Return the row found from the select call
*/
if (existingRow) {
if (mergeAttribute) {
existingRow.merge(rowObject, allowExtraProperties)
}
return existingRow
}
/**
* Otherwise create a new one
*/
return this.newUpWithOptions(rowObject, options, allowExtraProperties)
})
}
/**
* Returns the model query instance for the given model
*/
static query(options?: ModelAdapterOptions): any {
return this.$adapter.query(this, options)
}
/**
* Create a model instance from the adapter result. The result value must
* be a valid object, otherwise `null` is returned.
*/
static $createFromAdapterResult(
adapterResult: ModelObject,
sideloadAttributes?: ModelObject,
options?: ModelAdapterOptions
): any | null {
if (typeof adapterResult !== 'object' || Array.isArray(adapterResult)) {
return null
}
const instance = new this()
instance.$consumeAdapterResult(adapterResult, sideloadAttributes)
instance.$hydrateOriginals()
instance.$setOptionsAndTrx(options)
instance.$isPersisted = true
instance.$isLocal = false
return instance
}
/**
* Creates an array of models from the adapter results. The `adapterResults`
* must be an array with valid Javascript objects.
*
* 1. If top level value is not an array, then an empty array is returned.
* 2. If row is not an object, then it will be ignored.
*/
static $createMultipleFromAdapterResult<T extends LucidModel>(
this: T,
adapterResults: ModelObject[],
sideloadAttributes?: ModelObject,
options?: ModelAdapterOptions
): InstanceType<T>[] {
if (!Array.isArray(adapterResults)) {
return []
}
return adapterResults.reduce((models, row) => {
if (isObject(row)) {
models.push(this.$createFromAdapterResult(row, sideloadAttributes, options))
}
return models
}, []) as InstanceType<T>[]
}
/**
* Define a new column on the model. This is required, so that
* we differentiate between plain properties vs model attributes.
*/
static $addColumn(name: string, options: Partial<ColumnOptions>) {
const descriptor = Object.getOwnPropertyDescriptor(this.prototype, name)
const column: ModelColumnOptions = {
isPrimary: options.isPrimary || false,
columnName: options.columnName || this.namingStrategy.columnName(this, name),
hasGetter: !!(descriptor && descriptor.get),
hasSetter: !!(descriptor && descriptor.set),
serializeAs:
options.serializeAs !== undefined
? options.serializeAs
: this.namingStrategy.serializedName(this, name),
serialize: options.serialize,
prepare: options.prepare,
consume: options.consume,
meta: options.meta,
}
/**
* Set column as the primary column, when `primary` is true
*/
if (column.isPrimary) {
this.primaryKey = name
}
this.$columnsDefinitions.set(name, column)
this.$keys.attributesToColumns.add(name, column.columnName)
column.serializeAs && this.$keys.attributesToSerialized.add(name, column.serializeAs)
this.$keys.columnsToAttributes.add(column.columnName, name)
column.serializeAs && this.$keys.columnsToSerialized.add(column.columnName, column.serializeAs)
column.serializeAs && this.$keys.serializedToAttributes.add(column.serializeAs, name)
column.serializeAs && this.$keys.serializedToColumns.add(column.serializeAs, column.columnName)
return column
}
/**
* Returns a boolean telling if column exists on the model
*/
static $hasColumn(name: string): boolean {
return this.$columnsDefinitions.has(name)
}
/**
* Returns the column for a given name
*/
static $getColumn(name: string): ModelColumnOptions | undefined {
return this.$columnsDefinitions.get(name)
}
/**
* Adds a computed node
*/
static $addComputed(name: string, options: Partial<ComputedOptions>) {
const computed: ComputedOptions = {
serializeAs:
options.serializeAs !== undefined
? options.serializeAs
: this.namingStrategy.serializedName(this, name),
meta: options.meta,
}
this.$computedDefinitions.set(name, computed)
return computed
}
/**
* Find if some property is marked as computed
*/
static $hasComputed(name: string): boolean {
return this.$computedDefinitions.has(name)
}
/**
* Get computed node
*/
static $getComputed(name: string): ComputedOptions | undefined {
return this.$computedDefinitions.get(name)
}
/**
* Register has one relationship
*/
protected static $addHasOne(
name: string,
relatedModel: () => LucidModel,
options: RelationOptions<LucidModel, LucidModel, ModelRelations<LucidModel, LucidModel>>
) {
this.$relationsDefinitions.set(name, new HasOne(name, relatedModel, options, this))
}
/**
* Register has many relationship
*/
protected static $addHasMany(
name: string,
relatedModel: () => LucidModel,
options: RelationOptions<LucidModel, LucidModel, ModelRelations<LucidModel, LucidModel>>
) {
this.$relationsDefinitions.set(name, new HasMany(name, relatedModel, options, this))
}
/**
* Register belongs to relationship
*/
protected static $addBelongsTo(
name: string,
relatedModel: () => LucidModel,
options: RelationOptions<LucidModel, LucidModel, ModelRelations<LucidModel, LucidModel>>
) {
this.$relationsDefinitions.set(name, new BelongsTo(name, relatedModel, options, this))
}
/**
* Register many-to-many relationship
*/
protected static $addManyToMany(
name: string,
relatedModel: () => LucidModel,
options: ManyToManyRelationOptions<ModelRelations<LucidModel, LucidModel>>
) {
this.$relationsDefinitions.set(name, new ManyToMany(name, relatedModel, options, this))
}
/**
* Register has many through relationship
*/
protected static $addHasManyThrough(
name: string,
relatedModel: () => LucidModel,
options: ThroughRelationOptions<LucidModel, LucidModel, ModelRelations<LucidModel, LucidModel>>
) {
this.$relationsDefinitions.set(name, new HasManyThrough(name, relatedModel, options, this))
}
/**
* Adds a relationship
*/
static $addRelation(
name: string,
type: ModelRelations<LucidModel, LucidModel>['__opaque_type'],
relatedModel: () => LucidModel,
options: ModelRelationOptions
) {
switch (type) {
case 'hasOne':
this.$addHasOne(name, relatedModel, options)
break
case 'hasMany':
this.$addHasMany(name, relatedModel, options)
break
case 'belongsTo':
this.$addBelongsTo(name, relatedModel, options)
break
case 'manyToMany':
this.$addManyToMany(
name,
relatedModel,
options as ManyToManyRelationOptions<ModelRelations<LucidModel, LucidModel>>
)
break
case 'hasManyThrough':
this.$addHasManyThrough(
name,
relatedModel,
options as ThroughRelationOptions<
LucidModel,
LucidModel,
ModelRelations<LucidModel, LucidModel>
>
)
break
default:
throw new Error(`${type} is not a supported relation type`)
}
}
/**
* Find if some property is marked as a relation or not
*/
static $hasRelation(name: any): boolean {
return this.$relationsDefinitions.has(name)
}
/**
* Returns relationship node for a given relation
*/
static $getRelation(name: any): any {
return this.$relationsDefinitions.get(name)!
}
/**
* Define a static property on the model using the inherit or
* define strategy.
*
* Inherit strategy will clone the property from the parent model
* and will set it on the current model
*/
static $defineProperty<Model extends LucidModel, Prop extends keyof Model>(
this: Model,
propertyName: Prop,
defaultValue: Model[Prop],
strategy: 'inherit' | 'define' | ((value: Model[Prop]) => Model[Prop])
) {
defineStaticProperty(this, propertyName, {
initialValue: defaultValue,
strategy: strategy,
})
}
/**
* Boot the model
*/
static boot() {
/**
* Define the property when not defined on self
*/
if (!this.hasOwnProperty('booted')) {
this.booted = false
}
/**
* Return when already booted
*/
if (this.booted === true) {
return
}
this.booted = true
/**
* Table name is never inherited from the base model
*/
this.$defineProperty('table', this.namingStrategy.tableName(this), 'define')
/**
* Inherit primary key or default to "id"
*/
this.$defineProperty('primaryKey', 'id', 'inherit')
/**
* Inherit selfAssignPrimaryKey or default to "false"
*/
this.$defineProperty('selfAssignPrimaryKey', false, 'inherit')
/**
* Define the keys' property. This allows looking up variations
* for model keys
*/
this.$defineProperty(
'$keys',
{
attributesToColumns: new ModelKeys(),
attributesToSerialized: new ModelKeys(),
columnsToAttributes: new ModelKeys(),
columnsToSerialized: new ModelKeys(),
serializedToColumns: new ModelKeys(),
serializedToAttributes: new ModelKeys(),
},
(value) => {
return {
attributesToColumns: new ModelKeys(Object.assign({}, value.attributesToColumns.all())),
attributesToSerialized: new ModelKeys(
Object.assign({}, value.attributesToSerialized.all())
),
columnsToAttributes: new ModelKeys(Object.assign({}, value.columnsToAttributes.all())),
columnsToSerialized: new ModelKeys(Object.assign({}, value.columnsToSerialized.all())),
serializedToColumns: new ModelKeys(Object.assign({}, value.serializedToColumns.all())),
serializedToAttributes: new ModelKeys(
Object.assign({}, value.serializedToAttributes.all())
),
}
}
)
/**
* Define columns
*/
this.$defineProperty('$columnsDefinitions', new Map(), 'inherit')
/**
* Define computed properties
*/
this.$defineProperty('$computedDefinitions', new Map(), 'inherit')
/**
* Define relationships
*/
this.$defineProperty('$relationsDefinitions', new Map(), (value) => {
const relations = new Map<string, RelationshipsContract>()
value.forEach((relation, key) => {
const relationClone = relation.clone(this)
relations.set(key, relationClone)
})
return relations
})
/**
* Define hooks.
*/
this.$defineProperty('$hooks', new Hooks(), (value: Hooks<any>) => {
const hooks = new Hooks()
hooks.merge(value)
return hooks
})
}
/**
* Register before hooks
*/
static before<Model extends LucidModel, Event extends 'find' | 'fetch'>(
this: Model,
event: Event,
handler: HooksHandler<ModelQueryBuilderContract<Model>, Event>
): void
static before<Model extends LucidModel>(
this: Model,
event: 'paginate',
handler: HooksHandler<
[ModelQueryBuilderContract<Model>, ModelQueryBuilderContract<Model>],
'paginate'
>
): void
static before<Model extends LucidModel, Event extends EventsList>(
this: Model,
event: Event,
handler: HooksHandler<InstanceType<Model>, Event>
): void {
this.$hooks.add(`before:${event}`, handler)
}
/**
* Register after hooks
*/
static after<Model extends LucidModel>(
this: Model,
event: 'fetch',
handler: HooksHandler<InstanceType<Model>[], 'fetch'>
): void
static after<Model extends LucidModel>(
this: Model,
event: 'paginate',
handler: HooksHandler<ModelPaginatorContract<InstanceType<Model>>, 'paginate'>
): void
static after<Model extends LucidModel, Event extends EventsList>(
this: Model,
event: Event,
handler: HooksHandler<InstanceType<Model>, Event>
): void {
this.$hooks.add(`after:${event}`, handler)
}
/**
* Returns a fresh persisted instance of model by applying
* attributes to the model instance
*/
static async create(values: any, options?: ModelAssignOptions): Promise<any> {
const instance = this.newUpWithOptions(values, options, options?.allowExtraProperties)
await instance.save()
return instance
}
/**
* Same as [[BaseModel.create]], but persists multiple instances. The create
* many call will be wrapped inside a managed transaction for consistency.
* If required, you can also pass a transaction client and the method
* will use that instead of create a new one.
*/
static async createMany(values: any, options?: ModelAssignOptions): Promise<any[]> {
const client = this.$adapter.modelConstructorClient(this, options)
return managedTransaction(client, async (trx) => {
const modelInstances: LucidRow[] = []
const createOptions = {
client: trx,
allowExtraProperties: options?.allowExtraProperties,
}
for (let row of values) {
const modelInstance = await this.create(row, createOptions)
modelInstances.push(modelInstance)
}
return modelInstances
})
}
/**
* Find model instance using the primary key
*/
static async find(value: any, options?: ModelAdapterOptions) {
if (value === undefined) {
throw new Exception('"find" expects a value. Received undefined')
}
return this.findBy(this.primaryKey, value, options)
}
/**
* Find model instance using the primary key
*/
static async findOrFail(value: any, options?: ModelAdapterOptions) {
if (value === undefined) {
throw new Exception('"findOrFail" expects a value. Received undefined')
}
return this.findByOrFail(this.primaryKey, value, options)
}
/**
* Find model instance using a key/value pair
*/
// @ts-expect-error - Return type should be inferred when used in a model
static findBy(clause: Record<string, unknown>, options?: ModelAdapterOptions)
// @ts-expect-error - Return type should be inferred when used in a model
static findBy(key: string, value: any, options?: ModelAdapterOptions)
static async findBy(
key: string | Record<string, unknown>,
value?: any | ModelAdapterOptions,
options?: ModelAdapterOptions
) {
if (typeof key === 'object') {
return this.query(value as ModelAdapterOptions)
.where(key)
.first()
}
if (value === undefined) {
throw new Exception('"findBy" expects a value. Received undefined')
}
return this.query(options).where(key, value).first()
}
/**
* Find model instance using a key/value pair
*/
// @ts-expect-error - Return type should be inferred when used in a model
static findByOrFail(clause: Record<string, unknown>, options?: ModelAdapterOptions)
// @ts-expect-error - Return type should be inferred when used in a model
static findByOrFail(key: string, value: any, options?: ModelAdapterOptions)
static async findByOrFail(
key: string | Record<string, unknown>,
value?: any | ModelAdapterOptions,
options?: ModelAdapterOptions
) {
if (typeof key === 'object') {
return this.query(value as ModelAdapterOptions)
.where(key)
.firstOrFail()
}
if (value === undefined) {
throw new Exception('"findByOrFail" expects a value. Received undefined')
}
return this.query(options).where(key, value).firstOrFail()
}
/**
* Find multiple models instance using a key/value pair
*/
// @ts-expect-error - Return type should be inferred when used in a model
static findManyBy(clause: Record<string, unknown>, options?: ModelAdapterOptions)
// @ts-expect-error - Return type should be inferred when used in a model
static findManyBy(key: string, value: any[], options?: ModelAdapterOptions)
static findManyBy(
key: string | Record<string, unknown>,
value?: any[] | ModelAdapterOptions,
options?: ModelAdapterOptions
) {
if (typeof key === 'object') {
return this.query(value as ModelAdapterOptions)
.where(key)
.exec()
}
if (value === undefined) {
throw new Exception('"findManyBy" expects a value. Received undefined')
}
return this.query(options).where(key, value).exec()
}
/**
* Same as `query().first()`
*/
static async first(options?: ModelAdapterOptions) {
return this.query(options).first()
}
/**
* Same as `query().firstOrFail()`
*/
static async firstOrFail(options?: ModelAdapterOptions) {
return this.query(options).firstOrFail()
}
/**
* Find model instance using a key/value pair
*/
static async findMany(value: any[], options?: ModelAdapterOptions) {
if (value === undefined) {
throw new Exception('"findMany" expects a value. Received undefined')
}
return this.query(options)
.whereIn(this.primaryKey, value)
.orderBy(this.primaryKey, 'desc')
.exec()
}
/**
* Find model instance using a key/value pair or create a
* new one without persisting it.
*/
static async firstOrNew(
searchPayload: any,
savePayload?: any,
options?: ModelAssignOptions
): Promise<any> {
/**
* Search using the search payload and fetch the first row
*/
const query = this.query(options).where(searchPayload)
const row = await query.first()
/**
* Create a new one, if row is not found
*/
if (!row) {
return this.newUpWithOptions(
Object.assign({}, searchPayload, savePayload),
query.clientOptions,
options?.allowExtraProperties
)
}
return row
}
/**
* Same as `firstOrNew`, but also persists the newly created model instance.
*/
static async firstOrCreate(
searchPayload: any,
savePayload?: any,
options?: ModelAssignOptions
): Promise<any> {
/**
* Search using the search payload and fetch the first row
*/
const query = this.query(options).where(searchPayload)
let row = await query.first()
/**
* Create a new instance and persist it to the database
*/
if (!row) {
row = this.newUpWithOptions(
Object.assign({}, searchPayload, savePayload),
query.clientOptions,
options?.allowExtraProperties
)
await row.save()
}
return row
}
/**
* Updates or creates a new row inside the database
*/
static async updateOrCreate(
searchPayload: any,
updatedPayload: any,
options?: ModelAssignOptions
): Promise<any> {
const client = this.$adapter.modelConstructorClient(this as LucidModel, options)
/**
* We wrap updateOrCreate call inside a transaction and obtain an update
* lock on the selected row. This ensures that concurrent reads waits
* for the existing writes to finish
*/
return managedTransaction(client, async (trx) => {
const query = this.query({ client: trx }).forUpdate().where(searchPayload)
let row = await query.first()
/**
* Create a new instance or update the existing one (if found)
*/
if (!row) {
row = this.newUpWithOptions(
Object.assign({}, searchPayload, updatedPayload),
query.clientOptions,
options?.allowExtraProperties
)
} else {
row.merge(updatedPayload, options?.allowExtraProperties)
}
await row.save()
return row
})
}
/**
* Find existing rows or create an in-memory instances of the missing ones.
*/
static async fetchOrNewUpMany(
uniqueKeys: any,
payload: any,
options?: ModelAssignOptions
): Promise<any[]> {
uniqueKeys = Array.isArray(uniqueKeys) ? uniqueKeys : [uniqueKeys]
const uniquenessPair: { key: string; value: string[] }[] = uniqueKeys.map(
(uniqueKey: string) => {
return {
key: uniqueKey,
value: collectValues(payload, uniqueKey, () => {
throw new Exception(
`Value for the "${uniqueKey}" is null or undefined inside "fetchOrNewUpMany" payload`
)
}),
}
}
)
/**
* Find existing rows
*/
const query = this.query(options)
uniquenessPair.forEach(({ key, value }) => query.whereIn(key, value))
const existingRows = await query
/**
* Return existing rows as it is and create a model instance for missing one's
*/
return this.newUpIfMissing(
payload,
existingRows,
uniqueKeys,
false,
query.clientOptions,
options?.allowExtraProperties
)
}
/**
* Find existing rows or create missing one's. One database call per insert
* is invoked, so that each insert goes through the lifecycle of model
* hooks.
*/
static async fetchOrCreateMany(
uniqueKeys: any,
payload: any,
options?: ModelAssignOptions
): Promise<any[]> {
uniqueKeys = Array.isArray(uniqueKeys) ? uniqueKeys : [uniqueKeys]
const uniquenessPair: { key: string; value: string[] }[] = uniqueKeys.map(
(uniqueKey: string) => {
return {
key: uniqueKey,
value: collectValues(payload, uniqueKey, () => {
throw new Exception(
`Value for the "${uniqueKey}" is null or undefined inside "fetchOrCreateMany" payload`
)
}),
}
}
)
/**
* Find existing rows
*/
const query = this.query(options)
uniquenessPair.forEach(({ key, value }) => query.whereIn(key, value))
const existingRows = await query
/**
* Create model instance for the missing rows
*/
const rows = this.newUpIfMissing(
payload,
existingRows,
uniqueKeys,
false,
query.clientOptions,
options?.allowExtraProperties
)
/**
* Persist inside db inside a transaction
*/
await managedTransaction(query.client, async (trx) => {
for (let row of rows) {
/**
* If transaction `client` was passed, then the row will have
* the `trx` already set. But since, the trx of row will be
* same as the `trx` passed to this callback, we can safely
* re-set it.
*/
row.$trx = trx
if (!row.$isPersisted) {
await row.save()
}