-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
model.ts
697 lines (606 loc) · 23.2 KB
/
model.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
import { Trilogy } from "."
import { Hooks, Hook } from "./hooks"
import * as helpers from "./helpers"
import {
createTrigger,
normalizeSchema,
TriggerEvent,
Cast
} from "./schema-helpers"
import {
invariant, isString, isObject, toArray, firstOrValue
} from "./util"
import * as types from "./types"
import { Driver } from "./constants"
export type ModelWithShape <T extends types.LooseObject> =
Model<types.SchemaFromShape<T>>
const baseCount = async <
T extends types.Schema,
Props extends types.ModelProps<T>
> (
model: Model<T, Props>,
column: keyof Props["schema"],
criteria?: types.Criteria<Props["objectInput"]>,
options: types.AggregateOptions = {}
): Promise<number> => {
invariant(
column != null && isString(column),
`invalid column: expected string, got ${typeof column}`
)
types.AggregateOptions.check(options)
const val = `${String(column)} as count`
const builder = model.ctx.knex(model.name)
let query = options.distinct ? builder.countDistinct(val) : builder.count(val)
query = helpers.buildWhere(query, model.cast.toDefinition(
criteria ?? {},
{ raw: true, ...options }
))
if (options.group != null) query = query.groupBy(toArray(options.group))
// TODO: please, for the love of the cosmos, give me https://github.com/microsoft/TypeScript/pull/26349
const result = await helpers.getQueryResult<Driver, typeof query, Props, [{ count: number }] | undefined>(model.ctx, query, {
// TODO: get rid of this `any` cast
model: model as any
})
return Array.isArray(result) ? result[0].count : 0
}
const baseMinMax = async <
T extends types.Schema,
Props extends types.ModelProps<T>
> (
model: Model<T, Props>,
method: "min" | "max",
column: keyof Props["objectOutput"],
criteria?: types.Criteria<Props["objectOutput"]>,
options: types.AggregateOptions = {}
): Promise<number | undefined> => {
types.AggregateOptions.check(options)
const val = `${String(column)} as ${method}`
let query = model.ctx.knex(model.name)[method](val)
query = helpers.buildWhere(query, model.cast.toDefinition(
criteria ?? {},
{ raw: true, ...options }
))
if (options.group != null) query = query.groupBy(toArray(options.group))
// TODO: please, for the love of the cosmos, give me https://github.com/microsoft/TypeScript/pull/26349
const result = await helpers.getQueryResult<Driver, typeof query, Props, [Record<"min" | "max", number>] | undefined>(model.ctx, query, {
// TODO: get rid of this `any` cast
model: model as any
})
return Array.isArray(result) ? result[0][method] : undefined
}
const baseGet = async <
T extends types.Schema,
Props extends types.ModelProps<T>,
K extends keyof Props["objectOutput"],
V extends Props["objectOutput"][K]
> (
model: Model<T, Props>,
column: K,
criteria: types.Criteria<Props["objectOutput"]> | undefined,
defaultValue?: V,
options?: types.LooseObject
): Promise<V | undefined> => {
const data = await model.findOneIn<K, V>(column, criteria, options)
return data ?? defaultValue
}
const baseSet = async <
T extends types.Schema,
Props extends types.ModelProps<T>,
K extends keyof Props["objectOutput"]
> (
model: Model<T, Props>,
column: K,
criteria: types.Criteria<Props["objectOutput"]> | undefined,
value?: Props["objectOutput"][K],
options?: types.LooseObject
): Promise<Array<Props["objectOutput"]>> => {
invariant(
model.schema[column as string],
`no column by the name '${String(column)}' is defined in '${model.name}'`
)
return model.update(criteria, {
[column]: value
} as Partial<Props["objectOutput"]>, options)
}
/**
* Instances of `Model` manage the casting of values back and forth between the
* SQLite backend and their corresponding JavaScript types as well as calling
* hooks.
*
* Models are created using a trilogy instance's `model` method and are not
* intended to be created directly.
*
* @internal
*/
export default class Model <
// TODO: get rid of this `any`?
Schema extends types.Schema<any>,
Props extends types.ModelProps<Schema> = types.ModelProps<Schema>
> extends Hooks<Props> {
schema: types.SchemaNormalized<Schema>
cast: Cast<Props>
/**
* @param ctx trilogy instance used as a context for the model
* @param name Name associated with this model and used in the backend
* @param schema An object defining the fields & types of objects
* @param options
*/
constructor (
public ctx: Trilogy,
public name: string,
schema: Schema,
public options: types.ModelOptions
) {
super()
this.schema = normalizeSchema(schema, options)
this.cast = new Cast(this as any)
}
static withShape <
T extends types.LooseObject = never,
ModelSchema extends types.SchemaFromShape<T> = types.SchemaFromShape<T>
> (
ctx: Trilogy,
name: string,
schema: ModelSchema,
options: types.ModelOptions = {}
): ModelWithShape<T> {
return new Model<types.SchemaFromShape<T>>(ctx, name, schema, options)
}
/**
* Create an object on the given model. `object` should match the model's
* defined schema but values will cast into types as needed.
*
* @param object Data to insert
* @param options
*/
async create (
object: Props["objectInput"],
options: types.CreateOptions = {}
): Promise<Props["objectOutput"] | undefined> {
const { prevented } =
await this._callHook(Hook.BeforeCreate, object as Partial<Props["objectInput"]>, options)
if (prevented) return
const insertion = this.cast.toDefinition(object, options)
const [returning, cleanup] =
await createTrigger(this, TriggerEvent.Insert)
const query = this.ctx.knex.raw(
this.ctx.knex(this.name)
.insert(insertion)
.toSQL()
.sql
.replace(/^insert/i, "INSERT OR IGNORE")
)
await helpers.executeQuery<Props>(this.ctx, query, {
// TODO: get rid of this `any` cast
model: this as any
})
// TODO: please, for the love of the cosmos, give me https://github.com/microsoft/TypeScript/pull/26349
const result = await helpers.getQueryResult<Driver, typeof returning, Props, types.Nullable<Props["objectOutput"] | Array<Props["objectOutput"]>>>(this.ctx, returning, {
// TODO: get rid of this `any` cast
model: this as any,
internal: true
})
await cleanup()
const created = result == null || (Array.isArray(result) && result.length < 1)
? undefined
: this.cast.fromDefinition(firstOrValue(result), options)
await this._callHook(Hook.AfterCreate, created, options)
return created
}
/**
* Find all objects matching a given criteria.
*
* @param criteria Criteria used to restrict selection
* @param options
*/
async find (
criteria?: types.Criteria<Props["objectOutput"]>,
options: types.FindOptions = {}
): Promise<Array<Props["objectOutput"]>> {
types.FindOptions.check(options)
const order = options.random ? "random" : options.order
let query = this.ctx.knex(this.name).select()
query = helpers.buildWhere(query, this.cast.toDefinition(
criteria ?? {},
{ raw: true, ...options }
))
if (order != null) query = helpers.buildOrder(query, order)
if (options.limit != null) query = query.limit(options.limit)
if (options.skip != null) query = query.offset(options.skip)
// TODO: please, for the love of the cosmos, give me https://github.com/microsoft/TypeScript/pull/26349
const result = await helpers.getQueryResult<Driver, typeof query, Props, types.Nullable<Props["objectOutput"] | Array<Props["objectOutput"]>>>(this.ctx, query, {
// TODO: get rid of this `any` cast
model: this as any
})
if (!Array.isArray(result)) {
return result != null ? [result] : []
}
return result.map(object => {
return this.cast.fromDefinition(object, options)
})
}
/**
* Find all objects matching a given criteria and extract the values
* at `column`.
*
* @param column Property name of objects to extract the value from
* @param criteria Criteria used to restrict selection
* @param options
*/
async findIn (
column: keyof Props["objectOutput"],
criteria?: types.Criteria<Props["objectOutput"]>,
options?: types.FindOptions
): Promise<Array<types.ValueOf<Props["objectOutput"]>>> {
const result = await this.find(criteria, options)
return result.map(object => {
return this.cast.fromColumnDefinition(
column,
object[column],
options
)
})
}
/**
* Find a single object matching a given criteria. The first matching
* object is returned.
*
* @param criteria Criteria used to restrict selection
* @param options
*/
async findOne (
criteria?: types.Criteria<Props["objectOutput"]>,
options: types.FindOptions = {}
): Promise<Props["objectOutput"] | undefined> {
types.FindOptions.check(options)
const order = options.random ? "random" : options.order
let query = this.ctx.knex(this.name).first()
query = helpers.buildWhere(query, this.cast.toDefinition(
criteria ?? {},
{ raw: true, ...options }
))
if (order != null) query = helpers.buildOrder(query, order)
if (options.skip != null) query = query.offset(options.skip)
// TODO: please, for the love of the cosmos, give me https://github.com/microsoft/TypeScript/pull/26349
const response = await helpers.getQueryResult<Driver, typeof query, Props, types.Listable<Props["objectOutput"]>>(this.ctx, query, {
// TODO: get rid of this `any` cast
model: this as any
})
const result = firstOrValue<Props["objectOutput"]>(response)
if (result == null) return undefined
return this.cast.fromDefinition(result, options)
}
/**
* Find a single object matching a given criteria and extract the value
* at `column`. The first matching object is returned.
*
* @param column Property name of the selected object to extract the value from
* @param criteria Criteria used to restrict selection
* @param options
*/
async findOneIn <K extends keyof Props["objectOutput"] = keyof Props["objectOutput"], V = Props["objectOutput"][K]> (
column: K,
criteria?: types.Criteria<Props["objectOutput"]>,
options: types.FindOptions = {}
): Promise<V | undefined> {
return this.findOne(criteria, options)
.then(object => object != null ? object[column] as V : undefined)
}
/**
* Find a matching object based on the given criteria, or create it if it
* doesn't exist. When creating the object, a merged object created from
* `criteria` and `creation` will be used, with the properties from
* `creation` taking precedence.
*
* @param criteria Criteria to search for
* @param creation Data used to create the object if it doesn't exist
* @param options
*/
async findOrCreate (
criteria: types.CriteriaObj<Props["objectOutput"]>,
creation: Partial<Props["objectOutput"]> = {},
options?: types.FindOptions
): Promise<Props["objectOutput"] | undefined> {
return (
await this.findOne(criteria, options) ??
// TODO: get rid of this `any` cast
this.create({ ...criteria, ...creation } as any)
)
}
/**
* Modify the properties of an existing object. While optional, if `data`
* contains no properties no update queries will be run.
*
* @param criteria Criteria used to restrict selection
* @param data Updates to be made on matching objects
* @param options
*/
async update (
criteria: types.Criteria<Props["objectOutput"]> = {},
data: Partial<Props["objectOutput"]> = {},
options: types.UpdateOptions = {}
): Promise<Array<Props["objectOutput"]>> {
types.UpdateOptions.check(options)
if (Object.keys(data).length < 1) return []
const [returning, cleanup] =
await createTrigger(this, TriggerEvent.Update)
const { prevented } =
await this._callHook(Hook.BeforeUpdate, [data, criteria], options)
if (prevented) return []
const typedData = this.cast.toDefinition(data, options)
const typedCriteria = this.cast.toDefinition(criteria, options)
let query = this.ctx.knex(this.name).update(typedData)
query = helpers.buildWhere(query, typedCriteria)
// TODO: get rid of this `any` cast
await helpers.executeQuery<Props>(this.ctx, query, { model: this as any })
// TODO: please, for the love of the cosmos, give me https://github.com/microsoft/TypeScript/pull/26349
const updatedRaw = await helpers.getQueryResult<Driver, typeof returning, Props, Array<Props["objectOutput"]>>(this.ctx, returning, {
// TODO: get rid of this `any` cast
model: this as any,
internal: true
})
const updated = updatedRaw.map(object => {
return this.cast.fromDefinition(object, options)
})
await cleanup()
await this._callHook(Hook.AfterUpdate, updated, options)
return updated
}
/**
* Update an existing object or create it if it doesn't exist. If creation
* is necessary a merged object created from `criteria` and `data` will be
* used, with the properties from `data` taking precedence.
*
* @param criteria Criteria used to restrict selection
* @param data Updates to be made on matching objects
* @param options
*/
async updateOrCreate (
criteria: types.CriteriaObj<Props["objectOutput"]>,
data: Partial<Props["objectOutput"]>,
options: types.UpdateOptions & types.CreateOptions = {}
): Promise<Array<Props["objectOutput"]>> {
const found = await this.find(criteria, options)
if (found.length < 1) {
// TODO: get rid of this `any` cast
return this.create({ ...criteria, ...data } as any, options)
.then(res => toArray<Props["objectOutput"]>(res as Props["objectOutput"]))
} else {
return this.update(criteria, data, options)
}
}
/**
* Works similarly to the `get` methods in lodash, underscore, etc. Returns
* the value at `column` or, if it does not exist, the supplied `defaultValue`.
* Essentially a useful shorthand for some `find` scenarios.
*
* @param column Property name of the object to extract the value from
* @param criteria Criteria used to restrict selection
* @param defaultValue Value returned if the result doesn't exist
*/
async get <K extends keyof Props["objectOutput"] = keyof Props["objectOutput"], V extends Props["objectOutput"][K] = Props["objectOutput"][K]> (
column: K, criteria?: types.Criteria<Props["objectOutput"]>, defaultValue?: V
): Promise<V | undefined> {
return baseGet(this, column, criteria, defaultValue)
}
/**
* Works similarly to the `set` methods in lodash, underscore, etc. Updates
* the value at `column` to be `value` where the given criteria is met.
*
* @param column Property name of the object at which to set the value
* @param criteria Criteria used to restrict selection
* @param value Value returned if the result doesn't exist
*/
async set <K extends keyof Props["objectOutput"] = keyof Props["objectOutput"], V extends Props["objectOutput"][K] = Props["objectOutput"][K]> (
column: K, criteria: types.Criteria<Props["objectOutput"]>, value: V
): Promise<Array<Props["objectOutput"]>> {
return baseSet(this, column, criteria, value)
}
/**
* Works exactly like `get` but bypasses getters and retrieves the raw database value.
*
* @param column Property name of the object to extract the value from
* @param criteria Criteria used to restrict selection
* @param defaultValue Value returned if the result doesn't exist
*/
async getRaw <K extends keyof Props["objectOutput"] = keyof Props["objectOutput"], V extends Props["objectOutput"][K] = Props["objectOutput"][K]> (
column: K, criteria: types.Criteria<Props["objectOutput"]>, defaultValue?: V
): Promise<Props["objectOutput"][K] | undefined> {
return baseGet(this, column, criteria, defaultValue, { raw: true })
}
/**
* Works exactly like `set` but bypasses setters when updating the target value.
*
* @param column Property name of the object at which to set the value
* @param criteria Criteria used to restrict selection
* @param value Value returned if the result doesn't exist
*/
async setRaw <K extends keyof Props["objectOutput"] = keyof Props["objectOutput"], V extends Props["objectOutput"][K] = Props["objectOutput"][K]> (
column: K, criteria: types.Criteria<Props["objectOutput"]>, value: V
): Promise<Array<Props["objectOutput"]>> {
return baseSet(this, column, criteria, value, { raw: true })
}
/**
* Increment the value of a given model's property by the specified amount,
* which defaults to `1` if not provided.
*
* @param column Property at which to increment the value
* @param criteria Criteria used to restrict selection
* @param amount
*/
async increment (
column: keyof Props["objectOutput"],
criteria?: types.Criteria<Props["objectOutput"]>,
amount?: number
): Promise<Array<Props["objectOutput"]>> {
const { prevented } =
await this._callHook(Hook.BeforeUpdate, [{}, criteria as types.Criteria<Props["objectOutput"]>])
if (prevented) return []
const cast = Number(amount)
if (Number.isNaN(cast)) amount = 1
if (amount === 0) return []
const [returning, cleanup] = await createTrigger(this, TriggerEvent.Update)
let query = this.ctx.knex(this.name).increment(column as string, amount)
query = helpers.buildWhere(query, criteria)
// TODO: get rid of this `any` cast
const affected = await helpers.executeQuery<Props>(this.ctx, query, { model: this as any })
if (affected === 0) return []
// TODO: please, for the love of the cosmos, give me https://github.com/microsoft/TypeScript/pull/26349
const updatedRaw = await helpers.getQueryResult<Driver, typeof returning, Props, Array<Props["objectOutput"]>>(this.ctx, returning, {
// TODO: get rid of this `any` cast
model: this as any,
internal: true
})
const updated = updatedRaw.map(object => {
return this.cast.fromDefinition(object, {})
})
await cleanup()
await this._callHook(Hook.AfterUpdate, updated)
return updated
}
/**
* Decrement the value of a given model's property by the specified amount,
* which defaults to `1` if not provided.
*
* @param column Property at which to decrement the value
* @param criteria Criteria used to restrict selection
* @param amount
*/
async decrement (
column: keyof Props["objectOutput"],
criteria?: types.Criteria<Props["objectOutput"]>,
amount?: number,
allowNegative?: boolean
): Promise<Array<Props["objectOutput"]>> {
const { prevented } =
await this._callHook(Hook.BeforeUpdate, [{}, criteria as types.Criteria<Props["objectOutput"]>])
if (prevented) return []
const cast = Number(amount)
if (Number.isNaN(cast)) amount = 1
if (amount === 0) return []
const [returning, cleanup] = await createTrigger(this, TriggerEvent.Update)
const raw = allowNegative ? "?? - ?" : "MAX(0, ?? - ?)"
const query = helpers.buildWhere(
this.ctx.knex(this.name).update({
[column]: this.ctx.knex.raw(raw, [column, amount] as [string, number])
}),
criteria
)
// TODO: get rid of this `any` cast
const affected = await helpers.executeQuery<Props>(this.ctx, query, { model: this as any })
if (affected === 0) return []
// TODO: please, for the love of the cosmos, give me https://github.com/microsoft/TypeScript/pull/26349
const updatedRaw = await helpers.getQueryResult<Driver, typeof returning, Props, Array<Props["objectOutput"]>>(this.ctx, returning, {
// TODO: get rid of this `any` cast
model: this as any,
internal: true
})
const updated = updatedRaw.map(object => {
return this.cast.fromDefinition(object, {})
})
await cleanup()
await this._callHook(Hook.AfterUpdate, updated)
return updated
}
/**
* Delete objects from this model that match `criteria`.
*
* @remarks
* If `criteria` is empty or absent, nothing will be done. This is a safeguard
* against unintentionally deleting everything in the model. Use `clear` if
* you really want to remove all rows.
*
* @param criteria Criteria used to restrict selection
*/
async remove (criteria: types.Criteria<Props["objectOutput"]>): Promise<Array<Props["objectOutput"]>> {
const { prevented } =
await this._callHook(Hook.BeforeRemove, criteria)
if (prevented) return []
if (
!helpers.isValidWhere(criteria) ||
(isObject(criteria) && !Object.keys(criteria).length)
) return []
const [returning, cleanup] = await createTrigger(this, TriggerEvent.Delete)
let query = this.ctx.knex(this.name).del()
query = helpers.buildWhere(query, criteria)
const deleteCount = await helpers.executeQuery<Props>(this.ctx, query, {
// TODO: get rid of this `any` cast
model: this as any
})
if (deleteCount === 0) return []
// TODO: please, for the love of the cosmos, give me https://github.com/microsoft/TypeScript/pull/26349
const deleted = await helpers.getQueryResult<Driver, typeof returning, Props, Array<Props["objectOutput"]>>(this.ctx, returning, {
// TODO: get rid of this `any` cast
model: this as any,
internal: true
})
await cleanup()
await this._callHook(Hook.AfterRemove, deleted)
return deleted
}
/**
* Delete all objects from this model.
*/
async clear (): Promise<number> {
const query = this.ctx.knex(this.name).truncate()
// TODO: get rid of this `any` cast
return helpers.executeQuery<Props>(this.ctx, query, { model: this as any })
}
/**
* Count the number of objects in this model.
*
* @param criteria Criteria used to restrict selection
* @param options
*/
async count (
criteria?: types.Criteria<Props["objectInput"]>,
options: types.AggregateOptions = {}
): Promise<number> {
return baseCount(this, "*", criteria, options)
}
/**
* Count the number of objects in this model, selecting on column (meaning
* `NULL` values are not counted).
*
* @param column Property name to select on
* @param criteria Criteria used to restrict selection
* @param options
*/
async countIn (
column: types.StringKeys<Props["objectInput"]>,
criteria?: types.Criteria<Props["objectInput"]>,
options: types.AggregateOptions = {}
): Promise<number> {
return baseCount(this, column, criteria, options)
}
/**
* Find the minimum value contained in this model, comparing all values in
* `column` that match the given criteria.
*
* @param column Property name to inspect
* @param criteria Criteria used to restrict selection
* @param options
*/
async min (
column: keyof Props["objectOutput"],
criteria?: types.Criteria<Props["objectOutput"]>,
options: types.AggregateOptions = {}
): Promise<number | undefined> {
return baseMinMax(this, "min", column, criteria, options)
}
/**
* Find the maximum value contained in this model, comparing all values in
* `column` that match the given criteria.
*
* @param column Property name to inspect
* @param criteria Criteria used to restrict selection
* @param options
*/
async max (
column: keyof Props["objectOutput"],
criteria?: types.Criteria<Props["objectOutput"]>,
options?: types.AggregateOptions
): Promise<number | undefined> {
return baseMinMax(this, "max", column, criteria, options)
}
}