@forestfuture/active-record 0.7.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.
Files changed (33) hide show
  1. package/config-schema.json +6 -2
  2. package/dist/adapter.d.mts +3 -3
  3. package/dist/adapter.mjs +5 -4
  4. package/dist/batch-ReqVoCfa.mjs +9559 -0
  5. package/dist/cli.d.mts +55 -33
  6. package/dist/cli.mjs +4 -4
  7. package/dist/command.mjs +530 -271
  8. package/dist/d1.d.mts +2 -10
  9. package/dist/d1.mjs +0 -0
  10. package/dist/epoch-storage-CDlQZcBB.mjs +988 -0
  11. package/dist/{for-adapters-t3-LukJQ.d.mts → for-adapters-B0xMP6Dq.d.mts} +8 -6
  12. package/dist/{for-adapters-D_Iu0gS_.mjs → for-adapters-CfXMGeOu.mjs} +3 -5
  13. package/dist/{for-adapters-Ch6CoHD4.mjs → for-adapters-DhNV1mWf.mjs} +46 -10
  14. package/dist/{generated-model-Cnt0Ot9q.mjs → generated-model-g5oWsDKE.mjs} +728 -540
  15. package/dist/index-BATasvJa.d.mts +241 -0
  16. package/dist/index.d.mts +4 -3
  17. package/dist/index.mjs +5 -4
  18. package/dist/metadata-CzntpYzC.d.mts +182 -0
  19. package/dist/{plugin-Cyoej7qV.mjs → plugin-wOSILvSB.mjs} +211 -112
  20. package/dist/{plugin-XOHYndhP.mjs → plugin-x5-d3TSN.mjs} +148 -52
  21. package/dist/postgresql.d.mts +1 -9
  22. package/dist/postgresql.mjs +42 -26
  23. package/dist/src-D56_3odT.mjs +46 -0
  24. package/dist/{storage-override-CpbkdIqE.mjs → storage-override-n4w1cS_M.mjs} +61 -28
  25. package/dist/validations-DHDVV8hB.d.mts +1996 -0
  26. package/llms-full.txt +2354 -363
  27. package/package.json +1 -1
  28. package/skills/active-record/SKILL.md +22 -14
  29. package/dist/adapter-AGKp6wfO.d.mts +0 -1326
  30. package/dist/batch-BS_WseLf.mjs +0 -4255
  31. package/dist/epoch-storage-o2aoOH7H.mjs +0 -112
  32. package/dist/index-CyCJuM96.d.mts +0 -149
  33. package/dist/src-la_KkjCS.mjs +0 -1
