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