@forestfuture/active-record 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1293 +0,0 @@
1
- //#region src/sql.d.ts
2
- /**
3
- * A SQL fragment built with the `sql` tagged template (ADR-0006). The template
4
- * text is written by the developer; every interpolated value is bound as a
5
- * parameter and never becomes SQL text.
6
- */
7
- declare class SafeSql {
8
- readonly strings: readonly string[];
9
- readonly values: readonly unknown[];
10
- }
11
- declare function sql$1(strings: TemplateStringsArray, ...values: unknown[]): SafeSql;
12
- /** A reference to an attribute's column, resolved against the query's Model when compiled. */
13
- declare class ColumnReference {
14
- readonly attribute: string;
15
- /**
16
- * A value of this attribute for a fragment, converted as the attribute stores it: a `Date`
17
- * as the integer of an attribute kept as a Unix time, a boolean as 0 or 1, and so on. It's
18
- * still a bound parameter. Without it, a value has no attribute to say how it's stored (#142).
19
- */
20
- value(value: unknown): ColumnValue;
21
- }
22
- /** A value of an attribute, from `column(attribute).value(value)`, converted when compiled. */
23
- declare class ColumnValue {
24
- readonly attribute: string;
25
- /** What was given, before it's cast as an assigned value of the attribute. */
26
- readonly assigned: unknown;
27
- }
28
- /** Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004). */
29
- declare function column(attribute: string): ColumnReference;
30
- //#endregion
31
- //#region src/query.d.ts
32
- type OrderDirection = "asc" | "desc";
33
- type NullsPlacement = "first" | "last";
34
- //#endregion
35
- //#region src/attribute.d.ts
36
- /**
37
- * One attribute's value path, resolved once per Model class by `attributeFor` (#163). Which
38
- * Model and attribute a refusal names, whether the attribute is filtered, and how its type is
39
- * stored are known here, so a caller only says what the value is for.
40
- */
41
- declare class Attribute {
42
- #private;
43
- readonly name: string;
44
- readonly column: string;
45
- /** Whether it's a `string` attribute, which D1 compares as text, not by number. */
46
- get isText(): boolean;
47
- /**
48
- * An assigned value (a setter, `build`, `update`, `insert`, `permit`) as the attribute's type:
49
- * only what's unambiguous for it (#81). `undefined` throws, as it would store NULL silently;
50
- * what can't be cast throws `TypeError` naming the Model and attribute, showing the value
51
- * unless the attribute is filtered (#83).
52
- */
53
- cast(value: unknown): unknown;
54
- /**
55
- * A key copied from another record or inherited from a condition: cast as a condition's, but
56
- * one that can't be cast throws, naming the association it came through.
57
- */
58
- key(value: unknown, association?: string): unknown;
59
- /**
60
- * A condition's value (`where`, `find`, a preload) as the attribute's type, or `noMatch`: a
61
- * number also matches a string attribute as its digits, and a value that can't be cast
62
- * matches nothing, so a value from a URL is never an error.
63
- */
64
- condition(value: unknown): unknown;
65
- /** A condition's value in the form D1 stores, or `noMatch`. */
66
- conditionCell(value: unknown): unknown;
67
- /**
68
- * An already cast value in the form D1 stores. A `json` value changed in place into one JSON
69
- * can't write throws `TypeError` naming the attribute, as assigning it would (#146).
70
- */
71
- write(value: unknown): unknown;
72
- /** An assigned value cast, then in the form D1 stores. */
73
- store(value: unknown): unknown;
74
- /**
75
- * A cell D1 returned as the attribute's value. One that isn't (text in a Unix time column, or
76
- * past the range of a `Date`; a json cell that isn't JSON) throws `TypeError` naming the
77
- * attribute, with the cell hidden if it's filtered, not the parser's own error (#73, #146).
78
- */
79
- read(cell: unknown): unknown;
80
- /** A copy of a value: written as D1 stores it, then read back. */
81
- copy(value: unknown): unknown;
82
- /** Whether two values are the same as stored (dates by time, json by content). */
83
- same(a: unknown, b: unknown): boolean;
84
- /** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
85
- bind(params: unknown[], value: unknown): void;
86
- /**
87
- * Binds cells (as D1 holds them) as the attribute's, each hidden from `onQuery` listeners when
88
- * the attribute is filtered (#83); D1 still gets the real values. Filtering is asked at the
89
- * time, since `filterAttributes` is a static a Model may set after this was resolved.
90
- */
91
- bindCells(params: unknown[], ...cells: unknown[]): void;
92
- }
93
- //#endregion
94
- //#region src/dialect.d.ts
95
- /** The SQL a database needs in its own form. Everything else in the compiler is shared. */
96
- interface Dialect {
97
- /** `column` in a list of `cells` bound as one value, so any length fits a statement's limits. */
98
- inList(column: string, cells: readonly unknown[]): {
99
- sql: string;
100
- value: unknown;
101
- };
102
- /** `limit` and `offset`, at least one of them set, as this database writes them, their values added to `params`. */
103
- pagination(limit: number | undefined, offset: number | undefined, params: unknown[]): string;
104
- /** Where a bulk insert reads its rows of `attributes`, from one bound JSON value: its SELECT list and FROM. */
105
- bulkRows(attributes: readonly Attribute[]): {
106
- select: string;
107
- from: string;
108
- };
109
- }
110
- //#endregion
111
- //#region src/compiler.d.ts
112
- /** One SQL statement ready to send, with the Model whose table it reads or writes. */
113
- interface CompiledSql {
114
- sql: string;
115
- params: unknown[];
116
- model: ModelClass<Model>;
117
- }
118
- /** What `toSql()` shows: a query's SQL, with its values bound apart from it (ADR-0006). */
119
- interface QuerySql {
120
- sql: string;
121
- params: unknown[];
122
- }
123
- //#endregion
124
- //#region src/driver.d.ts
125
- /** One statement's result, the same on every database. */
126
- interface StatementResult {
127
- /** The rows it returned: a read's, or a write's `RETURNING`. */
128
- rows: Record<string, unknown>[];
129
- /** How many rows it inserted, updated or deleted. */
130
- rowsAffected: number;
131
- /** The database's own timing for it, when it reports one. */
132
- durationMs?: number | undefined;
133
- /** The database's own detail about it, for `onQuery` (D1's `meta`). */
134
- meta?: unknown;
135
- }
136
- /** Sends statements to one database. It knows nothing of Models, `onQuery` or error classes. */
137
- interface Driver {
138
- /** Sends one statement. */
139
- send(statement: CompiledSql): Promise<StatementResult>;
140
- /** Sends reads at once where it can, resolving to each one's result. They needn't be atomic. */
141
- read(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
142
- /** Sends writes atomically, all or none, resolving to each one's result. */
143
- write(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
144
- /** Whether sending again can succeed after `error`, having readied the connection for it. */
145
- recover(error: unknown): boolean;
146
- }
147
- //#endregion
148
- //#region src/executor.d.ts
149
- /**
150
- * Reported once for every statement sent to a database: to the database's `onQuery`, then to the
151
- * statement's Model's (`static onQuery`, usually on the app's base class). `meta` is the
152
- * database's own detail about the statement, typed by its adapter (D1's `D1Meta`).
153
- */
154
- interface QueryEvent<Meta = unknown> {
155
- /**
156
- * The Model the statement is for: its class name (`"Product"`). It's `""` for an anonymous
157
- * class, and a bundler that renames classes changes it; Wrangler keeps names by default.
158
- */
159
- model: string;
160
- sql: string;
161
- params: unknown[];
162
- durationMs: number;
163
- meta?: Meta;
164
- error?: unknown;
165
- }
166
- /**
167
- * Hears each statement's `QueryEvent`. Declared as a method's type, so a listener typed for one
168
- * adapter's `meta` (a D1 app's base class) can be a Model's `static onQuery`, which any adapter calls.
169
- */
170
- type QueryListener<Meta = unknown> = {
171
- listener(event: QueryEvent<Meta>): void;
172
- }["listener"];
173
- /**
174
- * The concrete database a handle sends to now. Private to this module (#93): callers ask
175
- * `oneDatabase` (through `jointly` and `pinBefore`) instead, so "is this the same database?" is
176
- * decided in one place.
177
- */
178
- declare const resolve: unique symbol;
179
- /** Where a Relation's or record's statements go: one database, or the current one (#77). */
180
- interface Executor {
181
- /** The kind of database it sends to, known before that database is found. */
182
- readonly adapter: Adapter;
183
- /** How its database writes the SQL the compiler can't share. */
184
- readonly dialect: Dialect;
185
- /** Runs one statement and resolves to its rows. */
186
- all(query: CompiledSql): Promise<Record<string, unknown>[]>;
187
- /** Runs one statement for its effect and resolves to its result. */
188
- run(query: CompiledSql): Promise<StatementResult>;
189
- /** Runs reads together and resolves to each one's result. They needn't be atomic. */
190
- read(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
191
- /** Runs statements atomically: one on its own, several as one batch. */
192
- write(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
193
- }
194
- /** Where a database came from, for errors to name it: `connect()`'s, the request's, or a binding's. */
195
- type Origin = "connect" | "request" | {
196
- binding: string;
197
- };
198
- /**
199
- * One database's Executor: every statement goes to its Driver and is reported to `onQuery`, and a
200
- * constraint failure becomes the matching `ConstraintViolation` for the statement's Model.
201
- */
202
- declare class DatabaseExecutor implements Executor {
203
- #private;
204
- readonly adapter: Adapter;
205
- constructor(adapter: Adapter, driver: Driver, onQuery?: QueryListener);
206
- get dialect(): Dialect;
207
- [resolve](): Promise<DatabaseExecutor>;
208
- /** Where this database came from; errors name it by this. */
209
- get origin(): Origin;
210
- /** Runs one statement and resolves to its rows. */
211
- all(query: CompiledSql): Promise<Record<string, unknown>[]>;
212
- /** Runs one statement for its effect and resolves to its result. */
213
- run(query: CompiledSql): Promise<StatementResult>;
214
- /** Runs reads together and resolves to each one's result. */
215
- read(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
216
- /** Runs statements atomically: one on its own, several all or none. Resolves to each result. */
217
- write(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
218
- }
219
- //#endregion
220
- //#region src/epoch-storage.d.ts
221
- /** A datetime held in an `INTEGER` column as seconds or milliseconds since 1970. */
222
- declare const epochStorages: readonly ["unixSeconds", "unixMilliseconds"];
223
- type EpochStorage = (typeof epochStorages)[number];
224
- //#endregion
225
- //#region src/metadata.d.ts
226
- type AttributeType = "string" | "integer" | "real" | "boolean" | "datetime" | "json";
227
- /** An attribute's spec written out: its type, and optionally nullability, column and default. */
228
- interface SpecObject {
229
- type: AttributeType;
230
- null?: boolean;
231
- column?: string;
232
- /** A `datetime` held as a Unix epoch integer, as Drizzle's timestamp modes write it (#73). */
233
- storage?: EpochStorage;
234
- /** Evaluated at `build()`, e.g. `() => new Date()`. */
235
- default?: () => unknown;
236
- /**
237
- * Made by the Model's `generateId` when not given, where a default would run: an
238
- * app-generated key (#99). Generated ids are strings, so only a string attribute has one.
239
- */
240
- generateId?: boolean;
241
- }
242
- /** Where a string attribute's value comes from when it isn't given: a default or `generateId`, never both. */
243
- type ValueSource = {
244
- default?: () => unknown;
245
- generateId?: false;
246
- } | {
247
- default?: never;
248
- generateId: true;
249
- };
250
- type AttributeSpec = AttributeType | (Omit<SpecObject, "default" | "generateId" | "storage"> & {
251
- type: "string";
252
- storage?: never;
253
- } & ValueSource) | (Omit<SpecObject, "type" | "generateId" | "storage"> & {
254
- type: Exclude<AttributeType, "string" | "datetime">;
255
- generateId?: false;
256
- storage?: never;
257
- }) | (Omit<SpecObject, "type" | "generateId"> & {
258
- type: "datetime";
259
- generateId?: false;
260
- });
261
- type AttributeSpecs = Record<string, AttributeSpec>;
262
- /**
263
- * `A`, with any key a spec doesn't have typed `never`, so a misspelled one (`nul: false`) is a
264
- * compile error: a generic parameter skips TypeScript's own check for unknown keys (#102).
265
- */
266
- type ExactSpecs<A> = { [K in keyof A]: A[K] extends object ? A[K] & Record<Exclude<keyof A[K], keyof SpecObject>, never> : A[K]; };
267
- /** An attribute's resolved metadata. */
268
- interface AttributeDefinition {
269
- type: AttributeType;
270
- column: string;
271
- default?: () => unknown;
272
- generateId?: true;
273
- storage?: EpochStorage;
274
- }
275
- type JsType<T extends AttributeType> = T extends "string" ? string : T extends "integer" | "real" ? number : T extends "boolean" ? boolean : T extends "datetime" ? Date : unknown;
276
- type AttributeValue<S> = S extends AttributeType ? JsType<S> | null : S extends {
277
- type: infer T extends AttributeType;
278
- null: false;
279
- } ? JsType<T> : S extends {
280
- type: infer T extends AttributeType;
281
- } ? JsType<T> | null : never;
282
- type AttributeProperties<A extends AttributeSpecs> = { -readonly [K in keyof A]: AttributeValue<A[K]>; };
283
- //#endregion
284
- //#region src/permit.d.ts
285
- /** What `permit` returns: the named attributes, each optional, as their types. */
286
- type Permitted<C extends ModelClass, K extends string> = Partial<Pick<AttributesOf<InstanceType<C>>, K & keyof AttributesOf<InstanceType<C>>>>;
287
- //#endregion
288
- //#region src/attribute-conversions.d.ts
289
- /**
290
- * What d1-record does with an attribute's values, by the attribute's type (and `storage`).
291
- * `T` is the attribute's JavaScript type. Each is a function of its own, so one can be passed
292
- * on or destructured.
293
- */
294
- interface AttributeConversions<T> {
295
- /**
296
- * `input` as the attribute's JavaScript value, as assigning it would: strict, so `TypeError`
297
- * naming the Model and attribute when it can't be. `null` stays `null`; `undefined` throws.
298
- * Nothing is floored: a `Date` with milliseconds keeps them, whatever the attribute's `storage`.
299
- */
300
- readonly cast: (input: unknown) => T;
301
- /**
302
- * `input`, cast, as D1 stores it: an ISO string, an integer for a `storage` attribute (seconds
303
- * are floored), `0` or `1`, JSON text. The value `column(attribute).value(input)` binds inside
304
- * an `sql` fragment; `undefined` throws as assigning it does.
305
- */
306
- readonly serialize: (input: unknown) => string | number | null;
307
- /**
308
- * A cell D1 returned, as the attribute's JavaScript value; `null` for NULL and `undefined`.
309
- * It reads as a record load does, so a cell that can't be read throws `TypeError` naming the
310
- * Model and attribute: text in a Unix time column, a number past the range of a `Date`, or text
311
- * in a `json` column that isn't JSON.
312
- */
313
- readonly deserialize: (stored: unknown) => T;
314
- }
315
- //#endregion
316
- //#region src/filtering.d.ts
317
- /**
318
- * An entry of `filterAttributes`: a string the attribute's snake_case name contains (in any
319
- * case), or a RegExp the attribute or its snake_case name matches.
320
- */
321
- type FilterAttribute = string | RegExp;
322
- /** The value D1 binds. */
323
- declare function boundValue(param: unknown): unknown;
324
- //#endregion
325
- //#region src/error-messages.d.ts
326
- /**
327
- * An error's message, after the attribute's name: `"can't be blank"`. With a count, one for
328
- * each plural form: `{ one: "needs 1 character", other: "needs %{count} characters" }`.
329
- */
330
- type ErrorMessage = string | {
331
- readonly one?: string;
332
- readonly other: string;
333
- };
334
- /** The messages of `restrictDependentDestroy`, for a has-one and a has-many association. */
335
- interface RestrictMessages {
336
- readonly hasOne: string;
337
- readonly hasMany: string;
338
- }
339
- /** Messages by attribute name (`N`: the names a Model has), then error type. */
340
- type AttributeErrorMessages<N extends string = string> = { readonly [K in N]?: {
341
- readonly [type: string]: ErrorMessage;
342
- }; };
343
- /**
344
- * What `errorMessages` declares: messages by error type (`blank`, `tooShort`, or a type of your
345
- * own), and under `attributes`, by attribute and type, which win over the class's others.
346
- */
347
- interface ErrorMessages<N extends string = string> {
348
- readonly [type: string]: ErrorMessage | RestrictMessages | AttributeErrorMessages<N> | undefined;
349
- readonly attributes?: AttributeErrorMessages<N>;
350
- readonly restrictDependentDestroy?: RestrictMessages;
351
- }
352
- /** The values an error's message can show as `%{name}`, such as `count`. */
353
- type ErrorValues = Readonly<Record<string, string | number>>;
354
- //#endregion
355
- //#region src/inspect-support.d.ts
356
- /** What Node's `util.inspect` passes a custom inspector; `src/` doesn't import Node's types. */
357
- interface InspectOptions {
358
- depth?: number | null;
359
- /** Wraps text in the color for a kind of value, or returns it as is when colors are off. */
360
- stylize?: (text: string, style: "special") => string;
361
- }
362
- type Inspect = (value: unknown, options?: InspectOptions) => string;
363
- /** Node and workerd call a value's inspector under this registered symbol. */
364
- declare const inspectCustom: unique symbol;
365
- //#endregion
366
- //#region src/errors-collection.d.ts
367
- /** One validation failure: which attribute (or `"base"`), what kind, and the message. */
368
- interface ValidationError {
369
- attribute: string;
370
- type: string;
371
- message: string;
372
- /** The values its message shows, such as `count`, when it has some; never the attribute's. */
373
- values?: ErrorValues;
374
- }
375
- /** A record's validation errors: `record.errors`. Cleared at the start of each validation run. */
376
- declare class Errors {
377
- #private;
378
- /**
379
- * Adds an error with this message; `type` defaults to `"invalid"`. Use `"base"` for the
380
- * record as a whole.
381
- */
382
- add(attribute: string, message: string, options?: {
383
- type?: string;
384
- }): void;
385
- /**
386
- * Adds an error of this type, whose message is looked up in `errorMessages` when it's read,
387
- * with `%{name}` filled in from the values given: `{ type: "tooShort", count: 3 }`.
388
- */
389
- add(attribute: string, error: {
390
- type: string;
391
- } & ErrorValues): void;
392
- /** The messages for one attribute (always an array). */
393
- get(attribute: string): string[];
394
- /** Every message with its attribute's human name first: "Email can't be blank". */
395
- fullMessages(): string[];
396
- /** Every error as `{ attribute, type, message }`, with its `values` when it has some (copies). */
397
- toArray(): ValidationError[];
398
- isEmpty(): boolean;
399
- get size(): number;
400
- /** `Errors [ { attribute, type, message }, … ]`, so a console shows what `#entries` holds (#104). */
401
- [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
402
- }
403
- //#endregion
404
- //#region src/spec-keys.d.ts
405
- /** An override written out: the parts of a spec it may change (not the column), any left out or `undefined` unchanged. */
406
- type SpecOverride = Partial<Omit<SpecObject, "column">>;
407
- //#endregion
408
- //#region src/generated-model.d.ts
409
- /** One table in a generated schema: its attributes, and which is the primary key. */
410
- interface TableSchema {
411
- readonly attributes: AttributeSpecs;
412
- readonly primaryKey: string;
413
- }
414
- /** A generated schema's tables, by name (`tables` in `src/db/schema.ts`). */
415
- type TableSchemas = Readonly<Record<string, TableSchema>>;
416
- /**
417
- * A change to a generated attribute: its type alone, or its type, nullability, default and
418
- * `generateId`, typed so `generateId` goes only with a string, and never with a default (#99).
419
- */
420
- type AttributeOverride = AttributeType | (Pick<SpecOverride, "null"> & {
421
- type?: "string";
422
- storage?: never;
423
- } & ValueSource) | (Pick<SpecOverride, "null" | "default"> & {
424
- type: Exclude<AttributeType, "string" | "datetime">;
425
- generateId?: false;
426
- storage?: never;
427
- }) | (Pick<SpecOverride, "null" | "default" | "storage"> & {
428
- type: "datetime";
429
- generateId?: false;
430
- });
431
- /** The type a spec declares, written either way. */
432
- type TypeOf<S> = S extends AttributeType ? S : S extends {
433
- type: infer T;
434
- } ? T : never;
435
- /** Whether a spec's attribute can be `null`. */
436
- type NullOf<S> = S extends {
437
- null: false;
438
- } ? false : true;
439
- /** An attribute's spec with its override applied. */
440
- type Overridden<S, O> = O extends AttributeType ? {
441
- type: O;
442
- null: NullOf<S>;
443
- } : O extends object ? {
444
- type: O extends {
445
- type: infer T extends AttributeType;
446
- } ? T : TypeOf<S>;
447
- null: O extends {
448
- null: infer N extends boolean;
449
- } ? N : NullOf<S>;
450
- } : S;
451
- /** A table's attributes after its overrides: changed ones merged, ignored ones gone. */
452
- type OverriddenSpecs<A, O> = { -readonly [K in keyof A as K extends keyof O ? (O[K] extends false ? never : K) : K]: K extends keyof O ? Overridden<A[K], O[K]> : A[K]; };
453
- /** `S` as attribute specs, without widening it to an index signature (which would type any name). */
454
- type AsSpecs<S> = S extends AttributeSpecs ? S : never;
455
- /**
456
- * A generated Model's changes to its table's attributes (`static override attributes = {...} as
457
- * const`): a type name, a spec's changes, or `false` to ignore the column.
458
- */
459
- type AttributeOverrides = Readonly<Record<string, AttributeOverride | false>>;
460
- /** What `active-record schema` generates for one database: its adapter, its tables, and its Models. */
461
- interface DatabaseSchema {
462
- readonly adapter: SchemaAdapter;
463
- readonly tables: TableSchemas;
464
- /**
465
- * The Models the schema was generated for: each one's class name, and its table. Absent only
466
- * while `active-record schema` loads the Models, before it has found them; then nothing is checked.
467
- */
468
- readonly models?: Readonly<Record<string, string>>;
469
- }
470
- //#endregion
471
- //#region src/record-state.d.ts
472
- /** `{ attribute: [before, after] }` */
473
- type Changes = Record<string, [before: unknown, after: unknown]>;
474
- //#endregion
475
- //#region src/comparisons.d.ts
476
- declare const comparedType: unique symbol;
477
- /**
478
- * A comparison condition for one attribute: `where({ age: gte(18) })`. Made by `gt`, `gte`,
479
- * `lt`, `lte` and `between`; a class, so it's never mistaken for a json attribute's value.
480
- */
481
- declare class Comparison<T = unknown> {
482
- #private;
483
- /** Type-only: the compared value's type, checked against the attribute's. */
484
- readonly [comparedType]?: T;
485
- }
486
- /** `attribute > value` */
487
- declare function gt<T>(value: T): Comparison<T>;
488
- /** `attribute >= value`, like Rails' endless range `value..` */
489
- declare function gte<T>(value: T): Comparison<T>;
490
- /** `attribute < value`, like Rails' beginless range `...value` */
491
- declare function lt<T>(value: T): Comparison<T>;
492
- /** `attribute <= value`, like Rails' beginless range `..value` */
493
- declare function lte<T>(value: T): Comparison<T>;
494
- /**
495
- * `attribute BETWEEN start AND end`, both ends included, like Rails' `start..end`. With
496
- * `excludeEnd`, `start <= attribute < end`, like `start...end` (e.g. a window of days).
497
- */
498
- declare function between<T>(start: T, end: T, options?: {
499
- excludeEnd?: boolean;
500
- }): Comparison<T>;
501
- //#endregion
502
- //#region src/relation-checks.d.ts
503
- /**
504
- * Attribute conditions for `where`/`findBy`: a value, an array meaning "any of these", or a
505
- * comparison (`gte(18)`, `between(a, b)`). `null` (alone or in an array) matches NULL, and is
506
- * only allowed for nullable attributes.
507
- */
508
- type Conditions<M> = { [K in keyof AttributesOf<M>]?: AttributesOf<M>[K] | readonly AttributesOf<M>[K][] | ComparisonOf<NonNullable<AttributesOf<M>[K]>>; };
509
- /** Numbers, strings and dates are ordered, so they can be compared; booleans and json can't. */
510
- type ComparisonOf<V> = [V] extends [number | string | Date] ? Comparison<V> : never;
511
- /**
512
- * The attributes a bulk insert or upsert returns of each row it writes: the primary key by
513
- * default, or `false` for none, which sends no `RETURNING`.
514
- */
515
- type Returning<M> = readonly (keyof AttributesOf<M> & string)[] | false;
516
- /**
517
- * `insert`/`insertAll` options: `onDuplicate: "skip"` skips rows that clash with a unique index,
518
- * and `returning` names the attributes to return of each row written.
519
- */
520
- interface InsertOptions<M = unknown> {
521
- onDuplicate?: "skip";
522
- returning?: Returning<M>;
523
- }
524
- /** `upsert`/`upsertAll` options: the attributes of the unique index to match on. */
525
- interface UpsertOptions<M> {
526
- uniqueBy?: (keyof AttributesOf<M> & string) | readonly (keyof AttributesOf<M> & string)[];
527
- returning?: Returning<M>;
528
- }
529
- /** `{ attribute: "asc" | "desc" }`; key order sets precedence. */
530
- type OrderSpec<M> = { [K in keyof AttributesOf<M>]?: OrderDirection | {
531
- direction: OrderDirection;
532
- nulls?: NullsPlacement;
533
- }; };
534
- //#endregion
535
- //#region src/statement.d.ts
536
- declare const rowType: unique symbol;
537
- /**
538
- * What a bulk write resolves to, alone or in `db.batch`: how many rows it inserted, updated or
539
- * deleted, and the attributes an insert or upsert returned of each row it wrote (`returning`,
540
- * the primary key by default), in no promised order. Other writes return no rows.
541
- */
542
- interface WriteResult<Row = Record<string, unknown>> {
543
- rowsAffected: number;
544
- rows: Row[];
545
- }
546
- /** Each returned row's type: the attributes `returning` names, any of them when it names none. */
547
- type ReturnedRow<M, R> = R extends false | readonly [] ? never : R extends readonly (infer K extends keyof AttributesOf<M>)[] ? Pick<AttributesOf<M>, K> : Partial<AttributesOf<M>>;
548
- /**
549
- * A write prepared for `db.batch([...])`, from a Relation's `to…` methods (`toInsert`,
550
- * `toUpdateAll`, `toDeleteAll`, …). It runs on the Database it was built from, and skips
551
- * validations, callbacks and hydration. It has no `then`, so it's never run by being awaited.
552
- */
553
- declare class Statement<Row = never> {
554
- #private;
555
- readonly [rowType]?: Row;
556
- /** The SQL this Statement sends and its bound values, unsent: see `Relation#toSql`. */
557
- toSql(): QuerySql;
558
- }
559
- //#endregion
560
- //#region src/pagination.d.ts
561
- /** What `paginate()` takes: which page, how many records on it, and whether to count them all. */
562
- interface PageOptions {
563
- /** The page, from 1: a number, or untrusted text such as a query string's `"2"`. */
564
- page?: number | string | null;
565
- /** Records on a page, a number or text as `page` is. */
566
- perPage?: number | string | null;
567
- /** `false` skips the `COUNT`: the page has no `total` or `totalPages`. */
568
- count?: boolean;
569
- }
570
- /** A page of records, from `paginate({ count: false })`: where it is, but no total. */
571
- interface CountlessPage<M extends Model> {
572
- records: M[];
573
- page: number;
574
- perPage: number;
575
- hasNext: boolean;
576
- hasPrevious: boolean;
577
- }
578
- /** A page of records, from `paginate()`, with the total it's a page of. */
579
- interface Page<M extends Model> extends CountlessPage<M> {
580
- total: number;
581
- totalPages: number;
582
- }
583
- /** `paginate` as a static of every Model, typed for the class it's called on. */
584
- interface PaginateStatic {
585
- <C extends QueryableClass>(this: C, options: PageOptions & {
586
- count: false;
587
- }): Promise<CountlessPage<InstanceType<C>>>;
588
- <C extends QueryableClass>(this: C, options?: PageOptions & {
589
- count?: true;
590
- }): Promise<Page<InstanceType<C>>>;
591
- <C extends QueryableClass>(this: C, options: PageOptions): Promise<Page<InstanceType<C>> | CountlessPage<InstanceType<C>>>;
592
- }
593
- //#endregion
594
- //#region src/relation.d.ts
595
- declare const scopeTypes: unique symbol;
596
- /** The record type an association accessor loads: `Post` for `HasMany<typeof Post>`. */
597
- type TargetRecord<F> = LoadedValue<F> extends readonly (infer T)[] ? T : NonNullable<LoadedValue<F>>;
598
- /**
599
- * What `includes()` accepts for records `M`: an association name, or `{ name: nested }` where
600
- * `nested` names associations of that association's records. Checked against their fields' types.
601
- */
602
- type IncludeSpec<M> = AssociationName<M> | { readonly [K in AssociationName<M>]?: IncludeSpec<TargetRecord<M[K]>> | readonly IncludeSpec<TargetRecord<M[K]>>[]; };
603
- /** A scope: receives the current Relation and its arguments, and returns a changed Relation. */
604
- type Scope<M extends Model> = (relation: Relation<M>, ...args: any[]) => Relation<M>;
605
- /** The scope methods a Model's scopes `S` add to its Relations: `active()`, `createdAfter(date)`. */
606
- type ScopeMethods<M extends Model, S> = { [K in keyof S]: S[K] extends ((this: never, ...args: infer A) => unknown) ? (...args: A) => Scoped<M, S> : never; };
607
- /** A Relation of Model records `M` with the Model's scope methods `S`. */
608
- type Scoped<M extends Model, S = {}> = [keyof S] extends [never] ? Relation<M, S> : Relation<M, S> & ScopeMethods<M, S>;
609
- /** A lazy, immutable description of a query against one Model. */
610
- declare class Relation<M extends Model, S = {}> {
611
- #private;
612
- /** Type-only: the Model's scopes, so chained calls keep their scope methods. */
613
- readonly [scopeTypes]?: S;
614
- /**
615
- * Relations come from `db.model(Model)` and from other Relations, never `new Relation()`:
616
- * what one is made from is the library's own business.
617
- */
618
- protected constructor(parts: unknown);
619
- where(conditions: Conditions<M> | SafeSql): Scoped<M, S>;
620
- /** Negates the whole condition: `NOT (…)`. Rows where it is NULL are excluded too. */
621
- whereNot(conditions: Conditions<M> | SafeSql): Scoped<M, S>;
622
- /** A Relation that matches nothing and never queries D1; it stays empty when chained. */
623
- none(): Scoped<M, S>;
624
- /**
625
- * Rows matching this Relation's conditions or `other`'s. Both must be of the same Model and
626
- * identical in everything but their conditions (select, order, limit, offset, distinct).
627
- */
628
- or(other: Relation<M, S>): Scoped<M, S>;
629
- /**
630
- * ANDs `other`'s conditions onto this Relation's. For select, order, limit, offset and
631
- * distinct, a clause `other` sets explicitly replaces this one's; one it doesn't set is kept.
632
- * Orders are replaced, not concatenated (a deliberate difference from Rails).
633
- */
634
- merge(other: Relation<M, S>): Scoped<M, S>;
635
- /**
636
- * Sorts by each key in turn (`{ createdAt: "desc" }`, or `{ role: { direction: "asc",
637
- * nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
638
- */
639
- order(spec: OrderSpec<M> | SafeSql): Scoped<M, S>;
640
- /** Replaces the order so far, as in Rails; `reorder()` removes it. */
641
- reorder(spec?: OrderSpec<M> | SafeSql): Scoped<M, S>;
642
- limit(count: number): Scoped<M, S>;
643
- offset(count: number): Scoped<M, S>;
644
- /** Loads only these attributes (a partial record); the primary key is always loaded. */
645
- select(...attributes: (keyof AttributesOf<M> & string)[]): Scoped<M, S>;
646
- /** Removes duplicate rows (of the selected attributes). */
647
- distinct(): Scoped<M, S>;
648
- /**
649
- * Preloads associations for every record this Relation loads, so reading them afterwards
650
- * sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
651
- */
652
- includes(...specs: IncludeSpec<M>[]): Scoped<M, S>;
653
- /**
654
- * A new, unsaved record of this Relation's Model. Built through a hasMany, it joins the
655
- * association, and saving the owner saves it too (autosave).
656
- */
657
- build(attributes?: Partial<AttributesOf<M>>): M;
658
- /**
659
- * Inserts one row now: `await db.model(Post).insert({ title })`. Resolves to how many rows it
660
- * wrote and the `returning` attributes of each (the primary key by default; `false` for none).
661
- * Skips validations and callbacks; declared defaults, generated ids, and timestamps apply, and
662
- * this Relation's equality conditions are inserted too, as with `build()`. A duplicate throws,
663
- * unless `onDuplicate: "skip"` (Rails' `insert`). `toInsert` is the same write, for a batch.
664
- */
665
- insert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: InsertOptions<M> & {
666
- returning?: R;
667
- }): Promise<WriteResult<ReturnedRow<M, R>>>;
668
- /** `insert`, as a Statement for `db.batch([...])`. */
669
- toInsert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: InsertOptions<M> & {
670
- returning?: R;
671
- }): Statement<ReturnedRow<M, R>>;
672
- /** Inserts several rows with the same attributes now, in one statement (Rails' `insert_all!`). */
673
- insertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: InsertOptions<M> & {
674
- returning?: R;
675
- }): Promise<WriteResult<ReturnedRow<M, R>>>;
676
- /** `insertAll`, as a Statement for `db.batch([...])`. */
677
- toInsertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: InsertOptions<M> & {
678
- returning?: R;
679
- }): Statement<ReturnedRow<M, R>>;
680
- /**
681
- * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
682
- * primary key by default): every given attribute but those and `createdAt`, with `updatedAt`
683
- * set, as Rails' `upsert` does. Resolves as `insert` does, returning inserted and updated rows.
684
- */
685
- upsert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: UpsertOptions<M> & {
686
- returning?: R;
687
- }): Promise<WriteResult<ReturnedRow<M, R>>>;
688
- /** `upsert`, as a Statement for `db.batch([...])`. */
689
- toUpsert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: UpsertOptions<M> & {
690
- returning?: R;
691
- }): Statement<ReturnedRow<M, R>>;
692
- /** `upsert` for several rows with the same attributes, now (Rails' `upsert_all`). */
693
- upsertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: UpsertOptions<M> & {
694
- returning?: R;
695
- }): Promise<WriteResult<ReturnedRow<M, R>>>;
696
- /** `upsertAll`, as a Statement for `db.batch([...])`. */
697
- toUpsertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: UpsertOptions<M> & {
698
- returning?: R;
699
- }): Statement<ReturnedRow<M, R>>;
700
- /**
701
- * Updates every row this Relation matches, now, setting attribute values or an `sql`
702
- * fragment: ``updateAll(sql`${column("views")} = ${column("views")} + 1`)``. Resolves to the
703
- * number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone, as in
704
- * Rails. A `none()` Relation sends nothing and resolves to 0.
705
- */
706
- updateAll(changes: Partial<AttributesOf<M>> | SafeSql): Promise<number>;
707
- /** `updateAll`, as a Statement for `db.batch([...])`. */
708
- toUpdateAll(changes: Partial<AttributesOf<M>> | SafeSql): Statement;
709
- /**
710
- * Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany
711
- * association itself (`user.posts().deleteAll()`), the rows' foreign key is set to NULL
712
- * instead unless its `dependent:` deletes, as in Rails. A `none()` Relation sends nothing and
713
- * resolves to 0.
714
- */
715
- deleteAll(): Promise<number>;
716
- /** `deleteAll`, as a Statement for `db.batch([...])`. */
717
- toDeleteAll(): Statement;
718
- /** Builds and saves a record; resolves to it whether or not it was saved (check `isPersisted()`). */
719
- create(attributes?: Partial<AttributesOf<M>>): Promise<M>;
720
- /** Builds and saves a record, throwing if it can't be saved. */
721
- createOrThrow(attributes?: Partial<AttributesOf<M>>): Promise<M>;
722
- /**
723
- * The record with this primary key, keeping this Relation's conditions. With several ids,
724
- * `find(1, 2)` or `find([1, 2])`, the records in the ids' order (or this Relation's order,
725
- * if it has one), as Rails does; `RecordNotFound` if any is missing.
726
- */
727
- find(id: string | number): Promise<M>;
728
- find(ids: readonly (string | number)[]): Promise<M[]>;
729
- find(first: string | number, second: string | number, ...rest: (string | number)[]): Promise<M[]>;
730
- /** The first record matching `conditions` (in no particular order), or null. */
731
- findBy(conditions: Conditions<M> | SafeSql): Promise<M | null>;
732
- /** Like `findBy`, but throws `RecordNotFound` instead of returning null. */
733
- findByOrThrow(conditions: Conditions<M> | SafeSql): Promise<M>;
734
- /** The first record by this Relation's order, or by primary key if it has none. */
735
- first(): Promise<M | null>;
736
- /**
737
- * The last record: the first in the reverse of every order direction. With `limit`/`offset`,
738
- * the last record of that page (loaded, then taken from the end).
739
- */
740
- last(): Promise<M | null>;
741
- /** One record in whatever order D1 returns, or null. */
742
- take(): Promise<M | null>;
743
- /** The number of matching records, or of non-null values of `attribute`. */
744
- count(attribute?: keyof AttributesOf<M> & string): Promise<number>;
745
- /**
746
- * The number of records, as Rails' `size`: a loaded association's (built records included)
747
- * without a query; otherwise a `COUNT(*)`, plus an association's unsaved built records.
748
- */
749
- size(): Promise<number>;
750
- /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
751
- isEmpty(): Promise<boolean>;
752
- /** Whether there are any records: the opposite of `isEmpty()` (Rails' `any?`). */
753
- hasAny(): Promise<boolean>;
754
- /** Whether any record matches, optionally with extra conditions. */
755
- exists(conditions?: Conditions<M> | SafeSql): Promise<boolean>;
756
- /** Converted values of one attribute, or tuples of several, in this Relation's order. */
757
- pluck<K extends keyof AttributesOf<M> & string>(attribute: K): Promise<AttributesOf<M>[K][]>;
758
- pluck<const K extends readonly [keyof AttributesOf<M> & string, keyof AttributesOf<M> & string, ...(keyof AttributesOf<M> & string)[]]>(...attributes: K): Promise<{ -readonly [I in keyof K]: AttributesOf<M>[K[I]]; }[]>;
759
- /**
760
- * One page of records and its total, by this Relation's order or the primary key, in one
761
- * round trip (#100). With `count: false`, no `COUNT`: the page has no total.
762
- */
763
- paginate(options: PageOptions & {
764
- count: false;
765
- }): Promise<CountlessPage<M>>;
766
- paginate(options?: PageOptions & {
767
- count?: true;
768
- }): Promise<Page<M>>;
769
- paginate(options: PageOptions): Promise<Page<M> | CountlessPage<M>>;
770
- /**
771
- * The SQL `toArray()` sends, and its bound values, without sending it (Rails' `to_sql`). Values
772
- * are never inlined into the SQL (ADR-0006), and none are redacted, filtered attributes included.
773
- */
774
- toSql(): QuerySql;
775
- /** Prints as `Relation<Model> { sql, params }`: the SELECT it would send, without sending it (#104). */
776
- [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
777
- toArray(): Promise<M[]>;
778
- }
779
- //#endregion
780
- //#region src/associations.d.ts
781
- /**
782
- * An association's scope, as Rails' `has_many :posts, -> { order(:created_at) }`: it receives
783
- * the target's Relation, with its scopes, and returns a narrowed one.
784
- */
785
- type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>, ScopesOf<C>>) => unknown;
786
- /** What an association declaration takes: the keys that link the Models, and a scope. */
787
- interface AssociationOptions<C extends ModelClass = ModelClass> {
788
- /**
789
- * The attribute holding the link: on the owner for belongsTo, on the target otherwise.
790
- * Inferred when left out, as Rails does: a belongsTo's name + `Id` (`author` → `authorId`),
791
- * or for a hasMany/hasOne the owner's class name + `Id` (`User` → `userId`).
792
- */
793
- foreignKey?: string;
794
- /** The attribute the foreign key points at; defaults to the pointed-at Model's primary key. */
795
- primaryKey?: string;
796
- /** Narrows or orders the target's records for this association: `(q) => q.order(…)`. */
797
- scope?: AssociationScope<C>;
798
- /** What destroying the owner does to this association's records (hasMany and hasOne). */
799
- dependent?: Dependent;
800
- }
801
- /** Rails' `dependent:` strategies for a hasMany. */
802
- type HasManyDependent = "destroy" | "deleteAll" | "nullify" | "restrictWithException" | "restrictWithError";
803
- /** Rails' `dependent:` strategies for a hasOne: `delete` in place of `deleteAll`. */
804
- type HasOneDependent = "destroy" | "delete" | "nullify" | "restrictWithException" | "restrictWithError";
805
- type Dependent = HasManyDependent | HasOneDependent;
806
- /**
807
- * `await post.author()`: the owning record, or null. `post.author.set(user)` points the post at
808
- * another record (Rails' `post.author = user`), and `build`/`create` make a new one for it.
809
- */
810
- interface BelongsTo<C extends ModelClass> {
811
- (): Promise<InstanceType<C> | null>;
812
- set(record: InstanceType<C> | null): void;
813
- build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
814
- create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
815
- createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
816
- }
817
- /**
818
- * `await user.profile()`: the one associated record, or null. `user.profile.build(attrs)` and
819
- * `create(attrs)` make a new one pointing at the user (Rails' `build_profile`).
820
- */
821
- interface HasOne<C extends ModelClass> {
822
- (): Promise<InstanceType<C> | null>;
823
- build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
824
- create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
825
- createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
826
- }
827
- /** `user.posts()`: a Relation of the associated records, with the target's scopes. */
828
- type HasMany<C extends ModelClass> = () => Scoped<InstanceType<C>, ScopesOf<C>>;
829
- //#endregion
830
- //#region src/model-statics.d.ts
831
- /** A Model's Relation, as its statics return them: `Product.where(…)` is `Product.all().where(…)`. */
832
- type RelationOf<C extends ModelClass> = Scoped<InstanceType<C>, ScopesOf<C>>;
833
- /** The Relation methods every Model has as statics (besides the overloaded ones). */
834
- declare const relationMethods: readonly ["where", "whereNot", "none", "or", "merge", "order", "reorder", "limit", "offset", "select", "distinct", "includes", "build", "insert", "toInsert", "insertAll", "toInsertAll", "upsert", "toUpsert", "upsertAll", "toUpsertAll", "updateAll", "toUpdateAll", "deleteAll", "toDeleteAll", "create", "createOrThrow", "findBy", "findByOrThrow", "first", "last", "take", "count", "size", "isEmpty", "hasAny", "exists", "toArray", "toSql"];
835
- /** A Relation method with no overloads, by name. */
836
- type RelationMethod = (typeof relationMethods)[number];
837
- /**
838
- * A Relation method as a static of every Model, typed for the class it's called on: `Product.where`
839
- * returns a Relation of `Product`, and on a subclass, of the subclass.
840
- */
841
- type RelationStatic<K extends RelationMethod> = <C extends QueryableClass>(this: C, ...args: RelationOf<C>[K] extends ((...args: infer A) => unknown) ? A : never) => RelationOf<C>[K] extends ((...args: never) => infer R) ? R : never;
842
- /** Every Relation method in the list as a static, mapped over Relation's so each keeps its doc comment. */
843
- type RelationStatics = { [K in keyof Pick<Relation<Model>, RelationMethod>]: RelationStatic<K>; };
844
- /** The Relation methods with overloads, typed by hand. */
845
- interface OverloadedStatics {
846
- paginate: PaginateStatic;
847
- find: {
848
- <C extends QueryableClass>(this: C, id: string | number): Promise<InstanceType<C>>;
849
- <C extends QueryableClass>(this: C, ids: readonly (string | number)[]): Promise<InstanceType<C>[]>;
850
- <C extends QueryableClass>(this: C, first: string | number, second: string | number, ...rest: (string | number)[]): Promise<InstanceType<C>[]>;
851
- };
852
- pluck: {
853
- <C extends QueryableClass, K extends keyof AttributesOf<InstanceType<C>> & string>(this: C, attribute: K): Promise<AttributesOf<InstanceType<C>>[K][]>;
854
- <C extends QueryableClass, const K extends readonly [keyof AttributesOf<InstanceType<C>> & string, keyof AttributesOf<InstanceType<C>> & string, ...(keyof AttributesOf<InstanceType<C>> & string)[]]>(this: C, ...attributes: K): Promise<{ -readonly [I in keyof K]: AttributesOf<InstanceType<C>>[K[I]]; }[]>;
855
- };
856
- }
857
- /** A callback static, typed for the class it's declared on: `this.beforeSave((record) => …)`. */
858
- type CallbackStatic = <C extends AbstractModelClass>(this: C, callback: Callback<InstanceType<C>>) => void;
859
- /** Every callback kind as a static, each documented here, so its doc comment shows on hover. */
860
- interface CallbackStatics {
861
- /** Runs before the validators, e.g. to normalize input. May `throw abort(reason)`. */
862
- beforeValidation: CallbackStatic;
863
- /** Runs after the validators, whether or not they passed. May `throw abort(reason)`. */
864
- afterValidation: CallbackStatic;
865
- /** Runs before every save (create or update), after validation. May `throw abort(reason)`. */
866
- beforeSave: CallbackStatic;
867
- /** Runs before inserting a new record, after `beforeSave`. May `throw abort(reason)`. */
868
- beforeCreate: CallbackStatic;
869
- /** Runs before updating a persisted record, after `beforeSave`. May `throw abort(reason)`. */
870
- beforeUpdate: CallbackStatic;
871
- /** Runs after a new record was inserted, before `afterSave`. */
872
- afterCreate: CallbackStatic;
873
- /** Runs after a persisted record was saved (even with nothing to write), before `afterSave`. */
874
- afterUpdate: CallbackStatic;
875
- /** Runs after every successful save; the record is already persisted and clean. */
876
- afterSave: CallbackStatic;
877
- /** Runs before deleting the row. May `throw abort(reason)` to refuse the destroy. */
878
- beforeDestroy: CallbackStatic;
879
- /** Runs after the row was deleted; the record is already destroyed. */
880
- afterDestroy: CallbackStatic;
881
- }
882
- /**
883
- * The class Model extends, for its statics' types only: at runtime it's empty, and
884
- * `defineStatics` puts the statics on Model itself, where scopes look for the names they
885
- * can't take.
886
- */
887
- declare const ModelStatics: (abstract new () => object) & RelationStatics & OverloadedStatics & CallbackStatics;
888
- //#endregion
889
- //#region src/validations.d.ts
890
- interface LengthOptions {
891
- minimum?: number;
892
- maximum?: number;
893
- is?: number;
894
- }
895
- interface NumericalityOptions {
896
- onlyInteger?: boolean;
897
- greaterThan?: number;
898
- greaterThanOrEqualTo?: number;
899
- lessThan?: number;
900
- lessThanOrEqualTo?: number;
901
- }
902
- /** The Model's attribute names for record type `R` (any string where `R` isn't known). */
903
- type AttributeName<R> = [R] extends [never] ? string : keyof AttributesOf<R> & string;
904
- interface UniquenessOptions<R = never> {
905
- /** Attributes that must also match for a value to count as taken. */
906
- scope?: readonly AttributeName<R>[];
907
- caseSensitive?: boolean;
908
- }
909
- /** The rules for one `validates(attribute, options)` call. `R` is the Model's record type. */
910
- interface ValidationOptions<R = never> {
911
- /** Not null, and not blank after trimming a string. */
912
- presence?: boolean;
913
- length?: LengthOptions;
914
- format?: RegExp | {
915
- with: RegExp;
916
- };
917
- inclusion?: readonly unknown[] | {
918
- in: readonly unknown[];
919
- };
920
- numericality?: boolean | NumericalityOptions;
921
- /**
922
- * No other row has this value (checked in D1 through the record's Database). `scope` adds
923
- * attributes that must match too; `caseSensitive: false` compares with `lower()` (ASCII only).
924
- * `null` is never taken, as with SQLite's UNIQUE. Not race-safe: the constraint has the final say.
925
- */
926
- uniqueness?: boolean | UniquenessOptions<R>;
927
- /** Skip these rules when the value is null. */
928
- allowNull?: boolean;
929
- /** Replaces the default message of every failure from these rules. */
930
- message?: string;
931
- /** Only run these rules when this returns true. */
932
- if?: (record: R) => boolean;
933
- }
934
- //#endregion
935
- //#region src/model.d.ts
936
- /** Type-only brand on a scope static (`static newest = this.scope(…)`); never set at runtime. */
937
- declare const scopeBrand: unique symbol;
938
- /**
939
- * A scope, as a static on its Model: called on that Model or any class extending it
940
- * (`Product.newest()`), it returns a Relation of that class, with all its scopes.
941
- */
942
- type ScopeStatic<A extends unknown[]> = (<C extends QueryableClass>(this: C, ...args: A) => Scoped<InstanceType<C>, ScopesOf<C>>) & {
943
- readonly [scopeBrand]: true;
944
- };
945
- /** A Model class's scopes: its statics made with `this.scope(…)`, its own and inherited. */
946
- type ScopesOf<C> = { [K in Exclude<keyof C, "prototype"> as C[K] extends {
947
- readonly [scopeBrand]: true;
948
- } ? K : never]: C[K]; };
949
- /** What `loaded()` returns for an association accessor: its records, or its record or null. */
950
- type LoadedValue<F> = F extends (() => Promise<infer R>) ? R : F extends (() => {
951
- toArray(): Promise<infer T>;
952
- }) ? T : never;
953
- /**
954
- * Any association accessor, whatever its target: by shape, since a Relation of one Model isn't
955
- * assignable to a Relation of the library's base class.
956
- */
957
- type AnyAssociation = BelongsTo<any> | HasOne<any> | (() => Relation<any, any>);
958
- /** The names of a record's association accessors (from their fields' types). */
959
- type AssociationName<R> = { [K in keyof R]: R[K] extends AnyAssociation ? K : never; }[keyof R] & string;
960
- /** A lifecycle callback; it receives the record and may be async. */
961
- type Callback<R> = (record: R) => unknown;
962
- /** Type-only key carrying a record's declared attribute types; never set at runtime. */
963
- declare const attributeTypes: unique symbol;
964
- /** An attribute's name on record type `R`. */
965
- type AttributeKey<R> = keyof AttributesOf<R> & string;
966
- /** `from`/`to` for the change checks: only matching when the value was, or became, this. */
967
- interface ChangeOptions<V = unknown> {
968
- from?: V;
969
- to?: V;
970
- }
971
- /**
972
- * What a Model's error messages and attribute names can name: its attributes, its associations
973
- * and `"base"`; any name on a class without attributes (the app's base class).
974
- */
975
- type ErrorAttributeName<R> = [AttributesOf<R>] extends [never] ? string : AttributeKey<R> | AssociationName<R> | "base";
976
- /** The declared attributes of a record type, excluding methods and getters. */
977
- type AttributesOf<M> = M extends {
978
- readonly [attributeTypes]?: infer A;
979
- } ? A : never;
980
- /**
981
- * The library's base class, as Rails' `ActiveRecord::Base`: an app's base class extends it, and
982
- * methods, statics, callbacks and scopes declared there are shared by every Model built on it.
983
- * It has no table, so it's never used as a Model itself.
984
- */
985
- declare class Model extends ModelStatics {
986
- /** The table's name: inferred from the class name (`BlogPost` → `blog_posts`) unless set. */
987
- static table: string;
988
- /** The primary key attribute: the generated table's, or `"id"` unless set. */
989
- static primaryKey: string;
990
- static attributeDefinitions: ReadonlyMap<string, AttributeDefinition>;
991
- /**
992
- * The generated schema, on an app's base class (`static override schema = schema`): the
993
- * Models built on it have its tables' attributes, and query its binding.
994
- */
995
- static schema?: DatabaseSchema;
996
- /**
997
- * A generated Model's changes to its table's attributes, as in the schema: `static override
998
- * attributes = { available: "boolean", internalNotes: false } as const`.
999
- */
1000
- static attributes?: AttributeOverrides;
1001
- /**
1002
- * Marks a class between the app's base class and its Models (`static override abstract =
1003
- * true`): it has no table, it shares its behavior, and each class directly below it has one.
1004
- */
1005
- static abstract?: boolean;
1006
- /**
1007
- * An app-wide query listener, as `connect(env.DB, { onQuery })` is a database's: called for
1008
- * every statement of this Model (and those extending it), whichever database runs it, after
1009
- * the database's own. Holds no request state, so it's safe on a class; a request's ID comes
1010
- * from a database opened for it with `withDatabase` (#78).
1011
- */
1012
- static onQuery: QueryListener | undefined;
1013
- /**
1014
- * Attributes whose values listeners and errors show as "[FILTERED]", as Rails'
1015
- * `filter_attributes`: an attribute whose snake_case name holds a string entry (in any
1016
- * case), or matches a RegExp. Rails' defaults; replace them on the app's base class (#83).
1017
- */
1018
- static filterAttributes: readonly FilterAttribute[];
1019
- /**
1020
- * Attribute names `toJSON()` leaves out, so `Response.json(record)` can't send them. Exact
1021
- * names; none by default. `attributes()` still has them (#101).
1022
- */
1023
- static hiddenAttributes: readonly string[];
1024
- /** An attribute's name as error messages show it: from `humanAttributeNames`, or "Created at". */
1025
- static humanAttributeName(attribute: string): string;
1026
- /** Records on a page of `paginate()` when it isn't given `perPage` (#100). */
1027
- static perPage: number;
1028
- /**
1029
- * The most records on a page of `paginate()`: a larger `perPage`, given or declared, is
1030
- * capped at it, since D1 bills every row read.
1031
- */
1032
- static maxPerPage: number;
1033
- /**
1034
- * Makes the value of an attribute declared with `generateId: true` that wasn't given: a
1035
- * UUID by default. Override it on the app's base class to choose the app's ids
1036
- * (`static override generateId = uuidv7`); it gets the attribute's name, never the record (#99).
1037
- */
1038
- static generateId(_attribute: string): string;
1039
- /**
1040
- * A Model whose attributes are declared here, the single source of truth for them (ADR-0007):
1041
- * `class Visit extends Model.define({ path: "string" }) {}`. It's built on the class it's
1042
- * called on, so a Model made with `ApplicationRecord.define({...})` shares the app's base.
1043
- */
1044
- static define<B extends BaseClass, const A extends AttributeSpecs>(this: B, specs: A & ExactSpecs<A>): ModelBaseFor<A, B>;
1045
- /**
1046
- * Declares a scope, as Rails' `scope :active, -> { … }`: `static active = this.scope((q) =>
1047
- * q.where({ isActive: true }))`. It's a static (`User.active()`) and a Relation method
1048
- * (`User.where(…).active()`), inherited like any static. Inside it, `q` has every Relation
1049
- * method, but not the Model's other scopes (their types would refer to themselves).
1050
- */
1051
- static scope<C extends AbstractModelClass, A extends unknown[]>(this: C, body: (q: Relation<InstanceType<C>>, ...args: A) => Relation<InstanceType<C>>): ScopeStatic<A>;
1052
- /**
1053
- * All of this Model's records, as Rails' `Product.all`: a Relation on the current database
1054
- * (the request's, set with `withDatabase`, or else the binding in its base class's schema).
1055
- */
1056
- static all<C extends QueryableClass>(this: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1057
- /**
1058
- * Only the named attributes of untrusted input (a JSON body, `FormData` or
1059
- * `URLSearchParams`), as Rails' `params.permit`:
1060
- * `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is
1061
- * dropped, and each value is cast as assigning it would be.
1062
- */
1063
- static permit<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, input: unknown, ...names: K[]): Permitted<C, K>;
1064
- /**
1065
- * An attribute's conversions, for SQL d1-record doesn't write, as Rails' `type_for_attribute`:
1066
- * `Post.typeForAttribute("publishedAt").serialize(date)` is what `publishedAt` stores a `Date`
1067
- * as, whatever its `storage`; `cast` and `deserialize` go the other way.
1068
- */
1069
- static typeForAttribute<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, name: K): AttributeConversions<AttributesOf<InstanceType<C>>[K]>;
1070
- /** Declares a validation, e.g. `this.validates("email", { presence: true })` in `static {}`. */
1071
- static validates<C extends AbstractModelClass>(this: C, attribute: keyof AttributesOf<InstanceType<C>> & string, options: ValidationOptions<InstanceType<C>>): void;
1072
- /**
1073
- * Error messages in place of the built-in ones, by type (`blank`, or a type of your own), and
1074
- * under `attributes` by attribute and type. A Model's own win over those of the classes it
1075
- * extends, the app's base class's included; a later call's over an earlier one's (#88).
1076
- */
1077
- static errorMessages<C extends AbstractModelClass>(this: C, messages: ErrorMessages<ErrorAttributeName<InstanceType<C>>>): void;
1078
- /**
1079
- * Attribute names as error messages show them, in place of the name made from the attribute
1080
- * ("createdAt" → "Created at"): `{ createdAt: "Signed up" }`. A Model's own win over those of
1081
- * the classes it extends (#88).
1082
- */
1083
- static humanAttributeNames<C extends AbstractModelClass>(this: C, names: { readonly [K in ErrorAttributeName<InstanceType<C>>]?: string; }): void;
1084
- /** The errors from the last validation run. */
1085
- get errors(): Errors;
1086
- /**
1087
- * A loaded association, synchronously: records for a hasMany, a record or null otherwise.
1088
- * Throws `AssociationNotLoaded` unless it was preloaded with `includes(...)` or already read
1089
- * (and its key hasn't changed since).
1090
- */
1091
- loaded<K extends AssociationName<this>>(name: K): LoadedValue<this[K]>;
1092
- /** Whether the association is loaded: preloaded or already read, for the key held now. */
1093
- isLoaded<K extends AssociationName<this>>(name: K): boolean;
1094
- /**
1095
- * Loads the association again, replacing what's cached, and returns it: Rails'
1096
- * `reload_author`, or `user.posts.reload` for a hasMany.
1097
- */
1098
- reloadAssociation<K extends AssociationName<this>>(name: K): Promise<LoadedValue<this[K]>>;
1099
- /** Why a callback last refused a save or destroy (`abort(reason)`); never copied into `errors`. */
1100
- get abortReason(): string | undefined;
1101
- /** Runs every validation, filling `errors` from scratch; `true` if there are none. */
1102
- isValid(): Promise<boolean>;
1103
- /** Whether any attribute differs from its value as last loaded or saved. */
1104
- isChanged(): boolean;
1105
- /** The names of the changed attributes. */
1106
- changed(): string[];
1107
- /** Each changed attribute's value before the change: `{ email: old }`. */
1108
- changedAttributes(): Record<string, unknown>;
1109
- /** Each changed attribute's value before and after: `{ email: [old, new] }`. */
1110
- changes(): Changes;
1111
- /** The changes the last successful save wrote; use it in after-save callbacks. */
1112
- savedChanges(): Changes;
1113
- /** The attribute's value before its unsaved change, as stored (Rails' `attribute_was`). */
1114
- attributeWas<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1115
- /**
1116
- * Whether the attribute has an unsaved change, optionally `from` and/or `to` given values
1117
- * (Rails' `attribute_changed?(name, from:, to:)`).
1118
- */
1119
- isAttributeChanged<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1120
- /** Whether saving now would write a change to the attribute (for before-callbacks). */
1121
- willSaveChangeTo<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1122
- /** The last save's change to the attribute, `[before, after]`, if it changed (for after-callbacks). */
1123
- savedChangeTo<R extends Model, K extends AttributeKey<R>>(this: R, name: K): [before: AttributesOf<R>[K], after: AttributesOf<R>[K]] | undefined;
1124
- /** Whether the last save changed the attribute, optionally `from` and/or `to` given values. */
1125
- hasSavedChangeTo<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1126
- /** The attribute's value before the last save (its current stored value, if that didn't change it). */
1127
- attributeBeforeLastSave<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1128
- /** Undoes unsaved changes to these attributes (all of them by default), as Rails' `restore_attributes`. */
1129
- restoreAttributes<R extends Model>(this: R, names?: readonly AttributeKey<R>[]): void;
1130
- /** Inserts a new record or updates a persisted one; `false` if it's invalid or a callback aborted. */
1131
- save(): Promise<boolean>;
1132
- /** Like `save()`, but throws `RecordInvalid` or `RecordNotSaved` instead of returning `false`. */
1133
- saveOrThrow(): Promise<true>;
1134
- /** Assigns several attributes without saving. */
1135
- assign(attributes: Partial<AttributesOf<this>>): this;
1136
- /** `assign` then `save`. */
1137
- update(attributes: Partial<AttributesOf<this>>): Promise<boolean>;
1138
- /** `assign` then `saveOrThrow`. */
1139
- updateOrThrow(attributes: Partial<AttributesOf<this>>): Promise<true>;
1140
- /**
1141
- * Deletes the row and resolves to this record, now a read-only destroyed snapshot.
1142
- * A row that's already gone still counts. `false` means a `beforeDestroy` callback aborted.
1143
- */
1144
- destroy(): Promise<this | false>;
1145
- /**
1146
- * This record's save, for `db.batch([...])`: its validations and callbacks run when the batch
1147
- * runs, and every record in the batch is written atomically.
1148
- */
1149
- toSave(): RecordStatement<this>;
1150
- /** This record's destroy, dependents included, for `db.batch([...])`. */
1151
- toDestroy(): RecordStatement<this>;
1152
- /** Like `destroy()`, but throws `RecordNotDestroyed` instead of returning `false`. */
1153
- destroyOrThrow(): Promise<this>;
1154
- /** Loads the stored row again, discarding unsaved changes; `RecordNotFound` if it's gone. */
1155
- reload(): Promise<this>;
1156
- /** Not yet saved: built, or created but not persisted. */
1157
- isNewRecord(): boolean;
1158
- /** Backed by a row: loaded, or saved successfully. */
1159
- isPersisted(): boolean;
1160
- /** Deleted by this instance; a read-only snapshot of the row. */
1161
- isDestroyed(): boolean;
1162
- /** The record's attributes as a plain object of JavaScript values. */
1163
- attributes(): Record<string, unknown>;
1164
- /** Prints as `Name { attribute: value, … }` in a console, a log or a test failure (#104). */
1165
- [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
1166
- /**
1167
- * The loaded attributes as JSON-ready values (dates as ISO strings), without the Model's
1168
- * `hiddenAttributes`, for `Response.json(record)`.
1169
- */
1170
- toJSON(): Record<string, unknown>;
1171
- }
1172
- /** Constructor type for any Model class, used wherever the library accepts one. */
1173
- type ModelClass<M extends Model = Model> = (new () => M) & Omit<typeof Model, "prototype">;
1174
- /**
1175
- * A Model class whose records have attributes, generated or declared with `define`: what the
1176
- * statics that query are called on, so an ungenerated Model's, or an abstract class's, are a
1177
- * compile error.
1178
- */
1179
- type QueryableClass<M extends Model = Model> = ModelClass<M & {
1180
- readonly [attributeTypes]: unknown;
1181
- }>;
1182
- /**
1183
- * What a generated declaration adds to a Model's records: its table's attributes `A`, with the
1184
- * Model's `static attributes` overrides `O` applied, typed.
1185
- */
1186
- type TableAttributes<A extends AttributeSpecs, O = {}> = AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>> & {
1187
- readonly [attributeTypes]: AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>>;
1188
- };
1189
- /**
1190
- * A Model class or a class Models are built on, abstract ones included (the app's base class):
1191
- * what the statics that declare behavior (callbacks, validations, scopes) are called on.
1192
- */
1193
- type AbstractModelClass<M extends Model = Model> = (abstract new () => M) & Omit<typeof Model, "prototype">;
1194
- /** A class to build Models on: `Model`, or an app's class extending it (`ApplicationRecord`'s). */
1195
- type BaseClass = abstract new () => Model;
1196
- /**
1197
- * The base class `Model.define({...})` makes: records with the attributes `A`, built on `B` (the
1198
- * library's base, or an app's), so they have its methods and statics too.
1199
- */
1200
- type ModelBaseFor<A extends AttributeSpecs, B extends BaseClass = typeof Model> = (new () => InstanceType<B> & AttributeProperties<A> & {
1201
- readonly [attributeTypes]: AttributeProperties<A>;
1202
- }) & Omit<B, "prototype">;
1203
- //#endregion
1204
- //#region src/record-statement.d.ts
1205
- declare const recordType: unique symbol;
1206
- /**
1207
- * A record's save or destroy for `db.batch([...])`: `user.toSave()`,
1208
- * `post.toDestroy()`. Unlike a Statement, nothing is compiled yet: the record's
1209
- * validations and callbacks run when the batch runs. It has no `then`, so it's never run by
1210
- * being awaited.
1211
- */
1212
- declare class RecordStatement<R extends Model = Model> {
1213
- #private;
1214
- /** Type-only: the record's type, so a statement of one Model isn't taken for another's. */
1215
- readonly [recordType]?: R;
1216
- }
1217
- //#endregion
1218
- //#region src/batch.d.ts
1219
- /**
1220
- * `db.batch`, on the database the entries were built on: the current one, for statements and
1221
- * records from a Model's statics (`Product.toUpdateAll(…)`, `Product.build(…).toSave()`), or one
1222
- * explicit `db`. Atomic, as `db.batch` is; entries from two databases throw `IncompatibleRelation`.
1223
- */
1224
- declare function batch<const T extends readonly BatchEntry[]>(entries: T): Promise<BatchResults<T>>;
1225
- /** What `db.batch` accepts: statements, and records' save or destroy. */
1226
- type BatchEntry = Statement<unknown> | RecordStatement;
1227
- /** `db.batch`'s result for each entry: a statement's `WriteResult`, or the saved or destroyed record. */
1228
- type BatchResults<T extends readonly BatchEntry[]> = { -readonly [K in keyof T]: T[K] extends RecordStatement<infer R> ? R : T[K] extends Statement<infer Row> ? WriteResult<Row> : never; };
1229
- //#endregion
1230
- //#region src/database.d.ts
1231
- /** One request-bound Relation per Model, keyed like the object passed to `db.models()`. */
1232
- type RelationsFor<T extends Record<string, ModelClass<Model>>> = { [K in keyof T]: Scoped<InstanceType<T[K]>, ScopesOf<T[K]>>; };
1233
- /** The key for a Database's Executor (the current database, #77), for adapters (`/adapter`). */
1234
- declare const databaseExecutor: unique symbol;
1235
- /** A per-request handle on a database; every query goes through it. */
1236
- declare class AnyDatabase {
1237
- #private;
1238
- /** A request-bound Relation over the Model's records, with its scopes as methods. */
1239
- model<C extends ModelClass<Model>>(model: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1240
- /** Request-bound relations for several models at once: `db.models({ User }).User`. */
1241
- models<const T extends Record<string, ModelClass<Model>>>(models: T): RelationsFor<T>;
1242
- /**
1243
- * Runs statements and record statements atomically: all of them are written, or none. Record
1244
- * statements (`user.toSave()`, `post.toDestroy()`) run their validations and before-callbacks
1245
- * first, in order; the first record that's invalid or
1246
- * aborts throws (`RecordInvalid`, `RecordNotSaved`, `RecordNotDestroyed`) and nothing is sent.
1247
- * After the batch, each record takes its saved state and runs its after-callbacks, in order.
1248
- * Resolves to each entry's result: a statement's `{ rowsAffected, rows }`, the record for a
1249
- * record statement.
1250
- */
1251
- batch<const T extends readonly BatchEntry[]>(entries: T): Promise<BatchResults<T>>;
1252
- }
1253
- //#endregion
1254
- //#region src/adapter.d.ts
1255
- /** What a database's error says about a constraint that failed. */
1256
- interface ConstraintFailure {
1257
- kind: "unique" | "notNull" | "foreignKey" | "check";
1258
- /** The table the error names, if it names one. */
1259
- table: string | undefined;
1260
- /** The columns the error names, if any. */
1261
- columns: string[];
1262
- }
1263
- /**
1264
- * What a generated schema names (`adapter: d1({ binding: "DB" })`): the kind of database its
1265
- * Models are on, and which of its databases. Made by an adapter's own function.
1266
- */
1267
- interface SchemaAdapter {
1268
- readonly adapter: Adapter;
1269
- /** The database's name in the app's config, its Binding: on D1, a Wrangler binding (`DB`). */
1270
- readonly binding: string;
1271
- }
1272
- /** One kind of database (ADR-0016). A `Driver` sends to one database of that kind. */
1273
- interface Adapter {
1274
- /** What the database is called in messages. */
1275
- readonly name: string;
1276
- readonly dialect: Dialect;
1277
- /** The most values one statement can bind. */
1278
- readonly maxBoundValues: number;
1279
- /** What `error` says failed, or undefined when it isn't a constraint failure. */
1280
- constraintFailure(error: unknown): ConstraintFailure | undefined;
1281
- /** The table `error` says doesn't exist, or undefined when it says something else. */
1282
- missingTable(error: unknown): string | undefined;
1283
- /** The error to throw when `error` means the query couldn't run here at all, or undefined. */
1284
- refusal(error: unknown): Error | undefined;
1285
- /**
1286
- * The database a query from a Model's statics uses now: one of the request's, `requested`, or
1287
- * this adapter's own for `binding`, the name in the Model's schema. A Model with no schema has
1288
- * none. Throws `NoDatabase` when there isn't one.
1289
- */
1290
- databaseFor(binding: string | undefined, requested: readonly AnyDatabase[]): Promise<AnyDatabase>;
1291
- }
1292
- //#endregion
1293
- export { ErrorMessages as $, Page as A, Comparison as B, HasOne as C, ScopeMethods as D, Scope as E, Conditions as F, lte as G, gt as H, InsertOptions as I, TableSchemas as J, DatabaseSchema as K, OrderSpec as L, ReturnedRow as M, Statement as N, Scoped as O, WriteResult as P, ErrorMessage as Q, Returning as R, HasManyDependent as S, Relation as T, gte as U, between as V, lt as W, ValidationError as X, Errors as Y, AttributeErrorMessages as Z, UniquenessOptions as _, ColumnValue as _t, RelationsFor as a, AttributeSpecs as at, BelongsTo as b, sql$1 as bt, BatchResults as c, DatabaseExecutor as ct, Model as d, Driver as dt, RestrictMessages as et, ModelClass as f, StatementResult as ft, NumericalityOptions as g, ColumnReference as gt, LengthOptions as h, Dialect as ht, AnyDatabase as i, AttributeSpec as it, PageOptions as j, CountlessPage as k, batch as l, QueryEvent as lt, TableAttributes as m, QuerySql as mt, ConstraintFailure as n, boundValue as nt, databaseExecutor as o, AttributeType as ot, ScopeStatic as p, CompiledSql as pt, TableSchema as q, SchemaAdapter as r, AttributeConversions as rt, BatchEntry as s, EpochStorage as st, Adapter as t, FilterAttribute as tt, RecordStatement as u, QueryListener as ut, ValidationOptions as v, SafeSql as vt, HasOneDependent as w, HasMany as x, AssociationOptions as y, column as yt, UpsertOptions as z };