@@ -0,0 +1,1996 @@
1
+ import { a as AttributeType, c as ValueSource, d as EnumNames, f as EnumValues, g as CustomType, h as AnyCustomType, i as AttributeSpecs, m as TextEnum, n as AttributeProperties, o as ExactSpecs, p as IntegerEnum, s as SpecObject, t as AttributeDefinition, u as EnumMapping } from "./metadata-CzntpYzC.mjs";
2
+ /** What `comparison` compares: numbers with numbers, strings with strings, Dates by their time. */
3
+ type Comparable = number | string | Date;
4
+ /** A bound: a value, or a function of the record being validated (`(event) => event.startsAt`). */
5
+ type ComparisonBound<R = never> = Comparable | ((record: R) => Comparable | null);
6
+ /** The bounds of a `comparison` rule, with Rails' error types as keys. `R` is the record type. */
7
+ interface ComparisonOptions<R = never> {
8
+ greaterThan?: ComparisonBound<R>;
9
+ greaterThanOrEqualTo?: ComparisonBound<R>;
10
+ lessThan?: ComparisonBound<R>;
11
+ lessThanOrEqualTo?: ComparisonBound<R>;
12
+ equalTo?: ComparisonBound<R>;
13
+ otherThan?: ComparisonBound<R>;
14
+ }
15
+ /** `S` in camelCase, as a method names it: `in_progress` → `inProgress`. */
16
+ type CamelCase<S extends string> = S extends `${infer Head}_${infer Tail}` ? `${Head}${Capitalize<CamelCase<Tail>>}` : S;
17
+ /** How a word reads inside a method's name: `in_progress` → `InProgress`. */
18
+ type MethodPart<N extends string> = Capitalize<CamelCase<N>>;
19
+ /** A `prefix` or `suffix` in a method's name: the attribute's name for `true`, else the word given. */
20
+ type Affix<K, A> = A extends true ? MethodPart<K & string> : A extends string ? MethodPart<A> : "";
21
+ /** The option `O` of a spec, if it gives one. */
22
+ type OptionOf<S, O extends string> = S extends { readonly [key in O]: infer V; } ? V : undefined;
23
+ /**
24
+ * Each name of attribute `K`'s enum as its methods name it, its prefix and suffix around it
25
+ * (`StatusActive`, `ActiveLevel`), or never for an attribute with no enum.
26
+ */
27
+ type Stems<K, S> = S extends {
28
+ enum: infer E extends EnumValues;
29
+ } ? `${Affix<K, OptionOf<S, "prefix">>}${MethodPart<EnumNames<E>>}${Affix<K, OptionOf<S, "suffix">>}` : never;
30
+ /** Every stem the enums of the specs `A` give a record's methods, unless one says `instanceMethods: false`. */
31
+ type RecordStems<A> = { [K in keyof A]: A[K] extends {
32
+ instanceMethods: false;
33
+ } ? never : Stems<K, A[K]>; }[keyof A];
34
+ /** Every stem the enums of the specs `A` give a Model's scopes, unless one says `scopes: false`. */
35
+ type ScopeStems<A> = { [K in keyof A]: A[K] extends {
36
+ scopes: false;
37
+ } ? never : Stems<K, A[K]>; }[keyof A];
38
+ /**
39
+ * What the enums of the specs `A` add to a record: a predicate for each name, and a setter that
40
+ * assigns it and saves, with its `OrThrow`, as Rails' `published!` updates the record.
41
+ */
42
+ type EnumMethods<A> = { [P in `is${RecordStems<A>}`]: () => boolean; } & { [P in `saveAs${RecordStems<A>}`]: () => Promise<boolean>; } & { [P in `saveAs${RecordStems<A>}OrThrow`]: () => Promise<true>; };
43
+ /** What the enums of the specs `A` add to a Model: a scope for each name, and a `not…` scope. */
44
+ type EnumStatics<A> = { [P in Uncapitalize<ScopeStems<A>> | `not${ScopeStems<A>}`]: ScopeStatic<[]>; };
45
+ /**
46
+ * A SQL fragment built with the `sql` tagged template (ADR-0006). The template
47
+ * text is written by the developer; every interpolated value is bound as a
48
+ * parameter and never becomes SQL text.
49
+ */
50
+ declare class SafeSql {
51
+ readonly strings: readonly string[];
52
+ readonly values: readonly unknown[];
53
+ }
54
+ declare function sql$1(strings: TemplateStringsArray, ...values: unknown[]): SafeSql;
55
+ /** A reference to an attribute's column, resolved against the query's Model when compiled. */
56
+ declare class ColumnReference {
57
+ readonly attribute: string;
58
+ /**
59
+ * A value of this attribute for a fragment, converted as the attribute stores it: a `Date`
60
+ * as the integer of an attribute kept as a Unix time, a boolean as 0 or 1, and so on. It's
61
+ * still a bound parameter. Without it, a value has no attribute to say how it's stored (#142).
62
+ */
63
+ value(value: unknown): ColumnValue;
64
+ }
65
+ /** A value of an attribute, from `column(attribute).value(value)`, converted when compiled. */
66
+ declare class ColumnValue {
67
+ readonly attribute: string;
68
+ /** What was given, before it's cast as an assigned value of the attribute. */
69
+ readonly assigned: unknown;
70
+ }
71
+ /** Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004). */
72
+ declare function column(attribute: string): ColumnReference;
73
+ type OrderDirection = "asc" | "desc";
74
+ type NullsPlacement = "first" | "last";
75
+ /** A part of a query `unscope()` drops: one by name, or the conditions on some attributes. */
76
+ type UnscopedPart = "where" | "order" | "limit" | "offset" | "select" | "distinct" | "includes" | "joins" | "leftJoins" | "createWith" | {
77
+ readonly where: readonly string[];
78
+ };
79
+ /**
80
+ * One attribute's value path, resolved once per Model class by `attributeFor` (#163). Which
81
+ * Model and attribute a refusal names, whether the attribute is filtered, and how its type is
82
+ * stored are known here, so a caller only says what the value is for.
83
+ */
84
+ declare class Attribute {
85
+ #private;
86
+ readonly name: string;
87
+ readonly column: string;
88
+ /** Whether it's a `string` attribute, which D1 compares as text, not by number. */
89
+ get isText(): boolean;
90
+ /** Whether it's a `binary` attribute, whose cells are bytes, which JSON can't hold (#20). */
91
+ get isBinary(): boolean;
92
+ /** Whether it's a `json` attribute, whose stored text is JSON itself. */
93
+ get isJson(): boolean;
94
+ /**
95
+ * An assigned value (a setter, `build`, `update`, `insert`, `permit`) as the attribute's type:
96
+ * only what's unambiguous for it (#81). `undefined` throws, as it would store NULL silently;
97
+ * what can't be cast throws `TypeError` naming the Model and attribute, showing the value
98
+ * unless the attribute is filtered (#83).
99
+ */
100
+ cast(value: unknown): unknown;
101
+ /**
102
+ * A key copied from another record or inherited from a condition: cast as a condition's, but
103
+ * one that can't be cast throws, naming the association it came through.
104
+ */
105
+ key(value: unknown, association?: string): unknown;
106
+ /**
107
+ * A condition's value (`where`, `find`, a preload) as the attribute's type, or `noMatch`: a
108
+ * number also matches a string attribute as its digits, and a value that can't be cast
109
+ * matches nothing, so a value from a URL is never an error.
110
+ */
111
+ condition(value: unknown): unknown;
112
+ /** A condition's value in the form D1 stores, or `noMatch`. */
113
+ conditionCell(value: unknown): unknown;
114
+ /**
115
+ * An already cast value in the form D1 stores. A `json` value changed in place into one JSON
116
+ * can't write throws `TypeError` naming the attribute, as assigning it would (#146).
117
+ */
118
+ write(value: unknown): unknown;
119
+ /** An assigned value cast, then in the form D1 stores. */
120
+ store(value: unknown): unknown;
121
+ /**
122
+ * A cell D1 returned as the attribute's value. One that isn't (text in a Unix time column, or
123
+ * past the range of a `Date`; a json cell that isn't JSON) throws `TypeError` naming the
124
+ * attribute, with the cell hidden if it's filtered, not the parser's own error (#73, #146).
125
+ */
126
+ read(cell: unknown): unknown;
127
+ /** A copy of a value: written as D1 stores it, then read back. */
128
+ copy(value: unknown): unknown;
129
+ /**
130
+ * Whether two values are the same as stored (dates by time, json and bytes by content). Each is
131
+ * cast as a condition's value first, so `isAttributeChanged`'s `from` and `to` compare as
132
+ * Rails' do, and one that can't be cast is the same as nothing (#20).
133
+ */
134
+ isSame(a: unknown, b: unknown): boolean;
135
+ /** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
136
+ bind(params: unknown[], value: unknown): void;
137
+ /**
138
+ * Binds cells (as D1 holds them) as the attribute's, each hidden from `onQuery` listeners when
139
+ * the attribute is filtered (#83); D1 still gets the real values. Filtering is asked at the
140
+ * time, since `filterAttributes` is a static a Model may set after this was resolved.
141
+ */
142
+ bindCells(params: unknown[], ...cells: unknown[]): void;
143
+ }
144
+ /**
145
+ * Where compiled SQL binds a value, in its own order. A dialect writes each as its database's
146
+ * placeholder once the SQL is complete, so a `?` in a raw `sql` fragment's text (Postgres's jsonb
147
+ * operator) is never read as one. NUL, since no database accepts it in a statement's text.
148
+ */
149
+ declare const valueMark = "\0";
150
+ /** The SQL a database needs in its own form. Everything else in the compiler is shared. */
151
+ interface Dialect {
152
+ /** The placeholder for the `index`th bound value, from 1: `?`, or `$1`. */
153
+ placeholder(index: number): string;
154
+ /**
155
+ * `column`, of `attribute`, in a list of `cells` bound as one value, so any length fits a
156
+ * statement's limits.
157
+ */
158
+ inList(column: string, cells: readonly unknown[], attribute: Attribute): {
159
+ sql: string;
160
+ value: unknown;
161
+ };
162
+ /**
163
+ * The place of `column`'s value in a list of `cells` (a NULL among them included) bound as one
164
+ * value, for `inOrderOf` (#350): earlier values sort first, and a value not in it is NULL.
165
+ */
166
+ placeInList(column: string, cells: readonly unknown[], attribute: Attribute): {
167
+ sql: string;
168
+ value: unknown;
169
+ };
170
+ /** `limit` and `offset`, at least one of them set, as this database writes them, their values added to `params`. */
171
+ pagination(limit: number | undefined, offset: number | undefined, params: unknown[]): string;
172
+ /**
173
+ * Where a bulk insert into `table` (quoted) reads its rows of `attributes`, from one bound JSON
174
+ * value: its SELECT list and FROM.
175
+ */
176
+ bulkRows(table: string, attributes: readonly Attribute[]): {
177
+ select: string;
178
+ from: string;
179
+ };
180
+ /**
181
+ * The most UTF-8 bytes one bound value may hold, when the database caps it: a bulk write whose
182
+ * rows would pass it is sent as several statements, in one atomic batch (#392).
183
+ */
184
+ maxValueBytes?: number;
185
+ /**
186
+ * The owners' `key` (a quoted column, of `keyAttribute`) as a linked condition selects it, so
187
+ * it matches `linked`'s column as a condition on `linked` would: by text for a text attribute.
188
+ */
189
+ linkedKey(key: string, keyAttribute: Attribute, linked: Attribute): string;
190
+ /**
191
+ * A bulk removal (a DELETE, or an UPDATE nullifying a key) and the counter caches it changes
192
+ * (#61), as one statement: `decrements` writes the counters' UPDATEs, given SQL counting the rows
193
+ * removed, and the statement returns one row, whose `removed` is how many. Without it, the
194
+ * counters are taken down by a COUNT sent just before the removal: exact where writes run one
195
+ * at a time.
196
+ */
197
+ countedRemoval?(removal: CompiledSql, decrements: (removed: string) => readonly CompiledSql[]): CompiledSql;
198
+ }
199
+ /** One SQL statement ready to send, with the Model whose table it reads or writes. */
200
+ interface CompiledSql {
201
+ sql: string;
202
+ params: unknown[];
203
+ model: ModelClass<Model>;
204
+ }
205
+ /** What `toSql()` shows: a query's SQL, with its values bound apart from it (ADR-0006). */
206
+ interface QuerySql {
207
+ sql: string;
208
+ params: unknown[];
209
+ }
210
+ /** What `user.posts()` has besides its Relation's methods, as Rails' collection proxy does. */
211
+ interface CollectionMethods<M extends Model> {
212
+ /**
213
+ * Adds records to the association (Rails' `<<`): sets each one's foreign key and saves them
214
+ * together, resolving to `false`, with nothing written, if one can't be saved.
215
+ */
216
+ push(...records: M[]): Promise<boolean>;
217
+ /**
218
+ * Removes records from the association by its `dependent:` strategy, as Rails' collection
219
+ * `delete`: destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and
220
+ * otherwise sets their foreign key to NULL. Resolves to the records.
221
+ */
222
+ delete(...records: M[]): Promise<M[]>;
223
+ /**
224
+ * Destroys records of the association, callbacks and dependents included, whatever its
225
+ * `dependent:` is, in one write: if one refuses, it throws `RecordNotDestroyed` and nothing
226
+ * is destroyed. Resolves to the records.
227
+ */
228
+ destroy(...records: M[]): Promise<M[]>;
229
+ /**
230
+ * Removes every record of the association as `deleteAll()` does, by its `dependent:`, and
231
+ * forgets the records built through it: afterwards it reads as empty without a query.
232
+ */
233
+ clear(): Promise<void>;
234
+ /**
235
+ * Destroys every record of the association, callbacks and dependents included, whatever its
236
+ * `dependent:` is, in one write, as `destroy` does; then it reads as empty without a query.
237
+ * Resolves to the records.
238
+ */
239
+ destroyAll(): Promise<M[]>;
240
+ }
241
+ /** What Node's `util.inspect` passes a custom inspector; `src/` doesn't import Node's types. */
242
+ interface InspectOptions {
243
+ depth?: number | null;
244
+ /** Wraps text in the color for a kind of value, or returns it as is when colors are off. */
245
+ stylize?: (text: string, style: "special") => string;
246
+ }
247
+ type Inspect = (value: unknown, options?: InspectOptions) => string;
248
+ /** Node and workerd call a value's inspector under this registered symbol. */
249
+ declare const inspectCustom: unique symbol;
250
+ /** What `inOrderOf` takes after its list: whether to keep only the records with a listed value. */
251
+ interface InOrderOfOptions {
252
+ /** Keep only the records whose value is in the list (the default), as Rails does; `false` keeps every one, those not in it last. */
253
+ filter?: boolean;
254
+ }
255
+ /** A part of a query `unscope` drops by name: `unscope("order")`. */
256
+ type QueryPart = Exclude<UnscopedPart, object>;
257
+ /** One attribute's name, or several: what `unscope({ where })` takes. */
258
+ type AttributeNames<M extends Model> = (keyof AttributesOf<M> & string) | readonly (keyof AttributesOf<M> & string)[];
259
+ declare const comparedType: unique symbol;
260
+ /**
261
+ * A comparison condition for one attribute: `where({ age: gte(18) })`. Made by `gt`, `gte`,
262
+ * `lt`, `lte` and `between`; a class, so it's never mistaken for a json attribute's value.
263
+ */
264
+ declare class Comparison<T = unknown> {
265
+ #private;
266
+ /** Type-only: the compared value's type, checked against the attribute's. */
267
+ readonly [comparedType]?: T;
268
+ }
269
+ /** `attribute > value` */
270
+ declare function gt<T>(value: T): Comparison<T>;
271
+ /** `attribute >= value`, like Rails' endless range `value..` */
272
+ declare function gte<T>(value: T): Comparison<T>;
273
+ /** `attribute < value`, like Rails' beginless range `...value` */
274
+ declare function lt<T>(value: T): Comparison<T>;
275
+ /** `attribute <= value`, like Rails' beginless range `..value` */
276
+ declare function lte<T>(value: T): Comparison<T>;
277
+ /**
278
+ * `attribute BETWEEN start AND end`, both ends included, like Rails' `start..end`. With
279
+ * `excludeEnd`, `start <= attribute < end`, like `start...end` (e.g. a window of days).
280
+ */
281
+ declare function between<T>(start: T, end: T, options?: {
282
+ excludeEnd?: boolean;
283
+ }): Comparison<T>;
284
+ /**
285
+ * Attribute conditions for `where`/`findBy`: a value, an array meaning "any of these", or a
286
+ * comparison (`gte(18)`, `between(a, b)`). `null` (alone or in an array) matches NULL, and is
287
+ * only allowed for nullable attributes.
288
+ */
289
+ type Conditions<M> = { [K in keyof AttributesOf<M>]?: AttributesOf<M>[K] | readonly AttributesOf<M>[K][] | ComparisonOf<NonNullable<AttributesOf<M>[K]>>; };
290
+ /**
291
+ * Values that can be compared: numbers, strings, dates, bytes (byte by byte), and a custom
292
+ * type's values, compared as their stored values are (#20). Booleans and json (`unknown`) can't
293
+ * be, nor a custom type stored as either, which `where` refuses when it's called.
294
+ */
295
+ type ComparisonOf<V> = [V] extends [boolean] ? never : unknown extends V ? never : Comparison<V>;
296
+ /**
297
+ * The attributes a bulk insert or upsert returns of each row it writes: the primary key by
298
+ * default, or `false` for none, which sends no `RETURNING`.
299
+ */
300
+ type Returning<M> = readonly (keyof AttributesOf<M> & string)[] | false;
301
+ /**
302
+ * `insert`/`insertAll` options: `onDuplicate: "skip"` skips rows that clash with a unique index,
303
+ * and `returning` names the attributes to return of each row written.
304
+ */
305
+ interface InsertOptions<M = unknown> {
306
+ onDuplicate?: "skip";
307
+ returning?: Returning<M>;
308
+ }
309
+ /** `upsert`/`upsertAll` options: the attributes of the unique index to match on. */
310
+ interface UpsertOptions<M> {
311
+ uniqueBy?: (keyof AttributesOf<M> & string) | readonly (keyof AttributesOf<M> & string)[];
312
+ returning?: Returning<M>;
313
+ }
314
+ /** `{ attribute: "asc" | "desc" }`; key order sets precedence. */
315
+ type OrderSpec<M> = { [K in keyof AttributesOf<M>]?: OrderDirection | {
316
+ direction: OrderDirection;
317
+ nulls?: NullsPlacement;
318
+ }; };
319
+ /** One statement's result, the same on every database. */
320
+ interface StatementResult {
321
+ /** The rows it returned: a read's, or a write's `RETURNING`. */
322
+ rows: Record<string, unknown>[];
323
+ /** How many rows it inserted, updated or deleted. */
324
+ rowsAffected: number;
325
+ /** The database's own timing for it, when it reports one. */
326
+ durationMs?: number | undefined;
327
+ /** The database's own detail about it, for `onQuery` (D1's `meta`). */
328
+ meta?: unknown;
329
+ }
330
+ /**
331
+ * Sends statements to one database. It knows nothing of Models, `onQuery` or error classes.
332
+ * `Scope` is what it holds for a `withDatabase` scope, handed back with each statement sent inside it.
333
+ */
334
+ interface Driver<Scope = unknown> {
335
+ /** Sends one statement, inside `scope` when one was opened. */
336
+ send(statement: CompiledSql, scope?: Scope): Promise<StatementResult>;
337
+ /** Sends reads at once where it can, resolving to each one's result. They needn't be atomic. */
338
+ read(statements: readonly CompiledSql[], scope?: Scope): Promise<StatementResult[]>;
339
+ /** Sends writes atomically, all or none, resolving to each one's result. */
340
+ write(statements: readonly CompiledSql[], scope?: Scope): Promise<StatementResult[]>;
341
+ /** Whether sending again can succeed after `error`, having readied the connection for it. */
342
+ recover(error: unknown): boolean;
343
+ /**
344
+ * A `withDatabase` call with this database has begun: what the driver holds for it, such as a
345
+ * connection, until `closeScope`. Each call opens its own, so overlapping requests sharing a
346
+ * Database never share one; a call nested in a running one with the same database shares the
347
+ * outer's. Statements sent after it ended (a `waitUntil` save) are still handed it.
348
+ */
349
+ openScope?(): Scope;
350
+ /**
351
+ * The scope `openScope` returned has ended: what it holds can be let go once its statements
352
+ * finish. `withDatabase` waits for it, so it shouldn't wait for them.
353
+ */
354
+ closeScope?(scope: Scope): Promise<void>;
355
+ }
356
+ declare const rowType: unique symbol;
357
+ /**
358
+ * What a bulk write resolves to, alone or in `db.batch`: how many rows it inserted, updated or
359
+ * deleted, and the attributes an insert or upsert returned of each row it wrote (`returning`,
360
+ * the primary key by default), in no promised order. Other writes return no rows.
361
+ */
362
+ interface WriteResult<Row = Record<string, unknown>> {
363
+ rowsAffected: number;
364
+ rows: Row[];
365
+ }
366
+ /** Each returned row's type: the attributes `returning` names, any of them when it names none. */
367
+ 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>>;
368
+ /**
369
+ * A bulk write prepared in a batch, by a Batch's methods (`b.insert`, `b.updateAll`,
370
+ * `b.deleteAll`, …). It runs on the Database it was built from, and skips validations,
371
+ * callbacks and hydration. It has no `then`, so it's never run by being awaited.
372
+ */
373
+ declare class Statement<Row = never> {
374
+ #private;
375
+ readonly [rowType]?: Row;
376
+ }
377
+ /**
378
+ * What a new record is handed to, once its attributes are assigned and before it's saved (Rails'
379
+ * block): `create({ email }, (user) => { user.role = "member" })`. Awaited where it's saved.
380
+ */
381
+ type Init<M> = (record: M) => void | Promise<void>;
382
+ /** Two or more of a Model's attributes, as `pluck` and `pick` take them for tuples. */
383
+ type AttributeList<M extends Model> = readonly [keyof AttributesOf<M> & string, keyof AttributesOf<M> & string, ...(keyof AttributesOf<M> & string)[]];
384
+ /** The types a sum or an average takes; a custom type stored as one of them too. */
385
+ declare const numberTypes: readonly ["integer", "real", "decimal"];
386
+ /** The types with no minimum or maximum: Postgres has none of a boolean, json or bytes. */
387
+ declare const unorderedTypes: readonly ["boolean", "json", "binary"];
388
+ /** The built-in type a spec is stored as: its type, or its custom type's `storedAs`. */
389
+ type StoredTypeOf<S> = (S extends {
390
+ type: infer T;
391
+ } ? T : S) extends (infer T) ? T extends CustomType<unknown, infer B> ? B : T : never;
392
+ /**
393
+ * The attributes of record type `M` a sum or an average takes: those stored as integers, reals
394
+ * or decimals, a custom type's too, but not an enum's.
395
+ */
396
+ type NumberAttribute<M> = { [K in keyof SpecsOf<M>]: SpecsOf<M>[K] extends {
397
+ enum: EnumValues;
398
+ } ? never : StoredTypeOf<SpecsOf<M>[K]> extends (typeof numberTypes)[number] ? K : never; }[keyof SpecsOf<M>] & keyof AttributesOf<M> & string;
399
+ /** The attributes of record type `M` with a minimum and maximum: not booleans, json or bytes. */
400
+ type OrderedAttribute<M> = { [K in keyof SpecsOf<M>]: StoredTypeOf<SpecsOf<M>[K]> extends (typeof unorderedTypes)[number] ? never : K; }[keyof SpecsOf<M>] & keyof AttributesOf<M> & string;
401
+ /**
402
+ * What a calculation of `K` resolves to besides `null`: an attribute's value, or for an `sql`
403
+ * fragment, `Fragment` (a sum's number, or an extreme's `unknown` cell).
404
+ */
405
+ type CalculatedValue<M, K, Fragment = number> = K extends SafeSql ? Fragment : NonNullable<AttributesOf<M>[K & keyof AttributesOf<M>]>;
406
+ /** What `group` takes for records `M`: one term or more. */
407
+ type GroupTerms<M> = readonly [GroupTerm<M>, ...GroupTerm<M>[]];
408
+ /** What `group` takes for records `M`: an attribute but a json one, or an `sql` fragment. */
409
+ type GroupTerm<M> = GroupableAttribute<M> | SafeSql;
410
+ /** The attributes of `M` that can be grouped: not json, which Postgres can't compare. */
411
+ type GroupableAttribute<M> = { [K in keyof SpecsOf<M>]: StoredTypeOf<SpecsOf<M>[K]> extends "json" ? never : K; }[keyof SpecsOf<M>] & keyof AttributesOf<M> & string;
412
+ /** A group's key for one term: an attribute's value (null included), or a fragment's cell. */
413
+ type TermKey<M, T> = T extends SafeSql ? unknown : AttributesOf<M>[T & keyof AttributesOf<M>];
414
+ /** A group's key: one term's value, or a tuple of several terms' values. */
415
+ type GroupKey<M, G extends readonly unknown[]> = G extends readonly [infer Only] ? TermKey<M, Only> : { -readonly [I in keyof G]: TermKey<M, G[I]>; };
416
+ /**
417
+ * A Relation grouped by `group(...)`: its calculations resolve to a Map from each group's key to
418
+ * the group's result, in the order the database returns the groups. It holds no records.
419
+ */
420
+ declare class GroupedRelation<M extends Model, G extends readonly GroupTerm<M>[]> {
421
+ #private;
422
+ /** Type-only: the terms it's grouped by, which type its keys. */
423
+ readonly groupTerms?: G;
424
+ /** Grouped Relations come from `group()`, never `new GroupedRelation()`. */
425
+ protected constructor(parts: unknown);
426
+ /** Only the rows matching `conditions`, as `where` on a Relation. */
427
+ where(conditions: Conditions<M> | SafeSql): GroupedRelation<M, G>;
428
+ /** Leaves out the rows matching `conditions`, as `whereNot` on a Relation. */
429
+ whereNot(conditions: Conditions<M> | SafeSql): GroupedRelation<M, G>;
430
+ /** Sorts the groups by grouped attributes, or a fragment such as ``sql`COUNT(*) DESC` ``. */
431
+ order(spec: OrderSpec<M> | SafeSql): GroupedRelation<M, G>;
432
+ /** Replaces the order, as `reorder` on a Relation. */
433
+ reorder(spec?: OrderSpec<M> | SafeSql): GroupedRelation<M, G>;
434
+ /** At most `count` groups. */
435
+ limit(count: number): GroupedRelation<M, G>;
436
+ /** Skips the first `count` groups. */
437
+ offset(count: number): GroupedRelation<M, G>;
438
+ /** Calculates each group's distinct values: a count, sum or average takes each once. */
439
+ distinct(): GroupedRelation<M, G>;
440
+ /** Matches nothing: each calculation is an empty Map, without a query. */
441
+ none(): GroupedRelation<M, G>;
442
+ /** Groups by more terms too, which join the key. */
443
+ group<const H extends GroupTerms<M>>(...terms: H): GroupedRelation<M, [...G, ...H]>;
444
+ /**
445
+ * Keeps the groups an `sql` fragment matches, written with their aggregates:
446
+ * ``having(sql`COUNT(*) > ${1}`)``. Several are ANDed.
447
+ */
448
+ having(condition: SafeSql): GroupedRelation<M, G>;
449
+ /** The number of rows in each group, or of their non-null values of `attribute`. */
450
+ count(attribute?: keyof AttributesOf<M> & string): Promise<Map<GroupKey<M, G>, number>>;
451
+ /** Each group's sum of `attribute`'s values or a fragment's, as `sum` on a Relation. */
452
+ sum<K extends NumberAttribute<M> | SafeSql>(attribute: K): Promise<Map<GroupKey<M, G>, CalculatedValue<M, K>>>;
453
+ /** Each group's mean of `attribute`'s values or a fragment's, or `null` with none. */
454
+ average(attribute: NumberAttribute<M> | SafeSql): Promise<Map<GroupKey<M, G>, number | null>>;
455
+ /** Each group's least value of `attribute` or a fragment, or `null` with none. */
456
+ minimum<K extends OrderedAttribute<M> | SafeSql>(attribute: K): Promise<Map<GroupKey<M, G>, CalculatedValue<M, K, unknown> | null>>;
457
+ /** Each group's greatest value of `attribute` or a fragment, or `null` with none. */
458
+ maximum<K extends OrderedAttribute<M> | SafeSql>(attribute: K): Promise<Map<GroupKey<M, G>, CalculatedValue<M, K, unknown> | null>>;
459
+ /** The calculation `operation` names, of each group, typed as that method is. */
460
+ calculate(operation: "count", attribute?: keyof AttributesOf<M> & string): Promise<Map<GroupKey<M, G>, number>>;
461
+ calculate<K extends NumberAttribute<M> | SafeSql>(operation: "sum", attribute: K): Promise<Map<GroupKey<M, G>, CalculatedValue<M, K>>>;
462
+ calculate(operation: "average", attribute: NumberAttribute<M> | SafeSql): Promise<Map<GroupKey<M, G>, number | null>>;
463
+ calculate<K extends OrderedAttribute<M> | SafeSql>(operation: "minimum" | "maximum", attribute: K): Promise<Map<GroupKey<M, G>, CalculatedValue<M, K, unknown> | null>>;
464
+ }
465
+ /** What `findEach`, `findInBatches` and `inBatches` take. */
466
+ interface IterationOptions {
467
+ /** Records in each batch: each is one query. 1000 by default. */
468
+ batchSize?: number;
469
+ /** The primary key to start from, included: the smallest, or with `order: "desc"`, the largest. */
470
+ start?: string | number;
471
+ /** The primary key to finish at, included: the largest, or with `order: "desc"`, the smallest. */
472
+ finish?: string | number;
473
+ /** `"asc"` (the default) from the smallest primary key up, or `"desc"` from the largest down. */
474
+ order?: "asc" | "desc";
475
+ }
476
+ declare const scopeTypes: unique symbol;
477
+ /** A scope: receives the current Relation and its arguments, and returns a changed Relation. */
478
+ type Scope<M extends Model> = (relation: Relation<M>, ...args: any[]) => Relation<M>;
479
+ /** The scope methods a Model's scopes `S` add to its Relations: `active()`, `createdAfter(date)`. */
480
+ 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; };
481
+ /** A Relation of Model records `M` with the Model's scope methods `S`. */
482
+ type Scoped<M extends Model, S = {}> = [keyof S] extends [never] ? Relation<M, S> : Relation<M, S> & ScopeMethods<M, S>;
483
+ /** A lazy, immutable description of a query against one Model. */
484
+ declare class Relation<M extends Model, S = {}> {
485
+ #private;
486
+ /** Type-only: the Model's scopes, so chained calls keep their scope methods. */
487
+ readonly [scopeTypes]?: S;
488
+ /**
489
+ * Relations come from `db.model(Model)` and from other Relations, never `new Relation()`:
490
+ * what one is made from is the library's own business.
491
+ */
492
+ protected constructor(parts: unknown);
493
+ where(conditions: Conditions<M> | SafeSql): Scoped<M, S>;
494
+ /** Negates the whole condition: `NOT (…)`. Rows where it is NULL are excluded too. */
495
+ whereNot(conditions: Conditions<M> | SafeSql): Scoped<M, S>;
496
+ /**
497
+ * Replaces the conditions on these attributes with these, as Rails' `rewhere`: those on other
498
+ * attributes, and fragments, are kept.
499
+ */
500
+ rewhere(conditions: Conditions<M>): Scoped<M, S>;
501
+ /**
502
+ * Drops parts of the query, as Rails' `unscope`: `unscope("order", "limit")`, or the conditions
503
+ * on some attributes, `unscope({ where: "role" })`. A default scope's are dropped too.
504
+ */
505
+ unscope(...parts: (QueryPart | {
506
+ where: AttributeNames<M>;
507
+ })[]): Scoped<M, S>;
508
+ /** Keeps only these parts of the query, as Rails' `only`: `only("where", "order")`. */
509
+ only(...parts: QueryPart[]): Scoped<M, S>;
510
+ /**
511
+ * Leaves these records out, by primary key, as Rails' `excluding`: `excluding(post)`, or
512
+ * `excluding(posts)`. A record not yet saved leaves nothing out.
513
+ */
514
+ excluding(...records: (M | readonly M[])[]): Scoped<M, S>;
515
+ /** A Relation that matches nothing and never queries D1; it stays empty when chained. */
516
+ none(): Scoped<M, S>;
517
+ /**
518
+ * Rows matching this Relation's conditions or `other`'s. Both must be of the same Model and
519
+ * identical in everything but their conditions (select, order, limit, offset, distinct).
520
+ */
521
+ or(other: Relation<M, S>): Scoped<M, S>;
522
+ /**
523
+ * ANDs `other`'s conditions onto this Relation's. For select, order, limit, offset and
524
+ * distinct, a clause `other` sets explicitly replaces this one's; one it doesn't set is kept.
525
+ * Orders are replaced, not concatenated (a deliberate difference from Rails). `other` may be a
526
+ * Relation of a Model this one joins once (#24): its conditions apply to the joined table.
527
+ */
528
+ merge<T extends Model = M, O = S>(other: Relation<T, O>): Scoped<M, S>;
529
+ /**
530
+ * Sorts by each key in turn (`{ createdAt: "desc" }`, or `{ role: { direction: "asc",
531
+ * nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
532
+ */
533
+ order(spec: OrderSpec<M> | SafeSql): Scoped<M, S>;
534
+ /** Replaces the order so far, as in Rails; `reorder()` removes it. */
535
+ reorder(spec?: OrderSpec<M> | SafeSql): Scoped<M, S>;
536
+ /**
537
+ * Orders by `attribute`'s place in `values`, then by any order after it, as Rails' `in_order_of`:
538
+ * `inOrderOf("status", ["open", "paid"])`. Keeps only the records with one of them, unless
539
+ * `filter: false`, which keeps the rest after them.
540
+ */
541
+ inOrderOf<K extends keyof AttributesOf<M> & string>(attribute: K, values: readonly AttributesOf<M>[K][], { filter }?: InOrderOfOptions): Scoped<M, S>;
542
+ limit(count: number): Scoped<M, S>;
543
+ offset(count: number): Scoped<M, S>;
544
+ /** Loads only these attributes (a partial record); the primary key is always loaded. */
545
+ select(...attributes: (keyof AttributesOf<M> & string)[]): Scoped<M, S>;
546
+ /** Removes duplicate rows (of the selected attributes). */
547
+ distinct(): Scoped<M, S>;
548
+ /**
549
+ * Preloads associations for every record this Relation loads, so reading them afterwards
550
+ * sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
551
+ */
552
+ includes(...specs: IncludeSpec<M>[]): Scoped<M, S>;
553
+ /**
554
+ * Joins associations (`INNER JOIN`), so only records with a linked record are found:
555
+ * `joins("author")`, nested `joins({ author: "company" })`. Loads only this Model's columns.
556
+ */
557
+ joins(...specs: JoinSpec<M>[]): Scoped<M, S>;
558
+ /** Joins associations as `joins()` does, but with `LEFT OUTER JOIN`: unlinked records stay. */
559
+ leftJoins(...specs: JoinSpec<M>[]): Scoped<M, S>;
560
+ /**
561
+ * Attributes for the records this Relation builds, creates or inserts, but not conditions its
562
+ * finders use: `createWith({ role: "member" }).findOrCreateBy({ email })`. Added to any it has;
563
+ * `null` removes them. They win over its conditions' values. Attributes given to `build` or
564
+ * `create` win over them, and a bulk write such as `insert` writes them over its own (#470).
565
+ */
566
+ createWith(attributes: Partial<AttributesOf<M>> | null): Scoped<M, S>;
567
+ /**
568
+ * A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing
569
+ * awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it
570
+ * joins the association, and saving the owner saves it too (autosave).
571
+ */
572
+ build(attributes?: Partial<AttributesOf<M>>, init?: (record: M) => void): M;
573
+ /**
574
+ * Inserts one row now: `await db.model(Post).insert({ title })`. Resolves to how many rows it
575
+ * wrote and the `returning` attributes of each (the primary key by default; `false` for none).
576
+ * Skips validations and callbacks; declared defaults, generated ids, and timestamps apply, and
577
+ * this Relation's equality conditions are inserted over the given attributes (#470). A
578
+ * duplicate throws, unless `onDuplicate: "skip"` (Rails' `insert`). `b.insert` is the same
579
+ * write, for a batch.
580
+ */
581
+ insert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: InsertOptions<M> & {
582
+ returning?: R;
583
+ }): Promise<WriteResult<ReturnedRow<M, R>>>;
584
+ /**
585
+ * Inserts several rows with the same attributes now (Rails' `insert_all!`): in one statement,
586
+ * or several in one atomic batch when they pass the database's cap on one value.
587
+ */
588
+ insertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: InsertOptions<M> & {
589
+ returning?: R;
590
+ }): Promise<WriteResult<ReturnedRow<M, R>>>;
591
+ /**
592
+ * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
593
+ * primary key by default): every given attribute and every value this Relation writes into the
594
+ * row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set, as Rails'
595
+ * `upsert` does. Resolves as `insert` does, returning inserted and updated rows.
596
+ */
597
+ upsert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: UpsertOptions<M> & {
598
+ returning?: R;
599
+ }): Promise<WriteResult<ReturnedRow<M, R>>>;
600
+ /** `upsert` for several rows with the same attributes, now (Rails' `upsert_all`). */
601
+ upsertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: UpsertOptions<M> & {
602
+ returning?: R;
603
+ }): Promise<WriteResult<ReturnedRow<M, R>>>;
604
+ /**
605
+ * Updates every row this Relation matches, now, setting attribute values or an `sql`
606
+ * fragment: ``updateAll(sql`${column("views")} = ${column("views")} + 1`)``. Resolves to the
607
+ * number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone, as in
608
+ * Rails. A `none()` Relation sends nothing and resolves to 0.
609
+ */
610
+ updateAll(changes: Partial<AttributesOf<M>> | SafeSql): Promise<number>;
611
+ /**
612
+ * Adds to number attributes in every row this Relation matches, now, in one statement:
613
+ * `updateCounters({ viewCount: 1 })` sets `view_count = COALESCE(view_count, 0) + 1`, so
614
+ * concurrent writes all count. Resolves to the number of rows; skips what `updateAll` skips.
615
+ */
616
+ updateCounters(counters: Counters<M>, { touch }?: CounterOptions<M>): Promise<number>;
617
+ /**
618
+ * Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany
619
+ * association itself (`user.posts().deleteAll()`), the rows' foreign key is set to NULL
620
+ * instead unless its `dependent:` deletes, as in Rails. A `none()` Relation sends nothing and
621
+ * resolves to 0.
622
+ */
623
+ deleteAll(): Promise<number>;
624
+ /**
625
+ * Loads the records this Relation matches and destroys each, callbacks and `dependent:`
626
+ * strategies included, as one write: if one refuses, it throws `RecordNotDestroyed` and nothing
627
+ * is destroyed. Resolves to the records, each once, though a join repeats it (#24). A `none()`
628
+ * Relation sends nothing and resolves to [].
629
+ * Through a hasMany, what its owner loaded is cleared.
630
+ */
631
+ destroyAll(): Promise<M[]>;
632
+ /** Destroys the records matching `conditions`, as `where(conditions).destroyAll()` does. */
633
+ destroyBy(conditions: Conditions<M> | SafeSql): Promise<M[]>;
634
+ /** Deletes the rows matching `conditions`, as `where(conditions).deleteAll()` does. */
635
+ deleteBy(conditions: Conditions<M> | SafeSql): Promise<number>;
636
+ /**
637
+ * Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or
638
+ * not it was saved (check `isPersisted()`).
639
+ */
640
+ create(attributes?: Partial<AttributesOf<M>>, init?: Init<M>): Promise<M>;
641
+ /** Like `create`, but throws if the record can't be saved. */
642
+ createOrThrow(attributes?: Partial<AttributesOf<M>>, init?: Init<M>): Promise<M>;
643
+ /**
644
+ * The record with this primary key, keeping this Relation's conditions. With several ids,
645
+ * `find(1, 2)` or `find([1, 2])`, the records in the ids' order (or this Relation's order,
646
+ * if it has one), as Rails does; `RecordNotFound` if any is missing.
647
+ */
648
+ find(id: string | number): Promise<M>;
649
+ find(ids: readonly (string | number)[]): Promise<M[]>;
650
+ find(first: string | number, second: string | number, ...rest: (string | number)[]): Promise<M[]>;
651
+ /** The first record matching `conditions` (in no particular order), or null. */
652
+ findBy(conditions: Conditions<M> | SafeSql): Promise<M | null>;
653
+ /**
654
+ * The first record with these attributes or, when none has them, one created with them (and
655
+ * handed to `init` before it's saved), as `create` does: check `isPersisted()`. Two requests at
656
+ * once can both create one; `createOrFindBy` is safe from that.
657
+ */
658
+ findOrCreateBy(attributes: Partial<AttributesOf<M>>, init?: Init<M>): Promise<M>;
659
+ /** Like `findOrCreateBy`, but throws if the record it creates can't be saved. */
660
+ findOrCreateByOrThrow(attributes: Partial<AttributesOf<M>>, init?: Init<M>): Promise<M>;
661
+ /**
662
+ * The first record with these attributes or, when none has them, a new one built with them and
663
+ * handed to `init`, which is awaited. Saves nothing.
664
+ */
665
+ findOrInitializeBy(attributes: Partial<AttributesOf<M>>, init?: Init<M>): Promise<M>;
666
+ /**
667
+ * Creates a record with these attributes (handing it to `init` first), as `create` does, or,
668
+ * when a unique index refuses it (`RecordNotUnique`), finds the record with these attributes:
669
+ * safe where two requests create at once, as `findOrCreateBy` isn't. Throws `RecordNotFound`
670
+ * if the index refused a value the attributes don't name. A record `init` gave others to save
671
+ * with it throws its `RecordNotUnique`, which may be theirs.
672
+ */
673
+ createOrFindBy(attributes: Partial<AttributesOf<M>>, init?: Init<M>): Promise<M>;
674
+ /** Like `createOrFindBy`, but throws if the record can't be saved. */
675
+ createOrFindByOrThrow(attributes: Partial<AttributesOf<M>>, init?: Init<M>): Promise<M>;
676
+ /** Like `findBy`, but throws `RecordNotFound` instead of returning null. */
677
+ findByOrThrow(conditions: Conditions<M> | SafeSql): Promise<M>;
678
+ /**
679
+ * The only matching record: `RecordNotFound` with none, `SoleRecordExceeded` with more than one.
680
+ * A join that repeats a record counts it each time.
681
+ */
682
+ sole(): Promise<M>;
683
+ /** The only record matching `conditions`, as `where(conditions).sole()` finds it. */
684
+ findSoleBy(conditions: Conditions<M> | SafeSql): Promise<M>;
685
+ /** The first record by this Relation's order, or by primary key if it has none. */
686
+ first(): Promise<M | null>;
687
+ /**
688
+ * The last record: the first in the reverse of every order direction. With `limit`/`offset`,
689
+ * the last record of that page (loaded, then taken from the end).
690
+ */
691
+ last(): Promise<M | null>;
692
+ /** One record in whatever order D1 returns, or null. */
693
+ take(): Promise<M | null>;
694
+ /** Like `first`, but throws `RecordNotFound` instead of returning null. */
695
+ firstOrThrow(): Promise<M>;
696
+ /** Like `last`, but throws `RecordNotFound` instead of returning null. */
697
+ lastOrThrow(): Promise<M>;
698
+ /** Like `take`, but throws `RecordNotFound` instead of returning null. */
699
+ takeOrThrow(): Promise<M>;
700
+ /** The number of matching records, or of non-null values of `attribute`. */
701
+ count(attribute?: keyof AttributesOf<M> & string): Promise<number>;
702
+ /** The total of `attribute`'s values over the records, leaving out NULLs; 0 with none. */
703
+ sum<K extends NumberAttribute<M> | SafeSql>(attribute: K): Promise<CalculatedValue<M, K>>;
704
+ /** The mean of `attribute`'s values over the records, leaving out NULLs; null with none. */
705
+ average(attribute: NumberAttribute<M> | SafeSql): Promise<number | null>;
706
+ /** The least of `attribute`'s values over the records, leaving out NULLs; null with none. */
707
+ minimum<K extends OrderedAttribute<M> | SafeSql>(attribute: K): Promise<CalculatedValue<M, K, unknown> | null>;
708
+ /** The greatest of `attribute`'s values over the records, leaving out NULLs; null with none. */
709
+ maximum<K extends OrderedAttribute<M> | SafeSql>(attribute: K): Promise<CalculatedValue<M, K, unknown> | null>;
710
+ /**
711
+ * The calculation `operation` names, of `attribute`: `calculate("sum", "total")` is
712
+ * `sum("total")`, and `calculate("count")` is `count()`.
713
+ */
714
+ calculate(operation: "count", attribute?: keyof AttributesOf<M> & string): Promise<number>;
715
+ calculate<K extends NumberAttribute<M> | SafeSql>(operation: "sum", attribute: K): Promise<CalculatedValue<M, K>>;
716
+ calculate(operation: "average", attribute: NumberAttribute<M> | SafeSql): Promise<number | null>;
717
+ calculate<K extends OrderedAttribute<M> | SafeSql>(operation: "minimum" | "maximum", attribute: K): Promise<CalculatedValue<M, K, unknown> | null>;
718
+ /** Groups the rows by attributes or `sql` fragments, for each group's calculations (#345). */
719
+ group<const G extends GroupTerms<M>>(...terms: G): GroupedRelation<M, G>;
720
+ /**
721
+ * The number of records, as Rails' `size`: a loaded association's (built records included)
722
+ * without a query; otherwise a `COUNT(*)`, plus an association's unsaved built records.
723
+ */
724
+ size(): Promise<number>;
725
+ /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
726
+ isEmpty(): Promise<boolean>;
727
+ /** Whether there are any records: the opposite of `isEmpty()` (Rails' `any?`). */
728
+ hasAny(): Promise<boolean>;
729
+ /** Whether more than one record matches, as Rails' `many?`: one `COUNT` of at most two rows. */
730
+ hasMoreThanOne(): Promise<boolean>;
731
+ /** Whether exactly one record matches, as Rails' `one?`: one `COUNT` of at most two rows. */
732
+ hasExactlyOne(): Promise<boolean>;
733
+ /** Whether any record matches, optionally with extra conditions. */
734
+ exists(conditions?: Conditions<M> | SafeSql): Promise<boolean>;
735
+ /** Converted values of one attribute, or tuples of several, in this Relation's order. */
736
+ pluck<K extends keyof AttributesOf<M> & string>(attribute: K): Promise<AttributesOf<M>[K][]>;
737
+ pluck<const K extends AttributeList<M>>(...attributes: K): Promise<{ -readonly [I in keyof K]: AttributesOf<M>[K[I]]; }[]>;
738
+ /** The first row's value of one attribute, or tuple of several, in this Relation's order; or null. */
739
+ pick<K extends keyof AttributesOf<M> & string>(attribute: K): Promise<AttributesOf<M>[K] | null>;
740
+ pick<const K extends AttributeList<M>>(...attributes: K): Promise<{ -readonly [I in keyof K]: AttributesOf<M>[K[I]]; } | null>;
741
+ /**
742
+ * Each record's primary key, in this Relation's order: `pluck` of the primary key, leaving out a
743
+ * loaded association's built records that have no key yet.
744
+ */
745
+ ids(): Promise<(string | number)[]>;
746
+ /**
747
+ * One page of records and its total, by this Relation's order or the primary key, in one
748
+ * round trip (#100). With `count: false`, no `COUNT`: the page has no total.
749
+ */
750
+ paginate(options: PageOptions & {
751
+ count: false;
752
+ }): Promise<CountlessPage<M>>;
753
+ paginate(options?: PageOptions & {
754
+ count?: true;
755
+ }): Promise<Page<M>>;
756
+ paginate(options: PageOptions): Promise<Page<M> | CountlessPage<M>>;
757
+ /**
758
+ * Each record this Relation matches, in primary-key order, loaded a batch at a time (#347):
759
+ * `for await (const user of User.findEach())`.
760
+ */
761
+ findEach(options?: IterationOptions): AsyncIterable<M>;
762
+ /** This Relation's records as arrays of up to `batchSize`, in primary-key order (#347). */
763
+ findInBatches(options?: IterationOptions): AsyncIterable<M[]>;
764
+ /**
765
+ * A Relation of each batch's records, in primary-key order (#347), to write a batch at a time:
766
+ * `for await (const posts of drafts.inBatches()) await posts.deleteAll()`.
767
+ */
768
+ inBatches(options?: IterationOptions): AsyncIterable<Scoped<M, S>>;
769
+ /**
770
+ * The SQL `toArray()` sends, and its bound values, without sending it (Rails' `to_sql`). Values
771
+ * are never inlined into the SQL (ADR-0006), and none are redacted, filtered attributes included.
772
+ */
773
+ toSql(): QuerySql;
774
+ /** Prints as `Relation<Model> { sql, params }`: the SELECT it would send, without sending it (#104). */
775
+ [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
776
+ toArray(): Promise<M[]>;
777
+ }
778
+ /**
779
+ * An association's scope, as Rails' `has_many :posts, -> { order(:created_at) }`: it receives
780
+ * the target's Relation, with its scopes, and returns a narrowed one.
781
+ */
782
+ type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>, ScopesOf<C>>) => unknown;
783
+ /** What an association declaration takes: the keys that link the Models, and a scope. */
784
+ interface AssociationOptions<C extends ModelClass = ModelClass> {
785
+ /**
786
+ * The attribute holding the link: on the owner for belongsTo, on the target otherwise.
787
+ * Inferred when left out, as Rails does: a belongsTo's name + `Id` (`author` → `authorId`),
788
+ * or for a hasMany/hasOne the owner's `modelName` + `Id` (`User` → `userId`).
789
+ */
790
+ foreignKey?: string;
791
+ /** The attribute the foreign key points at; defaults to the pointed-at Model's primary key. */
792
+ primaryKey?: string;
793
+ /** Narrows or orders the target's records for this association: `(q) => q.order(…)`. */
794
+ scope?: AssociationScope<C>;
795
+ /** What destroying the owner does to this association's records (hasMany and hasOne). */
796
+ dependent?: Dependent;
797
+ /**
798
+ * Saving the owner also saves this association's loaded records that changed, and destroys
799
+ * those marked with `markForDestruction()`, as Rails' `autosave: true` does (#37).
800
+ */
801
+ autosave?: true;
802
+ }
803
+ /**
804
+ * What an association through another takes (#59): `projects = hasMany(Project, { through:
805
+ * "assignments" })`. Its keys and `autosave` are its hops'; a hasMany's `dependent` acts on its
806
+ * join records (`ThroughDependent`).
807
+ */
808
+ interface ThroughOptions<C extends ModelClass = ModelClass> {
809
+ /** The owner's association it reaches its records through: one to the join Model. */
810
+ through: string;
811
+ /**
812
+ * The association of the `through` association's Model that reaches the records. Left out, it's
813
+ * the one named as this association, singular or plural (`projects` → `project`, `projects`).
814
+ */
815
+ source?: string;
816
+ /** Narrows or orders its records: `(q) => q.order(…)`. */
817
+ scope?: AssociationScope<C>;
818
+ }
819
+ /**
820
+ * What destroying the owner, and removing records with `delete`, do to a hasMany through
821
+ * another's join records (#434): destroy them, callbacks included, or delete their rows.
822
+ */
823
+ type ThroughDependent = "destroy" | "deleteAll";
824
+ /** Rails' `dependent:` strategies for a hasMany. */
825
+ type HasManyDependent = "destroy" | "deleteAll" | "nullify" | "restrictWithException" | "restrictWithError";
826
+ /** Rails' `dependent:` strategies for a hasOne: `delete` in place of `deleteAll`. */
827
+ type HasOneDependent = "destroy" | "delete" | "nullify" | "restrictWithException" | "restrictWithError";
828
+ type Dependent = HasManyDependent | HasOneDependent;
829
+ /**
830
+ * `await post.author()`: the owning record, or null. `post.author.set(user)` points the post at
831
+ * another record (Rails' `post.author = user`), and `build`/`create` make a new one for it.
832
+ */
833
+ interface BelongsTo<C extends ModelClass> {
834
+ (): Promise<InstanceType<C> | null>;
835
+ set(record: InstanceType<C> | null): void;
836
+ build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
837
+ create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
838
+ createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
839
+ }
840
+ /**
841
+ * `await remark.commentable()`: the record a polymorphic belongsTo points at (#60), of whichever
842
+ * listed Model its type names, or null. `remark.commentable.set(post)` points it at another,
843
+ * setting both the type and the key. There's no `build` or `create`: which Model to make isn't
844
+ * known.
845
+ */
846
+ interface PolymorphicBelongsTo<C extends ModelClass> {
847
+ (): Promise<InstanceType<C> | null>;
848
+ set(record: InstanceType<C> | null): void;
849
+ }
850
+ /**
851
+ * `await user.profile()`: the one associated record, or null. `await user.profile.set(profile)`
852
+ * gives the user another (Rails' `user.profile = profile`), and `build(attrs)` and
853
+ * `create(attrs)` make a new one pointing at the user (Rails' `build_profile`). Each replaces the
854
+ * old record, removed by `dependent:` when the new one is written.
855
+ */
856
+ interface HasOne<C extends ModelClass> {
857
+ (): Promise<InstanceType<C> | null>;
858
+ set(record: InstanceType<C> | null): Promise<void>;
859
+ build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
860
+ create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
861
+ createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
862
+ }
863
+ /**
864
+ * `user.posts()`: a Relation of the associated records, with the target's scopes, and the
865
+ * collection methods (`push`, `delete`, `destroy`, `clear`) that only the association itself has.
866
+ */
867
+ type HasMany<C extends ModelClass> = () => HasManyCollection<InstanceType<C>, ScopesOf<C>>;
868
+ /**
869
+ * `note.tags()` for an association through another (#59): a Relation of its records, which
870
+ * reads and preloads as any hasMany's, with the collection methods. Its writes go to its join
871
+ * records (#434): `push`, `build` and `create` make one, and `delete`, `destroy`, `clear`, and
872
+ * its own `deleteAll` and `destroyAll` remove them. Inserting and upserting, which make none, are typed `never`,
873
+ * so it's still a Relation, for `or`, `merge` and a batch's `updateAll`.
874
+ */
875
+ type HasManyThrough<C extends ModelClass> = () => Scoped<InstanceType<C>, ScopesOf<C>> & CollectionMethods<InstanceType<C>> & { readonly [W in ThroughWrite]: never; };
876
+ /** The writes a through association's own Relation refuses (#434): they make no join records. */
877
+ type ThroughWrite = "insert" | "insertAll" | "upsert" | "upsertAll";
878
+ /**
879
+ * `await mark.note()` for a hasOne through another (#59): its record, or null. `set(note)`
880
+ * points the owner's join record at another (#434); as in Rails, it has no `build` or `create`.
881
+ */
882
+ interface HasOneThrough<C extends ModelClass> {
883
+ (): Promise<InstanceType<C> | null>;
884
+ /**
885
+ * Points the owner's join record at `record`, saved at once on a saved owner, or builds one
886
+ * through the association it goes through; `null` destroys the join record.
887
+ */
888
+ set(record: InstanceType<C> | null): Promise<void>;
889
+ /** Type-only: marks the accessor, so a record method returning a Promise isn't one. */
890
+ readonly [throughTarget]: C;
891
+ }
892
+ declare const throughTarget: unique symbol;
893
+ /** What a hasMany accessor returns: its Relation, with the collection methods. */
894
+ type HasManyCollection<M extends Model, S = {}> = Scoped<M, S> & CollectionMethods<M>;
895
+ /** What `paginate()` takes: which page, how many records on it, and whether to count them all. */
896
+ interface PageOptions {
897
+ /** The page, from 1: a number, or untrusted text such as a query string's `"2"`. */
898
+ page?: number | string | null;
899
+ /** Records on a page, a number or text as `page` is. */
900
+ perPage?: number | string | null;
901
+ /** `false` skips the `COUNT`: the page has no `total` or `totalPages`. */
902
+ count?: boolean;
903
+ }
904
+ /** A page of records, from `paginate({ count: false })`: where it is, but no total. */
905
+ interface CountlessPage<M extends Model> {
906
+ records: M[];
907
+ page: number;
908
+ perPage: number;
909
+ hasNext: boolean;
910
+ hasPrevious: boolean;
911
+ }
912
+ /** A page of records, from `paginate()`, with the total it's a page of. */
913
+ interface Page<M extends Model> extends CountlessPage<M> {
914
+ total: number;
915
+ totalPages: number;
916
+ }
917
+ /** `paginate` as a static of every Model, typed for the class it's called on. */
918
+ interface PaginateStatic {
919
+ <C extends QueryableClass>(this: C, options: PageOptions & {
920
+ count: false;
921
+ }): Promise<CountlessPage<InstanceType<C>>>;
922
+ <C extends QueryableClass>(this: C, options?: PageOptions & {
923
+ count?: true;
924
+ }): Promise<Page<InstanceType<C>>>;
925
+ <C extends QueryableClass>(this: C, options: PageOptions): Promise<Page<InstanceType<C>> | CountlessPage<InstanceType<C>>>;
926
+ }
927
+ /** A validation context: `"create"`, `"update"`, or a name the app chooses (`"signup"`). */
928
+ type ValidationContext = "create" | "update" | (string & {});
929
+ /** One context, or several: of those `X` names, when it's a Model's. */
930
+ type ValidationContexts<X extends string = ValidationContext> = X | readonly X[];
931
+ /**
932
+ * The contexts the Model class `C` can name: `"create"`, `"update"`, and those it lists in
933
+ * `static validationContexts = [...] as const`.
934
+ */
935
+ type ContextOf<C> = "create" | "update" | (C extends {
936
+ validationContexts: readonly (infer N extends string)[];
937
+ } ? N : never);
938
+ /** The options of `beforeValidation` and `afterValidation`. */
939
+ interface ValidationCallbackOptions<X extends string = ValidationContext> {
940
+ /** Only run the callback in this validation context, or these. */
941
+ on?: ValidationContexts<X>;
942
+ }
943
+ /** The options of `save` and `saveOrThrow`. */
944
+ interface SaveOptions {
945
+ /** Validate in this context (`"signup"`), or these, in place of `"create"` or `"update"`. */
946
+ context?: ValidationContexts;
947
+ }
948
+ /** A Model's Relation, as its statics return them: `Product.where(…)` is `Product.all().where(…)`. */
949
+ type RelationOf<C extends ModelClass> = Scoped<InstanceType<C>, ScopesOf<C>>;
950
+ /** The Relation methods every Model has as statics (besides the overloaded ones). */
951
+ declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findOrCreateBy", "findOrCreateByOrThrow", "findOrInitializeBy", "createOrFindBy", "createOrFindByOrThrow", "first", "last", "take", "firstOrThrow", "lastOrThrow", "takeOrThrow", "sole", "count", "average", "size", "isEmpty", "hasAny", "hasMoreThanOne", "hasExactlyOne", "exists", "ids", "toArray", "toSql", "findEach", "findInBatches", "inBatches"];
952
+ /** A Relation method with no overloads, by name. */
953
+ type RelationMethod = (typeof relationMethods)[number];
954
+ /**
955
+ * A Relation method as a static of every Model, typed for the class it's called on: `Product.where`
956
+ * returns a Relation of `Product`, and on a subclass, of the subclass.
957
+ */
958
+ 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;
959
+ /** Every Relation method in the list as a static, mapped over Relation's so each keeps its doc comment. */
960
+ type RelationStatics = { [K in keyof Pick<Relation<Model>, RelationMethod>]: RelationStatic<K>; };
961
+ /** A calculation's static, of a class's attribute `K`, or an `sql` fragment: `Order.sum("total")`. */
962
+ type CalculationStatic<AttributeKind extends "number" | "ordered", Fragment, Null> = <C extends QueryableClass, K extends (AttributeKind extends "number" ? NumberAttribute<InstanceType<C>> : OrderedAttribute<InstanceType<C>>) | SafeSql>(this: C, attribute: K) => Promise<CalculatedValue<InstanceType<C>, K, Fragment> | Null>;
963
+ /** The Relation methods with overloads or type parameters, typed by hand. */
964
+ interface OverloadedStatics {
965
+ /**
966
+ * The class's Relation with `other`'s conditions ANDed on, and its explicit clauses replacing
967
+ * its own; `other` may be a Relation of a Model the Relation joins once (#24).
968
+ */
969
+ merge: <C extends QueryableClass, T extends Model, O>(this: C, other: Relation<T, O>) => RelationOf<C>;
970
+ sum: CalculationStatic<"number", number, never>;
971
+ minimum: CalculationStatic<"ordered", unknown, null>;
972
+ maximum: CalculationStatic<"ordered", unknown, null>;
973
+ calculate: {
974
+ <C extends QueryableClass>(this: C, operation: "count", attribute?: keyof AttributesOf<InstanceType<C>> & string): Promise<number>;
975
+ <C extends QueryableClass, K extends NumberAttribute<InstanceType<C>> | SafeSql>(this: C, operation: "sum", attribute: K): Promise<CalculatedValue<InstanceType<C>, K>>;
976
+ <C extends QueryableClass>(this: C, operation: "average", attribute: NumberAttribute<InstanceType<C>> | SafeSql): Promise<number | null>;
977
+ <C extends QueryableClass, K extends OrderedAttribute<InstanceType<C>> | SafeSql>(this: C, operation: "minimum" | "maximum", attribute: K): Promise<CalculatedValue<InstanceType<C>, K, unknown> | null>;
978
+ };
979
+ paginate: PaginateStatic;
980
+ /** The class's Relation ordered by `attribute`'s place in `values` (#350), as Rails' `in_order_of`. */
981
+ inOrderOf: <C extends QueryableClass, K extends keyof AttributesOf<InstanceType<C>> & string>(this: C, attribute: K, values: readonly AttributesOf<InstanceType<C>>[K][], options?: InOrderOfOptions) => RelationOf<C>;
982
+ group: <C extends QueryableClass, const G extends GroupTerms<InstanceType<C>>>(this: C, ...terms: G) => GroupedRelation<InstanceType<C>, G>;
983
+ find: {
984
+ <C extends QueryableClass>(this: C, id: string | number): Promise<InstanceType<C>>;
985
+ <C extends QueryableClass>(this: C, ids: readonly (string | number)[]): Promise<InstanceType<C>[]>;
986
+ <C extends QueryableClass>(this: C, first: string | number, second: string | number, ...rest: (string | number)[]): Promise<InstanceType<C>[]>;
987
+ };
988
+ pluck: {
989
+ <C extends QueryableClass, K extends keyof AttributesOf<InstanceType<C>> & string>(this: C, attribute: K): Promise<AttributesOf<InstanceType<C>>[K][]>;
990
+ <C extends QueryableClass, const K extends AttributeList<InstanceType<C>>>(this: C, ...attributes: K): Promise<{ -readonly [I in keyof K]: AttributesOf<InstanceType<C>>[K[I]]; }[]>;
991
+ };
992
+ pick: {
993
+ <C extends QueryableClass, K extends keyof AttributesOf<InstanceType<C>> & string>(this: C, attribute: K): Promise<AttributesOf<InstanceType<C>>[K] | null>;
994
+ <C extends QueryableClass, const K extends AttributeList<InstanceType<C>>>(this: C, ...attributes: K): Promise<{ -readonly [I in keyof K]: AttributesOf<InstanceType<C>>[K[I]]; } | null>;
995
+ };
996
+ }
997
+ /** A primary key, or several, as `find` takes them. */
998
+ type Keys = string | number | readonly (string | number)[];
999
+ /** Writes by primary key, statics only: a hasMany's `destroy` and `delete` take records instead. */
1000
+ interface KeyedWriteStatics {
1001
+ /**
1002
+ * Finds the records with these primary keys, as `find` does (`RecordNotFound` if one is
1003
+ * missing, before anything is destroyed), and destroys them together, callbacks and dependents
1004
+ * included: if one refuses, it throws `RecordNotDestroyed` and nothing is destroyed. Resolves
1005
+ * to the record, or the records in the order given.
1006
+ */
1007
+ destroy: {
1008
+ <C extends QueryableClass>(this: C, id: string | number): Promise<InstanceType<C>>;
1009
+ <C extends QueryableClass>(this: C, ids: readonly (string | number)[]): Promise<InstanceType<C>[]>;
1010
+ };
1011
+ /**
1012
+ * Deletes the rows with these primary keys, as `deleteBy` does: no callbacks, and no error for
1013
+ * a key with no row. Resolves to the number of rows deleted.
1014
+ */
1015
+ delete: <C extends QueryableClass>(this: C, ids: Keys) => Promise<number>;
1016
+ /**
1017
+ * Adds to number attributes in the rows with these primary keys, as a Relation's
1018
+ * `updateCounters` does, whatever the default scope: `Post.updateCounters(id, { viewCount: 1 })`.
1019
+ * Resolves to the number of rows.
1020
+ */
1021
+ updateCounters: <C extends QueryableClass>(this: C, ids: Keys, counters: Counters<InstanceType<C>>, options?: CounterOptions<InstanceType<C>>) => Promise<number>;
1022
+ /** `updateCounters` for one attribute, adding `by` (one by default): `{ by: 5, touch }`. */
1023
+ incrementCounter: CounterStatic;
1024
+ /** `updateCounters` for one attribute, taking `by` (one by default) away: `{ by: 5, touch }`. */
1025
+ decrementCounter: CounterStatic;
1026
+ /**
1027
+ * Sets the counter caches of the record with this primary key (#61) to how many records each
1028
+ * named hasMany has, counted in the same write: `Topic.resetCounters(id, "replies")`, or a
1029
+ * list of names, and `{ touch }`. A missing record is `RecordNotFound`, as `find`'s.
1030
+ */
1031
+ resetCounters: <C extends QueryableClass>(this: C, id: string | number, names: CollectionName<InstanceType<C>> | readonly CollectionName<InstanceType<C>>[], options?: CounterOptions<InstanceType<C>>) => Promise<void>;
1032
+ }
1033
+ /** `Post.incrementCounter("viewCount", id, { by })`, typed for the class it's called on. */
1034
+ type CounterStatic = <C extends QueryableClass>(this: C, name: NumberAttributeKey<InstanceType<C>>, ids: Keys, options?: {
1035
+ by?: number;
1036
+ } & CounterOptions<InstanceType<C>>) => Promise<number>;
1037
+ /** A callback static, typed for the class it's declared on: `this.beforeSave((record) => …)`. */
1038
+ type CallbackStatic = <C extends AbstractModelClass>(this: C, callback: Callback<InstanceType<C>>) => void;
1039
+ /**
1040
+ * A validation callback static, which can run only in some validation contexts (#51):
1041
+ * `this.beforeValidation((record) => …, { on: "create" })`.
1042
+ */
1043
+ type ValidationCallbackStatic = <C extends AbstractModelClass>(this: C, callback: Callback<InstanceType<C>>, options?: ValidationCallbackOptions<ContextOf<C>>) => void;
1044
+ /** Every callback kind as a static, each documented here, so its doc comment shows on hover. */
1045
+ interface CallbackStatics {
1046
+ /**
1047
+ * Runs before the validators, e.g. to normalize input. May `throw abort(reason)`. With `on`,
1048
+ * only in that validation context, or those.
1049
+ */
1050
+ beforeValidation: ValidationCallbackStatic;
1051
+ /**
1052
+ * Runs after the validators, whether or not they passed. May `throw abort(reason)`. With
1053
+ * `on`, only in that validation context, or those.
1054
+ */
1055
+ afterValidation: ValidationCallbackStatic;
1056
+ /** Runs before every save (create or update), after validation. May `throw abort(reason)`. */
1057
+ beforeSave: CallbackStatic;
1058
+ /** Runs before inserting a new record, after `beforeSave`. May `throw abort(reason)`. */
1059
+ beforeCreate: CallbackStatic;
1060
+ /** Runs before updating a persisted record, after `beforeSave`. May `throw abort(reason)`. */
1061
+ beforeUpdate: CallbackStatic;
1062
+ /** Runs after a new record was inserted, before `afterSave`. */
1063
+ afterCreate: CallbackStatic;
1064
+ /** Runs after a persisted record was saved (even with nothing to write), before `afterSave`. */
1065
+ afterUpdate: CallbackStatic;
1066
+ /** Runs after every successful save; the record is already persisted and clean. */
1067
+ afterSave: CallbackStatic;
1068
+ /** Runs before deleting the row. May `throw abort(reason)` to refuse the destroy. */
1069
+ beforeDestroy: CallbackStatic;
1070
+ /** Runs after the row was deleted; the record is already destroyed. */
1071
+ afterDestroy: CallbackStatic;
1072
+ /**
1073
+ * Runs when the database refused the record's save or destroy (a constraint, or another write in
1074
+ * its batch). Not for a validation failure or an `abort()`: nothing was sent then.
1075
+ */
1076
+ afterRollback: CallbackStatic;
1077
+ }
1078
+ /** The commit callbacks as statics: each runs after every after-callback of its write. */
1079
+ interface CommitStatics {
1080
+ /** Runs once a create, update or destroy is kept, after every after-callback. */
1081
+ afterCommit: CallbackStatic;
1082
+ /** Runs once a create is kept, after every after-callback. */
1083
+ afterCreateCommit: CallbackStatic;
1084
+ /** Runs once an update is kept, after every after-callback. */
1085
+ afterUpdateCommit: CallbackStatic;
1086
+ /** Runs once a create or update is kept, after every after-callback. */
1087
+ afterSaveCommit: CallbackStatic;
1088
+ /** Runs once a destroy is kept, after every after-callback. */
1089
+ afterDestroyCommit: CallbackStatic;
1090
+ }
1091
+ /**
1092
+ * The class Model extends, for its statics' types only: at runtime it's empty, and
1093
+ * `defineStatics` puts the statics on Model itself, where scopes look for the names they
1094
+ * can't take.
1095
+ */
1096
+ declare const ModelStatics: (abstract new () => object) & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & CommitStatics;
1097
+ /**
1098
+ * The built-in type a spec names: `"integer"` for `"integer"` or `{ type: "integer" }`, and
1099
+ * `"custom"` for a custom type, given bare or as `{ type }`.
1100
+ */
1101
+ type SpecType<S> = S extends string ? S : S extends {
1102
+ readonly type: infer T extends string;
1103
+ } ? T : "custom";
1104
+ /**
1105
+ * The names of record type `R`'s attributes of built-in type `T`, as the runtime checks them:
1106
+ * not an enum, nor a custom type, even one whose values are numbers.
1107
+ */
1108
+ type AttributeKeyOf<R, T> = { [K in keyof SpecsOf<R>]: SpecsOf<R>[K] extends {
1109
+ readonly enum: unknown;
1110
+ } ? never : SpecType<SpecsOf<R>[K]> extends T ? K : never; }[keyof SpecsOf<R>] & string;
1111
+ /** An attribute's name on record type `R`. */
1112
+ type AttributeKey$1<R> = keyof AttributesOf<R> & string;
1113
+ /** A record's number attributes, which `increment` and `decrement` take. */
1114
+ type NumberAttributeKey<R> = AttributeKeyOf<R, "integer" | "real">;
1115
+ /** A record's datetime attributes, which a counter's `touch` names (#61). */
1116
+ type DatetimeAttributeKey<R> = AttributeKeyOf<R, "datetime">;
1117
+ /** A record's boolean attributes, which `toggle` takes. */
1118
+ type BooleanAttributeKey<R> = AttributeKeyOf<R, "boolean">;
1119
+ /**
1120
+ * The record methods that change one attribute, between Model and its statics: Model's records
1121
+ * have them, and model.ts stays the record class's own.
1122
+ */
1123
+ declare abstract class AttributeWrites extends ModelStatics {
1124
+ /** Adds `by` (one by default) to a number attribute, null counting as zero; doesn't save. */
1125
+ increment<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): R;
1126
+ /** Takes `by` (one by default) from a number attribute, null counting as zero; doesn't save. */
1127
+ decrement<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): R;
1128
+ /** Flips a boolean attribute, null becoming `true`; doesn't save. */
1129
+ toggle<R extends Model>(this: R, name: BooleanAttributeKey<R>): R;
1130
+ /**
1131
+ * Writes these attributes straight to the row, with no validation, callback or `updatedAt`,
1132
+ * and leaves the record clean for them, as Rails' `update_columns`. Resolves to whether there
1133
+ * was a row to write. A new record is `RecordNotSaved`.
1134
+ */
1135
+ updateColumns<R extends Model>(this: R, attributes: Partial<AttributesOf<R>>): Promise<boolean>;
1136
+ /** `updateColumns` for one attribute. */
1137
+ updateColumn<R extends Model, K extends AttributeKey$1<R>>(this: R, name: K, value: AttributesOf<R>[K]): Promise<boolean>;
1138
+ /**
1139
+ * Adds `by` to a number attribute in the row, as `SET x = COALESCE(x, 0) + by`, so concurrent
1140
+ * writes all count, with no validation, callback or `updatedAt`; the record then holds the
1141
+ * row's new value. An unsaved change to it is added too, as Rails' `increment!`. Resolves to
1142
+ * whether there was a row to write.
1143
+ */
1144
+ incrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): Promise<boolean>;
1145
+ /** `incrementColumn`, taking `by` away. */
1146
+ decrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): Promise<boolean>;
1147
+ /**
1148
+ * Writes a boolean attribute's flipped value straight to the row, as `updateColumn` does: no
1149
+ * validation or callback, unlike Rails' `toggle!`, which runs the save callbacks.
1150
+ */
1151
+ toggleColumn<R extends Model>(this: R, name: BooleanAttributeKey<R>): Promise<boolean>;
1152
+ }
1153
+ /** What `updateCounters` adds to each number attribute: `{ viewCount: 1 }`. */
1154
+ type Counters<R> = { [K in NumberAttributeKey<R>]?: number; };
1155
+ /**
1156
+ * What a counter's write also sets to now (#61), as Rails' `touch:`: `true` for `updatedAt`, or
1157
+ * a datetime attribute's name, or several, set with `updatedAt`.
1158
+ */
1159
+ type Touch<R> = true | DatetimeAttributeKey<R> | readonly DatetimeAttributeKey<R>[];
1160
+ /** What the counter writes take besides their counters: `touch`. */
1161
+ interface CounterOptions<R> {
1162
+ touch?: Touch<R>;
1163
+ }
1164
+ declare const recordType: unique symbol;
1165
+ /**
1166
+ * A record's save or destroy in a batch: `b.save(user)`, `b.destroy(post)`. Unlike a
1167
+ * Statement, nothing is compiled yet: the record's validations and callbacks run when the batch
1168
+ * runs. It has no `then`, so it's never run by being awaited.
1169
+ */
1170
+ declare class RecordStatement<R extends Model = Model> {
1171
+ #private;
1172
+ /** Type-only: the record's type, so a statement of one Model isn't taken for another's. */
1173
+ readonly [recordType]?: R;
1174
+ }
1175
+ /** What a Batch writes to: a Model's table, or a Relation's rows (`Post.where(…)`, `user.posts()`). */
1176
+ type BatchTarget<M extends Model> = ModelClass<M> | Relation<M>;
1177
+ /**
1178
+ * The writes of one batch, prepared inside its callback: `b.insert(Author, { name })`. Each is
1179
+ * written when the batch runs, atomically with the rest, and none is sent on its own.
1180
+ */
1181
+ declare class Batch {
1182
+ #private;
1183
+ /**
1184
+ * Saves `record`, its autosaved associations included. Its validations and before-callbacks
1185
+ * run when the batch runs, before anything is written, and its after-callbacks once it is.
1186
+ * `context` validates it in that context (`"signup"`), as `save({ context })` does; one its
1187
+ * Model doesn't list throws `TypeError` here.
1188
+ */
1189
+ save<R extends Model>(record: R, options?: SaveOptions): RecordStatement<R>;
1190
+ /** Destroys `record`, with its dependents, its callbacks running as `save`'s do. */
1191
+ destroy<R extends Model>(record: R): RecordStatement<R>;
1192
+ /** Inserts one row, as `insert` does when it runs alone. */
1193
+ insert<M extends Model, const R extends Returning<M> | undefined = undefined>(target: BatchTarget<M>, attributes: Partial<AttributesOf<M>>, options?: InsertOptions<M> & {
1194
+ returning?: R;
1195
+ }): Statement<ReturnedRow<M, R>>;
1196
+ /** Inserts several rows with the same attributes, as `insertAll` does. */
1197
+ insertAll<M extends Model, const R extends Returning<M> | undefined = undefined>(target: BatchTarget<M>, rows: readonly Partial<AttributesOf<M>>[], options?: InsertOptions<M> & {
1198
+ returning?: R;
1199
+ }): Statement<ReturnedRow<M, R>>;
1200
+ /** Inserts a row, or updates the one it clashes with, as `upsert` does. */
1201
+ upsert<M extends Model, const R extends Returning<M> | undefined = undefined>(target: BatchTarget<M>, attributes: Partial<AttributesOf<M>>, options?: UpsertOptions<M> & {
1202
+ returning?: R;
1203
+ }): Statement<ReturnedRow<M, R>>;
1204
+ /** `upsert` for several rows with the same attributes, as `upsertAll` does. */
1205
+ upsertAll<M extends Model, const R extends Returning<M> | undefined = undefined>(target: BatchTarget<M>, rows: readonly Partial<AttributesOf<M>>[], options?: UpsertOptions<M> & {
1206
+ returning?: R;
1207
+ }): Statement<ReturnedRow<M, R>>;
1208
+ /** Updates every row `target` matches, as `updateAll` does: `b.updateAll(Post, { published: true })`. */
1209
+ updateAll<M extends Model>(target: BatchTarget<M>, changes: Partial<AttributesOf<M>> | SafeSql): Statement;
1210
+ /**
1211
+ * Adds to number attributes in every row `target` matches, as a Relation's `updateCounters`
1212
+ * does: `b.updateCounters(Post.where({ id }), { viewCount: 1 }, { touch: true })`.
1213
+ */
1214
+ updateCounters<M extends Model>(target: BatchTarget<M>, counters: Counters<M>, { touch }?: CounterOptions<M>): Statement;
1215
+ /** Deletes every row `target` matches, as `deleteAll` does (through a hasMany, it may nullify). */
1216
+ deleteAll<M extends Model>(target: BatchTarget<M>): Statement;
1217
+ }
1218
+ /**
1219
+ * `db.batch`, on the current database: `batch((b) => [b.updateAll(Product, …), b.save(product)])`.
1220
+ * A Model's rows are looked up on the current database, and a Relation or record runs on the one
1221
+ * it came from. Atomic, as `db.batch` is; writes on two databases throw `IncompatibleRelation`.
1222
+ */
1223
+ declare function batch<const T extends readonly BatchEntry[]>(build: (b: Batch) => T): Promise<BatchResults<T>>;
1224
+ /** What `db.batch` accepts: statements, and records' save or destroy. */
1225
+ type BatchEntry = Statement<unknown> | RecordStatement;
1226
+ /** `db.batch`'s result for each entry: a statement's `WriteResult`, or the saved or destroyed record. */
1227
+ 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; };
1228
+ /** One request-bound Relation per Model, keyed like the object passed to `db.models()`. */
1229
+ type RelationsFor<T extends Record<string, ModelClass<Model>>> = { [K in keyof T]: Scoped<InstanceType<T[K]>, ScopesOf<T[K]>>; };
1230
+ /** The key for a Database's Executor (the current database, #77), for adapters (`/adapter`). */
1231
+ declare const databaseExecutor: unique symbol;
1232
+ /** A per-request handle on a database; every query goes through it. */
1233
+ declare class AnyDatabase {
1234
+ #private;
1235
+ /** A request-bound Relation over the Model's records, with its scopes as methods. */
1236
+ model<C extends ModelClass<Model>>(model: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1237
+ /** Request-bound relations for several models at once: `db.models({ User }).User`. */
1238
+ models<const T extends Record<string, ModelClass<Model>>>(models: T): RelationsFor<T>;
1239
+ /**
1240
+ * Runs the writes `build` prepares atomically, on this Database: all of them are written, or
1241
+ * none. `db.batch((b) => [b.insert(Post, { title }), b.save(user)])`. The callback can't await,
1242
+ * since the batch is sent as one. Saves and destroys (`b.save(user)`, `b.destroy(post)`) run
1243
+ * their validations and before-callbacks first, in order; the first record that's invalid or
1244
+ * aborts throws (`RecordInvalid`, `RecordNotSaved`, `RecordNotDestroyed`) and nothing is sent.
1245
+ * After the batch, each record takes its saved state and runs its after-callbacks, in order.
1246
+ * Resolves to each write's result: a bulk write's `{ rowsAffected, rows }`, or the record.
1247
+ */
1248
+ batch<const T extends readonly BatchEntry[]>(build: (b: Batch) => T): Promise<BatchResults<T>>;
1249
+ }
1250
+ /** What a database's error says about a constraint that failed. */
1251
+ interface ConstraintFailure {
1252
+ kind: "unique" | "notNull" | "foreignKey" | "check";
1253
+ /** The table the error names, if it names one. */
1254
+ table: string | undefined;
1255
+ /** The columns the error names, if any. */
1256
+ columns: string[];
1257
+ }
1258
+ /**
1259
+ * What a generated schema names (`adapter: d1({ binding: "DB" })`): the kind of database its
1260
+ * Models are on, and which of its databases. Made by an adapter's own function.
1261
+ */
1262
+ interface SchemaAdapter {
1263
+ readonly adapter: Adapter;
1264
+ /** The database's name in the app's config, its Binding: on D1, a Wrangler binding (`DB`). */
1265
+ readonly binding: string;
1266
+ }
1267
+ /** One kind of database (ADR-0016). A `Driver` sends to one database of that kind. */
1268
+ interface Adapter {
1269
+ /** What the database is called in messages. */
1270
+ readonly name: string;
1271
+ readonly dialect: Dialect;
1272
+ /** The most values one statement can bind. */
1273
+ readonly maxBoundValues: number;
1274
+ /** What `error` says failed, or undefined when it isn't a constraint failure. */
1275
+ constraintFailure(error: unknown): ConstraintFailure | undefined;
1276
+ /** The table `error` says doesn't exist, or undefined when it says something else. */
1277
+ missingTable(error: unknown): string | undefined;
1278
+ /** The error to throw when `error` means the query couldn't run here at all, or undefined. */
1279
+ refusal(error: unknown): Error | undefined;
1280
+ /**
1281
+ * The database a query from a Model's statics uses now: one of the request's, `requested`, or
1282
+ * this adapter's own for `binding`, the name in the Model's schema. A Model with no schema has
1283
+ * none. Throws `NoDatabase` when there isn't one.
1284
+ */
1285
+ databaseFor(binding: string | undefined, requested: readonly AnyDatabase[]): Promise<AnyDatabase>;
1286
+ }
1287
+ /**
1288
+ * Reported once for every statement sent to a database: to the database's `onQuery`, then to the
1289
+ * statement's Model's (`static onQuery`, usually on the app's base class). `meta` is the
1290
+ * database's own detail about the statement, typed by its adapter (D1's `D1Meta`).
1291
+ */
1292
+ interface QueryEvent<Meta = unknown> {
1293
+ /**
1294
+ * The Model the statement is for: its class name (`"Product"`). It's `""` for an anonymous
1295
+ * class, and a bundler that renames classes changes it; Wrangler keeps names by default.
1296
+ */
1297
+ model: string;
1298
+ sql: string;
1299
+ params: unknown[];
1300
+ durationMs: number;
1301
+ meta?: Meta;
1302
+ error?: unknown;
1303
+ }
1304
+ /**
1305
+ * Hears each statement's `QueryEvent`. Declared as a method's type, so a listener typed for one
1306
+ * adapter's `meta` (a D1 app's base class) can be a Model's `static onQuery`, which any adapter calls.
1307
+ */
1308
+ type QueryListener<Meta = unknown> = {
1309
+ listener(event: QueryEvent<Meta>): void;
1310
+ }["listener"];
1311
+ /**
1312
+ * The concrete database a handle sends to now. Private to this module (#93): callers ask
1313
+ * `oneDatabase` (through `jointly` and `pinBefore`) instead, so "is this the same database?" is
1314
+ * decided in one place.
1315
+ */
1316
+ declare const resolve: unique symbol;
1317
+ /** Where a Relation's or record's statements go: one database, or the current one (#77). */
1318
+ interface Executor {
1319
+ /** The kind of database it sends to, known before that database is found. */
1320
+ readonly adapter: Adapter;
1321
+ /** How its database writes the SQL the compiler can't share. */
1322
+ readonly dialect: Dialect;
1323
+ /** Runs one statement and resolves to its rows. */
1324
+ all(query: CompiledSql): Promise<Record<string, unknown>[]>;
1325
+ /** Runs one statement for its effect and resolves to its result. */
1326
+ run(query: CompiledSql): Promise<StatementResult>;
1327
+ /** Runs reads together and resolves to each one's result. They needn't be atomic. */
1328
+ read(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
1329
+ /** Runs statements atomically: one on its own, several as one batch. */
1330
+ write(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
1331
+ }
1332
+ /** Where a database came from, for errors to name it: `connect()`'s, the request's, or a binding's. */
1333
+ type Origin = "connect" | "request" | {
1334
+ binding: string;
1335
+ };
1336
+ /**
1337
+ * One database's Executor: every statement goes to its Driver and is reported to `onQuery`, and a
1338
+ * constraint failure becomes the matching `ConstraintViolation` for the statement's Model.
1339
+ */
1340
+ declare class DatabaseExecutor implements Executor {
1341
+ #private;
1342
+ readonly adapter: Adapter;
1343
+ constructor(adapter: Adapter, driver: Driver, onQuery?: QueryListener);
1344
+ get dialect(): Dialect;
1345
+ [resolve](): Promise<DatabaseExecutor>;
1346
+ /** Where this database came from; errors name it by this. */
1347
+ get origin(): Origin;
1348
+ /** Runs one statement and resolves to its rows. */
1349
+ all(query: CompiledSql): Promise<Record<string, unknown>[]>;
1350
+ /** Runs one statement for its effect and resolves to its result. */
1351
+ run(query: CompiledSql): Promise<StatementResult>;
1352
+ /** Runs reads together and resolves to each one's result. */
1353
+ read(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
1354
+ /** Runs statements atomically: one on its own, several all or none. Resolves to each result. */
1355
+ write(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
1356
+ }
1357
+ /** What `permit` returns: the named attributes, each optional, as their types. */
1358
+ type Permitted<C extends ModelClass, K extends string> = Partial<Pick<AttributesOf<InstanceType<C>>, K & keyof AttributesOf<InstanceType<C>>>>;
1359
+ /**
1360
+ * What d1-record does with an attribute's values, by the attribute's type (and `storage`).
1361
+ * `T` is the attribute's JavaScript type. Each is a function of its own, so one can be passed
1362
+ * on or destructured.
1363
+ */
1364
+ interface AttributeConversions<T> {
1365
+ /**
1366
+ * `input` as the attribute's JavaScript value, as assigning it would: strict, so `TypeError`
1367
+ * naming the Model and attribute when it can't be. `null` stays `null`; `undefined` throws.
1368
+ * Nothing is floored: a `Date` with milliseconds keeps them, whatever the attribute's `storage`.
1369
+ */
1370
+ readonly cast: (input: unknown) => T;
1371
+ /**
1372
+ * `input`, cast, as D1 stores it: an ISO string, an integer for a `storage` attribute (seconds
1373
+ * are floored), `0` or `1`, JSON text, bytes for a `binary` attribute, or a custom type's value
1374
+ * as its stored type keeps it (#20). The value `column(attribute).value(input)` binds inside
1375
+ * an `sql` fragment; `undefined` throws as assigning it does.
1376
+ */
1377
+ readonly serialize: (input: unknown) => string | number | Uint8Array | null;
1378
+ /**
1379
+ * A cell D1 returned, as the attribute's JavaScript value; `null` for NULL and `undefined`.
1380
+ * It reads as a record load does, so a cell that can't be read throws `TypeError` naming the
1381
+ * Model and attribute: text in a Unix time column, a number past the range of a `Date`, or text
1382
+ * in a `json` column that isn't JSON.
1383
+ */
1384
+ readonly deserialize: (stored: unknown) => T;
1385
+ }
1386
+ /**
1387
+ * An entry of `filterAttributes`: a string the attribute's snake_case name contains, lowercased
1388
+ * or read in snake_case (`"apiKey"` as `api_key`), or a RegExp the attribute or its snake_case
1389
+ * name matches.
1390
+ */
1391
+ type FilterAttribute = string | RegExp;
1392
+ /** The value D1 binds. */
1393
+ declare function boundValue(param: unknown): unknown;
1394
+ /** An override written out: the parts of a spec it may change (not the column), any left out or `undefined` unchanged. */
1395
+ type SpecOverride = Partial<Omit<SpecObject, "column">>;
1396
+ /** One table in a generated schema: its attributes, and which is the primary key. */
1397
+ interface TableSchema {
1398
+ readonly attributes: AttributeSpecs;
1399
+ readonly primaryKey: string;
1400
+ }
1401
+ /** A generated schema's tables, by name (`tables` in `src/db/schema.ts`). */
1402
+ type TableSchemas = Readonly<Record<string, TableSchema>>;
1403
+ /** The keys an enum's override may give, besides its values (#340). */
1404
+ type EnumOptions = Pick<SpecOverride, "prefix" | "suffix" | "scopes" | "instanceMethods" | "validate">;
1405
+ /**
1406
+ * A change to a generated attribute: its type alone, or its type, nullability, default and
1407
+ * `generateId`, typed so `generateId` goes only with a string, and never with a default (#99); and
1408
+ * an enum on a string or an integer, whose stored values are of its type (#340).
1409
+ */
1410
+ type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "null"> & {
1411
+ type?: "string";
1412
+ storage?: never;
1413
+ /** Or `true`: a generated enum's names, with its methods; `false`: none of it (#64). */
1414
+ enum?: TextEnum | boolean;
1415
+ } & EnumOptions & ValueSource) | (Pick<SpecOverride, "null" | "default"> & {
1416
+ type?: "integer";
1417
+ generateId?: false;
1418
+ storage?: never;
1419
+ enum: IntegerEnum;
1420
+ } & EnumOptions) | (Pick<SpecOverride, "null" | "default"> & {
1421
+ type: Exclude<AttributeType, "string" | "datetime">;
1422
+ generateId?: false;
1423
+ storage?: never;
1424
+ enum?: never;
1425
+ }) | (Pick<SpecOverride, "null" | "default" | "storage"> & {
1426
+ type: "datetime";
1427
+ generateId?: false;
1428
+ enum?: never;
1429
+ }) | (Pick<SpecOverride, "null" | "default"> & {
1430
+ type: AnyCustomType;
1431
+ generateId?: false;
1432
+ storage?: never;
1433
+ enum?: never;
1434
+ });
1435
+ /** The type a spec declares, written either way. */
1436
+ type TypeOf<S> = S extends AttributeType | AnyCustomType ? S : S extends {
1437
+ type: infer T;
1438
+ } ? T : never;
1439
+ /** Whether a spec's attribute can be `null`. */
1440
+ type NullOf<S> = S extends {
1441
+ null: false;
1442
+ } ? false : true;
1443
+ /** An enum and its options: the keys an override carries into the merged spec's type (#340). */
1444
+ type EnumKey = "enum" | keyof EnumOptions;
1445
+ /** The switches a generated enum's methods are off by, which `enum: true` lifts (#64). */
1446
+ type MethodSwitch = "scopes" | "instanceMethods";
1447
+ /**
1448
+ * A spec's enum keys an override keeps: none when it gives a new type (they were for the old one)
1449
+ * or `enum: false`, none it gives itself, and not the switches `enum: true` lifts.
1450
+ */
1451
+ type KeptEnumKeys<S, O> = O extends {
1452
+ enum: false;
1453
+ } ? {} : O extends {
1454
+ type: infer T;
1455
+ } ? T extends TypeOf<S> ? Omit<Pick<S, EnumKey & keyof S>, OwnKeys<O>> : {} : Omit<Pick<S, EnumKey & keyof S>, OwnKeys<O>>;
1456
+ /**
1457
+ * The keys an override replaces: its own, but for `enum: true`, which keeps the spec's names; and
1458
+ * with `enum: true` or a list of its own, the switches a generated enum's methods are off by.
1459
+ */
1460
+ type OwnKeys<O> = O extends {
1461
+ enum: true;
1462
+ } ? Exclude<keyof O, "enum"> | MethodSwitch : O extends {
1463
+ enum: object;
1464
+ } ? keyof O | MethodSwitch : keyof O;
1465
+ /** The enum keys an override gives the merged spec: all it gives, but `enum: true` or `false` (#64). */
1466
+ type GivenEnumKeys<O> = Pick<O, Exclude<EnumKey & keyof O, O extends {
1467
+ enum: boolean;
1468
+ } ? "enum" : never>>;
1469
+ /** An attribute's spec with its override applied. */
1470
+ type Overridden<S, O> = O extends AttributeType | AnyCustomType ? {
1471
+ type: O;
1472
+ null: NullOf<S>;
1473
+ } : O extends object ? {
1474
+ type: O extends {
1475
+ type: infer T extends AttributeType | AnyCustomType;
1476
+ } ? T : TypeOf<S>;
1477
+ null: O extends {
1478
+ null: infer N extends boolean;
1479
+ } ? N : NullOf<S>;
1480
+ } & KeptEnumKeys<S, O> & GivenEnumKeys<O> : S;
1481
+ /** A table's attributes after its overrides: changed ones merged, ignored ones gone. */
1482
+ 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]; };
1483
+ /** `S` as attribute specs, without widening it to an index signature (which would type any name). */
1484
+ type AsSpecs<S> = S extends AttributeSpecs ? S : never;
1485
+ /**
1486
+ * A generated Model's changes to its table's attributes (`static override attributes = {...} as
1487
+ * const`): a type name, a spec's changes, or `false` to ignore the column.
1488
+ */
1489
+ type AttributeOverrides = Readonly<Record<string, AttributeOverride | false>>;
1490
+ /** What `active-record schema` generates for one database: its adapter, its tables, and its Models. */
1491
+ interface DatabaseSchema {
1492
+ readonly adapter: SchemaAdapter;
1493
+ readonly tables: TableSchemas;
1494
+ /**
1495
+ * The Models the schema was generated for: each one's `modelName`, and its table. Absent only
1496
+ * while `active-record schema` loads the Models, before it has found them; then nothing is checked.
1497
+ */
1498
+ readonly models?: Readonly<Record<string, string>>;
1499
+ /**
1500
+ * Each Model's enum scopes, by its `modelName` (#340): the statics `defineSchema` makes every
1501
+ * Model have from the start, where a Model's other attributes wait for its first use.
1502
+ */
1503
+ readonly enumScopes?: Readonly<Record<string, readonly string[]>>;
1504
+ }
1505
+ /** `{ attribute: [before, after] }` */
1506
+ type Changes = Record<string, [before: unknown, after: unknown]>;
1507
+ /** Type-only brand on a scope static (`static newest = this.scope(…)`); never set at runtime. */
1508
+ declare const scopeBrand: unique symbol;
1509
+ /**
1510
+ * A scope, as a static on its Model: called on that Model or any class extending it
1511
+ * (`Product.newest()`), it returns a Relation of that class, with all its scopes.
1512
+ */
1513
+ type ScopeStatic<A extends unknown[]> = (<C extends QueryableClass>(this: C, ...args: A) => Scoped<InstanceType<C>, ScopesOf<C>>) & {
1514
+ readonly [scopeBrand]: true;
1515
+ };
1516
+ /** A Model class's scopes: its statics made with `this.scope(…)`, its own and inherited. */
1517
+ type ScopesOf<C> = { [K in Exclude<keyof C, "prototype"> as C[K] extends {
1518
+ readonly [scopeBrand]: true;
1519
+ } ? K : never]: C[K]; };
1520
+ /** What `loaded()` returns for an association accessor: its records, or its record or null. */
1521
+ type LoadedValue<F> = F extends (() => Promise<infer R>) ? R : F extends (() => {
1522
+ toArray(): Promise<infer T>;
1523
+ }) ? T : never;
1524
+ /**
1525
+ * Any association accessor, whatever its target: by shape, since a Relation of one Model isn't
1526
+ * assignable to a Relation of the library's base class.
1527
+ */
1528
+ type Any = any;
1529
+ type AnyAssociation = BelongsTo<Any> | PolymorphicBelongsTo<Any> | HasOne<Any> | HasOneThrough<Any> | HasManyThrough<Any> | (() => Relation<Any, Any>);
1530
+ /** The names of a record's hasMany accessors, through another included (from their fields' types). */
1531
+ type CollectionName<R> = { [K in keyof R]: R[K] extends (() => Relation<Any, Any>) ? K : never; }[keyof R] & string;
1532
+ /** The names of a record's association accessors (from their fields' types). */
1533
+ type AssociationName<R> = { [K in keyof R]: R[K] extends AnyAssociation ? K : never; }[keyof R] & string;
1534
+ /** The record type an association accessor loads: `Post` for `HasMany<typeof Post>`. */
1535
+ type TargetRecord<F> = LoadedValue<F> extends readonly (infer T)[] ? T : NonNullable<LoadedValue<F>>;
1536
+ /**
1537
+ * What `includes()` accepts for records `M`: an association name, or `{ name: nested }` where
1538
+ * `nested` names associations of that association's records. Checked against their fields' types;
1539
+ * under a polymorphic belongsTo (#60), `M` is a union, and any of its Models' names is accepted.
1540
+ */
1541
+ type IncludeSpec<M> = M extends unknown ? AssociationName<M> | { readonly [K in AssociationName<M>]?: IncludeSpec<TargetRecord<M[K]>> | readonly IncludeSpec<TargetRecord<M[K]>>[]; } : never;
1542
+ /** What `joins()` and `leftJoins()` accept for records `M`: what `includes()` does. */
1543
+ type JoinSpec<M> = IncludeSpec<M>;
1544
+ /** A lifecycle callback; it receives the record and may be async. */
1545
+ type Callback<R> = (record: R) => unknown;
1546
+ /** Type-only key carrying a record's declared attribute types; never set at runtime. */
1547
+ declare const attributeTypes: unique symbol;
1548
+ /** Type-only key carrying a record's attribute specs, for what reads more than their types (#340). */
1549
+ declare const attributeSpecs: unique symbol;
1550
+ /** A record type's attribute specs. */
1551
+ type SpecsOf<M> = M extends {
1552
+ readonly [attributeSpecs]?: infer S;
1553
+ } ? S : never;
1554
+ /** The names of a record type's enum attributes. */
1555
+ type EnumAttributeKey<M> = { [K in keyof SpecsOf<M>]: SpecsOf<M>[K] extends {
1556
+ enum: EnumValues;
1557
+ } ? K : never; }[keyof SpecsOf<M>] & string;
1558
+ /** The enum of attribute `K` of record type `M`. */
1559
+ type EnumOf<M, K extends keyof SpecsOf<M>> = SpecsOf<M>[K] extends {
1560
+ enum: infer E;
1561
+ } ? E : never;
1562
+ /** An attribute's name on record type `R`. */
1563
+ type AttributeKey<R> = keyof AttributesOf<R> & string;
1564
+ /** `from`/`to` for the change checks: only matching when the value was, or became, this. */
1565
+ interface ChangeOptions<V = unknown> {
1566
+ from?: V;
1567
+ to?: V;
1568
+ }
1569
+ /**
1570
+ * What a Model's error messages and attribute names can name: its attributes, its associations
1571
+ * and `"base"`; any name on a class without attributes (the app's base class).
1572
+ */
1573
+ type ErrorAttributeName<R> = [AttributesOf<R>] extends [never] ? string : AttributeKey<R> | AssociationName<R> | "base";
1574
+ /** The declared attributes of a record type, excluding methods and getters. */
1575
+ type AttributesOf<M> = M extends {
1576
+ readonly [attributeTypes]?: infer A;
1577
+ } ? A : never;
1578
+ /**
1579
+ * The library's base class, as Rails' `ActiveRecord::Base`: an app's base class extends it, and
1580
+ * methods, statics, callbacks and scopes declared there are shared by every Model built on it.
1581
+ * It has no table, so it's never used as a Model itself.
1582
+ */
1583
+ declare class Model extends AttributeWrites {
1584
+ /** The table's name: inferred from `modelName` (`BlogPost` → `blog_posts`) unless set. */
1585
+ static table: string;
1586
+ /**
1587
+ * The Model's name, as Rails' `model_name`: its class name unless set (`static modelName =
1588
+ * "BlogPost"`), so names inferred from it survive a bundler that renames classes.
1589
+ */
1590
+ static modelName: string;
1591
+ /** The primary key attribute: the generated table's, or `"id"` unless set. */
1592
+ static primaryKey: string;
1593
+ static attributeDefinitions: ReadonlyMap<string, AttributeDefinition>;
1594
+ /**
1595
+ * The generated schema, on an app's base class (`static override schema = schema`): the
1596
+ * Models built on it have its tables' attributes, and query its binding.
1597
+ */
1598
+ static schema?: DatabaseSchema;
1599
+ /**
1600
+ * A generated Model's changes to its table's attributes, as in the schema: `static override
1601
+ * attributes = { available: "boolean", internalNotes: false } as const`.
1602
+ */
1603
+ static attributes?: AttributeOverrides;
1604
+ /**
1605
+ * Marks a class between the app's base class and its Models (`static override abstract =
1606
+ * true`): it has no table, it shares its behavior, and each class directly below it has one.
1607
+ */
1608
+ static abstract?: boolean;
1609
+ /**
1610
+ * An app-wide query listener, as `connect(env.DB, { onQuery })` is a database's: called for
1611
+ * every statement of this Model (and those extending it), whichever database runs it, after
1612
+ * the database's own. Holds no request state, so it's safe on a class; a request's ID comes
1613
+ * from a database opened for it with `withDatabase` (#78).
1614
+ */
1615
+ static onQuery: QueryListener | undefined;
1616
+ /**
1617
+ * Attributes whose values listeners and errors show as "[FILTERED]", as Rails'
1618
+ * `filter_attributes`: an attribute whose snake_case name holds a string entry, lowercased
1619
+ * or read in snake_case (`"apiKey"` as `api_key`), or matches a RegExp. Rails' defaults;
1620
+ * replace them on the app's base class (#83).
1621
+ */
1622
+ static filterAttributes: readonly FilterAttribute[];
1623
+ /**
1624
+ * Attribute names `toJSON()` leaves out, so `Response.json(record)` can't send them. Exact
1625
+ * names; none by default. `attributes()` still has them (#101).
1626
+ */
1627
+ static hiddenAttributes: readonly string[];
1628
+ /** An attribute's name as error messages show it: from `humanAttributeNames`, or "Created at". */
1629
+ static humanAttributeName(attribute: string): string;
1630
+ /** Records on a page of `paginate()` when it isn't given `perPage` (#100). */
1631
+ static perPage: number;
1632
+ /**
1633
+ * The most records on a page of `paginate()`: a larger `perPage`, given or declared, is
1634
+ * capped at it, since D1 bills every row read.
1635
+ */
1636
+ static maxPerPage: number;
1637
+ /**
1638
+ * Makes the value of an attribute declared with `generateId: true` that wasn't given: a
1639
+ * UUID by default. Override it on the app's base class to choose the app's ids
1640
+ * (`static override generateId = uuidv7`); it gets the attribute's name, never the record (#99).
1641
+ */
1642
+ static generateId(_attribute: string): string;
1643
+ /**
1644
+ * A Model whose attributes are declared here, the single source of truth for them (ADR-0007):
1645
+ * `class Visit extends Model.define({ path: "string" }) {}`. It's built on the class it's
1646
+ * called on, so a Model made with `ApplicationRecord.define({...})` shares the app's base.
1647
+ */
1648
+ static define<B extends BaseClass, const A extends AttributeSpecs>(this: B, specs: A & ExactSpecs<A>): ModelBaseFor<A, B>;
1649
+ /**
1650
+ * Declares a scope, as Rails' `scope :active, -> { … }`: `static active = this.scope((q) =>
1651
+ * q.where({ isActive: true }))`. It's a static (`User.active()`) and a Relation method
1652
+ * (`User.where(…).active()`), inherited like any static. Inside it, `q` has every Relation
1653
+ * method, but not the Model's other scopes (their types would refer to themselves).
1654
+ */
1655
+ static scope<C extends AbstractModelClass, A extends unknown[]>(this: C, body: (q: Relation<InstanceType<C>>, ...args: A) => Relation<InstanceType<C>>): ScopeStatic<A>;
1656
+ /**
1657
+ * All of this Model's records, as Rails' `Product.all`: a Relation on the current database
1658
+ * (the request's, set with `withDatabase`, or else the binding in its base class's schema).
1659
+ */
1660
+ static all<C extends QueryableClass>(this: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1661
+ /**
1662
+ * Only the named attributes of untrusted input (a JSON body, `FormData` or
1663
+ * `URLSearchParams`), as Rails' `params.permit`:
1664
+ * `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is
1665
+ * dropped, and each value is cast as assigning it would be.
1666
+ */
1667
+ static permit<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, input: unknown, ...names: K[]): Permitted<C, K>;
1668
+ /**
1669
+ * An enum's names, each with the value it's stored as, frozen (#340), as Rails' `Post.statuses`:
1670
+ * `Post.enumValues("status")` is `{ draft: "draft", published: "published" }`.
1671
+ */
1672
+ static enumValues<C extends QueryableClass, K extends EnumAttributeKey<InstanceType<C>>>(this: C, attribute: K): EnumMapping<EnumOf<InstanceType<C>, K>>;
1673
+ /**
1674
+ * An attribute's conversions, for SQL d1-record doesn't write, as Rails' `type_for_attribute`:
1675
+ * `Post.typeForAttribute("publishedAt").serialize(date)` is what `publishedAt` stores a `Date`
1676
+ * as, whatever its `storage`; `cast` and `deserialize` go the other way.
1677
+ */
1678
+ static typeForAttribute<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, name: K): AttributeConversions<AttributesOf<InstanceType<C>>[K]>;
1679
+ /**
1680
+ * Declares a default scope (#25), as Rails' `default_scope { … }`, in `static {}`:
1681
+ * `this.defaultScope((q) => q.where({ deletedAt: null }))`. Every query on the Model, its
1682
+ * associations' included, starts from it, and new records take its equality values. Several
1683
+ * are applied in order; a subclass adds to its parent's. `unscoped()` leaves them out.
1684
+ */
1685
+ static defaultScope<C extends AbstractModelClass>(this: C, body: (q: Relation<InstanceType<C>>) => Relation<InstanceType<C>>): void;
1686
+ /**
1687
+ * All of this Model's records without its default scopes (#25), as Rails' `Product.unscoped`,
1688
+ * on the current database. Only a static: a Relation keeps what it has.
1689
+ */
1690
+ static unscoped<C extends QueryableClass>(this: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1691
+ /** Declares a validation, e.g. `this.validates("email", { presence: true })` in `static {}`. */
1692
+ static validates<C extends AbstractModelClass>(this: C, attribute: keyof AttributesOf<InstanceType<C>> & string, options: ValidationOptions<InstanceType<C>, ContextOf<C>>): void;
1693
+ /**
1694
+ * Declares that an association's records must be valid too, e.g.
1695
+ * `this.validatesAssociated("posts")` in `static {}`: an invalid one adds "is invalid" to the
1696
+ * association's name. It loads the association first if it isn't loaded.
1697
+ */
1698
+ static validatesAssociated<C extends AbstractModelClass>(this: C, association: AssociationName<InstanceType<C>>, options?: AssociatedValidationOptions<InstanceType<C>, ContextOf<C>>): void;
1699
+ /**
1700
+ * Error messages in place of the built-in ones, by type (`blank`, or a type of your own), and
1701
+ * under `attributes` by attribute and type. A Model's own win over those of the classes it
1702
+ * extends, the app's base class's included; a later call's over an earlier one's (#88).
1703
+ */
1704
+ static errorMessages<C extends AbstractModelClass>(this: C, messages: ErrorMessages<ErrorAttributeName<InstanceType<C>>>): void;
1705
+ /**
1706
+ * Attribute names as error messages show them, in place of the name made from the attribute
1707
+ * ("createdAt" → "Created at"): `{ createdAt: "Signed up" }`. A Model's own win over those of
1708
+ * the classes it extends (#88).
1709
+ */
1710
+ static humanAttributeNames<C extends AbstractModelClass>(this: C, names: { readonly [K in ErrorAttributeName<InstanceType<C>>]?: string; }): void;
1711
+ /** The errors from the last validation run. */
1712
+ get errors(): Errors;
1713
+ /**
1714
+ * A loaded association, synchronously: records for a hasMany, a record or null otherwise.
1715
+ * Throws `AssociationNotLoaded` unless it was preloaded with `includes(...)` or already read
1716
+ * (and its key hasn't changed since).
1717
+ */
1718
+ loaded<K extends AssociationName<this>>(name: K): LoadedValue<this[K]>;
1719
+ /** Whether the association is loaded: preloaded or already read, for the key held now. */
1720
+ isLoaded<K extends AssociationName<this>>(name: K): boolean;
1721
+ /**
1722
+ * Loads the association again, replacing what's cached, and returns it: Rails'
1723
+ * `reload_author`, or `user.posts.reload` for a hasMany.
1724
+ */
1725
+ reloadAssociation<K extends AssociationName<this>>(name: K): Promise<LoadedValue<this[K]>>;
1726
+ /** Why a callback last refused a save or destroy (`abort(reason)`); never copied into `errors`. */
1727
+ get abortReason(): string | undefined;
1728
+ /**
1729
+ * Runs every validation, filling `errors` from scratch; `true` if there are none. A context
1730
+ * (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"`
1731
+ * once it's saved. Rules declared `on` another context don't run.
1732
+ */
1733
+ isValid(context?: ValidationContexts): Promise<boolean>;
1734
+ /** Whether any attribute differs from its value as last loaded or saved. */
1735
+ isChanged(): boolean;
1736
+ /** The names of the changed attributes. */
1737
+ changed(): string[];
1738
+ /** Each changed attribute's value before the change: `{ email: old }`. */
1739
+ changedAttributes(): Record<string, unknown>;
1740
+ /** Each changed attribute's value before and after: `{ email: [old, new] }`. */
1741
+ changes(): Changes;
1742
+ /** The changes the last successful save wrote; use it in after-save callbacks. */
1743
+ savedChanges(): Changes;
1744
+ /** The attribute's value before its unsaved change, as stored (Rails' `attribute_was`). */
1745
+ attributeWas<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1746
+ /**
1747
+ * Whether the attribute has an unsaved change, optionally `from` and/or `to` given values
1748
+ * (Rails' `attribute_changed?(name, from:, to:)`).
1749
+ */
1750
+ isAttributeChanged<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1751
+ /** Whether saving now would write a change to the attribute (for before-callbacks). */
1752
+ willSaveChangeTo<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1753
+ /** The last save's change to the attribute, `[before, after]`, if it changed (for after-callbacks). */
1754
+ savedChangeTo<R extends Model, K extends AttributeKey<R>>(this: R, name: K): [before: AttributesOf<R>[K], after: AttributesOf<R>[K]] | undefined;
1755
+ /** Whether the last save changed the attribute, optionally `from` and/or `to` given values. */
1756
+ hasSavedChangeTo<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1757
+ /** The attribute's value before the last save (its current stored value, if that didn't change it). */
1758
+ attributeBeforeLastSave<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1759
+ /** Undoes unsaved changes to these attributes (all of them by default), as Rails' `restore_attributes`. */
1760
+ restoreAttributes<R extends Model>(this: R, names?: readonly AttributeKey<R>[]): void;
1761
+ /**
1762
+ * Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted,
1763
+ * or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as
1764
+ * `isValid(context)` does.
1765
+ */
1766
+ save(options?: SaveOptions): Promise<boolean>;
1767
+ /**
1768
+ * Like `save()`, but throws `RecordInvalid`, `RecordNotSaved`, or `RecordNotDestroyed` (a
1769
+ * record marked for destruction refused) instead of returning `false`.
1770
+ */
1771
+ saveOrThrow(options?: SaveOptions): Promise<true>;
1772
+ /** Assigns several attributes without saving. */
1773
+ assign(attributes: Partial<AttributesOf<this>>): this;
1774
+ /** `assign` then `save`. */
1775
+ update(attributes: Partial<AttributesOf<this>>): Promise<boolean>;
1776
+ /** `assign` then `saveOrThrow`. */
1777
+ updateOrThrow(attributes: Partial<AttributesOf<this>>): Promise<true>;
1778
+ /**
1779
+ * Deletes the row and resolves to this record, now a read-only destroyed snapshot.
1780
+ * A row that's already gone still counts. `false` means a `beforeDestroy` callback aborted.
1781
+ */
1782
+ destroy(): Promise<this | false>;
1783
+ /** Like `destroy()`, but throws `RecordNotDestroyed` instead of returning `false`. */
1784
+ destroyOrThrow(): Promise<this>;
1785
+ /** Loads the stored row again, discarding unsaved changes; `RecordNotFound` if it's gone. */
1786
+ reload(): Promise<this>;
1787
+ /**
1788
+ * Marks the record to be destroyed when its owner is saved, through an association declared
1789
+ * `autosave: true`, as Rails' `mark_for_destruction` does. Nothing is written until then, and
1790
+ * `reload()` clears the mark.
1791
+ */
1792
+ markForDestruction(): void;
1793
+ /** Whether `markForDestruction()` marked it, since it was last loaded. */
1794
+ isMarkedForDestruction(): boolean;
1795
+ /** Not yet saved: built, or created but not persisted. */
1796
+ isNewRecord(): boolean;
1797
+ /**
1798
+ * Whether its last save created it, as Rails' `previously_new_record?`: true in a create's
1799
+ * after-callbacks and after it, false once it's saved again or destroyed.
1800
+ */
1801
+ isPreviouslyNewRecord(): boolean;
1802
+ /** Backed by a row: loaded, or saved successfully. */
1803
+ isPersisted(): boolean;
1804
+ /** Deleted by this instance; a read-only snapshot of the row. */
1805
+ isDestroyed(): boolean;
1806
+ /** The record's attributes as a plain object of JavaScript values. */
1807
+ attributes(): Record<string, unknown>;
1808
+ /** Prints as `Name { attribute: value, … }` in a console, a log or a test failure (#104). */
1809
+ [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
1810
+ /**
1811
+ * The loaded attributes as JSON-ready values (dates as ISO strings), without the Model's
1812
+ * `hiddenAttributes`, for `Response.json(record)`.
1813
+ */
1814
+ toJSON(): Record<string, unknown>;
1815
+ }
1816
+ /** Constructor type for any Model class, used wherever the library accepts one. */
1817
+ type ModelClass<M extends Model = Model> = (new () => M) & Omit<typeof Model, "prototype">;
1818
+ /**
1819
+ * A Model class whose records have attributes, generated or declared with `define`: what the
1820
+ * statics that query are called on, so an ungenerated Model's, or an abstract class's, are a
1821
+ * compile error.
1822
+ */
1823
+ type QueryableClass<M extends Model = Model> = ModelClass<M & {
1824
+ readonly [attributeTypes]: unknown;
1825
+ }>;
1826
+ /**
1827
+ * What a generated declaration adds to a Model's records: its table's attributes `A`, with the
1828
+ * Model's `static attributes` overrides `O` applied, typed, and its enums' methods (#340).
1829
+ */
1830
+ type TableAttributes<A extends AttributeSpecs, O = {}> = AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>> & EnumMethods<OverriddenSpecs<A, O>> & {
1831
+ readonly [attributeSpecs]: OverriddenSpecs<A, O>;
1832
+ readonly [attributeTypes]: AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>>;
1833
+ };
1834
+ /**
1835
+ * A Model class or a class Models are built on, abstract ones included (the app's base class):
1836
+ * what the statics that declare behavior (callbacks, validations, scopes) are called on.
1837
+ */
1838
+ type AbstractModelClass<M extends Model = Model> = (abstract new () => M) & Omit<typeof Model, "prototype">;
1839
+ /** A class to build Models on: `Model`, or an app's class extending it (`ApplicationRecord`'s). */
1840
+ type BaseClass = abstract new () => Model;
1841
+ /**
1842
+ * The base class `Model.define({...})` makes: records with the attributes `A`, built on `B` (the
1843
+ * library's base, or an app's), so they have its methods and statics too.
1844
+ */
1845
+ type ModelBaseFor<A extends AttributeSpecs, B extends BaseClass = typeof Model> = (new () => InstanceType<B> & AttributeProperties<A> & EnumMethods<A> & {
1846
+ readonly [attributeTypes]: AttributeProperties<A>;
1847
+ readonly [attributeSpecs]: A;
1848
+ }) & Omit<B, "prototype"> & EnumStatics<A>;
1849
+ /**
1850
+ * An error's message, after the attribute's name: `"can't be blank"`. With a count, one for
1851
+ * each plural form: `{ one: "needs 1 character", other: "needs %{count} characters" }`.
1852
+ */
1853
+ type ErrorMessage = string | {
1854
+ readonly one?: string;
1855
+ readonly other: string;
1856
+ };
1857
+ /** The messages of `restrictDependentDestroy`, for a has-one and a has-many association. */
1858
+ interface RestrictMessages {
1859
+ readonly hasOne: string;
1860
+ readonly hasMany: string;
1861
+ }
1862
+ /** Messages by attribute name (`N`: the names a Model has), then error type. */
1863
+ type AttributeErrorMessages<N extends string = string> = { readonly [K in N]?: {
1864
+ readonly [type: string]: ErrorMessage;
1865
+ }; };
1866
+ /**
1867
+ * What `errorMessages` declares: messages by error type (`blank`, `tooShort`, or a type of your
1868
+ * own), and under `attributes`, by attribute and type, which win over the class's others.
1869
+ */
1870
+ interface ErrorMessages<N extends string = string> {
1871
+ readonly [type: string]: ErrorMessage | RestrictMessages | AttributeErrorMessages<N> | undefined;
1872
+ readonly attributes?: AttributeErrorMessages<N>;
1873
+ readonly restrictDependentDestroy?: RestrictMessages;
1874
+ }
1875
+ /** The values an error's message can show as `%{name}`, such as `count`. */
1876
+ type ErrorValues = Readonly<Record<string, string | number>>;
1877
+ /** One validation failure: which attribute (or `"base"`), what kind, and the message. */
1878
+ interface ValidationError {
1879
+ attribute: string;
1880
+ type: string;
1881
+ message: string;
1882
+ /** The values its message shows, such as `count`, when it has some; never the attribute's. */
1883
+ values?: ErrorValues;
1884
+ }
1885
+ /** A record's validation errors: `record.errors`. Cleared at the start of each validation run. */
1886
+ declare class Errors {
1887
+ #private;
1888
+ /**
1889
+ * Adds an error with this message; `type` defaults to `"invalid"`. Use `"base"` for the
1890
+ * record as a whole.
1891
+ */
1892
+ add(attribute: string, message: string, options?: {
1893
+ type?: string;
1894
+ }): void;
1895
+ /**
1896
+ * Adds an error of this type, whose message is looked up in `errorMessages` when it's read,
1897
+ * with `%{name}` filled in from the values given: `{ type: "tooShort", count: 3 }`.
1898
+ */
1899
+ add(attribute: string, error: {
1900
+ type: string;
1901
+ } & ErrorValues): void;
1902
+ /** The messages for one attribute (always an array). */
1903
+ get(attribute: string): string[];
1904
+ /** Every message with its attribute's human name first: "Email can't be blank". */
1905
+ fullMessages(): string[];
1906
+ /** Every error as `{ attribute, type, message }`, with its `values` when it has some (copies). */
1907
+ toArray(): ValidationError[];
1908
+ isEmpty(): boolean;
1909
+ get size(): number;
1910
+ /** `Errors [ { attribute, type, message }, … ]`, so a console shows what `#entries` holds (#104). */
1911
+ [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
1912
+ }
1913
+ interface LengthOptions {
1914
+ minimum?: number;
1915
+ maximum?: number;
1916
+ is?: number;
1917
+ }
1918
+ interface NumericalityOptions {
1919
+ onlyInteger?: boolean;
1920
+ greaterThan?: number;
1921
+ greaterThanOrEqualTo?: number;
1922
+ lessThan?: number;
1923
+ lessThanOrEqualTo?: number;
1924
+ }
1925
+ /** The values `inclusion` and `exclusion` list: an array, or `{ in: [...] }`. */
1926
+ type ValueList = readonly unknown[] | {
1927
+ in: readonly unknown[];
1928
+ };
1929
+ /** The Model's attribute names for record type `R` (any string where `R` isn't known). */
1930
+ type AttributeName<R> = [R] extends [never] ? string : keyof AttributesOf<R> & string;
1931
+ interface UniquenessOptions<R = never> {
1932
+ /** Attributes that must also match for a value to count as taken. */
1933
+ scope?: readonly AttributeName<R>[];
1934
+ caseSensitive?: boolean;
1935
+ }
1936
+ /**
1937
+ * The rules for one `validates(attribute, options)` call. `R` is the Model's record type, and `X`
1938
+ * the validation contexts it can name.
1939
+ */
1940
+ interface ValidationOptions<R = never, X extends string = ValidationContext> {
1941
+ /** Not null, and not blank after trimming a string. */
1942
+ presence?: boolean;
1943
+ /** Null, or blank after trimming a string: what `presence` fails ("must be blank"). */
1944
+ absence?: boolean;
1945
+ length?: LengthOptions;
1946
+ format?: RegExp | {
1947
+ with: RegExp;
1948
+ };
1949
+ inclusion?: ValueList;
1950
+ /** Not one of these values ("is reserved"); null passes unless the list holds it. */
1951
+ exclusion?: ValueList;
1952
+ numericality?: boolean | NumericalityOptions;
1953
+ /**
1954
+ * Bounds the value must meet: numbers, strings (in JavaScript's order) or Dates (by time).
1955
+ */
1956
+ comparison?: ComparisonOptions<R>;
1957
+ /**
1958
+ * The value is one of `accept` (`true` and `"1"` unless given): a box that must be ticked.
1959
+ * Null fails, since an unticked checkbox sends nothing; `allowNull: true` lets it pass.
1960
+ */
1961
+ acceptance?: boolean | {
1962
+ accept: readonly unknown[];
1963
+ };
1964
+ /**
1965
+ * No other row has this value (checked in D1 through the record's Database). `scope` adds
1966
+ * attributes that must match too; `caseSensitive: false` compares with `lower()` (ASCII only).
1967
+ * `null` is never taken, as with SQLite's UNIQUE. Not race-safe: the constraint has the final say.
1968
+ */
1969
+ uniqueness?: boolean | UniquenessOptions<R>;
1970
+ /** Skip these rules when the value is null. */
1971
+ allowNull?: boolean;
1972
+ /** Skip these rules when the value is blank: null, or a string that's only whitespace. */
1973
+ allowBlank?: boolean;
1974
+ /** Replaces the default message of every failure from these rules. */
1975
+ message?: string;
1976
+ /**
1977
+ * Throw `StrictValidationFailed` with a failure's full message instead of adding it to
1978
+ * `errors`: for a value only a bug in the app's own code could give. An Error class is thrown
1979
+ * in its place, made with the same message.
1980
+ */
1981
+ strict?: true | (new (message: string) => Error);
1982
+ /** Only run these rules when this returns true. */
1983
+ if?: (record: R) => boolean;
1984
+ /** Skip these rules when this returns true; with `if`, both must allow them. */
1985
+ unless?: (record: R) => boolean;
1986
+ /**
1987
+ * Only run these rules in this validation context, or these: `"create"` while the record is
1988
+ * new, `"update"` once it's saved, or a name given to `isValid` or `save`.
1989
+ */
1990
+ on?: ValidationContexts<X>;
1991
+ /** Skip these rules in this validation context, or these, and run them in any other. */
1992
+ exceptOn?: ValidationContexts<X>;
1993
+ }
1994
+ /** The options of a `validatesAssociated(association, options)` call. */
1995
+ type AssociatedValidationOptions<R = never, X extends string = ValidationContext> = Pick<ValidationOptions<R, X>, "message" | "strict" | "if" | "unless" | "on" | "exceptOn">;
1996
+ export { PolymorphicBelongsTo as $, databaseExecutor as A, valueMark as At, ValidationContexts as B, QueryEvent as C, lt as Ct, SchemaAdapter as D, CompiledSql as Dt, ConstraintFailure as E, InOrderOfOptions as Et, RecordStatement as F, column as Ft, BelongsTo as G, Page as H, NumberAttributeKey as I, sql$1 as It, HasManyDependent as J, HasMany as K, SaveOptions as L, Comparable as Lt, BatchResults as M, ColumnReference as Mt, batch as N, ColumnValue as Nt, AnyDatabase as O, QuerySql as Ot, Batch as P, SafeSql as Pt, HasOneThrough as Q, ValidationCallbackOptions as R, ComparisonBound as Rt, DatabaseExecutor as S, gte as St, Adapter as T, QueryPart as Tt, PageOptions as U, CountlessPage as V, AssociationOptions as W, HasOne as X, HasManyThrough as Y, HasOneDependent as Z, TableSchema as _, Returning as _t, ValidationOptions as a, Scoped as at, boundValue as b, between as bt, AttributeErrorMessages as c, Init as ct, RestrictMessages as d, WriteResult as dt, ThroughDependent as et, Model as f, Driver as ft, DatabaseSchema as g, OrderSpec as gt, TableAttributes as h, InsertOptions as ht, UniquenessOptions as i, ScopeMethods as it, BatchEntry as j, Attribute as jt, RelationsFor as k, Dialect as kt, ErrorMessage as l, ReturnedRow as lt, ScopeStatic as m, Conditions as mt, LengthOptions as n, Relation as nt, Errors as o, IterationOptions as ot, ModelClass as p, StatementResult as pt, HasManyCollection as q, NumericalityOptions as r, Scope as rt, ValidationError as s, GroupedRelation as st, AssociatedValidationOptions as t, ThroughOptions as tt, ErrorMessages as u, Statement as ut, TableSchemas as v, UpsertOptions as vt, QueryListener as w, lte as wt, AttributeConversions as x, gt as xt, FilterAttribute as y, Comparison as yt, ValidationContext as z, ComparisonOptions as zt };