@forestfuture/active-record 0.7.0 → 0.8.1

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-Ms5p9lKq.mjs +9777 -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/{for-adapters-t3-LukJQ.d.mts → for-adapters-BT2GDjIA.d.mts} +8 -6
  11. package/dist/{for-adapters-Ch6CoHD4.mjs → for-adapters-BbIMUNcz.mjs} +46 -10
  12. package/dist/{for-adapters-D_Iu0gS_.mjs → for-adapters-C-MQxaIx.mjs} +3 -5
  13. package/dist/{generated-model-Cnt0Ot9q.mjs → generated-model-DJA8vmNE.mjs} +705 -508
  14. package/dist/identifiers-Dh5DFACX.mjs +989 -0
  15. package/dist/index-D5getfHx.d.mts +242 -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-CZPDqguF.mjs} +211 -112
  20. package/dist/{plugin-XOHYndhP.mjs → plugin-Cf-5Z0_h.mjs} +148 -52
  21. package/dist/postgresql.d.mts +1 -9
  22. package/dist/postgresql.mjs +42 -26
  23. package/dist/src-BAVZKQ7J.mjs +46 -0
  24. package/dist/{storage-override-CpbkdIqE.mjs → storage-override-0ZgeP2sc.mjs} +61 -28
  25. package/dist/validations-BSZ5gVeI.d.mts +2024 -0
  26. package/llms-full.txt +2326 -229
  27. package/package.json +1 -1
  28. package/skills/active-record/SKILL.md +24 -15
  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
@@ -1,4255 +0,0 @@
1
- import { $ as CallbackAbort, A as requireDefined, B as shownKey, C as castInherited, D as attributesForColumn, E as attributeOf, F as zonelessDateTime, G as modelClassName, H as explainMissingTable, I as Filtered, K as rejectAbstract, L as boundValue, M as castValue, N as uncastable, O as define, P as writeUntypedValue, Q as AssociationNotLoaded, R as defaultFilterAttributes, S as attributeFor, T as storedRows, U as ignoresColumns, V as shownValue, W as inferTableNames, X as AbortAfterPersistence, Y as ancestors, _ as attributesNamedInMessages, a as isGenerated, at as InvalidModel, b as declared, c as RecordState, ct as NoDatabase, dt as RecordInvalid, et as CheckViolation, f as addFailure, ft as RecordNotDestroyed, g as printed, gt as UnknownAssociation, h as inspectCustom, ht as RecordNotUnique, it as InvalidForeignKey, j as specProblem, k as initialValues, l as linksOf, lt as NotNullViolation, m as FilteredMark, mt as RecordNotSaved, n as defineAttributeAccessors, nt as DeleteRestriction, o as schemaAdapter, ot as IrreversibleOrder, p as clearErrors, pt as RecordNotFound, q as requireTableName, r as defineGeneratedStatics, rt as IncompatibleRelation, s as settleGenerated, t as attributesSettled, u as state, v as humanAttributeName, w as noMatch, x as seal, y as declare, z as isFiltered } from "./generated-model-Cnt0Ot9q.mjs";
2
- import { a as underscore, i as camelize } from "./epoch-storage-o2aoOH7H.mjs";
3
- //#region src/foreign-keys.ts
4
- /**
5
- * Gives each declaration its foreign key: the one passed, or else inferred by Rails'
6
- * convention, where the association's name and its declaring class are known.
7
- */
8
- function withForeignKeys(declarations, className) {
9
- return Object.fromEntries(Object.entries(declarations).map(([name, declaration]) => [name, declaration.foreignKey === void 0 ? {
10
- ...declaration,
11
- ...inferForeignKey(declaration.kind, name, className)
12
- } : {
13
- ...declaration,
14
- foreignKey: declaration.foreignKey
15
- }]));
16
- }
17
- /**
18
- * A belongsTo's name + `Id` (`author` → `authorId`); for a hasMany or hasOne, the declaring
19
- * class's name + `Id`, through `underscore` (`User` → `userId`, `APIKey` → `apiKeyId`).
20
- */
21
- function inferForeignKey(kind, associationName, className) {
22
- return kind === "belongsTo" ? {
23
- foreignKey: `${associationName}Id`,
24
- inferredFrom: {
25
- source: "associationName",
26
- name: associationName
27
- }
28
- } : {
29
- foreignKey: `${camelize(underscore(className))}Id`,
30
- inferredFrom: {
31
- source: "className",
32
- name: className
33
- }
34
- };
35
- }
36
- /** Why an inferred key is missing, and what to do about it. */
37
- function inferenceHint({ source, name }) {
38
- if (source === "associationName") return `inferred from the association name ${name}; declare it, or pass foreignKey`;
39
- return `inferred from the class name ${name}; declare it, or pass foreignKey (and keep class names if your bundler renames them)`;
40
- }
41
- //#endregion
42
- //#region src/association-fields.ts
43
- /**
44
- * How many `newRecord` calls are constructing a record now. Module-level, but not request state
45
- * (ADR-0003): it's back to 0 before `newRecord` returns, with no await in between.
46
- */
47
- let makingRecords = 0;
48
- /** A field's accessor on a record constructed directly: it and its methods throw `NoDatabase`. */
49
- function throwingField() {
50
- const field = () => {
51
- throw new NoDatabase("this record was constructed directly (new …); build or load records through db.model(…) to use its associations");
52
- };
53
- return Object.assign(field, {
54
- set: field,
55
- build: field,
56
- create: field,
57
- createOrThrow: field
58
- });
59
- }
60
- /**
61
- * Every association field's value while `newRecord` constructs a record. That record's fields are
62
- * removed, but one constructed directly meanwhile (`new Other()` in a field initializer) keeps
63
- * them, so it throws as a real field does.
64
- */
65
- const placeholderField = Object.freeze(throwingField());
66
- /** Marks a record field's value as an association declaration, and holds it. */
67
- const declarationKey = Symbol("d1-record association");
68
- /**
69
- * An association declaration, as a record field's value: `posts = hasMany(Post)`. Its
70
- * type is the accessor's, so TypeScript knows `user.posts()` with no `declare` line (ADR-0008).
71
- * Records from `build()` and queries get the real accessor; on a record constructed directly
72
- * (`new User()`), calling the field throws `NoDatabase`, as any database operation does.
73
- */
74
- function declaration(kind, target, options) {
75
- if (makingRecords > 0) return placeholderField;
76
- const field = throwingField();
77
- return Object.assign(field, { [declarationKey]: {
78
- kind,
79
- target: () => target,
80
- ...options
81
- } });
82
- }
83
- /** This record points at one `target` record through `foreignKey` (its own attribute). */
84
- function belongsTo(target, options = {}) {
85
- return declaration("belongsTo", target, options);
86
- }
87
- /** Many `target` records point at this record through `foreignKey` (theirs). */
88
- function hasMany(target, options = {}) {
89
- return declaration("hasMany", target, options);
90
- }
91
- /** One `target` record points at this record through `foreignKey` (its own). */
92
- function hasOne(target, options = {}) {
93
- return declaration("hasOne", target, options);
94
- }
95
- /**
96
- * Each Model's associations, read once from a probe record's fields, with foreign keys given
97
- * or inferred. Module-level, but not request state (ADR-0003): derived only from the class.
98
- */
99
- const definitions = /* @__PURE__ */ new WeakMap();
100
- /** One record of each Model, made once, to read its fields. Not request state (ADR-0003). */
101
- const probes = /* @__PURE__ */ new WeakMap();
102
- /** A Model's probe record: its fields as declared, before any are removed. */
103
- function probeOf(model) {
104
- let probe = probes.get(model);
105
- if (probe === void 0) {
106
- const making = makingRecords;
107
- makingRecords = 0;
108
- try {
109
- probe = new model();
110
- } finally {
111
- makingRecords = making;
112
- }
113
- probes.set(model, probe);
114
- }
115
- return probe;
116
- }
117
- /** The declaration a field holds, if it's an association's. */
118
- function declarationIn(value) {
119
- return typeof value === "function" ? value[declarationKey] : void 0;
120
- }
121
- /**
122
- * A Model's associations by name, in the order its fields declare them. A Map, so a name every
123
- * object inherits (`constructor`, from a URL's `?include=`) is never one (#84).
124
- */
125
- function associationsOf(model) {
126
- let found = definitions.get(model);
127
- if (found === void 0) {
128
- const probe = probeOf(model);
129
- const declared = {};
130
- for (const name of Object.keys(probe)) {
131
- const field = declarationIn(probe[name]);
132
- if (field !== void 0) declared[name] = field;
133
- }
134
- found = new Map(Object.entries(withForeignKeys(declared, modelClassName(model))));
135
- definitions.set(model, found);
136
- }
137
- return found;
138
- }
139
- /**
140
- * A new record of `model`, its association fields removed so the accessors on the Model's
141
- * prototype answer instead. Removed newest first: when they're a record's last fields, as
142
- * they usually are, that undoes their additions and keeps the object's shape fast.
143
- */
144
- function newRecord(model) {
145
- const record = constructWithoutAssociations(model);
146
- const names = [...associationsOf(model).keys()];
147
- for (let index = names.length - 1; index >= 0; index--) delete record[names[index]];
148
- return record;
149
- }
150
- /** A record of `model` from its constructor, its association fields left as `placeholderField`. */
151
- function constructWithoutAssociations(model) {
152
- makingRecords++;
153
- try {
154
- return new model();
155
- } finally {
156
- makingRecords--;
157
- }
158
- }
159
- /** A Model's association by name; `UnknownAssociation` for any other name. */
160
- function associationOf(model, name) {
161
- const definition = associationsOf(model).get(name);
162
- if (definition === void 0) throw new UnknownAssociation(`${model.name} has no association "${name}"`);
163
- return definition;
164
- }
165
- //#endregion
166
- //#region src/comparisons.ts
167
- /** @internal The library's key for reading a Comparison's parts. */
168
- const comparisonParts = Symbol("comparisonParts");
169
- /**
170
- * A comparison condition for one attribute: `where({ age: gte(18) })`. Made by `gt`, `gte`,
171
- * `lt`, `lte` and `between`; a class, so it's never mistaken for a json attribute's value.
172
- */
173
- var Comparison = class {
174
- #operator;
175
- #values;
176
- /** @internal Use `gt`, `gte`, `lt`, `lte` or `between`. */
177
- constructor(operator, values) {
178
- for (const value of values) if (value === null || value === void 0) throw new TypeError(`A comparison needs a value, not ${String(value)}; use where({ attribute: null }) to match NULL`);
179
- this.#operator = operator;
180
- this.#values = values;
181
- }
182
- /** @internal What the compiler needs: the operator, and the values to bind in order. */
183
- get [comparisonParts]() {
184
- return {
185
- operator: this.#operator,
186
- values: this.#values
187
- };
188
- }
189
- };
190
- /** `attribute > value` */
191
- function gt(value) {
192
- return new Comparison(">", [value]);
193
- }
194
- /** `attribute >= value`, like Rails' endless range `value..` */
195
- function gte(value) {
196
- return new Comparison(">=", [value]);
197
- }
198
- /** `attribute < value`, like Rails' beginless range `...value` */
199
- function lt(value) {
200
- return new Comparison("<", [value]);
201
- }
202
- /** `attribute <= value`, like Rails' beginless range `..value` */
203
- function lte(value) {
204
- return new Comparison("<=", [value]);
205
- }
206
- /**
207
- * `attribute BETWEEN start AND end`, both ends included, like Rails' `start..end`. With
208
- * `excludeEnd`, `start <= attribute < end`, like `start...end` (e.g. a window of days).
209
- */
210
- function between(start, end, options = {}) {
211
- return new Comparison(options.excludeEnd ? "betweenExcludingEnd" : "between", [start, end]);
212
- }
213
- //#endregion
214
- //#region src/sql.ts
215
- /**
216
- * A SQL fragment built with the `sql` tagged template (ADR-0006). The template
217
- * text is written by the developer; every interpolated value is bound as a
218
- * parameter and never becomes SQL text.
219
- */
220
- var SafeSql = class {
221
- strings;
222
- values;
223
- /** @internal Use the `sql` tag instead. */
224
- constructor(strings, values) {
225
- this.strings = strings;
226
- this.values = values;
227
- }
228
- };
229
- function sql(strings, ...values) {
230
- return new SafeSql([...strings], values);
231
- }
232
- /** A reference to an attribute's column, resolved against the query's Model when compiled. */
233
- var ColumnReference = class {
234
- attribute;
235
- /** @internal Use `column()` instead. */
236
- constructor(attribute) {
237
- this.attribute = attribute;
238
- }
239
- /**
240
- * A value of this attribute for a fragment, converted as the attribute stores it: a `Date`
241
- * as the integer of an attribute kept as a Unix time, a boolean as 0 or 1, and so on. It's
242
- * still a bound parameter. Without it, a value has no attribute to say how it's stored (#142).
243
- */
244
- value(value) {
245
- return new ColumnValue(this.attribute, value);
246
- }
247
- };
248
- /** A value of an attribute, from `column(attribute).value(value)`, converted when compiled. */
249
- var ColumnValue = class {
250
- attribute;
251
- /** What was given, before it's cast as an assigned value of the attribute. */
252
- assigned;
253
- /** @internal Use `column(attribute).value(value)` instead. */
254
- constructor(attribute, assigned) {
255
- this.attribute = attribute;
256
- this.assigned = assigned;
257
- }
258
- };
259
- /** Whether a fragment's interpolated value names an attribute: a column, or a typed value. */
260
- function namesAttribute(value) {
261
- return value instanceof ColumnReference || value instanceof ColumnValue;
262
- }
263
- /** Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004). */
264
- function column(attribute) {
265
- return new ColumnReference(attribute);
266
- }
267
- //#endregion
268
- //#region src/query.ts
269
- /**
270
- * A condition from preloading (#217): `attribute` is the `ownerKey` of one of the records
271
- * `owners` finds, so a preload finds its owners' keys with a subquery, not with keys bound once
272
- * they're loaded.
273
- */
274
- var LinkedTo = class {
275
- attribute;
276
- /** The owners' query. */
277
- owners;
278
- ownerKey;
279
- constructor(attribute, owners, ownerKey) {
280
- this.attribute = attribute;
281
- this.owners = owners;
282
- this.ownerKey = ownerKey;
283
- }
284
- };
285
- /** A condition from `or`: either side's conditions (each ANDed together) may match. */
286
- var Either = class {
287
- left;
288
- right;
289
- constructor(left, right) {
290
- this.left = left;
291
- this.right = right;
292
- }
293
- };
294
- /** A condition from `whereNot`: the whole condition is negated, `NOT (…)`. */
295
- var Negated = class {
296
- condition;
297
- constructor(condition) {
298
- this.condition = condition;
299
- }
300
- };
301
- /** All of `model`'s rows, in no particular order. */
302
- function allOf(model) {
303
- return {
304
- model,
305
- conditions: [],
306
- order: []
307
- };
308
- }
309
- /** Everything but the conditions: what `or` requires to match and `merge` may replace. */
310
- const SHAPE_CLAUSES = [
311
- "select",
312
- "order",
313
- "limit",
314
- "offset",
315
- "distinct"
316
- ];
317
- /** Whether two descriptions agree on one shape clause, by that clause's own rule. */
318
- function sameClause(clause, a, b) {
319
- switch (clause) {
320
- case "select": return sameList(a.select, b.select, (x, y) => x === y);
321
- case "order": return sameList(a.order, b.order, sameOrderTerm);
322
- default: return Object.is(a[clause], b[clause]);
323
- }
324
- }
325
- function sameOrderTerm(x, y) {
326
- if (x instanceof SafeSql || y instanceof SafeSql) return x instanceof SafeSql && y instanceof SafeSql && sameFragment(x, y);
327
- return x.attribute === y.attribute && x.direction === y.direction && x.nulls === y.nulls;
328
- }
329
- /** Fragments with the same text and the same values. */
330
- function sameFragment(x, y) {
331
- return sameList(x.strings, y.strings, (a, b) => a === b) && sameList(x.values, y.values, sameValue$1);
332
- }
333
- /** Columns by attribute, typed values by attribute and value, dates by time, the rest by identity. */
334
- function sameValue$1(a, b) {
335
- if (a instanceof ColumnReference && b instanceof ColumnReference) return a.attribute === b.attribute;
336
- if (a instanceof ColumnValue && b instanceof ColumnValue) return a.attribute === b.attribute && sameInput(a.assigned, b.assigned);
337
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
338
- return Object.is(a, b);
339
- }
340
- /** A typed value's input: an object (a json value) by its JSON text, else as `sameValue`. */
341
- function sameInput(a, b) {
342
- if (!(typeof a === "object" && a !== null && typeof b === "object" && b !== null) || a instanceof Date || b instanceof Date || Object.is(a, b)) return sameValue$1(a, b);
343
- try {
344
- return JSON.stringify(a) === JSON.stringify(b);
345
- } catch {
346
- return false;
347
- }
348
- }
349
- function sameList(a, b, same) {
350
- if (a === void 0 || b === void 0) return a === b;
351
- return a.length === b.length && a.every((item, index) => same(item, b[index]));
352
- }
353
- /**
354
- * Whether a clause was set explicitly; an empty order or an unset flag counts as not set,
355
- * unless the order came from `reorder()`.
356
- */
357
- function isSet(query, clause) {
358
- if (clause === "order" && query.reordered) return true;
359
- const value = query[clause];
360
- return Array.isArray(value) ? value.length > 0 : value !== void 0 && value !== false;
361
- }
362
- /**
363
- * Rows matching `a`'s conditions or `b`'s (`or()`). Both must be identical in everything but
364
- * their conditions; a `none()` side contributes nothing.
365
- */
366
- function either(a, b) {
367
- if (a.none) return b;
368
- if (b.none) return a;
369
- for (const clause of SHAPE_CLAUSES) if (!sameClause(clause, a, b)) throw new IncompatibleRelation(`or() needs relations that differ only in their conditions, but their ${clause} differs`);
370
- if (!sameTree(a.includes ?? {}, b.includes ?? {})) throw new IncompatibleRelation("or() needs relations that differ only in their conditions, but their includes differ");
371
- return {
372
- ...a,
373
- conditions: [new Either(a.conditions, b.conditions)]
374
- };
375
- }
376
- /**
377
- * `b`'s conditions ANDed onto `a`'s (`merge()`). For select, order, limit, offset and distinct,
378
- * a clause `b` sets explicitly replaces `a`'s; one it doesn't set is kept. Includes are unioned.
379
- */
380
- function merged(a, b) {
381
- const result = {
382
- ...a,
383
- conditions: [...a.conditions, ...b.conditions],
384
- ...b.none === true && { none: true },
385
- ...b.includes !== void 0 && { includes: mergeTrees(a.includes ?? {}, b.includes) }
386
- };
387
- for (const clause of SHAPE_CLAUSES) if (isSet(b, clause)) Object.assign(result, { [clause]: b[clause] });
388
- if (b.reordered) result.reordered = true;
389
- return result;
390
- }
391
- /**
392
- * The single equality values of the conditions (a value or null), which a record built from a
393
- * Relation starts with. Arrays, comparisons, `whereNot`, `or` and fragments carry nothing over.
394
- */
395
- function inheritedAttributes(conditions) {
396
- const inherited = {};
397
- for (const condition of conditions) {
398
- if (condition instanceof SafeSql || condition instanceof Negated || condition instanceof Either) continue;
399
- for (const [name, value] of Object.entries(condition)) if (!Array.isArray(value) && !(value instanceof Comparison)) inherited[name] = value;
400
- }
401
- return inherited;
402
- }
403
- /** The union of two include trees. */
404
- function mergeTrees(a, b) {
405
- const merged = { ...a };
406
- for (const [name, nested] of Object.entries(b)) merged[name] = mergeTrees(merged[name] ?? {}, nested);
407
- return merged;
408
- }
409
- /** Whether two include trees name the same associations at every level. */
410
- function sameTree(a, b) {
411
- const names = Object.keys(a);
412
- if (names.length !== Object.keys(b).length) return false;
413
- return names.every((name) => b[name] !== void 0 && sameTree(a[name], b[name]));
414
- }
415
- //#endregion
416
- //#region src/dialect.ts
417
- /**
418
- * Where compiled SQL binds a value, in its own order. A dialect writes each as its database's
419
- * placeholder once the SQL is complete, so a `?` in a raw `sql` fragment's text (Postgres's jsonb
420
- * operator) is never read as one. NUL, since no database accepts it in a statement's text.
421
- */
422
- const valueMark = "\0";
423
- /** `compiled` with each `valueMark` written as `dialect`'s placeholder: the SQL as it's sent. */
424
- function withPlaceholders(dialect, compiled) {
425
- if (!compiled.sql.includes("\0")) return compiled;
426
- let index = 0;
427
- const sql = compiled.sql.replaceAll("\0", () => dialect.placeholder(++index));
428
- return {
429
- ...compiled,
430
- sql
431
- };
432
- }
433
- //#endregion
434
- //#region src/compiler.ts
435
- /** `compiled` as `toSql()` shows it: the values D1 binds, and not the Model it is for. */
436
- function querySql({ sql, params }) {
437
- return {
438
- sql,
439
- params: params.map(boundValue)
440
- };
441
- }
442
- /** Quotes an identifier; embedded double quotes are doubled. */
443
- function quoteIdentifier(name) {
444
- return `"${name.replaceAll("\"", "\"\"")}"`;
445
- }
446
- /** `projection` is the SELECT list; the library builds it, never the caller. */
447
- function compileSelect(dialect, query, projection) {
448
- const params = [];
449
- const list = projection ?? compileColumns(query.model, query.select);
450
- let sql = `SELECT ${query.distinct ? "DISTINCT " : ""}${list}`;
451
- sql += ` FROM ${quoteIdentifier(query.model.table)}`;
452
- sql += compileWhere(dialect, query, params);
453
- sql += compileOrder(query, params);
454
- sql += compilePagination(dialect, query, params);
455
- return {
456
- sql,
457
- params,
458
- model: query.model
459
- };
460
- }
461
- function compileWhere(dialect, { model, conditions }, params) {
462
- return conditions.length === 0 ? "" : ` WHERE ${compileAll(dialect, conditions, model, params)}`;
463
- }
464
- /** Conditions ANDed together as one predicate; no conditions matches everything. */
465
- function compileAll(dialect, conditions, model, params) {
466
- if (conditions.length === 0) return "(1 = 1)";
467
- return `(${conditions.map((condition) => compileCondition(dialect, condition, model, params)).join(" AND ")})`;
468
- }
469
- /** One condition as a single parenthesized predicate. */
470
- function compileCondition(dialect, condition, model, params) {
471
- if (condition instanceof Either) return `(${compileAll(dialect, condition.left, model, params)} OR ${compileAll(dialect, condition.right, model, params)})`;
472
- if (condition instanceof Negated) return `(NOT ${compileCondition(dialect, condition.condition, model, params)})`;
473
- if (condition instanceof SafeSql) return `(${compileFragment(condition, model, params)})`;
474
- if (condition instanceof LinkedTo) return `(${compileLinkedTo(dialect, condition, model, params)})`;
475
- return `(${Object.entries(condition).map(([name, value]) => {
476
- const attribute = attributeFor(model, name);
477
- return value instanceof Comparison ? compileComparison(attribute, value, params) : compileEquality(dialect, attribute, value, params);
478
- }).join(" AND ")})`;
479
- }
480
- /**
481
- * `attr IN (SELECT key FROM … WHERE …)`: the keys of the records `owners` finds. With a limit
482
- * or offset, its order picks those records; without, it's left out, as it can't change them.
483
- * The dialect selects the key so it compares with `attr` as a condition would, across key types.
484
- */
485
- function compileLinkedTo(dialect, { attribute, owners, ownerKey }, model, params) {
486
- const linked = attributeFor(model, attribute);
487
- const keyAttribute = attributeFor(owners.model, ownerKey);
488
- const column = quoteIdentifier(linked.column);
489
- const keyColumn = quoteIdentifier(keyAttribute.column);
490
- const selected = dialect.linkedKey(keyColumn, keyAttribute, linked);
491
- const order = owners.limit !== void 0 || owners.offset !== void 0 ? owners.order : [];
492
- const inner = compileSelect(dialect, {
493
- ...owners,
494
- order,
495
- distinct: false
496
- }, selected);
497
- params.push(...inner.params);
498
- return `${column} IN (${inner.sql})`;
499
- }
500
- /**
501
- * `INSERT … RETURNING` the row (`*`, or the declared columns) for the given attribute values, or
502
- * `DEFAULT VALUES` for none. `returning` names the attributes to return instead; none sends no
503
- * `RETURNING`.
504
- */
505
- function compileInsert(model, assignments, returning) {
506
- const table = quoteIdentifier(model.table);
507
- const returned = compileReturning(model, returning);
508
- if (assignments.length === 0) return {
509
- sql: `INSERT INTO ${table} DEFAULT VALUES${returned}`,
510
- params: [],
511
- model
512
- };
513
- const columns = assignments.map(([name]) => quoteIdentifier(attributeFor(model, name).column)).join(", ");
514
- const placeholders = assignments.map(() => "\0").join(", ");
515
- const params = [];
516
- for (const [name, value] of assignments) attributeFor(model, name).bind(params, value);
517
- return {
518
- sql: `INSERT INTO ${table} (${columns}) VALUES (${placeholders})${returned}`,
519
- params,
520
- model
521
- };
522
- }
523
- /** ` RETURNING` the whole row, or the columns of `attributes`, or nothing when there are none. */
524
- function compileReturning(model, attributes) {
525
- if (attributes?.length === 0) return "";
526
- return ` RETURNING ${compileColumns(model, attributes)}`;
527
- }
528
- /**
529
- * `INSERT` of several rows, all with the attributes `names`, bound as one JSON parameter, which
530
- * the dialect reads them from. One statement and one bound value, whatever the number of rows,
531
- * within D1's limit of 100 bound parameters per statement.
532
- */
533
- function compileInsertRows(dialect, model, { names, rows, conflict, returning }) {
534
- const attributes = names.map((name) => attributeFor(model, name));
535
- const columns = attributes.map(({ column }) => quoteIdentifier(column)).join(", ");
536
- const table = quoteIdentifier(model.table);
537
- const { select, from } = dialect.bulkRows(table, attributes);
538
- const json = storedRows(model, names, rows);
539
- return {
540
- sql: `INSERT INTO ${table} (${columns}) SELECT ${select} FROM ${from} WHERE true${compileConflict(model, names, conflict)}` + compileReturning(model, returning),
541
- params: [json],
542
- model
543
- };
544
- }
545
- /**
546
- * `ON CONFLICT DO NOTHING`, or `ON CONFLICT (…) DO UPDATE SET` the `update` attributes (every
547
- * inserted one by default) except the `uniqueBy` ones and `createdAt`, as Rails' upsert does.
548
- */
549
- function compileConflict(model, names, conflict) {
550
- if (conflict === void 0) return "";
551
- if (conflict.kind === "skip") return " ON CONFLICT DO NOTHING";
552
- const column = (name) => quoteIdentifier(attributeFor(model, name).column);
553
- const target = conflict.uniqueBy.map(column).join(", ");
554
- const updated = (conflict.update ?? names).filter((name) => !conflict.uniqueBy.includes(name) && name !== "createdAt");
555
- if (updated.length === 0) return ` ON CONFLICT (${target}) DO NOTHING`;
556
- return ` ON CONFLICT (${target}) DO UPDATE SET ${updated.map((name) => `${column(name)} = excluded.${column(name)}`).join(", ")}`;
557
- }
558
- /**
559
- * `UPDATE … SET … WHERE <primary key> = ?` for the given attribute values. `storedKey` is
560
- * the key as stored in D1 (the row's key before any change to it), so it's bound as-is.
561
- */
562
- function compileUpdate(model, assignments, storedKey) {
563
- const params = [];
564
- const sets = compileSets(model, assignments, params);
565
- const primaryKey = attributeFor(model, model.primaryKey);
566
- attributeFor(model, model.primaryKey).bindCells(params, storedKey);
567
- return {
568
- sql: `UPDATE ${quoteIdentifier(model.table)} SET ${sets} WHERE ${quoteIdentifier(primaryKey.column)} = `,
569
- params,
570
- model
571
- };
572
- }
573
- /** `"col" = ?, …` for attribute values, or an `sql` fragment's own text. */
574
- function compileSets(model, changes, params) {
575
- if (changes instanceof SafeSql) return compileFragment(changes, model, params);
576
- return changes.map(([name, value]) => {
577
- const attribute = attributeFor(model, name);
578
- attribute.bind(params, value);
579
- return `${quoteIdentifier(attribute.column)} = `;
580
- }).join(", ");
581
- }
582
- /**
583
- * The WHERE clause for writing to the rows `query` describes, as Rails does it: its conditions;
584
- * with a limit or offset, `<primary key> IN (SELECT <primary key> … ORDER … LIMIT … OFFSET)`;
585
- * `1 = 0` for `none()`. Order without a limit, select and includes don't matter to a write.
586
- */
587
- function compileTarget(dialect, query, params) {
588
- if (query.none) return " WHERE 1 = 0";
589
- if (query.limit === void 0 && query.offset === void 0) return compileWhere(dialect, query, params);
590
- const key = quoteIdentifier(attributeFor(query.model, query.model.primaryKey).column);
591
- const inner = compileSelect(dialect, {
592
- ...query,
593
- distinct: false
594
- }, key);
595
- params.push(...inner.params);
596
- return ` WHERE ${key} IN (${inner.sql})`;
597
- }
598
- /** `UPDATE … SET … WHERE …` for every row `query` describes. */
599
- function compileUpdateAll(dialect, query, changes) {
600
- const params = [];
601
- const sets = compileSets(query.model, changes, params);
602
- const target = compileTarget(dialect, query, params);
603
- return {
604
- sql: `UPDATE ${quoteIdentifier(query.model.table)} SET ${sets}${target}`,
605
- params,
606
- model: query.model
607
- };
608
- }
609
- /** `DELETE … WHERE …` for every row `query` describes. */
610
- function compileDeleteAll(dialect, query) {
611
- const params = [];
612
- const target = compileTarget(dialect, query, params);
613
- return {
614
- sql: `DELETE FROM ${quoteIdentifier(query.model.table)}${target}`,
615
- params,
616
- model: query.model
617
- };
618
- }
619
- /** `DELETE … WHERE <primary key> = ?`, with the key as stored in D1. */
620
- function compileDelete(model, storedKey) {
621
- const { column } = attributeFor(model, model.primaryKey);
622
- const params = [];
623
- attributeFor(model, model.primaryKey).bindCells(params, storedKey);
624
- return {
625
- sql: `DELETE FROM ${quoteIdentifier(model.table)} WHERE ${quoteIdentifier(column)} = `,
626
- params,
627
- model
628
- };
629
- }
630
- /** A whole row: `*`, or the declared columns when the Model ignores some of its table's. */
631
- function allColumns(model) {
632
- return ignoresColumns(model) ? compileColumns(model, [...model.attributeDefinitions.keys()]) : "*";
633
- }
634
- /** The quoted columns for `attributes`, or the whole row. */
635
- function compileColumns(model, attributes) {
636
- if (attributes === void 0) return allColumns(model);
637
- return attributes.map((name) => quoteIdentifier(attributeFor(model, name).column)).join(", ");
638
- }
639
- /**
640
- * Counts over the whole query as a subquery, so `count()` always equals the number of
641
- * rows `toArray()` would return (including limit, offset, select and distinct).
642
- * `count(attr)` counts non-null values, or distinct non-null values after `distinct()`.
643
- */
644
- function compileCount(dialect, query, attribute) {
645
- const toCount = queryToCount(query);
646
- if (attribute === void 0) {
647
- const inner = compileSelect(dialect, toCount);
648
- return {
649
- ...inner,
650
- sql: `SELECT COUNT(*) AS count FROM (${inner.sql}) AS counted`
651
- };
652
- }
653
- const inner = compileSelect(dialect, {
654
- ...toCount,
655
- select: void 0,
656
- distinct: false
657
- });
658
- const column = quoteIdentifier(attributeFor(query.model, attribute).column);
659
- const counted = query.distinct ? `DISTINCT ${column}` : column;
660
- return {
661
- ...inner,
662
- sql: `SELECT COUNT(${counted}) AS count FROM (${inner.sql}) AS counted`
663
- };
664
- }
665
- /**
666
- * The query a count reads: without the order unless a limit or offset picks the rows by it,
667
- * so SQLite doesn't sort every match only to count it (#215).
668
- */
669
- function queryToCount(query) {
670
- if (query.limit !== void 0 || query.offset !== void 0) return query;
671
- return {
672
- ...query,
673
- order: []
674
- };
675
- }
676
- /**
677
- * `SELECT 1 …` for whether any row `query` describes exists, within its limit and offset. The
678
- * order is left out: it can't change whether a row exists, even past an offset (#215).
679
- * `DISTINCT 1` would make the matches one row, which an offset skips, so a distinct query with
680
- * an offset keeps its own select list: the rows `toArray()` reads (#222).
681
- */
682
- function compileExists(dialect, query) {
683
- const unordered = {
684
- ...query,
685
- order: []
686
- };
687
- if (query.distinct && query.offset !== void 0) return compileSelect(dialect, unordered);
688
- return compileSelect(dialect, unordered, "1");
689
- }
690
- /** `attr >= ?`, `attr BETWEEN ? AND ?`, …, with the values converted like the attribute's. */
691
- function compileComparison(attribute, comparison, params) {
692
- const { operator, values } = comparison[comparisonParts];
693
- const stored = values.map((value) => attribute.conditionCell(value));
694
- if (stored.includes(noMatch)) return NOTHING;
695
- attribute.bindCells(params, ...stored);
696
- return COMPARISON_SQL[operator](quoteIdentifier(attribute.column));
697
- }
698
- /**
699
- * A condition that matches no row: an empty list, or a value that can't be cast (#81), as in
700
- * Rails 6.1+, so a value from a URL is never an error or a NULL match.
701
- */
702
- const NOTHING = "1 = 0";
703
- /** Each comparison's SQL for a quoted column; values are bound in order. */
704
- const COMPARISON_SQL = {
705
- ">": (column) => `${column} > `,
706
- ">=": (column) => `${column} >= `,
707
- "<": (column) => `${column} < `,
708
- "<=": (column) => `${column} <= `,
709
- between: (column) => `${column} BETWEEN AND `,
710
- betweenExcludingEnd: (column) => `(${column} >= AND ${column} < )`
711
- };
712
- /** `attr = value`, with NULL and arrays (IN) handled the way the contract specifies. */
713
- function compileEquality(dialect, attribute, value, params) {
714
- const column = quoteIdentifier(attribute.column);
715
- if (value === null) return `${column} IS NULL`;
716
- if (!Array.isArray(value)) {
717
- const stored = attribute.conditionCell(value);
718
- if (stored === noMatch) return NOTHING;
719
- attribute.bindCells(params, stored);
720
- return `${column} = `;
721
- }
722
- const present = value.filter((item) => item !== null).map((item) => attribute.conditionCell(item)).filter((item) => item !== noMatch);
723
- const parts = [];
724
- if (present.length > 0) {
725
- const list = dialect.inList(column, present);
726
- attribute.bindCells(params, list.value);
727
- parts.push(list.sql);
728
- }
729
- if (value.includes(null)) parts.push(`${column} IS NULL`);
730
- return parts.length > 0 ? `(${parts.join(" OR ")})` : NOTHING;
731
- }
732
- function compileOrder({ model, order }, params) {
733
- if (order.length === 0) return "";
734
- return ` ORDER BY ${order.map((term) => {
735
- if (term instanceof SafeSql) return compileFragment(term, model, params);
736
- const { attribute, direction, nulls } = term;
737
- return `${quoteIdentifier(attributeFor(model, attribute).column)} ${direction.toUpperCase()}${nulls ? ` NULLS ${nulls.toUpperCase()}` : ""}`;
738
- }).join(", ")}`;
739
- }
740
- function compilePagination(dialect, { limit, offset }, params) {
741
- if (limit === void 0 && offset === void 0) return "";
742
- return dialect.pagination(limit, offset, params);
743
- }
744
- /** Appends the fragment's values to `params` and returns its SQL text. */
745
- function compileFragment(fragment, model, params) {
746
- let text = fragment.strings[0] ?? "";
747
- fragment.values.forEach((value, index) => {
748
- if (value instanceof ColumnReference) text += quoteIdentifier(attributeFor(model, value.attribute).column);
749
- else if (value instanceof ColumnValue) {
750
- attributeFor(model, value.attribute).bind(params, value.assigned);
751
- text += "\0";
752
- } else {
753
- params.push(writeUntypedValue(value));
754
- text += "\0";
755
- }
756
- text += fragment.strings[index + 1] ?? "";
757
- });
758
- return text;
759
- }
760
- //#endregion
761
- //#region src/permit.ts
762
- /**
763
- * The named attributes of untrusted `input`, as Rails' `params.permit`: every other key is
764
- * dropped, so it never reaches a record (#82). Each value is cast as assigning it would be
765
- * (#81), so the result is what its type says even before it's assigned.
766
- */
767
- function permitted(model, input, names) {
768
- for (const name of names) attributeOf(model, name);
769
- const given = givenValues(model, input);
770
- return Object.fromEntries(names.filter((name) => given.has(name)).map((name) => [name, castPermitted(model, name, given.get(name))]));
771
- }
772
- /** A permitted value, cast; a file (from a form) is refused, since no attribute stores one. */
773
- function castPermitted(model, name, value) {
774
- if (value instanceof Blob) throw new TypeError(`${model.name}: "${name}" is a file, and no attribute stores one`);
775
- return attributeFor(model, name).cast(value);
776
- }
777
- /**
778
- * Each key of `input` and its value: a plain object's own keys, so `__proto__` never counts,
779
- * or a form's or query string's, where a repeated key takes its last value.
780
- */
781
- function givenValues(model, input) {
782
- if (input instanceof FormData || input instanceof URLSearchParams) return new Map(input);
783
- if (!isPlainObject(input)) throw new TypeError(`${model.name}.permit() takes an object, FormData or URLSearchParams`);
784
- return new Map(Object.entries(input));
785
- }
786
- /** An object literal or parsed JSON: not an array, a `Map`, a `Date` or a class's instance. */
787
- function isPlainObject(input) {
788
- if (typeof input !== "object" || input === null) return false;
789
- const prototype = Object.getPrototypeOf(input);
790
- return prototype === Object.prototype || prototype === null;
791
- }
792
- //#endregion
793
- //#region src/attribute-conversions.ts
794
- /** The conversions of `model`'s `attribute`; `UnknownAttribute` if it has none by that name. */
795
- function conversionsFor(model, attribute) {
796
- const resolved = attributeFor(model, attribute);
797
- return Object.freeze({
798
- cast: (input) => resolved.cast(input),
799
- serialize: (input) => resolved.store(input),
800
- deserialize: (stored) => resolved.read(stored)
801
- });
802
- }
803
- //#endregion
804
- //#region src/record-statement.ts
805
- /** @internal The library's key for what `db.batch` needs from a RecordStatement. */
806
- const recordStatementParts = Symbol("recordStatementParts");
807
- /**
808
- * A record's save or destroy for `db.batch([...])`: `user.toSave()`,
809
- * `post.toDestroy()`. Unlike a Statement, nothing is compiled yet: the record's
810
- * validations and callbacks run when the batch runs. It has no `then`, so it's never run by
811
- * being awaited.
812
- */
813
- var RecordStatement = class {
814
- #record;
815
- #kind;
816
- /** @internal Use `record.toSave()` or `record.toDestroy()`. */
817
- constructor(record, kind) {
818
- this.#record = record;
819
- this.#kind = kind;
820
- }
821
- /**
822
- * @internal Hidden from the types so calling it doesn't compile. A Statement has `toSql()`;
823
- * this tells whoever calls it anyway, such as from JavaScript, why a record statement has none.
824
- */
825
- toSql() {
826
- throw new TypeError("toSql() isn't available on a record's toSave() or toDestroy(): its SQL depends on validations and callbacks that only run inside db.batch");
827
- }
828
- /** @internal What `db.batch` needs: the record, and whether it's saved or destroyed. */
829
- get [recordStatementParts]() {
830
- return {
831
- record: this.#record,
832
- kind: this.#kind
833
- };
834
- }
835
- };
836
- //#endregion
837
- //#region src/record-inspect.ts
838
- /** An unsaved change: the new value, and the one the record was loaded or saved with, if any. */
839
- var Unsaved = class {
840
- #value;
841
- #previous;
842
- constructor(value, previous) {
843
- this.#value = value;
844
- this.#previous = previous;
845
- }
846
- [inspectCustom](_depth, options, inspect) {
847
- const now = inspect(this.#value, options);
848
- return this.#previous === void 0 ? `${now} (changed)` : `${now} (was ${inspect(this.#previous, options)})`;
849
- }
850
- };
851
- /** One attribute as it prints: filtered values marked, unsaved changes flagged. */
852
- function printedValue(model, name, value, changes) {
853
- const change = changes[name];
854
- if (isFiltered(model, name) && (value !== null || change)) return new FilteredMark(!!change);
855
- return change ? new Unsaved(value, change[0]) : value;
856
- }
857
- /** `Name { attribute: value, … }`, its values printed by the runtime's own `inspect`. */
858
- function inspectRecord(model, record, args) {
859
- const changes = record.isPersisted ? record.changesSinceLoad() : {};
860
- const body = () => Object.fromEntries(Object.entries(record.attributes()).map(([name, value]) => [name, printedValue(model, name, value, changes)]));
861
- return printed(model.name, model.name, body, args);
862
- }
863
- //#endregion
864
- //#region src/association-writers.ts
865
- /**
866
- * A belongsTo's accessor for `owner`: `await post.author()`, plus `set`, `build`, `create` and
867
- * `createOrThrow`, as Rails' `post.author =`, `build_author` and `create_author`.
868
- */
869
- function belongsToAccessor(owner, association) {
870
- const read = () => cachedRead(owner, association, (key) => association.all(owner[state].executor).findBy({ [association.targetAttribute]: key }));
871
- const set = (record) => pointOwnerAt(owner, association, record);
872
- const make = (attributes) => buildRecord(association.target, attributes, owner[state].executor);
873
- const create = (save) => async (attributes = {}) => {
874
- const record = make(attributes);
875
- await save(record);
876
- set(record);
877
- return record;
878
- };
879
- return Object.assign(read, {
880
- set,
881
- build(attributes = {}) {
882
- const record = make(attributes);
883
- set(record);
884
- return record;
885
- },
886
- create: create((record) => record.save()),
887
- createOrThrow: create((record) => record.saveOrThrow())
888
- });
889
- }
890
- /**
891
- * Points `owner` at `record` (or at nothing): its foreign key takes the record's key, and the
892
- * record becomes the loaded association. A new record is saved first when the owner is
893
- * (autosave), and the key filled in then if D1 generates it.
894
- */
895
- function pointOwnerAt(owner, association, record) {
896
- const { name, target, ownerAttribute, targetAttribute } = association;
897
- if (record !== null && !(record instanceof target)) throw new TypeError(`${association.label}.set() takes a ${target.name} record or null`);
898
- const key = record === null ? null : record[state].read(targetAttribute);
899
- owner[state].pointAt(name, ownerAttribute, key, record);
900
- owner[state].autosaves.setBelongsTo(name, record !== null && record[state].isNew ? record : void 0);
901
- }
902
- /**
903
- * A hasOne's accessor for `owner`: `await user.profile()`, plus `build`, `create` and
904
- * `createOrThrow`, as Rails' `build_profile` and `create_profile`. An existing record is left
905
- * as it is (Rails' replacement rules are #40).
906
- */
907
- function hasOneAccessor(owner, association) {
908
- const read = () => cachedRead(owner, association, (key) => association.inOrder(association.linkedTo(owner[state].executor, key)).first());
909
- return Object.assign(read, {
910
- build(attributes = {}) {
911
- const record = buildOne(owner, association, attributes);
912
- owner[state].autosaves.addBuilt(association.name, record);
913
- return record;
914
- },
915
- create: createOne(owner, association, (record) => record.save()),
916
- createOrThrow: createOne(owner, association, (record) => record.saveOrThrow())
917
- });
918
- }
919
- /**
920
- * A hasOne's `create` or `createOrThrow` (by `save`): needs a saved owner, as in Rails. A
921
- * record that doesn't save is kept as built, so saving the owner tries again, as Rails does.
922
- */
923
- function createOne(owner, association, save) {
924
- return async (attributes = {}) => {
925
- requireSavedOwner(owner, association);
926
- const record = buildOne(owner, association, attributes);
927
- try {
928
- await save(record);
929
- } finally {
930
- if (record[state].isNew) owner[state].autosaves.addBuilt(association.name, record);
931
- }
932
- return record;
933
- };
934
- }
935
- /** As in Rails, records can't be created through an owner that hasn't been saved. */
936
- function requireSavedOwner(owner, association) {
937
- if (!owner[state].isNew) return;
938
- throw new RecordNotSaved(`You cannot create a ${association.target.name} here: ${association.refusalFor(owner)}`);
939
- }
940
- /** A new record of a hasOne, pointing at its owner and loaded as the association. */
941
- function buildOne(owner, association, attributes) {
942
- const { name, target, ownerAttribute, definition } = association;
943
- const key = owner[state].read(ownerAttribute);
944
- const { [definition.foreignKey]: _given, ...rest } = attributes;
945
- const record = buildRecord(target, rest, owner[state].executor);
946
- record[state].writeKey(definition.foreignKey, key, name);
947
- owner[state].associations.set(name, ownerAttribute, record);
948
- return record;
949
- }
950
- //#endregion
951
- //#region src/validations.ts
952
- function isBlank(value) {
953
- return value === null || typeof value === "string" && value.trim() === "";
954
- }
955
- const presence = (value, { presence: required }) => required && isBlank(value) ? [{ type: "blank" }] : [];
956
- const length = (value, { length: rule }) => {
957
- if (rule === void 0) return [];
958
- const size = typeof value === "string" || Array.isArray(value) ? value.length : 0;
959
- const failures = [];
960
- if (rule.is !== void 0 && size !== rule.is) failures.push({
961
- type: "wrongLength",
962
- values: { count: rule.is }
963
- });
964
- if (rule.minimum !== void 0 && size < rule.minimum) failures.push({
965
- type: "tooShort",
966
- values: { count: rule.minimum }
967
- });
968
- if (rule.maximum !== void 0 && size > rule.maximum) failures.push({
969
- type: "tooLong",
970
- values: { count: rule.maximum }
971
- });
972
- return failures;
973
- };
974
- const format = (value, { format: rule }) => {
975
- if (rule === void 0) return [];
976
- const pattern = rule instanceof RegExp ? rule : rule.with;
977
- return typeof value === "string" && value.search(pattern) !== -1 ? [] : [{ type: "invalid" }];
978
- };
979
- /** Equality for inclusion: dates match by their time, everything else by identity. */
980
- function sameValue(a, b) {
981
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
982
- return Object.is(a, b);
983
- }
984
- const inclusion = (value, { inclusion: rule }) => {
985
- if (rule === void 0) return [];
986
- return (Array.isArray(rule) ? rule : rule.in).some((item) => sameValue(item, value)) ? [] : [{ type: "inclusion" }];
987
- };
988
- const COMPARISONS = [
989
- ["greaterThan", (a, b) => a > b],
990
- ["greaterThanOrEqualTo", (a, b) => a >= b],
991
- ["lessThan", (a, b) => a < b],
992
- ["lessThanOrEqualTo", (a, b) => a <= b]
993
- ];
994
- /** Only real numbers pass; a numeric string like "12" is not a number (convert input first). */
995
- const numericality = (value, { numericality: rule }) => {
996
- if (rule === void 0 || rule === false) return [];
997
- if (typeof value !== "number" || Number.isNaN(value)) return [{ type: "notANumber" }];
998
- const options = rule === true ? {} : rule;
999
- if (options.onlyInteger && !Number.isInteger(value)) return [{ type: "notAnInteger" }];
1000
- return COMPARISONS.flatMap(([type, holds]) => {
1001
- const bound = options[type];
1002
- return bound === void 0 || holds(value, bound) ? [] : [{
1003
- type,
1004
- values: { count: bound }
1005
- }];
1006
- });
1007
- };
1008
- /** Applied in this order within one `validates` call. */
1009
- const CHECKS = [
1010
- presence,
1011
- length,
1012
- format,
1013
- inclusion,
1014
- numericality
1015
- ];
1016
- async function uniquenessFailures(target, attribute, value, { uniqueness: rule }) {
1017
- if (rule === void 0 || rule === false || value === null) return [];
1018
- return await target.isTaken(attribute, value, rule === true ? {} : rule) ? [{ type: "taken" }] : [];
1019
- }
1020
- /** Runs every validation in declaration order, adding failures to `errors`. */
1021
- async function runValidations(validations, target) {
1022
- for (const { attribute, options } of validations) {
1023
- if (options.if && !options.if(target.record)) continue;
1024
- const value = target.read(attribute);
1025
- if (options.allowNull && value === null) continue;
1026
- const failures = [...CHECKS.flatMap((check) => check(value, options)), ...await uniquenessFailures(target, attribute, value, options)];
1027
- for (const failure of failures) target.errors[addFailure](attribute, {
1028
- ...failure,
1029
- message: options.message
1030
- });
1031
- }
1032
- }
1033
- /** The attributes a validation names (its own, and a uniqueness `scope`'s) must be the Model's. */
1034
- function checkValidatedNames(model, { attribute, options }) {
1035
- attributeOf(model, attribute);
1036
- const { uniqueness } = options;
1037
- if (typeof uniqueness === "object") for (const name of uniqueness.scope ?? []) attributeOf(model, name);
1038
- }
1039
- //#endregion
1040
- //#region src/verify-model.ts
1041
- const verified = /* @__PURE__ */ new WeakSet();
1042
- /** Checks a Model's declaration the first time it's used; throws `InvalidModel`. */
1043
- function verifyModel(model) {
1044
- if (verified.has(model)) return;
1045
- settleGenerated(model);
1046
- if (!isGenerated(model)) rejectAbstract(model);
1047
- requireTableName(model);
1048
- requirePrimaryKeyAttribute(model);
1049
- rejectReservedAttributeNames(model);
1050
- rejectBadSpecs(model);
1051
- for (const validation of declared(model, "validations")) checkValidatedNames(model, validation);
1052
- rejectUnknownHiddenAttributes(model);
1053
- rejectUnknownMessageNames(model);
1054
- rejectShadowingFields(model);
1055
- rejectBadPageSizes(model);
1056
- for (const each of ancestors(model)) {
1057
- if (each === Model) break;
1058
- seal(each);
1059
- }
1060
- verified.add(model);
1061
- }
1062
- function requirePrimaryKeyAttribute(model) {
1063
- if (!model.attributeDefinitions.has(model.primaryKey)) throw new InvalidModel(`${model.name}'s primaryKey "${model.primaryKey}" isn't a declared attribute; declare it in Model.define({...}) or set \`static primaryKey\``);
1064
- }
1065
- function rejectReservedAttributeNames(model) {
1066
- for (const name of model.attributeDefinitions.keys()) if (name in Model.prototype) throw new InvalidModel(`${model.name} declares an attribute "${name}", which is the name of a record method or property; rename the attribute and map it with { column }`);
1067
- }
1068
- /**
1069
- * A spec key its type can't have, one given with a key it conflicts with, or a storage that isn't
1070
- * an epoch unit: the rules are in `src/spec-keys.ts`.
1071
- */
1072
- function rejectBadSpecs(model) {
1073
- for (const [name, definition] of model.attributeDefinitions) {
1074
- const problem = specProblem(`${model.name}.${name}`, definition);
1075
- if (problem !== void 0) throw new InvalidModel(problem);
1076
- }
1077
- }
1078
- /** `perPage` and `maxPerPage` are page sizes: whole numbers from 1, so the cap always holds. */
1079
- function rejectBadPageSizes(model) {
1080
- for (const name of ["perPage", "maxPerPage"]) {
1081
- const size = model[name];
1082
- if (!Number.isSafeInteger(size) || size < 1) throw new InvalidModel(`${model.name}'s ${name} is ${String(size)}; set it to a whole number from 1`);
1083
- }
1084
- }
1085
- /**
1086
- * A name in `hiddenAttributes` must be an attribute, so a typo doesn't leave one in the JSON.
1087
- * Names listed by a class without attributes (the app's base class) are the exception: they
1088
- * apply to the Models that have them (#101).
1089
- */
1090
- function rejectUnknownHiddenAttributes(model) {
1091
- const inherited = namesListedByAttributelessAncestors(model);
1092
- for (const name of model.hiddenAttributes) if (!inherited.has(name) && !model.attributeDefinitions.has(name)) throw new InvalidModel(`${model.name} hides "${name}" from toJSON, but has no such attribute; hiddenAttributes names attributes exactly`);
1093
- }
1094
- /** The `hiddenAttributes` of the classes above `model` that have no attributes of their own. */
1095
- function namesListedByAttributelessAncestors(model) {
1096
- const names = /* @__PURE__ */ new Set();
1097
- for (const each of ancestors(model).slice(1)) if (Object.hasOwn(each, "hiddenAttributes") && hasNoAttributes(each)) each.hiddenAttributes?.forEach((name) => names.add(name));
1098
- return names;
1099
- }
1100
- /**
1101
- * A Model's messages and attribute names must be for its attributes, its associations or
1102
- * `"base"`, so a typo isn't left unused. Those of a class without attributes (the app's base
1103
- * class) are the exception: they apply to the Models that have them (#88).
1104
- */
1105
- function rejectUnknownMessageNames(model) {
1106
- const associations = associationsOf(model).keys();
1107
- const known = /* @__PURE__ */ new Set([
1108
- "base",
1109
- ...model.attributeDefinitions.keys(),
1110
- ...associations
1111
- ]);
1112
- for (const { from, declaration, names } of attributesNamedInMessages(model)) {
1113
- const unknown = names.find((name) => !known.has(name));
1114
- if (unknown === void 0 || hasNoAttributes(from)) continue;
1115
- const where = declaration === "errorMessages" ? "errorMessages has messages for" : "humanAttributeNames names";
1116
- throw new InvalidModel(`${from.name}'s ${where} "${unknown}", which isn't one of its attributes or associations; name them exactly`);
1117
- }
1118
- }
1119
- /** Whether a class has no attributes, as the app's base class: names it lists apply where a Model has them. */
1120
- function hasNoAttributes(model) {
1121
- return model.attributeDefinitions?.size === 0;
1122
- }
1123
- function rejectShadowingFields(model) {
1124
- const probe = probeOf(model);
1125
- for (const name of model.attributeDefinitions.keys()) if (Object.hasOwn(probe, name) && declarationIn(probe[name]) === void 0) throw new InvalidModel(`${model.name} declares a class field "${name}" that hides the attribute's accessor; remove it (attributes are declared in Model.define({...}))`);
1126
- }
1127
- //#endregion
1128
- //#region src/owned-collection.ts
1129
- /** A plain query's: no owner, so it holds nothing, refuses nothing, and a deleteAll deletes. */
1130
- const unowned = {
1131
- loaded: () => void 0,
1132
- created: () => {},
1133
- built: () => {},
1134
- invalidate: () => {},
1135
- unsavedCount: () => 0,
1136
- refusal: void 0,
1137
- nullifies: void 0,
1138
- link: void 0,
1139
- narrowed: () => unowned
1140
- };
1141
- /** `owner`'s hasMany `association`, as its Relation sees it. */
1142
- function ownedCollection(owner, association) {
1143
- const key = association.keyOf(owner);
1144
- return key === null ? withoutKey(owner, association) : withKey(owner, association, key);
1145
- }
1146
- /** An owner with a key: its loaded records live in its association cache. */
1147
- function withKey(owner, association, key) {
1148
- const { associations: loadedAssociations, autosaves } = owner[state];
1149
- const { name, ownerAttribute, definition } = association;
1150
- const built = () => autosaves.built(name);
1151
- const withBuilt = (stored) => [...stored, ...built().filter((record) => !stored.includes(record))];
1152
- const collection = {
1153
- loaded() {
1154
- const stored = loadedAssociations.get(name)?.value;
1155
- return stored === void 0 ? void 0 : withBuilt(stored);
1156
- },
1157
- startFill() {
1158
- const keep = loadedAssociations.startLoad(name, ownerAttribute, key);
1159
- return (records) => {
1160
- keep(records);
1161
- return withBuilt(records);
1162
- };
1163
- },
1164
- created(record) {
1165
- const loaded = collection.loaded();
1166
- if (loaded === void 0) {
1167
- loadedAssociations.clear(name);
1168
- return;
1169
- }
1170
- const index = indexOfRow(loaded, record, association.target.primaryKey);
1171
- loadedAssociations.set(name, ownerAttribute, index === -1 ? [...loaded, record] : loaded.map((each, at) => at === index ? record : each));
1172
- },
1173
- built: (record) => autosaves.addBuilt(name, record),
1174
- invalidate: () => loadedAssociations.clear(name),
1175
- unsavedCount: () => built().filter((record) => record[state].isNew).length,
1176
- refusal: void 0,
1177
- nullifies: association.deletesOnDeleteAll ? void 0 : definition.foreignKey,
1178
- link: {
1179
- attribute: definition.foreignKey,
1180
- association: name
1181
- },
1182
- narrowed: () => narrowedOf(collection)
1183
- };
1184
- return collection;
1185
- }
1186
- /**
1187
- * Where `records` hold `record`'s row, or -1. By primary key, not identity: a read sent after the
1188
- * record's INSERT and answered before its create finished loaded its own copy of the row (#181).
1189
- */
1190
- function indexOfRow(records, record, primaryKey) {
1191
- const key = record[state].read(primaryKey);
1192
- return records.findIndex((loaded) => Object.is(loaded[state].read(primaryKey), key));
1193
- }
1194
- /** An owner without a key: no stored records, just what was built through it. */
1195
- function withoutKey(owner, association) {
1196
- const { name, definition } = association;
1197
- const collection = {
1198
- loaded: () => [...owner[state].autosaves.built(name)],
1199
- created: () => {},
1200
- built: (record) => owner[state].autosaves.addBuilt(name, record),
1201
- invalidate: () => {},
1202
- unsavedCount: () => 0,
1203
- refusal: association.refusalFor(owner),
1204
- nullifies: definition.foreignKey,
1205
- link: {
1206
- attribute: definition.foreignKey,
1207
- association: name
1208
- },
1209
- narrowed: () => narrowedOf(collection)
1210
- };
1211
- return collection;
1212
- }
1213
- /**
1214
- * `collection`, joined with a Relation holding `other` (`or()`, `merge()`, or a scope that starts
1215
- * a new query): a statement built or a record created through it clears `other`'s owner too,
1216
- * since it can reach the same rows (#194). Nothing else of `other` carries over: records built or
1217
- * created through it join only `collection`'s owner.
1218
- */
1219
- function alsoClearing(collection, other) {
1220
- if (other === unowned || other === collection) return collection;
1221
- return {
1222
- ...collection,
1223
- created(record) {
1224
- collection.created(record);
1225
- other.invalidate();
1226
- },
1227
- invalidate() {
1228
- collection.invalidate();
1229
- other.invalidate();
1230
- },
1231
- narrowed: () => alsoClearing(collection.narrowed(), other)
1232
- };
1233
- }
1234
- /**
1235
- * A narrowed Relation's form: building, creating and bulk writes still reach the owner (a write
1236
- * through a `where` can change what the owner holds); reads query.
1237
- */
1238
- function narrowedOf(collection) {
1239
- const narrowed = {
1240
- loaded: () => void 0,
1241
- created: (record) => collection.created(record),
1242
- built: (record) => collection.built(record),
1243
- invalidate: () => collection.invalidate(),
1244
- unsavedCount: () => 0,
1245
- refusal: collection.refusal,
1246
- nullifies: void 0,
1247
- link: collection.link,
1248
- narrowed: () => narrowed
1249
- };
1250
- return narrowed;
1251
- }
1252
- //#endregion
1253
- //#region src/constraints.ts
1254
- /** Each kind's class, and a readable label, since bundlers may rename the error classes. */
1255
- const VIOLATIONS = {
1256
- unique: [RecordNotUnique, "not unique"],
1257
- notNull: [NotNullViolation, "must not be null"],
1258
- foreignKey: [InvalidForeignKey, "foreign key constraint failed"],
1259
- check: [CheckViolation, "check constraint failed"]
1260
- };
1261
- /**
1262
- * A constraint failure from a write to the tables of `models` (one statement's, or a batch's) as
1263
- * the matching `ConstraintViolation`. Any other error is returned unchanged.
1264
- */
1265
- function translateConstraintError(adapter, error, models) {
1266
- const failure = adapter.constraintFailure(error);
1267
- return failure === void 0 ? error : violation(failure, models, error);
1268
- }
1269
- /**
1270
- * The Model a failure belongs to: the one whose table the error names, or, when it names
1271
- * none, the only Model written to. Undefined when it names another table (a trigger's), or
1272
- * when a batch writes to several.
1273
- */
1274
- function failedModel(table, models) {
1275
- if (table !== void 0) return models.find((model) => model.table === table);
1276
- return new Set(models).size === 1 ? models[0] : void 0;
1277
- }
1278
- /** `table` is the one the error names, or else the failed Model's; null if neither. */
1279
- function violation({ kind, table, columns }, models, cause) {
1280
- const [Kind, label] = VIOLATIONS[kind];
1281
- const model = failedModel(table, models);
1282
- const attributes = model === void 0 ? [] : columns.flatMap((column) => attributesForColumn(model, column));
1283
- const failedTable = table ?? model?.table ?? null;
1284
- const named = columns.length > 0 ? ` (${columns.join(", ")})` : "";
1285
- return new Kind(`${model?.name ?? failedTable ?? "batch"}${named}: ${label}`, {
1286
- table: failedTable,
1287
- columns,
1288
- attributes,
1289
- cause
1290
- });
1291
- }
1292
- //#endregion
1293
- //#region src/request-store.ts
1294
- /** The storage, once `withDatabase` has been called. */
1295
- let storage;
1296
- /** Node's AsyncLocalStorage, loaded when it's first needed, so Workers without Node.js compatibility still build. */
1297
- function newStorage() {
1298
- const hooks = globalThis.process?.getBuiltinModule?.("node:async_hooks");
1299
- if (hooks === void 0) throw new NoDatabase("withDatabase needs Node.js compatibility: a compatibility_date of 2026-08-04 or later, or the nodejs_compat flag, in your Wrangler config");
1300
- return new hooks.AsyncLocalStorage();
1301
- }
1302
- /** What the current `withDatabase` keeps, if code runs inside one. */
1303
- function requestStore() {
1304
- return storage?.getStore();
1305
- }
1306
- /** Runs `fn` with `store` as the request's. */
1307
- function runWithStore(store, fn) {
1308
- storage ??= newStorage();
1309
- return storage.run(store, fn);
1310
- }
1311
- //#endregion
1312
- //#region src/executor.ts
1313
- /**
1314
- * Calls a query listener, which never changes the query's outcome: a listener that throws is
1315
- * logged, and the query's result or D1's error reaches the caller as it would have (#78).
1316
- */
1317
- function notify(listener, event) {
1318
- if (listener === void 0) return;
1319
- try {
1320
- listener(event);
1321
- } catch (error) {
1322
- console.error("onQuery threw; the query's result is unaffected:", error);
1323
- }
1324
- }
1325
- /**
1326
- * The concrete database a handle sends to now. Private to this module (#93): callers ask
1327
- * `oneDatabase` (through `jointly` and `pinBefore`) instead, so "is this the same database?" is
1328
- * decided in one place.
1329
- */
1330
- const resolve = Symbol("resolve");
1331
- /** How an error names a database by its origin. */
1332
- function nameOf(origin) {
1333
- if (origin === "connect") return "a connect() database";
1334
- if (origin === "request") return "the request's database";
1335
- return `the ${origin.binding} binding's database`;
1336
- }
1337
- /**
1338
- * One database's Executor: every statement goes to its Driver and is reported to `onQuery`, and a
1339
- * constraint failure becomes the matching `ConstraintViolation` for the statement's Model.
1340
- */
1341
- var DatabaseExecutor = class {
1342
- adapter;
1343
- #driver;
1344
- #onQuery;
1345
- #origin = "connect";
1346
- constructor(adapter, driver, onQuery) {
1347
- this.adapter = adapter;
1348
- this.#driver = driver;
1349
- this.#onQuery = onQuery;
1350
- }
1351
- get dialect() {
1352
- return this.adapter.dialect;
1353
- }
1354
- async [resolve]() {
1355
- return this;
1356
- }
1357
- /** Where this database came from; errors name it by this. */
1358
- get origin() {
1359
- return this.#origin;
1360
- }
1361
- /**
1362
- * @internal Sets where this database came from (#170): `withDatabase` makes it `"request"`, and
1363
- * a binding's own Database takes `{ binding }`. It lives on the executor because records keep
1364
- * their DatabaseExecutor and outlive `withDatabase`, so a per-request lookup couldn't find it later.
1365
- * Sticky: a Database given to `withDatabase` is "the request's database" for its life, including
1366
- * when it's used explicitly outside `withDatabase`.
1367
- */
1368
- setOrigin(origin) {
1369
- this.#origin = origin;
1370
- }
1371
- /** @internal A `withDatabase` scope with this database has begun: what its driver holds for it. */
1372
- openScope() {
1373
- return this.#driver.openScope?.();
1374
- }
1375
- /** @internal The scope `openScope` began has ended. */
1376
- async closeScope(scope) {
1377
- await this.#driver.closeScope?.(scope);
1378
- }
1379
- /** What the driver opened for the `withDatabase` scope a statement is sent in, if any. */
1380
- #scope() {
1381
- return requestStore()?.scopes.get(this)?.held;
1382
- }
1383
- /** Runs one statement and resolves to its rows. */
1384
- async all(query) {
1385
- return (await this.#one(this.#sendable(query))).rows;
1386
- }
1387
- /** Runs one statement for its effect and resolves to its result. */
1388
- async run(query) {
1389
- return this.#one(this.#sendable(query));
1390
- }
1391
- /** Runs reads together and resolves to each one's result. */
1392
- async read(statements) {
1393
- const sent = statements.map((statement) => this.#sendable(statement));
1394
- return this.#together(sent, () => this.#driver.read(sent, this.#scope()));
1395
- }
1396
- /** `query` as it's sent and reported: with its database's placeholders. */
1397
- #sendable(query) {
1398
- return withPlaceholders(this.dialect, query);
1399
- }
1400
- /** `statements`, sent by `send`, unless there are none. On failure every one is reported. */
1401
- async #together(statements, send, mayRetry = true) {
1402
- if (statements.length === 0) return [];
1403
- const started = performance.now();
1404
- let results;
1405
- try {
1406
- results = await send();
1407
- } catch (error) {
1408
- const durationMs = performance.now() - started;
1409
- for (const statement of statements) this.#report(statement, {
1410
- durationMs,
1411
- error
1412
- });
1413
- if (mayRetry && this.#driver.recover(error)) return this.#together(statements, send, false);
1414
- throw this.#explained(error, statements.map(({ model }) => model));
1415
- }
1416
- const elapsed = performance.now() - started;
1417
- statements.forEach((statement, index) => {
1418
- const { durationMs = elapsed, meta } = results[index];
1419
- this.#report(statement, {
1420
- durationMs,
1421
- meta
1422
- });
1423
- });
1424
- return results;
1425
- }
1426
- /** Runs statements atomically: one on its own, several all or none. Resolves to each result. */
1427
- async write(statements) {
1428
- const sent = statements.map((statement) => this.#sendable(statement));
1429
- const [only] = sent;
1430
- if (sent.length === 1 && only !== void 0) return [await this.#one(only)];
1431
- return this.#together(sent, () => this.#driver.write(sent, this.#scope()));
1432
- }
1433
- async #one(query, mayRetry = true) {
1434
- const started = performance.now();
1435
- let result;
1436
- try {
1437
- result = await this.#driver.send(query, this.#scope());
1438
- } catch (error) {
1439
- this.#report(query, {
1440
- durationMs: performance.now() - started,
1441
- error
1442
- });
1443
- if (mayRetry && this.#driver.recover(error)) return this.#one(query, false);
1444
- throw this.#explained(error, [query.model]);
1445
- }
1446
- this.#report(query, {
1447
- durationMs: performance.now() - started,
1448
- meta: result.meta
1449
- });
1450
- return result;
1451
- }
1452
- /** What to throw for `error` from a statement on `models`' tables. */
1453
- #explained(error, models) {
1454
- const { adapter } = this;
1455
- return adapter.refusal(error) ?? explainMissingTable(adapter, translateConstraintError(adapter, error, models), models);
1456
- }
1457
- /** Reports a statement to the database's listener, then to its Model's (`static onQuery`). */
1458
- #report({ sql, params, model }, outcome) {
1459
- const event = {
1460
- model: model.name,
1461
- sql,
1462
- params: params.map(shownValue),
1463
- ...outcome
1464
- };
1465
- notify(this.#onQuery, event);
1466
- notify(model.onQuery, event);
1467
- }
1468
- };
1469
- /** An Executor that finds its DatabaseExecutor when a statement runs, and sends the statement there. */
1470
- var ForwardingExecutor = class {
1471
- get dialect() {
1472
- return this.adapter.dialect;
1473
- }
1474
- async all(query) {
1475
- return (await this[resolve]()).all(query);
1476
- }
1477
- async run(query) {
1478
- return (await this[resolve]()).run(query);
1479
- }
1480
- async read(statements) {
1481
- return (await this[resolve]()).read(statements);
1482
- }
1483
- async write(statements) {
1484
- return (await this[resolve]()).write(statements);
1485
- }
1486
- };
1487
- /**
1488
- * The current database's Executor (#77): finds the DatabaseExecutor to use each time a statement runs,
1489
- * the request's or the binding's, so a Relation built from a Model's statics can be built anywhere.
1490
- */
1491
- var CurrentExecutor = class extends ForwardingExecutor {
1492
- #adapter;
1493
- #find;
1494
- constructor(adapter, find) {
1495
- super();
1496
- this.#adapter = adapter;
1497
- this.#find = find;
1498
- }
1499
- get adapter() {
1500
- return this.#adapter();
1501
- }
1502
- [resolve]() {
1503
- return this.#find();
1504
- }
1505
- };
1506
- /** The DatabaseExecutor `handle` sends to now. */
1507
- function databaseNow(handle) {
1508
- return handle[resolve]();
1509
- }
1510
- /**
1511
- * The one database these handles resolve to now: their DatabaseExecutor. Two databases throw
1512
- * `IncompatibleRelation` (#93): "`needs` on one database", naming where each came from. Every
1513
- * check of "the same database" (merge, or, scopes, batches, saves) and every pin goes here.
1514
- */
1515
- async function oneDatabase(handles, needs) {
1516
- const [first, second] = [...new Set(await Promise.all(handles.map((handle) => handle[resolve]())))];
1517
- if (second !== void 0) {
1518
- const [one, two] = [nameOf(first.origin), nameOf(second.origin)];
1519
- throw new IncompatibleRelation(`${needs} on one database; these are on ${one} and ${one === two ? "another" : two}`);
1520
- }
1521
- return first;
1522
- }
1523
- /**
1524
- * The one database `links` (and `handles`, a batch's statements) share, each record pinned to
1525
- * it before anything runs (#93): two databases throw `IncompatibleRelation`, with no validation,
1526
- * callback or write run. A record keeps the database it was first written on.
1527
- */
1528
- async function pinBefore(links, needs, handles = []) {
1529
- const database = await oneDatabase([...handles, ...links.map((link) => link.executor)], needs);
1530
- for (const link of links) link.belongTo(database);
1531
- return database;
1532
- }
1533
- /**
1534
- * The records a write prepared, pinned to its database too: any a callback added on the way,
1535
- * from another database, still throws `IncompatibleRelation` before anything is written.
1536
- */
1537
- async function pinClaimed(links, database, needs) {
1538
- await pinBefore(links, needs, [database]);
1539
- }
1540
- /**
1541
- * Handles combined into one (`merge`, `or`, a scope's result): checked when a statement runs, since
1542
- * a level-1 binding can only be found then. The same handle twice is just that handle.
1543
- */
1544
- function jointly(a, b, needs) {
1545
- return a === b ? a : new JointExecutor([a, b], needs);
1546
- }
1547
- /** Several handles that must be one database, found each time a statement runs. */
1548
- var JointExecutor = class extends ForwardingExecutor {
1549
- #handles;
1550
- #needs;
1551
- constructor(handles, needs) {
1552
- super();
1553
- this.#handles = handles;
1554
- this.#needs = needs;
1555
- }
1556
- get adapter() {
1557
- return this.#handles[0].adapter;
1558
- }
1559
- [resolve]() {
1560
- return oneDatabase(this.#handles, this.#needs);
1561
- }
1562
- };
1563
- //#endregion
1564
- //#region src/finder-order.ts
1565
- /** The same term sorting the other way; NULLs move to the other end too, as in Rails. */
1566
- function reversed(term) {
1567
- if (term instanceof SafeSql) throw new IrreversibleOrder("last() can't reverse an order given as an sql fragment; order by attributes, or reverse the fragment yourself and use first()");
1568
- const direction = term.direction === "asc" ? "desc" : "asc";
1569
- const nulls = term.nulls && (term.nulls === "first" ? "last" : "first");
1570
- return {
1571
- ...term,
1572
- direction,
1573
- ...nulls && { nulls }
1574
- };
1575
- }
1576
- /** One record from the page: `limit(0)` stays empty, and `offset` is kept by the caller. */
1577
- function atMostOne(limit) {
1578
- return Math.min(limit ?? 1, 1);
1579
- }
1580
- /**
1581
- * `query`'s order, ended with what makes a row unique, so tied rows keep their pages between
1582
- * requests: the primary key, or after `distinct()`, the selected attributes (the key isn't
1583
- * loaded). Those already in the order aren't added again.
1584
- */
1585
- function stableOrder(model, query) {
1586
- const unique = query.distinct && query.select ? query.select : [model.primaryKey];
1587
- const ordered = new Set(query.order.map((term) => !(term instanceof SafeSql) && term.attribute));
1588
- const ties = unique.filter((attribute) => !ordered.has(attribute)).map((attribute) => ({
1589
- attribute,
1590
- direction: "asc"
1591
- }));
1592
- return [...query.order, ...ties];
1593
- }
1594
- //#endregion
1595
- //#region src/load.ts
1596
- /** How `query`, a Relation's, runs: on `executor`, unless it's a `none()` query. */
1597
- function runnerFor(executor, model, query) {
1598
- if (query.none) return nothing;
1599
- return {
1600
- load: (description) => loadRecords(executor, model, description),
1601
- loadCounted: (description, counted) => loadCounted(executor, model, description, counted),
1602
- loadAhead: (description) => loadAhead(executor, model, description),
1603
- rows: (sql) => executor.all(sql()),
1604
- changes: async (write) => (await write()).rowsAffected
1605
- };
1606
- }
1607
- /** A `none()` query's runner: nothing is sent, so nothing is found or changed. */
1608
- const nothing = {
1609
- load: async () => [],
1610
- loadCounted: async () => ({
1611
- records: [],
1612
- count: 0
1613
- }),
1614
- loadAhead: async () => ({
1615
- records: [],
1616
- hasMore: false
1617
- }),
1618
- rows: async () => [],
1619
- changes: async () => 0
1620
- };
1621
- /** One SELECT for `query`'s records, hydrated, with its includes preloaded. */
1622
- async function loadRecords(executor, model, query) {
1623
- const own = (loaded) => [selectFor(executor.dialect, model, loaded)];
1624
- return (await loadWith(executor, model, {
1625
- query,
1626
- own,
1627
- rowsOf: ([rows]) => rows
1628
- })).records;
1629
- }
1630
- /** The count of `counted` and the SELECT for `query`'s records as one batch: one round trip. */
1631
- async function loadCounted(executor, model, query, counted) {
1632
- const { dialect } = executor;
1633
- const countSql = compileCount(dialect, counted);
1634
- const own = (loaded) => [countSql, selectFor(dialect, model, loaded)];
1635
- const loaded = await loadWith(executor, model, {
1636
- query,
1637
- own,
1638
- rowsOf: ([, rows]) => rows
1639
- });
1640
- const [countRows] = loaded.results;
1641
- return {
1642
- records: loaded.records,
1643
- count: Number(countRows?.[0]?.["count"] ?? 0)
1644
- };
1645
- }
1646
- /** One SELECT for `query`'s records and one past its limit, which is read but not loaded. */
1647
- async function loadAhead(executor, model, query) {
1648
- const own = (loaded) => [selectFor(executor.dialect, model, {
1649
- ...loaded,
1650
- limit: query.limit + 1
1651
- })];
1652
- const rowsOf = ([rows]) => rows?.slice(0, query.limit);
1653
- const { records, results } = await loadWith(executor, model, {
1654
- query,
1655
- own,
1656
- rowsOf
1657
- });
1658
- return {
1659
- records,
1660
- hasMore: (results[0]?.length ?? 0) > query.limit
1661
- };
1662
- }
1663
- /**
1664
- * Sends a load's own statements and those preloading its query's includes together, in one
1665
- * round trip, then makes its records and attaches the preloads. Resolves to the records and
1666
- * the own statements' rows.
1667
- */
1668
- async function loadWith(executor, model, load) {
1669
- const query = withPreloadOrder(model, load.query);
1670
- const own = load.own(query);
1671
- const plan = query.includes === void 0 ? void 0 : planPreload(query, executor);
1672
- const results = await sendTogether(executor, [...own, ...plan?.statements ?? []]);
1673
- const database = await databaseNow(executor);
1674
- const records = (load.rowsOf(results) ?? []).map((row) => hydrate(model, row, database));
1675
- await plan?.attach([records], results.slice(own.length), database);
1676
- return {
1677
- records,
1678
- results: results.slice(0, own.length)
1679
- };
1680
- }
1681
- /**
1682
- * `query`, with its order ended by the primary key if it has includes and a limit or offset.
1683
- * Its preloads select its keys with a subquery of it, so a total order makes them find the
1684
- * records it loads: a limit could otherwise pick tied rows, or rows in no order, differently.
1685
- */
1686
- function withPreloadOrder(model, query) {
1687
- if (query.includes === void 0) return query;
1688
- if (query.limit === void 0 && query.offset === void 0) return query;
1689
- return {
1690
- ...query,
1691
- order: stableOrder(model, query)
1692
- };
1693
- }
1694
- /** The rows of each of `queries`, sent in one round trip. */
1695
- async function sendTogether(executor, queries) {
1696
- const [only] = queries;
1697
- if (queries.length === 1 && only !== void 0) return [await executor.all(only)];
1698
- return (await executor.read(queries)).map((result) => result.rows);
1699
- }
1700
- /** The SELECT for `query`'s records. */
1701
- function selectFor(dialect, model, query) {
1702
- return compileSelect(dialect, query, compileColumns(model, query.select && !query.distinct ? [.../* @__PURE__ */ new Set([
1703
- model.primaryKey,
1704
- ...keysForIncludes(model, query.includes),
1705
- ...query.select
1706
- ])] : query.select));
1707
- }
1708
- /**
1709
- * The SELECT `toSql()` shows for `query`. A `none()` query is never sent, so it shows what
1710
- * matching nothing would be: its conditions and `1 = 0`.
1711
- */
1712
- function selectForToSql(dialect, model, query) {
1713
- const never = sql`1 = 0`;
1714
- return withPlaceholders(dialect, selectFor(dialect, model, query.none ? {
1715
- ...query,
1716
- conditions: [...query.conditions, never]
1717
- } : query));
1718
- }
1719
- /**
1720
- * The primary keys `find(...)` looks up: each cast to the key's type as a condition is, then
1721
- * each once, as Rails does. One that can't be cast stays as given, matches nothing, and is
1722
- * reported missing.
1723
- */
1724
- function keysToFind(model, ids) {
1725
- const key = attributeFor(model, model.primaryKey);
1726
- const keys = ids.map((id) => {
1727
- const cast = key.condition(id);
1728
- return cast === noMatch ? id : cast;
1729
- });
1730
- return [...new Set(keys)];
1731
- }
1732
- /** Found `records` in the order of their primary keys in `keys`. */
1733
- function inKeyOrder(records, keys) {
1734
- const byKey = new Map(records.map((record) => [primaryKeyOf(record), record]));
1735
- return keys.map((key) => byKey.get(key));
1736
- }
1737
- //#endregion
1738
- //#region src/scoped-relation.ts
1739
- const relationClasses = /* @__PURE__ */ new WeakMap();
1740
- /** Each scope static, to its body: what `Product.newest()` and `relation.newest()` run. */
1741
- const scopeBodies = /* @__PURE__ */ new WeakMap();
1742
- /** The library's base class: where a Model's scopes stop, and whose statics no scope may take. */
1743
- let base;
1744
- /** Makes a Model ready on first use (verified, its accessors installed, its declarations sealed). */
1745
- let ready;
1746
- /** @internal Called once by model.ts, after Model and its statics are defined. */
1747
- function useModelBase(root, readyModel) {
1748
- base = {
1749
- root,
1750
- statics: new Set(Object.getOwnPropertyNames(root))
1751
- };
1752
- ready = readyModel;
1753
- }
1754
- /** What model.ts handed over; missing means a load order bug, not a user's. */
1755
- function setUp() {
1756
- if (base === void 0 || ready === void 0) throw new Error("d1-record: model.ts must load before a Model is used");
1757
- return {
1758
- ...base,
1759
- ready
1760
- };
1761
- }
1762
- /** A Model's scopes, by name: its statics made with `this.scope(…)`, the nearest class's first. */
1763
- function scopesOf(model) {
1764
- const scopes = /* @__PURE__ */ new Map();
1765
- for (const each of ancestors(model)) {
1766
- if (each === setUp().root) break;
1767
- for (const name of Object.getOwnPropertyNames(each)) {
1768
- const value = each[name];
1769
- if (typeof value === "function" && scopeBodies.has(value) && !scopes.has(name)) scopes.set(name, value);
1770
- }
1771
- }
1772
- return scopes;
1773
- }
1774
- /** The name `model` (or a class it extends) gives the scope static `scoped`, once it's been used. */
1775
- function scopeName(model, scoped) {
1776
- const name = relationClasses.get(model)?.names.get(scoped);
1777
- if (name === void 0) throw new InvalidModel(`${model.name} has a scope that isn't one of its statics`);
1778
- return name;
1779
- }
1780
- /** Rejects a scope named like a Relation method or a Model static, or "then". */
1781
- function requireScopeName(model, name) {
1782
- if (name === "then" || name in Relation.prototype || setUp().statics.has(name)) throw new InvalidModel(`${model.name} declares a scope "${name}", which is the name of a Relation method or a Model static; rename the scope`);
1783
- }
1784
- function relationClassFor(model) {
1785
- const scopes = scopesOf(model);
1786
- const signature = [...scopes.values()];
1787
- const cached = relationClasses.get(model);
1788
- if (cached !== void 0) {
1789
- if (!(cached.scopes.length === signature.length && cached.scopes.every((scope, index) => scope === signature[index]))) throw new InvalidModel(`${model.name}'s scopes changed after its first use; declare them once, in the class body (static name = this.scope(…))`);
1790
- return cached.Class;
1791
- }
1792
- const ScopedRelation = class extends Relation {
1793
- constructor(parts) {
1794
- super(parts);
1795
- }
1796
- };
1797
- for (const [name, scoped] of scopes) {
1798
- requireScopeName(model, name);
1799
- const body = scopeBodies.get(scoped);
1800
- Object.defineProperty(ScopedRelation.prototype, name, { value(...args) {
1801
- return this[applyScope](name, body, args);
1802
- } });
1803
- }
1804
- const names = new Map([...scopes].map(([name, scoped]) => [scoped, name]));
1805
- relationClasses.set(model, {
1806
- Class: ScopedRelation,
1807
- scopes: signature,
1808
- names
1809
- });
1810
- return ScopedRelation;
1811
- }
1812
- /** A fresh Relation over all of `model`'s records, with the Model's scopes as methods. */
1813
- function relationFor(executor, model) {
1814
- setUp().ready(model);
1815
- return new (relationClassFor(model))({
1816
- executor,
1817
- model
1818
- });
1819
- }
1820
- //#endregion
1821
- //#region src/resolved-association.ts
1822
- /**
1823
- * How an association links records: the owner's `ownerAttribute` equals the target's
1824
- * `targetAttribute`. For belongsTo that's owner.foreignKey = target.primaryKey; for
1825
- * hasMany/hasOne it's owner.primaryKey = target.foreignKey. The one place this is decided.
1826
- */
1827
- function linkOf(definition, owner, target) {
1828
- return definition.kind === "belongsTo" ? {
1829
- ownerAttribute: definition.foreignKey,
1830
- targetAttribute: definition.primaryKey ?? target.primaryKey
1831
- } : {
1832
- ownerAttribute: definition.primaryKey ?? owner.primaryKey,
1833
- targetAttribute: definition.foreignKey
1834
- };
1835
- }
1836
- /**
1837
- * One declared association of one Model, worked out once: its target Model (made ready for
1838
- * use), the attributes that link the two, and the queries for its records, with its scope and
1839
- * order. Everything that reads, preloads, writes or destroys through an association asks this,
1840
- * so they agree on how records are linked and ordered.
1841
- */
1842
- var ResolvedAssociation = class {
1843
- owner;
1844
- name;
1845
- definition;
1846
- target;
1847
- /** The owner's attribute holding the link (a foreign key for belongsTo, a key otherwise). */
1848
- ownerAttribute;
1849
- /** The target's attribute the owner's links to. */
1850
- targetAttribute;
1851
- constructor(owner, name) {
1852
- this.owner = owner;
1853
- this.name = name;
1854
- this.definition = associationOf(owner, name);
1855
- this.target = this.definition.target();
1856
- readyModel(this.target);
1857
- ({ownerAttribute: this.ownerAttribute, targetAttribute: this.targetAttribute} = linkOf(this.definition, owner, this.target));
1858
- }
1859
- /** `User.posts`: how the association is named in messages. */
1860
- get label() {
1861
- return `${this.owner.name}.${this.name}`;
1862
- }
1863
- /** The target's records, with the association's scope applied. */
1864
- all(executor) {
1865
- const relation = relationFor(executor, this.target);
1866
- const { scope } = this.definition;
1867
- if (scope === void 0) return relation;
1868
- return relation[applyScope](this.label, scope, []);
1869
- }
1870
- /** The target's records linked to `key` (one value, or a list), with the scope applied. */
1871
- linkedTo(executor, key) {
1872
- return this.all(executor).where({ [this.targetAttribute]: key });
1873
- }
1874
- /** Why records can't be created through the association for `owner`, which has no key. */
1875
- refusalFor(owner) {
1876
- const { name } = this.owner;
1877
- return owner[state].isNew ? `the ${name} hasn't been saved; save the ${name} first` : `the ${name} has no ${this.ownerAttribute}`;
1878
- }
1879
- /**
1880
- * Whether `deleteAll()` on the association itself deletes the records (`dependent:
1881
- * "destroy"` or `"deleteAll"`) rather than nullifying their foreign key, as in Rails.
1882
- */
1883
- get deletesOnDeleteAll() {
1884
- const { dependent } = this.definition;
1885
- return dependent === "destroy" || dependent === "deleteAll";
1886
- }
1887
- /**
1888
- * `relation` in the association's order: its scope's, then the target's primary key, so
1889
- * lazy reads, preloads and dependents agree, and a hasOne on its one record.
1890
- */
1891
- inOrder(relation) {
1892
- return relation.order({ [this.target.primaryKey]: "asc" });
1893
- }
1894
- /**
1895
- * The owner's value its targets are linked by: a belongsTo's foreign key, or for a
1896
- * hasMany/hasOne the owner's key, null while the owner is new (it has no stored records).
1897
- */
1898
- keyOf(owner) {
1899
- if (this.definition.kind !== "belongsTo" && owner[state].isNew) return null;
1900
- return owner[state].read(this.ownerAttribute);
1901
- }
1902
- };
1903
- /** Each Model's resolved associations, worked out on first use. Derived from the class only. */
1904
- const resolved = /* @__PURE__ */ new WeakMap();
1905
- /** The association `name` of `owner`, resolved once. */
1906
- function resolveAssociation(owner, name) {
1907
- readyModel(owner);
1908
- const perModel = resolved.get(owner) ?? /* @__PURE__ */ new Map();
1909
- resolved.set(owner, perModel);
1910
- let association = perModel.get(name);
1911
- if (association === void 0) {
1912
- association = new ResolvedAssociation(owner, name);
1913
- perModel.set(name, association);
1914
- }
1915
- return association;
1916
- }
1917
- //#endregion
1918
- //#region src/preload.ts
1919
- /**
1920
- * Plans the preloads of `query`'s includes before the query is sent, so they go with it, every
1921
- * level in one round trip: each association's query selects its owners' keys with a subquery
1922
- * of theirs. Throws `IncompatibleRelation`, sending nothing, for a scope that can't be preloaded.
1923
- */
1924
- function planPreload(query, executor) {
1925
- const tree = query.includes ?? {};
1926
- for (const [name, nested] of Object.entries(tree)) checkPreloadable(resolveAssociation(query.model, name), nested, executor);
1927
- return planFrom([{
1928
- model: query.model,
1929
- owners: { query },
1930
- tree,
1931
- written: tree
1932
- }], executor);
1933
- }
1934
- /**
1935
- * Throws `IncompatibleRelation` if `association`, or one under it (named in `nested` or its
1936
- * scope's includes), has a scope that can't be preloaded: checked for the whole tree before
1937
- * anything is sent. Each association's scope includes are followed once (`checked`), so a
1938
- * scope that includes itself, a tree of records, still ends.
1939
- */
1940
- function checkPreloadable(association, nested, executor, checked = /* @__PURE__ */ new Set()) {
1941
- const query = association.all(executor)[preloadQuery](association.label);
1942
- const scoped = checked.has(association) ? {} : query.includes ?? {};
1943
- checked.add(association);
1944
- for (const [name, under] of Object.entries(mergeTrees(scoped, nested))) checkPreloadable(resolveAssociation(association.target, name), under, executor, checked);
1945
- }
1946
- /** The plan preloading each start's tree. */
1947
- function planFrom(starts, executor) {
1948
- const planning = {
1949
- steps: [],
1950
- afterwards: [],
1951
- offset: starts.length,
1952
- executor
1953
- };
1954
- starts.forEach((start, ownersAt) => planSteps(planning, start, {
1955
- ownersAt,
1956
- path: /* @__PURE__ */ new Set()
1957
- }));
1958
- return {
1959
- statements: planning.steps.flatMap((step) => step.select ?? []),
1960
- attach: (records, rows, executor) => attachSteps(planning, records, rows, executor)
1961
- };
1962
- }
1963
- /**
1964
- * Adds a step for each association in `start`'s tree, each followed by the steps under it. One
1965
- * in `level`'s path, that a scope's includes reach again (a tree of records) and the caller
1966
- * didn't write out there, is left for afterwards: how deep it goes isn't known until its
1967
- * records are.
1968
- */
1969
- function planSteps(planning, start, level) {
1970
- const { now, afterwards } = splitRepeated(start, level.path);
1971
- const { model } = start;
1972
- leaveForAfterwards(planning, {
1973
- ownersAt: level.ownersAt,
1974
- model,
1975
- tree: afterwards,
1976
- written: {}
1977
- });
1978
- for (const name of Object.keys(now)) planStep(planning, {
1979
- ...start,
1980
- tree: now
1981
- }, level, name);
1982
- }
1983
- /**
1984
- * Adds the step for one association of `start`'s, then the steps under it. One that, with the
1985
- * subqueries of the levels above, would bind more values than the database allows is left for
1986
- * afterwards, when its owners' keys are bound as one value.
1987
- */
1988
- function planStep(planning, { model, owners, tree, written }, { ownersAt, path }, name) {
1989
- const association = resolveAssociation(model, name);
1990
- const query = linkedQuery(association, owners, planning.executor);
1991
- const targets = query && targetsOf(planning.executor.dialect, association, query, tree[name] ?? {});
1992
- if (overBoundValues(owners, targets, planning.executor.adapter.maxBoundValues)) {
1993
- const onlyThis = (from) => from[name] === void 0 ? {} : { [name]: from[name] };
1994
- leaveForAfterwards(planning, {
1995
- ownersAt,
1996
- model,
1997
- tree: onlyThis(tree),
1998
- written: onlyThis(written)
1999
- });
2000
- return;
2001
- }
2002
- const step = {
2003
- association,
2004
- ownersAt,
2005
- select: targets?.select
2006
- };
2007
- const position = planning.offset + planning.steps.push(step) - 1;
2008
- if (query === void 0 || targets === void 0) return;
2009
- const { target } = association;
2010
- planSteps(planning, {
2011
- model: target,
2012
- owners: { query },
2013
- tree: targets.includes,
2014
- written: written[name] ?? {}
2015
- }, {
2016
- ownersAt: position,
2017
- path: /* @__PURE__ */ new Set([...path, association])
2018
- });
2019
- }
2020
- /**
2021
- * Whether `targets`' SELECT, selecting the keys of `owners`' query with a subquery, binds more
2022
- * values than `limit`, what the database allows in one statement.
2023
- */
2024
- function overBoundValues(owners, targets, limit) {
2025
- return "query" in owners && (targets?.select.params.length ?? 0) > limit;
2026
- }
2027
- /** Adds `deferred` to what's preloaded afterwards, merged with anything left for its owners. */
2028
- function leaveForAfterwards(planning, deferred) {
2029
- if (Object.keys(deferred.tree).length === 0) return;
2030
- const existing = planning.afterwards.find(({ ownersAt }) => ownersAt === deferred.ownersAt);
2031
- if (existing === void 0) {
2032
- planning.afterwards.push(deferred);
2033
- return;
2034
- }
2035
- existing.tree = mergeTrees(existing.tree, deferred.tree);
2036
- existing.written = mergeTrees(existing.written, deferred.written);
2037
- }
2038
- /**
2039
- * `association`'s query for its owners' records, in its order: linked by a subquery of the
2040
- * owners' query, or by the loaded owners' keys (one bound value, however many). None when
2041
- * nothing can match: no owner has a key, or the scope is `none()`.
2042
- */
2043
- function linkedQuery(association, owners, executor) {
2044
- const { ownerAttribute, targetAttribute } = association;
2045
- if ("query" in owners) {
2046
- const linked = new LinkedTo(targetAttribute, owners.query, ownerAttribute);
2047
- const scoped = scopedQuery(association, association.all(executor));
2048
- return scoped && {
2049
- ...scoped,
2050
- conditions: [...scoped.conditions, linked]
2051
- };
2052
- }
2053
- const keys = owners.records.map((record) => record[state].read(ownerAttribute));
2054
- const distinct = [...new Set(keys.filter((key) => key !== null && key !== void 0))];
2055
- if (distinct.length === 0) return void 0;
2056
- return scopedQuery(association, association.linkedTo(executor, distinct));
2057
- }
2058
- /** `relation`, of `association`'s targets, in its order, as a preload: none for a `none()`. */
2059
- function scopedQuery(association, relation) {
2060
- const query = association.inOrder(relation)[preloadQuery](association.label);
2061
- return query.none ? void 0 : query;
2062
- }
2063
- /**
2064
- * `start`'s tree split into the associations to plan now, and those in `path` that the part
2065
- * the caller wrote out doesn't name, for afterwards.
2066
- */
2067
- function splitRepeated({ model, tree, written }, path) {
2068
- const now = {};
2069
- const afterwards = {};
2070
- for (const [name, nested] of Object.entries(tree)) {
2071
- const repeated = written[name] === void 0 && path.has(resolveAssociation(model, name));
2072
- (repeated ? afterwards : now)[name] = nested;
2073
- }
2074
- return {
2075
- now,
2076
- afterwards
2077
- };
2078
- }
2079
- /**
2080
- * Attaches each step's targets, from its statement's rows, to its owners: `records`, a plan's
2081
- * starts, or an earlier step's targets. Then preloads, together in one more round trip, what
2082
- * was left for afterwards.
2083
- */
2084
- async function attachSteps({ steps, afterwards }, records, rows, executor) {
2085
- const owners = [...records];
2086
- const results = rows.values();
2087
- for (const { association, ownersAt, select } of steps) {
2088
- const targets = (select === void 0 ? [] : results.next().value ?? []).map((row) => hydrate(association.target, row, executor));
2089
- attach(owners[ownersAt] ?? [], association, targets);
2090
- owners.push(targets);
2091
- }
2092
- const starts = afterwards.flatMap(({ ownersAt, ...deferred }) => {
2093
- const loaded = owners[ownersAt] ?? [];
2094
- return loaded.length === 0 ? [] : [{
2095
- ...deferred,
2096
- owners: { records: loaded }
2097
- }];
2098
- });
2099
- if (starts.length > 0) await preloadStarts(starts, executor);
2100
- }
2101
- /** Preloads each start's tree from records already loaded, in one round trip. */
2102
- async function preloadStarts(starts, executor) {
2103
- const plan = planFrom(starts, executor);
2104
- const rows = await sendTogether(executor, plan.statements);
2105
- const records = starts.map(({ owners }) => "records" in owners ? owners.records : []);
2106
- await plan.attach(records, rows, executor);
2107
- }
2108
- /** The SELECT for an association's targets, `query`, and what to preload for them. */
2109
- function targetsOf(dialect, association, query, nested) {
2110
- const includes = mergeTrees(query.includes ?? {}, nested);
2111
- const columns = query.select && [...query.select, association.targetAttribute];
2112
- return {
2113
- select: selectFor(dialect, association.target, {
2114
- ...query,
2115
- select: columns,
2116
- includes
2117
- }),
2118
- includes
2119
- };
2120
- }
2121
- /**
2122
- * Attaches `targets`, an association's records, to their owners, `records`: each gets the
2123
- * targets whose linking attribute matches its own (hasMany: all of them; belongsTo/hasOne: the
2124
- * first, or null).
2125
- */
2126
- function attach(records, association, targets) {
2127
- const { name, definition, ownerAttribute, target, targetAttribute } = association;
2128
- const byKey = groupBy(targets, targetAttribute);
2129
- const targetKey = attributeFor(target, targetAttribute);
2130
- for (const record of records) {
2131
- const key = record[state].read(ownerAttribute);
2132
- const group = byKey.get(targetKey.condition(key)) ?? [];
2133
- const value = definition.kind === "hasMany" ? group : group[0] ?? null;
2134
- record[state].associations.set(name, ownerAttribute, value);
2135
- }
2136
- }
2137
- /** Records grouped by one attribute's value, keeping their order. */
2138
- function groupBy(records, attribute) {
2139
- const groups = /* @__PURE__ */ new Map();
2140
- for (const record of records) {
2141
- const key = record[state].read(attribute);
2142
- const group = groups.get(key);
2143
- if (group === void 0) groups.set(key, [record]);
2144
- else group.push(record);
2145
- }
2146
- return groups;
2147
- }
2148
- /** Normalizes `includes()` arguments into a tree, checking every name against its Model. */
2149
- function includeTree(model, specs) {
2150
- let tree = {};
2151
- for (const spec of specs) {
2152
- const entries = typeof spec === "string" ? [[spec, []]] : Object.entries(spec).map(([name, nested]) => [name, Array.isArray(nested) ? nested : [nested]]);
2153
- for (const [name, nested] of entries) {
2154
- const { target } = resolveAssociation(model, name);
2155
- tree = mergeTrees(tree, { [name]: includeTree(target, nested) });
2156
- }
2157
- }
2158
- return tree;
2159
- }
2160
- /** The attributes a record must have loaded for its includes to be preloaded. */
2161
- function keysForIncludes(model, includes) {
2162
- return Object.keys(includes ?? {}).map((name) => resolveAssociation(model, name).ownerAttribute);
2163
- }
2164
- //#endregion
2165
- //#region src/relation-inspect.ts
2166
- /** `Relation<Model> { sql, params }`, filtered params as `[FILTERED]`; `[Relation]` past `depth`. */
2167
- function inspectRelation(modelName, { sql, params }, args) {
2168
- const body = () => ({
2169
- sql,
2170
- params: params.map((param) => param instanceof Filtered ? new FilteredMark(false) : param)
2171
- });
2172
- return printed(`Relation<${modelName}>`, "Relation", body, args);
2173
- }
2174
- //#endregion
2175
- //#region src/fragment-guard.ts
2176
- /** A comparison operator, alone between two interpolations. */
2177
- const comparison = /^\s*(?:=|==|<>|!=|<=|>=|<|>)\s*$/;
2178
- /** `BETWEEN` or `NOT BETWEEN`, alone before the first bound. */
2179
- const betweenLower = /^\s*(?:NOT\s+)?BETWEEN\s*$/i;
2180
- /** `AND`, alone between the two bounds. */
2181
- const betweenUpper = /^\s*AND\s*$/i;
2182
- /** What a bare value is, when it's date text a datetime column wouldn't hold as it is. */
2183
- function bareDatetimeKind(value) {
2184
- if (value instanceof Date) return "Date";
2185
- if (typeof value !== "string") return void 0;
2186
- return castValue({ type: "datetime" }, value) !== uncastable || zonelessDateTime.test(value) ? "string" : void 0;
2187
- }
2188
- /** The column a value at `index` follows, with only a comparison or `BETWEEN` between them. */
2189
- function columnBefore(fragment, index) {
2190
- const { strings, values } = fragment;
2191
- const between = strings[index] ?? "";
2192
- const before = values[index - 1];
2193
- if (before instanceof ColumnReference && (comparison.test(between) || betweenLower.test(between))) return before;
2194
- const column = values[index - 2];
2195
- return betweenUpper.test(between) && betweenLower.test(strings[index - 1] ?? "") && column instanceof ColumnReference ? column : void 0;
2196
- }
2197
- /** The column a value at `index` precedes: after a comparison, or the bounds of `BETWEEN`. */
2198
- function columnAfter(fragment, index) {
2199
- const { strings, values } = fragment;
2200
- const between = strings[index + 1] ?? "";
2201
- const after = values[index + 1];
2202
- if (after instanceof ColumnReference && (comparison.test(between) || betweenLower.test(between))) return after;
2203
- const upper = values[index + 2];
2204
- return betweenLower.test(between) && betweenUpper.test(strings[index + 2] ?? "") && upper instanceof ColumnReference ? upper : void 0;
2205
- }
2206
- /**
2207
- * Throws `TypeError` when a fragment puts a bare date directly beside the column of an attribute
2208
- * stored as a Unix time: it's bound as ISO text, which never compares with an integer (#149).
2209
- * Only the text between interpolations is read, never a value.
2210
- */
2211
- function refuseBareDates(model, fragment) {
2212
- fragment.values.forEach((value, index) => {
2213
- const kind = bareDatetimeKind(value);
2214
- if (kind === void 0) return;
2215
- const reference = columnBefore(fragment, index) ?? columnAfter(fragment, index);
2216
- if (reference === void 0) return;
2217
- const { storage } = attributeOf(model, reference.attribute);
2218
- if (storage === void 0) return;
2219
- throw new TypeError(`${model.name}: a ${kind} beside "${reference.attribute}", which is stored as ${storage}, is bound as ISO text. Use column("${reference.attribute}").value(…) for it.`);
2220
- });
2221
- }
2222
- //#endregion
2223
- //#region src/relation-checks.ts
2224
- function requireObjectOrFragment(conditions, method) {
2225
- if (typeof conditions !== "object" || conditions === null || Array.isArray(conditions)) throw new TypeError(`${method}() takes an object of attribute values or an sql\`…\` fragment; plain strings are not accepted`);
2226
- }
2227
- /** An undefined value (alone or in an array) would bind NULL into `= ?` and match nothing. */
2228
- function rejectUndefined(value, name, method) {
2229
- if (value === void 0 || Array.isArray(value) && value.includes(void 0)) throw new TypeError(`${method}() got undefined for "${name}"; use null to match NULL, or leave the key out`);
2230
- }
2231
- /** Only ordered values compare meaningfully; booleans (0/1) and json text don't. */
2232
- function requireOrdered(type, name, method) {
2233
- if (type === "boolean" || type === "json") throw new TypeError(`${method}() can't compare "${name}", a ${type} attribute; match values instead`);
2234
- }
2235
- /** `"desc"` or `{ direction: "desc", nulls: "last" }` for `attribute`, checked. */
2236
- function attributeOrder(attribute, value, method) {
2237
- const [direction, nulls] = typeof value === "object" && value !== null ? [Reflect.get(value, "direction"), Reflect.get(value, "nulls")] : [value, void 0];
2238
- if (direction !== "asc" && direction !== "desc") throw new TypeError(`${method}() direction for "${attribute}" must be "asc" or "desc"`);
2239
- if (nulls !== void 0 && nulls !== "first" && nulls !== "last") throw new TypeError(`${method}() nulls for "${attribute}" must be "first" or "last"`);
2240
- return nulls === void 0 ? {
2241
- attribute,
2242
- direction
2243
- } : {
2244
- attribute,
2245
- direction,
2246
- nulls
2247
- };
2248
- }
2249
- /**
2250
- * A fragment's `column()` references must name declared attributes, and so must its typed
2251
- * values, which must also be values those attributes can hold, so a mistake surfaces where the
2252
- * fragment is written, not when the query runs (#142). A bare date beside an integer-stored
2253
- * column is refused too (#149).
2254
- */
2255
- function checkFragment(model, fragment) {
2256
- for (const value of fragment.values) {
2257
- if (!namesAttribute(value)) continue;
2258
- attributeOf(model, value.attribute);
2259
- if (value instanceof ColumnValue) attributeFor(model, value.attribute).cast(value.assigned);
2260
- }
2261
- refuseBareDates(model, fragment);
2262
- }
2263
- /** `{}` adds no condition at all (common when an object is built from optional filters). */
2264
- function isEmptyConditions(conditions) {
2265
- return !(conditions instanceof SafeSql) && Object.keys(conditions).length === 0;
2266
- }
2267
- /**
2268
- * Validates conditions when they're written, not when they run: rejects plain strings,
2269
- * unknown attributes, and undefined values (which would otherwise silently match nothing).
2270
- */
2271
- function checkConditions(model, conditions, method) {
2272
- requireObjectOrFragment(conditions, method);
2273
- if (conditions instanceof SafeSql) {
2274
- checkFragment(model, conditions);
2275
- return;
2276
- }
2277
- for (const [name, value] of Object.entries(conditions)) {
2278
- const { type } = attributeOf(model, name);
2279
- rejectUndefined(value, name, method);
2280
- if (value instanceof Comparison) requireOrdered(type, name, method);
2281
- }
2282
- }
2283
- /** Attribute changes for `updateAll`, checked like conditions: declared, and not undefined. */
2284
- function checkChanges(model, changes) {
2285
- checkConditions(model, changes, "updateAll");
2286
- if (changes instanceof SafeSql) return changes;
2287
- const assignments = Object.entries(changes);
2288
- if (assignments.length === 0) throw new TypeError("updateAll() needs at least one attribute to change");
2289
- return assignments;
2290
- }
2291
- /** Checks an order spec when it's written, not when it runs. */
2292
- function orderTerms(model, spec, method) {
2293
- requireObjectOrFragment(spec, method);
2294
- if (spec instanceof SafeSql) {
2295
- checkFragment(model, spec);
2296
- return [spec];
2297
- }
2298
- return Object.entries(spec).map(([attribute, value]) => {
2299
- attributeOf(model, attribute);
2300
- return attributeOrder(attribute, value, method);
2301
- });
2302
- }
2303
- /** The conflict for `onDuplicate: "skip"`, checked; none without it. */
2304
- function skipOn({ onDuplicate }, method) {
2305
- if (onDuplicate === void 0) return void 0;
2306
- if (onDuplicate !== "skip") throw new TypeError(`${method}() onDuplicate must be "skip"`);
2307
- return { kind: "skip" };
2308
- }
2309
- /** The attributes `returning` names, checked: the primary key when it's not given, none for `false`. */
2310
- function returnedNames(model, returning) {
2311
- if (returning !== void 0 && returning !== false && !Array.isArray(returning)) throw new TypeError("returning must be a list of attributes, or false");
2312
- return returning === void 0 ? [model.primaryKey] : returning === false ? [] : [...returning];
2313
- }
2314
- /** An upsert's conflict: update, matching on `uniqueBy` (the primary key by default). */
2315
- function updateOn(model, options) {
2316
- const uniqueBy = [options.uniqueBy ?? model.primaryKey].flat();
2317
- for (const name of uniqueBy) attributeOf(model, name);
2318
- return {
2319
- kind: "update",
2320
- uniqueBy
2321
- };
2322
- }
2323
- /** The query a write statement targets; rows from `distinct()` have no identity to write to. */
2324
- function writableQuery(query, method) {
2325
- if (query.distinct) throw new IncompatibleRelation(`${method}() can't be combined with distinct()`);
2326
- return query;
2327
- }
2328
- //#endregion
2329
- //#region src/timestamps.ts
2330
- /** Whether the Model declares `name` as a datetime attribute, which turns its timestamp on. */
2331
- function hasTimestamp(model, name) {
2332
- return model.attributeDefinitions.get(name)?.type === "datetime";
2333
- }
2334
- /**
2335
- * The timestamps to add to a write: `createdAt` and `updatedAt` on insert, `updatedAt` on
2336
- * update. Never one the write already assigns.
2337
- */
2338
- function timestampsFor(model, write, own) {
2339
- const now = /* @__PURE__ */ new Date();
2340
- const assigned = new Set(own.map(([name]) => name));
2341
- return (write === "insert" ? ["createdAt", "updatedAt"] : ["updatedAt"]).filter((name) => hasTimestamp(model, name) && !assigned.has(name)).map((name) => [name, now]);
2342
- }
2343
- //#endregion
2344
- //#region src/statement.ts
2345
- /** @internal The library's key for what `db.batch` needs from a Statement. */
2346
- const statementParts = Symbol("statementParts");
2347
- const noRows = () => [];
2348
- /**
2349
- * A write prepared for `db.batch([...])`, from a Relation's `to…` methods (`toInsert`,
2350
- * `toUpdateAll`, `toDeleteAll`, …). It runs on the Database it was built from, and skips
2351
- * validations, callbacks and hydration. It has no `then`, so it's never run by being awaited.
2352
- */
2353
- var Statement = class {
2354
- #executor;
2355
- #query;
2356
- #landed;
2357
- #rows;
2358
- /**
2359
- * @internal Statements are built by Relations' `to…` methods. `landed` runs once D1 has
2360
- * written it, alone or in a batch (a hasMany's clears what its owner has loaded, #187), and
2361
- * `rows` reads what it returned.
2362
- */
2363
- constructor(executor, query, landed = () => {}, rows = noRows) {
2364
- this.#executor = executor;
2365
- this.#query = query;
2366
- this.#landed = landed;
2367
- this.#rows = rows;
2368
- }
2369
- /** The SQL this Statement sends and its bound values, unsent: see `Relation#toSql`. */
2370
- toSql() {
2371
- return querySql(withPlaceholders(this.#executor.dialect, this.#query));
2372
- }
2373
- /**
2374
- * @internal The Database's Executor it runs on, its compiled SQL, what runs once written, and
2375
- * its `WriteResult` from what the database returned.
2376
- */
2377
- get [statementParts]() {
2378
- const resultOf = ({ rowsAffected, rows }) => ({
2379
- rowsAffected,
2380
- rows: this.#rows(rows)
2381
- });
2382
- return {
2383
- executor: this.#executor,
2384
- query: this.#query,
2385
- landed: this.#landed,
2386
- resultOf
2387
- };
2388
- }
2389
- };
2390
- /** Runs a statement on its own, then its `landed`, resolving to its `WriteResult`: what a Relation's write methods do. */
2391
- async function runAlone(statement) {
2392
- const { executor, query, landed, resultOf } = statement[statementParts];
2393
- const result = await executor.run(query);
2394
- landed();
2395
- return resultOf(result);
2396
- }
2397
- /** Reads the attributes `names` of each returned row, each as its type. */
2398
- function rowReader(model, names) {
2399
- if (names.length === 0) return noRows;
2400
- const attributes = names.map((name) => attributeFor(model, name));
2401
- return (rows) => rows.map((row) => Object.fromEntries(attributes.map((attribute) => [attribute.name, attribute.read(row[attribute.column])])));
2402
- }
2403
- /**
2404
- * The attributes an insert statement writes: the given ones, then initial values for the
2405
- * rest (where app-generated keys come from), then `createdAt`/`updatedAt` unless given.
2406
- */
2407
- function insertAssignments(model, attributes) {
2408
- for (const name of Object.keys(attributes)) attributeOf(model, name);
2409
- const values = [...Object.entries(attributes), ...initialValues(model, attributes)];
2410
- for (const [name, value] of values) requireDefined(model, name, value);
2411
- return [...values, ...timestampsFor(model, "insert", values)];
2412
- }
2413
- /**
2414
- * `INSERT` of `rows` into `model`'s table, as one Statement. Every row must have the same
2415
- * attributes as given, as in Rails; `conflict` skips or updates rows that clash with a unique
2416
- * index. An update sets only the given attributes (and `updatedAt`), never filled-in defaults.
2417
- * It returns the attributes `returning` names of each row written.
2418
- */
2419
- function insertStatement(executor, model, rows, { conflict, method, landed, returning }) {
2420
- const read = rowReader(model, returning);
2421
- const given = sameAttributes(rows, method);
2422
- const assigned = rows.map((row) => new Map(insertAssignments(model, row)));
2423
- const names = [...assigned[0]?.keys() ?? []];
2424
- if (names.length === 0) {
2425
- if (rows.length === 1 && conflict === void 0) return new Statement(executor, compileInsert(model, [], returning), landed, read);
2426
- throw new TypeError(`${method}(): nothing to insert; give each row at least one attribute`);
2427
- }
2428
- const values = assigned.map((row) => names.map((name) => row.get(name)));
2429
- const resolved = conflict?.kind === "update" ? {
2430
- ...conflict,
2431
- update: [...given, ...names.includes("updatedAt") ? ["updatedAt"] : []]
2432
- } : conflict;
2433
- return new Statement(executor, compileInsertRows(executor.dialect, model, {
2434
- names,
2435
- rows: values,
2436
- conflict: resolved,
2437
- returning
2438
- }), landed, read);
2439
- }
2440
- /** The attributes every row was given; they must be the same for all rows, in any order. */
2441
- function sameAttributes(rows, method) {
2442
- const [first, ...rest] = rows.map((row) => Object.keys(row));
2443
- if (first === void 0) throw new TypeError(`${method}() needs at least one row`);
2444
- for (const [index, keys] of rest.entries()) if (keys.length !== first.length || !first.every((name) => keys.includes(name))) throw new TypeError(`${method}() rows must all have the same attributes: row ${index + 2} differs from the first (${first.join(", ")})`);
2445
- return first;
2446
- }
2447
- //#endregion
2448
- //#region src/pagination.ts
2449
- /**
2450
- * One page of `paged`'s records. Counted, the `COUNT` and the page's SELECT go as one batch;
2451
- * with `count: false`, one SELECT fetches a record past the page to learn whether there's a next.
2452
- */
2453
- async function paginate({ model, query, runner }, options) {
2454
- if (query.limit !== void 0 || query.offset !== void 0) throw new IncompatibleRelation("paginate() pages with its own limit and offset; remove the Relation's limit() and offset()");
2455
- const page = pageNumber("page", options.page) ?? 1;
2456
- const perPage = Math.min(pageNumber("perPage", options.perPage) ?? model.perPage, model.maxPerPage);
2457
- const onPage = {
2458
- ...query,
2459
- order: stableOrder(model, query),
2460
- limit: perPage,
2461
- offset: offsetOf(page, perPage)
2462
- };
2463
- const hasPrevious = page > 1;
2464
- if (options.count === false) {
2465
- const { records, hasMore } = await runner.loadAhead(onPage);
2466
- return {
2467
- records,
2468
- page,
2469
- perPage,
2470
- hasNext: hasMore,
2471
- hasPrevious
2472
- };
2473
- }
2474
- const { records, count } = await runner.loadCounted(onPage, query);
2475
- const totalPages = Math.ceil(count / perPage);
2476
- return {
2477
- records,
2478
- page,
2479
- perPage,
2480
- total: count,
2481
- totalPages,
2482
- hasNext: page < totalPages,
2483
- hasPrevious
2484
- };
2485
- }
2486
- /**
2487
- * The rows before `page`. A page so far that the rows to it (and one more, for `count: false`)
2488
- * aren't a safe integer is a `TypeError`, as an uncastable page is, rather than an inexact offset.
2489
- */
2490
- function offsetOf(page, perPage) {
2491
- const offset = (page - 1) * perPage;
2492
- if (!Number.isSafeInteger(offset + perPage + 1)) throw new TypeError("paginate()'s page is too far to reach");
2493
- return offset;
2494
- }
2495
- /**
2496
- * A page or page size, cast as an integer attribute is (#81), so `"2"` is 2. Missing, `null` or
2497
- * `""` is `undefined`, for the default; anything else not a whole number from 1 is a `TypeError`.
2498
- */
2499
- function pageNumber(name, value) {
2500
- if (value === void 0 || value === null || value === "") return void 0;
2501
- const cast = castValue({ type: "integer" }, value);
2502
- if (cast === uncastable || cast < 1) throw new TypeError(`paginate()'s ${name} must be a whole number from 1`);
2503
- return cast;
2504
- }
2505
- //#endregion
2506
- //#region src/relation.ts
2507
- /** @internal The library's key for the query preloading a Relation sends, checked first. */
2508
- const preloadQuery = Symbol("preloadQuery");
2509
- /** @internal The library's key for making a hasMany Relation of an owner. */
2510
- const ofOwner = Symbol("ofOwner");
2511
- /** @internal The library's key for running a scope on a Relation. */
2512
- const applyScope = Symbol("applyScope");
2513
- /** A lazy, immutable description of a query against one Model. */
2514
- var Relation = class Relation {
2515
- #executor;
2516
- #model;
2517
- #query;
2518
- /** How its query runs: on D1, or not at all for `none()`. */
2519
- #runner;
2520
- /** What a hasMany's owner already knows about it, or `unowned`. Not query data. */
2521
- #collection;
2522
- /**
2523
- * Relations come from `db.model(Model)` and from other Relations, never `new Relation()`:
2524
- * what one is made from is the library's own business.
2525
- */
2526
- constructor(parts) {
2527
- const { executor, model, query, collection } = parts;
2528
- this.#executor = executor;
2529
- this.#model = model;
2530
- this.#query = query ?? allOf(model);
2531
- this.#runner = runnerFor(executor, model, this.#query);
2532
- this.#collection = collection ?? unowned;
2533
- }
2534
- where(conditions) {
2535
- checkConditions(this.#model, conditions, "where");
2536
- if (isEmptyConditions(conditions)) return this.#scoped(this);
2537
- return this.#with({ conditions: [...this.#query.conditions, conditions] });
2538
- }
2539
- /** Negates the whole condition: `NOT (…)`. Rows where it is NULL are excluded too. */
2540
- whereNot(conditions) {
2541
- checkConditions(this.#model, conditions, "whereNot");
2542
- if (isEmptyConditions(conditions)) return this.#scoped(this);
2543
- return this.#with({ conditions: [...this.#query.conditions, new Negated(conditions)] });
2544
- }
2545
- /** A Relation that matches nothing and never queries D1; it stays empty when chained. */
2546
- none() {
2547
- return this.#with({ none: true });
2548
- }
2549
- /**
2550
- * Rows matching this Relation's conditions or `other`'s. Both must be of the same Model and
2551
- * identical in everything but their conditions (select, order, limit, offset, distinct).
2552
- */
2553
- or(other) {
2554
- this.#requireSameModel(other, "or");
2555
- return this.#joining(other, "or()").#describing(either(this.#query, other.#query));
2556
- }
2557
- /**
2558
- * ANDs `other`'s conditions onto this Relation's. For select, order, limit, offset and
2559
- * distinct, a clause `other` sets explicitly replaces this one's; one it doesn't set is kept.
2560
- * Orders are replaced, not concatenated (a deliberate difference from Rails).
2561
- */
2562
- merge(other) {
2563
- this.#requireSameModel(other, "merge");
2564
- return this.#joining(other, "merge()").#describing(merged(this.#query, other.#query));
2565
- }
2566
- /**
2567
- * Sorts by each key in turn (`{ createdAt: "desc" }`, or `{ role: { direction: "asc",
2568
- * nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
2569
- */
2570
- order(spec) {
2571
- return this.#with({ order: [...this.#query.order, ...orderTerms(this.#model, spec, "order")] });
2572
- }
2573
- /** Replaces the order so far, as in Rails; `reorder()` removes it. */
2574
- reorder(spec) {
2575
- const order = spec === void 0 ? [] : orderTerms(this.#model, spec, "reorder");
2576
- return this.#with({
2577
- order,
2578
- reordered: true
2579
- });
2580
- }
2581
- limit(count) {
2582
- return this.#with({ limit: count });
2583
- }
2584
- offset(count) {
2585
- return this.#with({ offset: count });
2586
- }
2587
- /** Loads only these attributes (a partial record); the primary key is always loaded. */
2588
- select(...attributes) {
2589
- for (const name of attributes) attributeOf(this.#model, name);
2590
- return this.#with({ select: attributes });
2591
- }
2592
- /** Removes duplicate rows (of the selected attributes). */
2593
- distinct() {
2594
- return this.#with({ distinct: true });
2595
- }
2596
- /**
2597
- * Preloads associations for every record this Relation loads, so reading them afterwards
2598
- * sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
2599
- */
2600
- includes(...specs) {
2601
- const added = includeTree(this.#model, specs);
2602
- return this.#with({ includes: mergeTrees(this.#query.includes ?? {}, added) });
2603
- }
2604
- /**
2605
- * @internal This Relation as a hasMany of an owner: answered from what the owner holds
2606
- * once loaded, or, for an owner without a key, finding nothing stored and refusing `create`.
2607
- */
2608
- [ofOwner](collection) {
2609
- const Class = this.constructor;
2610
- const query = collection.refusal === void 0 ? this.#query : {
2611
- ...this.#query,
2612
- none: true
2613
- };
2614
- return new Class({
2615
- executor: this.#executor,
2616
- model: this.#model,
2617
- query,
2618
- collection
2619
- });
2620
- }
2621
- /**
2622
- * @internal This Relation's query, if an association scope can be preloaded with it: a limit,
2623
- * offset or distinct would apply to every owner's records together, not to each owner's.
2624
- */
2625
- [preloadQuery](association) {
2626
- const { limit, offset, distinct } = this.#query;
2627
- if (limit !== void 0 || offset !== void 0 || distinct) throw new IncompatibleRelation(`${association} can't be preloaded: its scope uses limit, offset or distinct, which would apply to every owner's records together; read it lazily instead`);
2628
- return this.#query;
2629
- }
2630
- /**
2631
- * A new, unsaved record of this Relation's Model. Built through a hasMany, it joins the
2632
- * association, and saving the owner saves it too (autosave).
2633
- */
2634
- build(attributes = {}) {
2635
- const record = this.#build(attributes);
2636
- this.#collection.built(record);
2637
- return record;
2638
- }
2639
- #build(attributes) {
2640
- return buildRecord(this.#model, {
2641
- ...this.#inherited(),
2642
- ...attributes
2643
- }, this.#executor);
2644
- }
2645
- /** What a record built or inserted through this Relation takes from its conditions and owner. */
2646
- #inherited() {
2647
- const { conditions } = this.#query;
2648
- return castInherited(this.#model, inheritedAttributes(conditions), this.#collection.link);
2649
- }
2650
- /** As in Rails, records can't be created through an owner that has no key yet. */
2651
- #requireSavedOwner() {
2652
- const reason = this.#collection.refusal;
2653
- if (reason !== void 0) throw new RecordNotSaved(`You cannot create a ${this.#model.name} here: ${reason}`);
2654
- }
2655
- /**
2656
- * Inserts one row now: `await db.model(Post).insert({ title })`. Resolves to how many rows it
2657
- * wrote and the `returning` attributes of each (the primary key by default; `false` for none).
2658
- * Skips validations and callbacks; declared defaults, generated ids, and timestamps apply, and
2659
- * this Relation's equality conditions are inserted too, as with `build()`. A duplicate throws,
2660
- * unless `onDuplicate: "skip"` (Rails' `insert`). `toInsert` is the same write, for a batch.
2661
- */
2662
- async insert(attributes, options = {}) {
2663
- return runAlone(this.toInsert(attributes, options));
2664
- }
2665
- /** `insert`, as a Statement for `db.batch([...])`. */
2666
- toInsert(attributes, options = {}) {
2667
- return this.#insertStatement([attributes], skipOn(options, "insert"), "insert", options);
2668
- }
2669
- /** Inserts several rows with the same attributes now, in one statement (Rails' `insert_all!`). */
2670
- async insertAll(rows, options = {}) {
2671
- return runAlone(this.toInsertAll(rows, options));
2672
- }
2673
- /** `insertAll`, as a Statement for `db.batch([...])`. */
2674
- toInsertAll(rows, options = {}) {
2675
- return this.#insertStatement(rows, skipOn(options, "insertAll"), "insertAll", options);
2676
- }
2677
- /**
2678
- * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
2679
- * primary key by default): every given attribute but those and `createdAt`, with `updatedAt`
2680
- * set, as Rails' `upsert` does. Resolves as `insert` does, returning inserted and updated rows.
2681
- */
2682
- async upsert(attributes, options = {}) {
2683
- return runAlone(this.toUpsert(attributes, options));
2684
- }
2685
- /** `upsert`, as a Statement for `db.batch([...])`. */
2686
- toUpsert(attributes, options = {}) {
2687
- return this.#insertStatement([attributes], updateOn(this.#model, options), "upsert", options);
2688
- }
2689
- /** `upsert` for several rows with the same attributes, now (Rails' `upsert_all`). */
2690
- async upsertAll(rows, options = {}) {
2691
- return runAlone(this.toUpsertAll(rows, options));
2692
- }
2693
- /** `upsertAll`, as a Statement for `db.batch([...])`. */
2694
- toUpsertAll(rows, options = {}) {
2695
- return this.#insertStatement(rows, updateOn(this.#model, options), "upsertAll", options);
2696
- }
2697
- #insertStatement(rows, conflict, method, { returning }) {
2698
- this.#requireSavedOwner();
2699
- const inherited = this.#inherited();
2700
- const withInherited = rows.map((row) => ({
2701
- ...inherited,
2702
- ...row
2703
- }));
2704
- return insertStatement(this.#executor, this.#model, withInherited, {
2705
- conflict,
2706
- method,
2707
- landed: this.#clearCollectionUntilWritten(),
2708
- returning: returnedNames(this.#model, returning)
2709
- });
2710
- }
2711
- /**
2712
- * Clears what an owner has loaded through this Relation's hasMany, for a statement built
2713
- * through it; the function it returns clears it again once the statement is written (#187).
2714
- */
2715
- #clearCollectionUntilWritten() {
2716
- const collection = this.#collection;
2717
- collection.invalidate();
2718
- return () => collection.invalidate();
2719
- }
2720
- /**
2721
- * Updates every row this Relation matches, now, setting attribute values or an `sql`
2722
- * fragment: ``updateAll(sql`${column("views")} = ${column("views")} + 1`)``. Resolves to the
2723
- * number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone, as in
2724
- * Rails. A `none()` Relation sends nothing and resolves to 0.
2725
- */
2726
- async updateAll(changes) {
2727
- checkChanges(this.#model, changes);
2728
- writableQuery(this.#query, "updateAll");
2729
- return this.#countOf(() => this.toUpdateAll(changes));
2730
- }
2731
- /** `updateAll`, as a Statement for `db.batch([...])`. */
2732
- toUpdateAll(changes) {
2733
- const checked = checkChanges(this.#model, changes);
2734
- const query = compileUpdateAll(this.#dialect, writableQuery(this.#query, "updateAll"), checked);
2735
- return new Statement(this.#executor, query, this.#clearCollectionUntilWritten());
2736
- }
2737
- /**
2738
- * Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany
2739
- * association itself (`user.posts().deleteAll()`), the rows' foreign key is set to NULL
2740
- * instead unless its `dependent:` deletes, as in Rails. A `none()` Relation sends nothing and
2741
- * resolves to 0.
2742
- */
2743
- async deleteAll() {
2744
- writableQuery(this.#query, "deleteAll");
2745
- return this.#countOf(() => this.toDeleteAll());
2746
- }
2747
- /** `deleteAll`, as a Statement for `db.batch([...])`. */
2748
- toDeleteAll() {
2749
- const query = writableQuery(this.#query, "deleteAll");
2750
- const landed = this.#clearCollectionUntilWritten();
2751
- const nullifies = this.#collection.nullifies;
2752
- const compiled = nullifies === void 0 ? compileDeleteAll(this.#dialect, query) : compileUpdateAll(this.#dialect, query, [[nullifies, null]]);
2753
- return new Statement(this.#executor, compiled, landed);
2754
- }
2755
- /**
2756
- * Builds and runs a statement from this Relation: the rows it changed, or 0 without a query on
2757
- * `none()`, which never builds it, so it needs no database to compile for.
2758
- */
2759
- async #countOf(build) {
2760
- return this.#runner.changes(() => runAlone(build()));
2761
- }
2762
- /** Builds and saves a record; resolves to it whether or not it was saved (check `isPersisted()`). */
2763
- async create(attributes = {}) {
2764
- this.#requireSavedOwner();
2765
- const record = this.#build(attributes);
2766
- if (await record.save()) this.#collection.created(record);
2767
- return record;
2768
- }
2769
- /** Builds and saves a record, throwing if it can't be saved. */
2770
- async createOrThrow(attributes = {}) {
2771
- this.#requireSavedOwner();
2772
- const record = this.#build(attributes);
2773
- await record.saveOrThrow();
2774
- this.#collection.created(record);
2775
- return record;
2776
- }
2777
- async find(...args) {
2778
- const [only] = args;
2779
- if (args.length === 1 && (typeof only === "string" || typeof only === "number")) return this.#findById(only);
2780
- const ids = keysToFind(this.#model, args.flat());
2781
- return ids.length === 0 ? [] : this.#findSome(ids);
2782
- }
2783
- async #findById(id) {
2784
- const record = await this.#findOne({ [this.#model.primaryKey]: id });
2785
- if (record === null) throw new RecordNotFound(`${this.#model.name} with ${this.#model.primaryKey} ${shownKey(this.#model, id)} not found`);
2786
- return record;
2787
- }
2788
- async #findSome(ids) {
2789
- const { primaryKey, name } = this.#model;
2790
- const query = {
2791
- ...this.#finderQuery({ [primaryKey]: ids }),
2792
- order: this.#query.order
2793
- };
2794
- const records = await this.#runner.load(query);
2795
- if (records.length < ids.length) throw new RecordNotFound(`Couldn't find all ${name} records with '${primaryKey}': (${ids.map((id) => shownKey(this.#model, id)).join(", ")}) (found ${records.length} results, but was looking for ${ids.length})`);
2796
- if (this.#query.order.length > 0) return records;
2797
- return inKeyOrder(records, ids);
2798
- }
2799
- /** The first record matching `conditions` (in no particular order), or null. */
2800
- async findBy(conditions) {
2801
- return this.where(conditions).#findOne();
2802
- }
2803
- /** Like `findBy`, but throws `RecordNotFound` instead of returning null. */
2804
- async findByOrThrow(conditions) {
2805
- const record = await this.findBy(conditions);
2806
- if (record === null) throw new RecordNotFound(`${this.#model.name} not found`);
2807
- return record;
2808
- }
2809
- /** The first record by this Relation's order, or by primary key if it has none. */
2810
- async first() {
2811
- const cached = this.#cached();
2812
- if (cached !== void 0) return cached[0] ?? null;
2813
- return this.#one(this.#orderOrPrimaryKey());
2814
- }
2815
- /**
2816
- * The last record: the first in the reverse of every order direction. With `limit`/`offset`,
2817
- * the last record of that page (loaded, then taken from the end).
2818
- */
2819
- async last() {
2820
- const cached = this.#cached();
2821
- if (cached !== void 0) return cached.at(-1) ?? null;
2822
- const { limit, offset } = this.#query;
2823
- if (limit !== void 0 || offset !== void 0) return (await this.#runner.load({
2824
- ...this.#query,
2825
- order: this.#orderOrPrimaryKey()
2826
- })).at(-1) ?? null;
2827
- return this.#one(this.#orderOrPrimaryKey().map(reversed));
2828
- }
2829
- /** One record in whatever order D1 returns, or null. */
2830
- async take() {
2831
- const cached = this.#cached();
2832
- if (cached !== void 0) return cached[0] ?? null;
2833
- return this.#one(this.#query.order);
2834
- }
2835
- /** The number of matching records, or of non-null values of `attribute`. */
2836
- async count(attribute) {
2837
- if (attribute !== void 0) attributeFor(this.#model, attribute);
2838
- const counting = () => compileCount(this.#dialect, this.#query, attribute);
2839
- const [row] = await this.#runner.rows(counting);
2840
- return Number(row?.["count"] ?? 0);
2841
- }
2842
- /**
2843
- * The number of records, as Rails' `size`: a loaded association's (built records included)
2844
- * without a query; otherwise a `COUNT(*)`, plus an association's unsaved built records.
2845
- */
2846
- async size() {
2847
- const cached = this.#cached();
2848
- if (cached !== void 0) return cached.length;
2849
- return await this.count() + this.#collection.unsavedCount();
2850
- }
2851
- /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
2852
- async isEmpty() {
2853
- const cached = this.#cached();
2854
- if (cached !== void 0) return cached.length === 0;
2855
- if (this.#collection.unsavedCount() > 0) return false;
2856
- return !await this.exists();
2857
- }
2858
- /** Whether there are any records: the opposite of `isEmpty()` (Rails' `any?`). */
2859
- async hasAny() {
2860
- return !await this.isEmpty();
2861
- }
2862
- /** Whether any record matches, optionally with extra conditions. */
2863
- async exists(conditions) {
2864
- const relation = conditions === void 0 ? this : this.where(conditions);
2865
- const query = {
2866
- ...relation.#query,
2867
- limit: atMostOne(relation.#query.limit)
2868
- };
2869
- return (await this.#runner.rows(() => compileExists(this.#dialect, query))).length > 0;
2870
- }
2871
- async pluck(...attributes) {
2872
- if (attributes.length === 0) throw new TypeError("pluck() needs at least one attribute");
2873
- const resolved = attributes.map((name) => attributeFor(this.#model, name));
2874
- const cached = this.#cached();
2875
- const values = cached === void 0 ? (await this.#runner.rows(() => compileSelect(this.#dialect, this.#query, compileColumns(this.#model, attributes)))).map((row) => resolved.map((attribute) => attribute.read(row[attribute.column]))) : cached.map((record) => resolved.map((attribute) => attribute.copy(Reflect.get(record, attribute.name))));
2876
- return attributes.length === 1 ? values.map(([value]) => value) : values;
2877
- }
2878
- async paginate(options = {}) {
2879
- return paginate({
2880
- model: this.#model,
2881
- query: this.#query,
2882
- runner: this.#runner
2883
- }, options);
2884
- }
2885
- /**
2886
- * The SQL `toArray()` sends, and its bound values, without sending it (Rails' `to_sql`). Values
2887
- * are never inlined into the SQL (ADR-0006), and none are redacted, filtered attributes included.
2888
- */
2889
- toSql() {
2890
- return querySql(selectForToSql(this.#dialect, this.#model, this.#query));
2891
- }
2892
- /** Prints as `Relation<Model> { sql, params }`: the SELECT it would send, without sending it (#104). */
2893
- [inspectCustom](depth, options, inspect) {
2894
- const compiled = selectForToSql(this.#dialect, this.#model, this.#query);
2895
- return inspectRelation(this.#model.name, compiled, {
2896
- depth,
2897
- options,
2898
- inspect
2899
- });
2900
- }
2901
- async toArray() {
2902
- const cached = this.#cached();
2903
- if (cached !== void 0) return [...cached];
2904
- const keepIfCurrent = this.#collection.startFill?.();
2905
- if (keepIfCurrent === void 0) return this.#runner.load(this.#query);
2906
- return keepIfCurrent(await this.#runner.load({
2907
- ...this.#query,
2908
- order: this.#withPrimaryKeyOrder()
2909
- }));
2910
- }
2911
- get #dialect() {
2912
- return this.#executor.dialect;
2913
- }
2914
- /** The owner's loaded records for this hasMany, if it has them. */
2915
- #cached() {
2916
- return this.#collection.loaded();
2917
- }
2918
- /**
2919
- * This Relation on its and `other`'s databases, which must be one when it runs (#93), and
2920
- * clearing `other`'s owner's loaded collection too when a statement is built through it (#194).
2921
- */
2922
- #joining(other, method) {
2923
- const executor = jointly(this.#executor, other.#executor, `${method} needs its relations`);
2924
- const collection = alsoClearing(this.#collection, other.#collection);
2925
- if (executor === this.#executor && collection === this.#collection) return this;
2926
- const Class = this.constructor;
2927
- return new Class({
2928
- executor,
2929
- model: this.#model,
2930
- query: this.#query,
2931
- collection
2932
- });
2933
- }
2934
- #requireSameModel(other, method) {
2935
- if (other.#model !== this.#model) throw new IncompatibleRelation(`${method}() needs relations of the same Model, not ${this.#model.name} and ${other.#model.name}`);
2936
- }
2937
- /** @internal Runs a scope on this Relation, checking it returned a Relation of the same Model. */
2938
- [applyScope](name, scope, args) {
2939
- const result = scope(this, ...args);
2940
- if (!(result instanceof Relation) || result.#model !== this.#model) {
2941
- const model = this.#model.name;
2942
- throw new TypeError(`${model} scope "${name}" must return a Relation of ${model}, e.g. (q) => q.where(...)`);
2943
- }
2944
- return result.#joining(this, `${this.#model.name} scope "${name}"`);
2945
- }
2946
- /**
2947
- * `relation` typed with its scope methods. Sound because every Relation is made by
2948
- * `relationFor` (the constructor needs the internal Executor), whose class has them.
2949
- */
2950
- #scoped(relation) {
2951
- return relation;
2952
- }
2953
- /** A copy with `changes` to its query. */
2954
- #with(changes) {
2955
- return this.#describing({
2956
- ...this.#query,
2957
- ...changes
2958
- });
2959
- }
2960
- /** A Relation of this same class for `query`, so a Model's scope methods survive chaining. */
2961
- #describing(query) {
2962
- const Class = this.constructor;
2963
- if (query.includes !== void 0 && query.select !== void 0 && query.distinct) throw new IncompatibleRelation("includes() can't be combined with select(...).distinct(): preloading needs keys the distinct select leaves out");
2964
- const collection = this.#collection.narrowed();
2965
- return new Class({
2966
- executor: this.#executor,
2967
- model: this.#model,
2968
- query,
2969
- collection
2970
- });
2971
- }
2972
- /** This Relation's order, then the primary key ascending, so ties come back the same way. */
2973
- #withPrimaryKeyOrder() {
2974
- return [...this.#query.order, {
2975
- attribute: this.#model.primaryKey,
2976
- direction: "asc"
2977
- }];
2978
- }
2979
- #orderOrPrimaryKey() {
2980
- const { order } = this.#query;
2981
- return order.length > 0 ? order : [{
2982
- attribute: this.#model.primaryKey,
2983
- direction: "asc"
2984
- }];
2985
- }
2986
- async #one(order) {
2987
- const [record] = await this.#runner.load({
2988
- ...this.#query,
2989
- order,
2990
- limit: atMostOne(this.#query.limit)
2991
- });
2992
- return record ?? null;
2993
- }
2994
- /** One matching row by the finder rules: keeps conditions, ignores order and pagination. */
2995
- async #findOne(extra) {
2996
- const [record] = await this.#runner.load({
2997
- ...this.#finderQuery(extra),
2998
- limit: 1
2999
- });
3000
- return record ?? null;
3001
- }
3002
- /** The finder rules: this Relation's conditions (plus `extra`) and includes, full rows. */
3003
- #finderQuery(extra) {
3004
- const conditions = extra === void 0 ? this.#query.conditions : [...this.#query.conditions, extra];
3005
- return {
3006
- model: this.#model,
3007
- conditions,
3008
- order: [],
3009
- includes: this.#query.includes
3010
- };
3011
- }
3012
- };
3013
- //#endregion
3014
- //#region src/associations.ts
3015
- const DEPENDENTS = {
3016
- belongsTo: [],
3017
- hasMany: [
3018
- "destroy",
3019
- "deleteAll",
3020
- "nullify",
3021
- "restrictWithException",
3022
- "restrictWithError"
3023
- ],
3024
- hasOne: [
3025
- "destroy",
3026
- "delete",
3027
- "nullify",
3028
- "restrictWithException",
3029
- "restrictWithError"
3030
- ]
3031
- };
3032
- /** Each prepared Model. */
3033
- const prepared = /* @__PURE__ */ new WeakSet();
3034
- /**
3035
- * Makes a Model ready for use, once: verifies its declaration, checks its associations and
3036
- * installs their accessors. Module-level, but not request state (ADR-0003): derived only from
3037
- * the class.
3038
- */
3039
- function readyModel(model) {
3040
- verifyModel(model);
3041
- if (prepared.has(model)) return;
3042
- for (const [name, definition] of associationsOf(model)) {
3043
- checkAssociation(model, name, definition);
3044
- Object.defineProperty(model.prototype, name, accessorProperty(name, definition));
3045
- }
3046
- prepared.add(model);
3047
- }
3048
- /** An association's name must be free, its target a Model, and its keys declared attributes. */
3049
- function checkAssociation(model, name, definition) {
3050
- const label = `${model.name || "A Model class's"} association "${name}"`;
3051
- checkName(label, model, name);
3052
- checkKeys(label, model, checkTarget(label, definition), definition);
3053
- checkDependent(label, definition);
3054
- }
3055
- /** Its name can't be an attribute's, or a record method's or property's. */
3056
- function checkName(label, model, name) {
3057
- if (model.attributeDefinitions.has(name)) throw new InvalidModel(`${label} has the same name as an attribute; rename one of them`);
3058
- if (name in Model.prototype) throw new InvalidModel(`${label} is the name of a record method or property; rename it`);
3059
- }
3060
- /** Its target must be a Model class. */
3061
- function checkTarget(label, definition) {
3062
- const target = definition.target();
3063
- if (typeof target !== "function" || !(target.prototype instanceof Model)) throw new InvalidModel(`${label} must point at a Model class: hasMany(Post, …)`);
3064
- return target;
3065
- }
3066
- /** Its keys must be declared attributes: the foreign key the owner's for a belongsTo, else the target's. */
3067
- function checkKeys(label, model, target, definition) {
3068
- if (definition.inferredFrom?.source === "className" && definition.inferredFrom.name === "") throw new InvalidModel(`${label} has no class name to infer its foreign key from; pass foreignKey`);
3069
- const { ownerAttribute, targetAttribute } = linkOf(definition, model, target);
3070
- const [ownerHint, targetHint] = definition.kind === "belongsTo" ? [keyHint(definition), "check primaryKey"] : ["check primaryKey", keyHint(definition)];
3071
- requireAttribute(label, model, ownerAttribute, ownerHint);
3072
- requireAttribute(label, target, targetAttribute, targetHint);
3073
- }
3074
- /** Its `dependent:` strategy must be one its kind has. */
3075
- function checkDependent(label, { dependent, kind }) {
3076
- if (dependent !== void 0 && !DEPENDENTS[kind].includes(dependent)) {
3077
- const allowed = DEPENDENTS[kind].map((each) => `"${each}"`).join(", ");
3078
- throw new InvalidModel(`${label}: a ${kind} can't be dependent: "${dependent}"${allowed ? `; use one of ${allowed}` : ""}`);
3079
- }
3080
- }
3081
- /** What to check when the foreign key isn't an attribute: where it was inferred from, if it was. */
3082
- function keyHint({ inferredFrom }) {
3083
- return inferredFrom === void 0 ? "check foreignKey" : inferenceHint(inferredFrom);
3084
- }
3085
- function requireAttribute(label, model, name, hint) {
3086
- if (model.attributeDefinitions.has(name)) return;
3087
- throw new InvalidModel(`${label}: ${model.name} has no attribute "${name}" (${hint})`);
3088
- }
3089
- /** Each record's belongsTo and hasOne accessors, made on first use. Not request state. */
3090
- const accessors = /* @__PURE__ */ new WeakMap();
3091
- /**
3092
- * The property an association adds to its Model's records. A hasMany is a method returning a
3093
- * Relation; a belongsTo or hasOne is a getter for the record's own accessor, a function
3094
- * (`await post.author()`) that also has `set`/`build`/`create` bound to that record.
3095
- */
3096
- function accessorProperty(name, definition) {
3097
- if (definition.kind === "hasMany") {
3098
- const method = function hasMany() {
3099
- return hasManyRelation(this, resolveAssociation(modelOf(this), name));
3100
- };
3101
- return {
3102
- configurable: true,
3103
- get: () => method,
3104
- set: keepAssignedField(name)
3105
- };
3106
- }
3107
- const accessorFor = definition.kind === "belongsTo" ? belongsToAccessor : hasOneAccessor;
3108
- return {
3109
- configurable: true,
3110
- set: keepAssignedField(name),
3111
- get() {
3112
- const perRecord = accessors.get(this) ?? /* @__PURE__ */ new Map();
3113
- accessors.set(this, perRecord);
3114
- if (!perRecord.has(name)) perRecord.set(name, accessorFor(this, resolveAssociation(modelOf(this), name)));
3115
- return perRecord.get(name);
3116
- }
3117
- };
3118
- }
3119
- /**
3120
- * The setter for an association's field when it's assigned rather than defined (a class field
3121
- * compiled without useDefineForClassFields, or below ES2022): it keeps the declaration on the
3122
- * record, as a defined field would be, for `newRecord` to remove.
3123
- */
3124
- function keepAssignedField(name) {
3125
- return function(value) {
3126
- Object.defineProperty(this, name, {
3127
- value,
3128
- writable: true,
3129
- enumerable: true,
3130
- configurable: true
3131
- });
3132
- };
3133
- }
3134
- /**
3135
- * A hasMany's Relation for `owner`: its target's records linked to the owner, answering from
3136
- * what the owner holds (its owned collection) where it can.
3137
- */
3138
- function hasManyRelation(owner, association) {
3139
- return association.linkedTo(owner[state].executor, association.keyOf(owner))[ofOwner](ownedCollection(owner, association));
3140
- }
3141
- /**
3142
- * A belongsTo or hasOne read: the loaded record (or null) while the key it was loaded for is
3143
- * current, otherwise `load` for the key the owner holds now, kept only if nothing changed the
3144
- * association meanwhile (#189).
3145
- */
3146
- async function cachedRead(owner, association, load) {
3147
- const { name, ownerAttribute } = association;
3148
- const cached = owner[state].associations.get(name);
3149
- if (cached !== void 0) return cached.value;
3150
- const key = association.keyOf(owner);
3151
- const keep = owner[state].associations.startLoad(name, ownerAttribute, key);
3152
- const value = key === null ? null : await load(key);
3153
- keep(value);
3154
- return value;
3155
- }
3156
- //#endregion
3157
- //#region src/model-statics.ts
3158
- /** The Relation methods every Model has as statics (besides the overloaded ones). */
3159
- const relationMethods = [
3160
- "where",
3161
- "whereNot",
3162
- "none",
3163
- "or",
3164
- "merge",
3165
- "order",
3166
- "reorder",
3167
- "limit",
3168
- "offset",
3169
- "select",
3170
- "distinct",
3171
- "includes",
3172
- "build",
3173
- "insert",
3174
- "toInsert",
3175
- "insertAll",
3176
- "toInsertAll",
3177
- "upsert",
3178
- "toUpsert",
3179
- "upsertAll",
3180
- "toUpsertAll",
3181
- "updateAll",
3182
- "toUpdateAll",
3183
- "deleteAll",
3184
- "toDeleteAll",
3185
- "create",
3186
- "createOrThrow",
3187
- "findBy",
3188
- "findByOrThrow",
3189
- "first",
3190
- "last",
3191
- "take",
3192
- "count",
3193
- "size",
3194
- "isEmpty",
3195
- "hasAny",
3196
- "exists",
3197
- "toArray",
3198
- "toSql"
3199
- ];
3200
- /**
3201
- * The callback kinds, one static each. Both `satisfies` make the list, `CallbackKind` and
3202
- * `CallbackStatics` name the same kinds: none missing from any, and none extra.
3203
- */
3204
- const callbackKinds = Object.keys({
3205
- beforeValidation: true,
3206
- afterValidation: true,
3207
- beforeSave: true,
3208
- beforeCreate: true,
3209
- beforeUpdate: true,
3210
- afterCreate: true,
3211
- afterUpdate: true,
3212
- afterSave: true,
3213
- beforeDestroy: true,
3214
- afterDestroy: true
3215
- });
3216
- /**
3217
- * The class Model extends, for its statics' types only: at runtime it's empty, and
3218
- * `defineStatics` puts the statics on Model itself, where scopes look for the names they
3219
- * can't take.
3220
- */
3221
- const ModelStatics = class {};
3222
- /**
3223
- * Defines the statics on `base`: every Relation method, as Rails delegates them to `all`, and
3224
- * a static for each callback kind, which declares a callback of that kind.
3225
- */
3226
- function defineStatics(base) {
3227
- for (const kind of callbackKinds) defineStatic(base, kind, function(callback) {
3228
- declare(this, kind, callback);
3229
- });
3230
- for (const name of [
3231
- ...relationMethods,
3232
- "find",
3233
- "pluck",
3234
- "paginate"
3235
- ]) defineStatic(base, name, function(...args) {
3236
- return this.all()[name](...args);
3237
- });
3238
- }
3239
- /** `method` as the static `name` of `base`, named and described as a class's own static is. */
3240
- function defineStatic(base, name, method) {
3241
- Object.defineProperty(method, "name", { value: name });
3242
- Object.defineProperty(base, name, {
3243
- value: method,
3244
- writable: true,
3245
- configurable: true
3246
- });
3247
- }
3248
- //#endregion
3249
- //#region src/database.ts
3250
- /** The key for a Database's Executor (the current database, #77), for adapters (`/adapter`). */
3251
- const databaseExecutor = Symbol("databaseExecutor");
3252
- /** A per-request handle on a database; every query goes through it. */
3253
- var AnyDatabase = class {
3254
- #executor;
3255
- /** @internal Built by an adapter, through its own `connect`. */
3256
- constructor(executor) {
3257
- this.#executor = executor;
3258
- }
3259
- /** @internal Its Executor. */
3260
- get [databaseExecutor]() {
3261
- return this.#executor;
3262
- }
3263
- /** A request-bound Relation over the Model's records, with its scopes as methods. */
3264
- model(model) {
3265
- return relationFor(this.#executor, model);
3266
- }
3267
- /** Request-bound relations for several models at once: `db.models({ User }).User`. */
3268
- models(models) {
3269
- return Object.fromEntries(Object.entries(models).map(([name, model]) => [name, this.model(model)]));
3270
- }
3271
- /**
3272
- * Runs statements and record statements atomically: all of them are written, or none. Record
3273
- * statements (`user.toSave()`, `post.toDestroy()`) run their validations and before-callbacks
3274
- * first, in order; the first record that's invalid or
3275
- * aborts throws (`RecordInvalid`, `RecordNotSaved`, `RecordNotDestroyed`) and nothing is sent.
3276
- * After the batch, each record takes its saved state and runs its after-callbacks, in order.
3277
- * Resolves to each entry's result: a statement's `{ rowsAffected, rows }`, the record for a
3278
- * record statement.
3279
- */
3280
- async batch(entries) {
3281
- return runBatch(entries, "db.batch() needs its statements and records", [this.#executor]);
3282
- }
3283
- };
3284
- //#endregion
3285
- //#region src/current-database.ts
3286
- /**
3287
- * Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and
3288
- * everything it awaits) use the one on that Model's binding, with its Session and `onQuery`.
3289
- * Usually called once per request, in middleware. Nested calls add to the outer ones.
3290
- *
3291
- * Each call is a scope of its own, even with a Database another request shares. An adapter may
3292
- * hold a connection for the scope (the PostgreSQL adapter does, from a connection string). A nested call with
3293
- * the same Database shares the outer call's scope while that call is running. When `fn` settles,
3294
- * the scope ends, and the adapter lets its connection go once the queries still running on it
3295
- * finish. Work that outlives the scope, such as a `waitUntil` save, gets a connection of its own.
3296
- */
3297
- async function withDatabase(databases, fn) {
3298
- const outer = requestStore();
3299
- const inner = Array.isArray(databases) ? databases : [databases];
3300
- const scopes = new Map(outer?.scopes);
3301
- const opened = [];
3302
- try {
3303
- openScopes(inner, scopes, opened);
3304
- return await runWithStore({
3305
- databases: [.../* @__PURE__ */ new Set([...inner, ...outer?.databases ?? []])],
3306
- scopes
3307
- }, fn);
3308
- } finally {
3309
- await Promise.all(opened.map(({ executor, scope }) => {
3310
- scope.hasEnded = true;
3311
- return executor.closeScope(scope.held);
3312
- }));
3313
- }
3314
- }
3315
- /**
3316
- * Opens a scope for each of `databases` not already in a running one, added to `scopes` and to `opened` as
3317
- * it opens, so the ones opened before a driver throws are still closed.
3318
- */
3319
- function openScopes(databases, scopes, opened) {
3320
- for (const db of databases) {
3321
- const executor = db[databaseExecutor];
3322
- executor.setOrigin("request");
3323
- if (scopes.get(executor)?.hasEnded === false) continue;
3324
- const scope = {
3325
- held: executor.openScope(),
3326
- hasEnded: false
3327
- };
3328
- scopes.set(executor, scope);
3329
- opened.push({
3330
- executor,
3331
- scope
3332
- });
3333
- }
3334
- }
3335
- /**
3336
- * The adapter a statement compiles for. Statements compile when they're built, before their
3337
- * database is found, so this can't wait to find it: the one its Model's schema names, or else
3338
- * the request's database's. A Model with neither can't compile, so it throws `NoDatabase`.
3339
- */
3340
- function adapterFor(named) {
3341
- if (named !== void 0) return named.adapter;
3342
- const [first] = requestStore()?.databases ?? [];
3343
- if (first === void 0) throw noSchemaOrDatabase();
3344
- return first[databaseExecutor].adapter;
3345
- }
3346
- function noSchemaOrDatabase() {
3347
- return new NoDatabase("No database for this query: its Model's base class holds no generated schema, which names its adapter. Wrap the code in withDatabase(db, …), or use db.model(Model)");
3348
- }
3349
- /** The database a query uses now, on the adapter its Model's schema names. */
3350
- function databaseFor(named) {
3351
- return adapterFor(named).databaseFor(named?.binding, requestStore()?.databases ?? []);
3352
- }
3353
- /**
3354
- * One Executor per adapter and binding (from a Model's schema), finding the current database each
3355
- * time a query runs; Models on one binding share it, so their statements can share a batch.
3356
- */
3357
- const executors = /* @__PURE__ */ new Map();
3358
- /** The Executor for queries started from a Model whose schema names `named`. */
3359
- function currentExecutor(named) {
3360
- let byBinding = executors.get(named?.adapter);
3361
- if (byBinding === void 0) executors.set(named?.adapter, byBinding = /* @__PURE__ */ new Map());
3362
- let executor = byBinding.get(named?.binding);
3363
- if (executor === void 0) {
3364
- executor = new CurrentExecutor(() => adapterFor(named), async () => (await databaseFor(named))[databaseExecutor]);
3365
- byBinding.set(named?.binding, executor);
3366
- }
3367
- return executor;
3368
- }
3369
- /** A Relation over all of `model`'s records, on the current database (`Product.all()`). */
3370
- function currentRelation(model) {
3371
- return relationFor(currentExecutor(schemaAdapter(model)), model);
3372
- }
3373
- //#endregion
3374
- //#region src/model.ts
3375
- /**
3376
- * The library's base class, as Rails' `ActiveRecord::Base`: an app's base class extends it, and
3377
- * methods, statics, callbacks and scopes declared there are shared by every Model built on it.
3378
- * It has no table, so it's never used as a Model itself.
3379
- */
3380
- var Model = class extends ModelStatics {
3381
- /**
3382
- * An app-wide query listener, as `connect(env.DB, { onQuery })` is a database's: called for
3383
- * every statement of this Model (and those extending it), whichever database runs it, after
3384
- * the database's own. Holds no request state, so it's safe on a class; a request's ID comes
3385
- * from a database opened for it with `withDatabase` (#78).
3386
- */
3387
- static onQuery;
3388
- /**
3389
- * Attributes whose values listeners and errors show as "[FILTERED]", as Rails'
3390
- * `filter_attributes`: an attribute whose snake_case name holds a string entry (in any
3391
- * case), or matches a RegExp. Rails' defaults; replace them on the app's base class (#83).
3392
- */
3393
- static filterAttributes = defaultFilterAttributes;
3394
- /**
3395
- * Attribute names `toJSON()` leaves out, so `Response.json(record)` can't send them. Exact
3396
- * names; none by default. `attributes()` still has them (#101).
3397
- */
3398
- static hiddenAttributes = [];
3399
- /** An attribute's name as error messages show it: from `humanAttributeNames`, or "Created at". */
3400
- static humanAttributeName(attribute) {
3401
- return humanAttributeName(this, attribute);
3402
- }
3403
- /** Records on a page of `paginate()` when it isn't given `perPage` (#100). */
3404
- static perPage = 25;
3405
- /**
3406
- * The most records on a page of `paginate()`: a larger `perPage`, given or declared, is
3407
- * capped at it, since D1 bills every row read.
3408
- */
3409
- static maxPerPage = 100;
3410
- /**
3411
- * Makes the value of an attribute declared with `generateId: true` that wasn't given: a
3412
- * UUID by default. Override it on the app's base class to choose the app's ids
3413
- * (`static override generateId = uuidv7`); it gets the attribute's name, never the record (#99).
3414
- */
3415
- static generateId(_attribute) {
3416
- return crypto.randomUUID();
3417
- }
3418
- /**
3419
- * A Model whose attributes are declared here, the single source of truth for them (ADR-0007):
3420
- * `class Visit extends Model.define({ path: "string" }) {}`. It's built on the class it's
3421
- * called on, so a Model made with `ApplicationRecord.define({...})` shares the app's base.
3422
- */
3423
- static define(specs) {
3424
- return defineModel(specs, this);
3425
- }
3426
- /**
3427
- * Declares a scope, as Rails' `scope :active, -> { … }`: `static active = this.scope((q) =>
3428
- * q.where({ isActive: true }))`. It's a static (`User.active()`) and a Relation method
3429
- * (`User.where(…).active()`), inherited like any static. Inside it, `q` has every Relation
3430
- * method, but not the Model's other scopes (their types would refer to themselves).
3431
- */
3432
- static scope(body) {
3433
- function scoped(...args) {
3434
- return this.all()[scopeName(this, scoped)](...args);
3435
- }
3436
- scopeBodies.set(scoped, body);
3437
- return scoped;
3438
- }
3439
- /**
3440
- * All of this Model's records, as Rails' `Product.all`: a Relation on the current database
3441
- * (the request's, set with `withDatabase`, or else the binding in its base class's schema).
3442
- */
3443
- static all() {
3444
- return currentRelation(this);
3445
- }
3446
- /**
3447
- * Only the named attributes of untrusted input (a JSON body, `FormData` or
3448
- * `URLSearchParams`), as Rails' `params.permit`:
3449
- * `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is
3450
- * dropped, and each value is cast as assigning it would be.
3451
- */
3452
- static permit(input, ...names) {
3453
- return permitted(this, input, names);
3454
- }
3455
- /**
3456
- * An attribute's conversions, for SQL d1-record doesn't write, as Rails' `type_for_attribute`:
3457
- * `Post.typeForAttribute("publishedAt").serialize(date)` is what `publishedAt` stores a `Date`
3458
- * as, whatever its `storage`; `cast` and `deserialize` go the other way.
3459
- */
3460
- static typeForAttribute(name) {
3461
- return conversionsFor(this, name);
3462
- }
3463
- /** Declares a validation, e.g. `this.validates("email", { presence: true })` in `static {}`. */
3464
- static validates(attribute, options) {
3465
- const validation = {
3466
- attribute,
3467
- options
3468
- };
3469
- if (attributesSettled(this)) checkValidatedNames(this, validation);
3470
- declare(this, "validations", validation);
3471
- }
3472
- /**
3473
- * Error messages in place of the built-in ones, by type (`blank`, or a type of your own), and
3474
- * under `attributes` by attribute and type. A Model's own win over those of the classes it
3475
- * extends, the app's base class's included; a later call's over an earlier one's (#88).
3476
- */
3477
- static errorMessages(messages) {
3478
- declare(this, "errorMessages", messages);
3479
- }
3480
- /**
3481
- * Attribute names as error messages show them, in place of the name made from the attribute
3482
- * ("createdAt" → "Created at"): `{ createdAt: "Signed up" }`. A Model's own win over those of
3483
- * the classes it extends (#88).
3484
- */
3485
- static humanAttributeNames(names) {
3486
- declare(this, "humanAttributeNames", names);
3487
- }
3488
- /** @internal This record's values, lifecycle and Snapshot; only `RecordState` changes them. */
3489
- [state] = new RecordState(this.constructor);
3490
- /** The errors from the last validation run. */
3491
- get errors() {
3492
- return this[state].errors;
3493
- }
3494
- /**
3495
- * A loaded association, synchronously: records for a hasMany, a record or null otherwise.
3496
- * Throws `AssociationNotLoaded` unless it was preloaded with `includes(...)` or already read
3497
- * (and its key hasn't changed since).
3498
- */
3499
- loaded(name) {
3500
- const model = this.constructor;
3501
- associationOf(model, name);
3502
- const cached = this[state].associations.get(name);
3503
- if (cached === void 0) throw new AssociationNotLoaded(`${model.name} record hasn't loaded "${name}"; preload it with includes("${name}"), or read it first`);
3504
- const { value } = cached;
3505
- return Array.isArray(value) ? [...value] : value;
3506
- }
3507
- /** Whether the association is loaded: preloaded or already read, for the key held now. */
3508
- isLoaded(name) {
3509
- associationOf(this.constructor, name);
3510
- return this[state].associations.get(name) !== void 0;
3511
- }
3512
- /**
3513
- * Loads the association again, replacing what's cached, and returns it: Rails'
3514
- * `reload_author`, or `user.posts.reload` for a hasMany.
3515
- */
3516
- async reloadAssociation(name) {
3517
- const { kind } = associationOf(this.constructor, name);
3518
- this[state].resetAssociation(name);
3519
- const read = this[name].call(this);
3520
- return kind === "hasMany" ? await read.toArray() : await read;
3521
- }
3522
- /** Why a callback last refused a save or destroy (`abort(reason)`); never copied into `errors`. */
3523
- get abortReason() {
3524
- return this[state].abortReason;
3525
- }
3526
- /** Runs every validation, filling `errors` from scratch; `true` if there are none. */
3527
- async isValid() {
3528
- return validateRecord(this);
3529
- }
3530
- /** Whether any attribute differs from its value as last loaded or saved. */
3531
- isChanged() {
3532
- return this[state].changedNames().length > 0;
3533
- }
3534
- /** The names of the changed attributes. */
3535
- changed() {
3536
- return this[state].changedNames();
3537
- }
3538
- /** Each changed attribute's value before the change: `{ email: old }`. */
3539
- changedAttributes() {
3540
- return Object.fromEntries(Object.entries(this[state].changes()).map(([name, [before]]) => [name, before]));
3541
- }
3542
- /** Each changed attribute's value before and after: `{ email: [old, new] }`. */
3543
- changes() {
3544
- return this[state].changes();
3545
- }
3546
- /** The changes the last successful save wrote; use it in after-save callbacks. */
3547
- savedChanges() {
3548
- return this[state].savedChanges();
3549
- }
3550
- /** The attribute's value before its unsaved change, as stored (Rails' `attribute_was`). */
3551
- attributeWas(name) {
3552
- return this[state].valueInDatabase(name);
3553
- }
3554
- /**
3555
- * Whether the attribute has an unsaved change, optionally `from` and/or `to` given values
3556
- * (Rails' `attribute_changed?(name, from:, to:)`).
3557
- */
3558
- isAttributeChanged(name, options = {}) {
3559
- return this[state].isAttributeChanged(name, options);
3560
- }
3561
- /** Whether saving now would write a change to the attribute (for before-callbacks). */
3562
- willSaveChangeTo(name, options = {}) {
3563
- return this[state].isAttributeChanged(name, options);
3564
- }
3565
- /** The last save's change to the attribute, `[before, after]`, if it changed (for after-callbacks). */
3566
- savedChangeTo(name) {
3567
- this[state].read(name);
3568
- const change = this[state].savedChanges()[name];
3569
- return change === void 0 ? void 0 : [...change];
3570
- }
3571
- /** Whether the last save changed the attribute, optionally `from` and/or `to` given values. */
3572
- hasSavedChangeTo(name, options = {}) {
3573
- return this[state].hasSavedChangeTo(name, options);
3574
- }
3575
- /** The attribute's value before the last save (its current stored value, if that didn't change it). */
3576
- attributeBeforeLastSave(name) {
3577
- this[state].read(name);
3578
- const change = this[state].savedChanges()[name];
3579
- return change === void 0 ? this[state].valueInDatabase(name) : change[0];
3580
- }
3581
- /** Undoes unsaved changes to these attributes (all of them by default), as Rails' `restore_attributes`. */
3582
- restoreAttributes(names) {
3583
- this[state].restore(names);
3584
- }
3585
- /** Inserts a new record or updates a persisted one; `false` if it's invalid or a callback aborted. */
3586
- async save() {
3587
- return (await saveLifecycle(this)).status === "saved";
3588
- }
3589
- /** Like `save()`, but throws `RecordInvalid` or `RecordNotSaved` instead of returning `false`. */
3590
- async saveOrThrow() {
3591
- const outcome = await saveLifecycle(this);
3592
- if (outcome.status === "invalid") throw new RecordInvalid(this);
3593
- if (outcome.status === "aborted") throw new RecordNotSaved(outcome.reason);
3594
- return true;
3595
- }
3596
- /** Assigns several attributes without saving. */
3597
- assign(attributes) {
3598
- this[state].assign(attributes);
3599
- return this;
3600
- }
3601
- /** `assign` then `save`. */
3602
- async update(attributes) {
3603
- this[state].requireLive("be updated");
3604
- return this.assign(attributes).save();
3605
- }
3606
- /** `assign` then `saveOrThrow`. */
3607
- async updateOrThrow(attributes) {
3608
- this[state].requireLive("be updated");
3609
- return this.assign(attributes).saveOrThrow();
3610
- }
3611
- /**
3612
- * Deletes the row and resolves to this record, now a read-only destroyed snapshot.
3613
- * A row that's already gone still counts. `false` means a `beforeDestroy` callback aborted.
3614
- */
3615
- async destroy() {
3616
- return (await destroyLifecycle(this)).status === "destroyed" ? this : false;
3617
- }
3618
- /**
3619
- * This record's save, for `db.batch([...])`: its validations and callbacks run when the batch
3620
- * runs, and every record in the batch is written atomically.
3621
- */
3622
- toSave() {
3623
- return new RecordStatement(this, "save");
3624
- }
3625
- /** This record's destroy, dependents included, for `db.batch([...])`. */
3626
- toDestroy() {
3627
- return new RecordStatement(this, "destroy");
3628
- }
3629
- /** Like `destroy()`, but throws `RecordNotDestroyed` instead of returning `false`. */
3630
- async destroyOrThrow() {
3631
- const outcome = await destroyLifecycle(this);
3632
- if (outcome.status !== "destroyed") throw new RecordNotDestroyed(outcome.reason);
3633
- return this;
3634
- }
3635
- /** Loads the stored row again, discarding unsaved changes; `RecordNotFound` if it's gone. */
3636
- async reload() {
3637
- await reloadRecord(this);
3638
- return this;
3639
- }
3640
- /** Not yet saved: built, or created but not persisted. */
3641
- isNewRecord() {
3642
- return this[state].isNew;
3643
- }
3644
- /** Backed by a row: loaded, or saved successfully. */
3645
- isPersisted() {
3646
- return this[state].isPersisted;
3647
- }
3648
- /** Deleted by this instance; a read-only snapshot of the row. */
3649
- isDestroyed() {
3650
- return this[state].isDestroyed;
3651
- }
3652
- /** The record's attributes as a plain object of JavaScript values. */
3653
- attributes() {
3654
- return this[state].attributes();
3655
- }
3656
- /** Prints as `Name { attribute: value, … }` in a console, a log or a test failure (#104). */
3657
- [inspectCustom](depth, options, inspect) {
3658
- return inspectRecord(modelOf(this), this[state], {
3659
- depth,
3660
- options,
3661
- inspect
3662
- });
3663
- }
3664
- /**
3665
- * The loaded attributes as JSON-ready values (dates as ISO strings), without the Model's
3666
- * `hiddenAttributes`, for `Response.json(record)`.
3667
- */
3668
- toJSON() {
3669
- const { hiddenAttributes } = modelOf(this);
3670
- return Object.fromEntries(Object.entries(this[state].attributes()).filter(([name]) => !hiddenAttributes.includes(name)).map(([name, value]) => [name, value instanceof Date ? value.toISOString() : value]));
3671
- }
3672
- };
3673
- defineStatics(Model);
3674
- defineGeneratedStatics(Model);
3675
- useModelBase(Model, readyModel);
3676
- /** `Model.define({...})` on `base`: a class with the attributes' accessors, extending `base`. */
3677
- function defineModel(specs, base) {
3678
- const Parent = base;
3679
- class DefinedModel extends Parent {
3680
- static attributeDefinitions = new Map(Object.entries(specs).map(([name, spec]) => [name, define(name, spec)]));
3681
- }
3682
- inferTableNames(DefinedModel);
3683
- defineAttributeAccessors(DefinedModel.prototype, Object.keys(specs));
3684
- return DefinedModel;
3685
- }
3686
- /** A record's Model: its class. */
3687
- function modelOf(record) {
3688
- return record.constructor;
3689
- }
3690
- /** The record's primary key value. */
3691
- function primaryKeyOf(record) {
3692
- return record[state].read(modelOf(record).primaryKey);
3693
- }
3694
- /** Builds a persisted record of `model` from a D1 row. */
3695
- function hydrate(model, row, executor) {
3696
- const record = newRecord(model);
3697
- record[state].belongTo(executor);
3698
- record[state].loadRow(row);
3699
- return record;
3700
- }
3701
- /**
3702
- * A new, unsaved record. Every attribute reads as null until assigned; defaults are
3703
- * evaluated now and count as assigned, and so are the given attributes.
3704
- */
3705
- function buildRecord(model, attributes, executor) {
3706
- const record = newRecord(model);
3707
- record[state].belongTo(executor);
3708
- record[state].build(attributes);
3709
- return record;
3710
- }
3711
- //#endregion
3712
- //#region src/autosave.ts
3713
- /**
3714
- * What saving `owner` autosaves after it: the records built through its hasMany and hasOne
3715
- * associations that are still new, leaving out any already claimed by the write being prepared.
3716
- */
3717
- function autosavesOf(owner, claimed) {
3718
- const model = modelOf(owner);
3719
- return owner[state].autosaves.allBuilt().map(([name, built]) => ({
3720
- association: resolveAssociation(model, name),
3721
- records: built.filter((record) => record[state].isNew && !claimed.has(record))
3722
- })).filter(({ records }) => records.length > 0);
3723
- }
3724
- /** Whether every record's foreign key can be set before anything is written. */
3725
- function ownerKeysKnown(owner, autosaves) {
3726
- return autosaves.every(({ association }) => owner[state].read(association.ownerAttribute) !== null);
3727
- }
3728
- /**
3729
- * Points every autosaved record at its owner. A hasOne's record stays the owner's loaded
3730
- * association under the owner's new key.
3731
- */
3732
- function linkRecords(owner, autosaves) {
3733
- for (const { association, records } of autosaves) {
3734
- const { name, definition, ownerAttribute } = association;
3735
- const value = owner[state].read(ownerAttribute);
3736
- for (const record of records) {
3737
- record[state].writeKey(definition.foreignKey, value, name);
3738
- if (definition.kind === "hasOne") owner[state].associations.set(name, ownerAttribute, record);
3739
- }
3740
- }
3741
- }
3742
- /**
3743
- * The records `owner` was pointed at through belongsTo while they were new. Its foreign keys
3744
- * are linked to them when it's saved, even if they were saved on their own since (Rails links
3745
- * whenever the association was set); the ones still new and unclaimed are saved first.
3746
- */
3747
- function belongsToAutosavesOf(owner) {
3748
- const model = modelOf(owner);
3749
- return owner[state].autosaves.allBelongsTo().map(([name, record]) => ({
3750
- association: resolveAssociation(model, name),
3751
- record
3752
- }));
3753
- }
3754
- /** The records `owner` points at to save before it: new, and not already part of the write. */
3755
- function unsavedBelongsTo(pointedAt, claimed) {
3756
- return pointedAt.map(({ record }) => record).filter((record) => record[state].isNew && !claimed.has(record));
3757
- }
3758
- /** Whether every pointed-at record's key is known before it's written (generated in code). */
3759
- function belongsToKeysKnown(pointedAt) {
3760
- return pointedAt.every(({ association, record }) => record[state].read(association.targetAttribute) !== null);
3761
- }
3762
- /** Points the owner at the records it points at, now that their keys exist, keeping them loaded. */
3763
- function linkBelongsTo(owner, pointedAt) {
3764
- for (const { association, record } of pointedAt) {
3765
- const { name, ownerAttribute, targetAttribute } = association;
3766
- owner[state].pointAt(name, ownerAttribute, record[state].read(targetAttribute), record);
3767
- owner[state].autosaves.setBelongsTo(name, void 0);
3768
- }
3769
- }
3770
- //#endregion
3771
- //#region src/unit-of-work.ts
3772
- /** A prepared write for plain statements: nothing to commit, no callbacks. */
3773
- function statementWrite(statements) {
3774
- return {
3775
- statements,
3776
- commit: () => {},
3777
- after: async () => {}
3778
- };
3779
- }
3780
- /**
3781
- * Sends every write's statements as one atomic batch (or one statement on its own), then
3782
- * commits each write with its own results. Nothing is committed if D1 refuses the batch.
3783
- */
3784
- async function writeAll(executor, writes) {
3785
- const statements = writes.flatMap((write) => write.statements);
3786
- const results = statements.length === 0 ? [] : await executor.write(statements);
3787
- let offset = 0;
3788
- for (const write of writes) {
3789
- write.commit(results.slice(offset, offset + write.statements.length));
3790
- offset += write.statements.length;
3791
- }
3792
- return results;
3793
- }
3794
- /** Runs the after-callbacks of written writes, in order. */
3795
- async function runAfter(writes) {
3796
- for (const write of writes) await write.after();
3797
- }
3798
- //#endregion
3799
- //#region src/dependents.ts
3800
- /**
3801
- * Prepares the owner's `dependent:` strategies, in the contract's order: restrictions first, so
3802
- * a restricted owner touches nothing; then each `destroy` record's own prepared destroy (its
3803
- * callbacks and dependents); then the `deleteAll`/`delete`/`nullify` statements. The caller
3804
- * writes all of it in one batch with the owner's DELETE.
3805
- */
3806
- async function prepareDependents(owner, claimed) {
3807
- const model = modelOf(owner);
3808
- const dependencies = [...associationsOf(model)].filter(([, definition]) => definition.dependent !== void 0).map(([name]) => resolveAssociation(model, name));
3809
- for (const association of dependencies) {
3810
- const reason = await checkRestriction(owner, association);
3811
- if (reason !== void 0) return {
3812
- status: "restricted",
3813
- reason
3814
- };
3815
- }
3816
- const stages = [];
3817
- for (const association of dependencies) stages.push(...await destroyRecords(owner, association, claimed));
3818
- const statements = dependencies.flatMap((association) => statementFor(owner, association));
3819
- return {
3820
- status: "ready",
3821
- writes: () => [...stages.flatMap((stage) => stage()), statementWrite(statements)]
3822
- };
3823
- }
3824
- /** The association's records for this owner (a hasOne's first one only), with its scope. */
3825
- function recordsOf$1(owner, association) {
3826
- const records = association.linkedTo(owner[state].executor, association.keyOf(owner));
3827
- return association.definition.kind === "hasOne" ? association.inOrder(records).limit(1) : records;
3828
- }
3829
- /** Why a restrict strategy refuses the destroy, if it does (Rails' wording). */
3830
- async function checkRestriction(owner, association) {
3831
- const { name, definition } = association;
3832
- const { dependent, kind } = definition;
3833
- if (dependent !== "restrictWithException" && dependent !== "restrictWithError") return void 0;
3834
- if (!await recordsOf$1(owner, association).exists()) return void 0;
3835
- if (dependent === "restrictWithException") throw new DeleteRestriction(`Cannot delete record because of dependent ${name}`);
3836
- const record = humanAttributeName(modelOf(owner), name).toLowerCase();
3837
- return owner.errors[addFailure]("base", {
3838
- type: "restrictDependentDestroy",
3839
- values: { record },
3840
- form: kind === "hasOne" ? "hasOne" : "hasMany"
3841
- });
3842
- }
3843
- /**
3844
- * `destroy`: each record's prepared destroy, callbacks and dependents included. A record that
3845
- * refuses stops the owner's destroy before anything is written.
3846
- */
3847
- async function destroyRecords(owner, association, claimed) {
3848
- if (association.definition.dependent !== "destroy") return [];
3849
- const stages = [];
3850
- for (const record of await recordsOf$1(owner, association).toArray()) {
3851
- const plan = await prepareDestroy(record, claimed);
3852
- if (plan.status !== "ready") throw refusalError(record, plan, "destroy");
3853
- stages.push(...plan.stages);
3854
- }
3855
- return stages;
3856
- }
3857
- /** The statement for `deleteAll`, `delete` or `nullify`, if that's the strategy. */
3858
- function statementFor(owner, association) {
3859
- const { dependent, foreignKey } = association.definition;
3860
- let statement;
3861
- if (dependent === "deleteAll" || dependent === "delete") statement = recordsOf$1(owner, association).toDeleteAll();
3862
- else if (dependent === "nullify") statement = recordsOf$1(owner, association).toUpdateAll({ [foreignKey]: null });
3863
- else return [];
3864
- return [statement[statementParts].query];
3865
- }
3866
- //#endregion
3867
- //#region src/lifecycle.ts
3868
- /**
3869
- * Whether another row already has `value` for `attribute`: a `SELECT 1 … LIMIT 1` through the
3870
- * record's own Database (so its Session), within the scope, leaving out the record's own row.
3871
- */
3872
- async function isTaken(record, attribute, value, { scope = [], caseSensitive = true }) {
3873
- const model = modelOf(record);
3874
- const recordState = record[state];
3875
- const conditions = [caseSensitive ? { [attribute]: value } : sql`lower(${column(attribute)}) = lower(${value})`, ...scope.map((name) => ({ [name]: recordState.read(name) }))];
3876
- if (!recordState.isNew) {
3877
- recordState.requireKey("be checked for uniqueness");
3878
- conditions.push(new Negated({ [model.primaryKey]: recordState.storedKeyValue }));
3879
- }
3880
- const { executor } = recordState;
3881
- const query = compileSelect(executor.dialect, {
3882
- model,
3883
- conditions,
3884
- order: [],
3885
- limit: 1
3886
- }, "1");
3887
- return (await executor.all(query)).length > 0;
3888
- }
3889
- /** Runs the Model's callbacks of `kind` in declaration order, awaiting each. */
3890
- async function runCallbacks(record, kind) {
3891
- for (const callback of declared(modelOf(record), kind)) await callback(record);
3892
- }
3893
- /** Runs callbacks of `kind`; an `abort()` from one sets `abortReason` and returns `false`. */
3894
- async function runAbortableCallbacks(record, kind) {
3895
- try {
3896
- await runCallbacks(record, kind);
3897
- return true;
3898
- } catch (error) {
3899
- if (!(error instanceof CallbackAbort)) throw error;
3900
- record[state].abortReason = error.reason;
3901
- return false;
3902
- }
3903
- }
3904
- /** Whether the record is valid: `isValid()`'s answer. */
3905
- async function validateRecord(record) {
3906
- return await validation(record, /* @__PURE__ */ new Set()) === "valid";
3907
- }
3908
- /**
3909
- * Clears `errors` and `abortReason`, then beforeValidation → validators → afterValidation.
3910
- * An `abort()` in either callback makes the record "aborted" (not valid).
3911
- */
3912
- async function validation(record, claimed) {
3913
- const recordState = record[state];
3914
- recordState.errors[clearErrors]();
3915
- recordState.abortReason = void 0;
3916
- if (!await runAbortableCallbacks(record, "beforeValidation")) return "aborted";
3917
- await runValidations(declared(modelOf(record), "validations"), {
3918
- record,
3919
- read: (attribute) => recordState.read(attribute),
3920
- errors: recordState.errors,
3921
- isTaken: (attribute, value, options) => isTaken(record, attribute, value, options)
3922
- });
3923
- await validateAutosaves(record, claimed);
3924
- if (!await runAbortableCallbacks(record, "afterValidation")) return "aborted";
3925
- return recordState.errors.isEmpty() ? "valid" : "invalid";
3926
- }
3927
- /** The error a refused save or destroy throws where there's no `false` to return. */
3928
- function refusalError(record, plan, kind) {
3929
- if (plan.status === "invalid") return new RecordInvalid(record);
3930
- return kind === "save" ? new RecordNotSaved(plan.reason) : new RecordNotDestroyed(plan.reason);
3931
- }
3932
- function aborted(record) {
3933
- return {
3934
- status: "aborted",
3935
- reason: record[state].abortReason ?? ""
3936
- };
3937
- }
3938
- /**
3939
- * New records built through the record's hasMany associations are validated with it, one
3940
- * after another, as Rails' `validate: true` does: an invalid one adds "is invalid" to the
3941
- * association's name.
3942
- */
3943
- async function validateAutosaves(record, claimed) {
3944
- for (const { association, record: pointedAt } of belongsToAutosavesOf(record)) {
3945
- const { name } = association;
3946
- if (!pointedAt[state].isNew || claimed.has(pointedAt)) continue;
3947
- if (await validation(pointedAt, claimed) !== "valid") record[state].errors.add(name, { type: "invalid" });
3948
- }
3949
- for (const { association, records } of autosavesOf(record, claimed)) {
3950
- const { name } = association;
3951
- let valid = true;
3952
- for (const each of records) if (await validation(each, claimed) !== "valid") valid = false;
3953
- if (!valid) record[state].errors.add(name, { type: "invalid" });
3954
- }
3955
- }
3956
- /**
3957
- * The save lifecycle, in the contract's order:
3958
- * can this record be used → beforeValidation → validators → afterValidation
3959
- * → beforeSave → beforeCreate | beforeUpdate → write (skipped when clean) → commit state
3960
- * → afterCreate | afterUpdate → afterSave.
3961
- */
3962
- async function saveLifecycle(record) {
3963
- const database = await pinBefore(linksOf(recordsSaving(record)), "save() needs its records");
3964
- const claimed = /* @__PURE__ */ new Set();
3965
- const plan = await prepareSave(record, claimed);
3966
- if (plan.status !== "ready") return plan;
3967
- await pinClaimed(linksOf(claimed), database, "save() needs its records");
3968
- await runPlan(database, plan);
3969
- return { status: "saved" };
3970
- }
3971
- /**
3972
- * The records saving `record` would write: it, the new records it points at through belongsTo,
3973
- * and the new records built through its associations, at every level. Found without running
3974
- * any validation or callback, so a save can be checked before anything runs (#93).
3975
- */
3976
- function recordsSaving(record) {
3977
- const found = /* @__PURE__ */ new Set();
3978
- const visit = (each) => {
3979
- if (found.has(each)) return;
3980
- found.add(each);
3981
- for (const { record: target } of belongsToAutosavesOf(each)) if (target[state].isNew) visit(target);
3982
- for (const { records } of autosavesOf(each, found)) records.forEach(visit);
3983
- };
3984
- visit(record);
3985
- return [...found];
3986
- }
3987
- /** Everything a save does before writing: validation and the before-callbacks. */
3988
- async function prepareSave(record, claimed) {
3989
- if (claimed.has(record)) return {
3990
- status: "ready",
3991
- stages: []
3992
- };
3993
- record[state].requireLive("be saved");
3994
- const validity = await validation(record, claimed);
3995
- if (validity === "invalid") return { status: "invalid" };
3996
- if (validity === "aborted") return aborted(record);
3997
- return prepareWrites(record, claimed);
3998
- }
3999
- /**
4000
- * A validated record's before-callbacks and writes, then its autosaved records' (and theirs,
4001
- * at every level). If the owner's key is known, its records join its batch; if D1 generates
4002
- * it, they follow in the next one, once the owner is written.
4003
- */
4004
- async function prepareWrites(record, claimed) {
4005
- claimed.add(record);
4006
- const pointedAt = belongsToAutosavesOf(record);
4007
- const firstPlans = await prepareEach(unsavedBelongsTo(pointedAt, claimed), claimed);
4008
- if (!Array.isArray(firstPlans)) return firstPlans;
4009
- const isInsert = record[state].isNew;
4010
- if (!await beforeWrite(record, isInsert)) return aborted(record);
4011
- const own = () => {
4012
- linkBelongsTo(record, pointedAt);
4013
- return [saveWrite(record, isInsert)];
4014
- };
4015
- const autosaves = autosavesOf(record, claimed);
4016
- const childPlans = await prepareEach(autosaves.flatMap(({ records }) => records), claimed);
4017
- if (!Array.isArray(childPlans)) return childPlans;
4018
- const stages = withChildren(record, own, autosaves, childPlans);
4019
- if (firstPlans.length === 0) return {
4020
- status: "ready",
4021
- stages
4022
- };
4023
- const first = combine(firstPlans.map((plan) => plan.stages));
4024
- return {
4025
- status: "ready",
4026
- stages: belongsToKeysKnown(pointedAt) ? combine([first, stages]) : [...first, ...stages]
4027
- };
4028
- }
4029
- /** Each record's prepared writes, in order; the first refusal stops them. */
4030
- async function prepareEach(records, claimed) {
4031
- const plans = [];
4032
- for (const each of records) {
4033
- const plan = await prepareWrites(each, claimed);
4034
- if (plan.status !== "ready") return plan;
4035
- plans.push(plan);
4036
- }
4037
- return plans;
4038
- }
4039
- /**
4040
- * The owner's stage with its autosaved records': in the same batch when the owner's key is
4041
- * known, else in the next one. The records are linked to the owner just before their first
4042
- * stage builds its statements.
4043
- */
4044
- function withChildren(owner, own, autosaves, plans) {
4045
- if (plans.length === 0) return [own];
4046
- const [first, ...rest] = combine(plans.map(({ stages }) => stages));
4047
- const linked = [() => (linkRecords(owner, autosaves), first()), ...rest];
4048
- return ownerKeysKnown(owner, autosaves) ? combine([[own], linked]) : [own, ...linked];
4049
- }
4050
- /** Stage lists merged position by position: every plan's first stage in one batch, and so on. */
4051
- function combine(stageLists) {
4052
- const length = Math.max(...stageLists.map((stages) => stages.length));
4053
- return Array.from({ length }, (_, index) => () => stageLists.flatMap((stages) => stages[index]?.() ?? []));
4054
- }
4055
- /**
4056
- * Writes a plan's stages one after another, each as one atomic batch, then runs the written
4057
- * writes' after-callbacks in order. If a later stage fails, the earlier ones stay written, so
4058
- * their after-callbacks still run before the error is thrown.
4059
- */
4060
- async function runPlan(executor, plan) {
4061
- const written = [];
4062
- let failure;
4063
- try {
4064
- for (const stage of plan.stages) {
4065
- const writes = stage();
4066
- await writeAll(executor, writes);
4067
- written.push(...writes);
4068
- }
4069
- } catch (error) {
4070
- failure = { error };
4071
- }
4072
- await runAfter(written);
4073
- if (failure !== void 0) throw failure.error;
4074
- }
4075
- /**
4076
- * Runs after-write callbacks. The write already succeeded, so an `abort()` here can't refuse
4077
- * anything: it becomes `AbortAfterPersistence`. Any other error propagates unchanged.
4078
- */
4079
- async function runAfterCallbacks(record, kind, lifecycle) {
4080
- try {
4081
- await runCallbacks(record, kind);
4082
- } catch (error) {
4083
- if (error instanceof CallbackAbort) throw new AbortAfterPersistence(kind, lifecycle, error);
4084
- throw error;
4085
- }
4086
- }
4087
- /** beforeSave, then beforeCreate or beforeUpdate; `false` if one aborted. */
4088
- async function beforeWrite(record, isInsert) {
4089
- return await runAbortableCallbacks(record, "beforeSave") && await runAbortableCallbacks(record, isInsert ? "beforeCreate" : "beforeUpdate");
4090
- }
4091
- /**
4092
- * A save's write: INSERT the assigned attributes (`RETURNING *` loads what D1 stored), or
4093
- * UPDATE the changed ones, plus timestamps; a clean record sends nothing. Its after-callbacks
4094
- * are afterCreate or afterUpdate, then afterSave.
4095
- */
4096
- function saveWrite(record, isInsert) {
4097
- const recordState = record[state];
4098
- const model = modelOf(record);
4099
- const after = async () => {
4100
- await runAfterCallbacks(record, isInsert ? "afterCreate" : "afterUpdate", "save");
4101
- await runAfterCallbacks(record, "afterSave", "save");
4102
- };
4103
- if (isInsert) {
4104
- const own = recordState.insertAssignments();
4105
- return {
4106
- statements: [compileInsert(model, [...own, ...timestampsFor(model, "insert", own)])],
4107
- commit: ([result]) => recordState.commitInsert(result?.rows[0]),
4108
- after
4109
- };
4110
- }
4111
- const own = recordState.updateAssignments();
4112
- if (own.length === 0) return {
4113
- statements: [],
4114
- commit: () => recordState.commitClean(),
4115
- after
4116
- };
4117
- const stamps = timestampsFor(model, "update", own);
4118
- return {
4119
- statements: [compileUpdate(model, [...own, ...stamps], recordState.storedKey)],
4120
- commit: () => recordState.commitUpdate(stamps),
4121
- after
4122
- };
4123
- }
4124
- /**
4125
- * The destroy lifecycle: can this record be used → beforeDestroy → its `dependent:` strategies
4126
- * → DELETE by the stored key (skipped for a never-saved record: there's no row, as in Rails)
4127
- * → mark destroyed → afterDestroy. Every write, dependents' included, is one atomic batch.
4128
- */
4129
- async function destroyLifecycle(record) {
4130
- const database = await pinBefore(linksOf([record]), "destroy() needs its records");
4131
- const claimed = /* @__PURE__ */ new Set();
4132
- const plan = await prepareDestroy(record, claimed);
4133
- if (plan.status !== "ready") return plan;
4134
- await pinClaimed(linksOf(claimed), database, "destroy() needs its records");
4135
- await runPlan(database, plan);
4136
- return { status: "destroyed" };
4137
- }
4138
- /** Everything a destroy does before writing: beforeDestroy, then its dependents' plans. */
4139
- async function prepareDestroy(record, claimed) {
4140
- if (claimed.has(record)) return {
4141
- status: "ready",
4142
- stages: []
4143
- };
4144
- claimed.add(record);
4145
- const recordState = record[state];
4146
- recordState.requireLive("be destroyed");
4147
- recordState.abortReason = void 0;
4148
- if (!await runAbortableCallbacks(record, "beforeDestroy")) return aborted(record);
4149
- const dependents = recordState.isNew ? {
4150
- status: "ready",
4151
- writes: () => []
4152
- } : await prepareDependents(record, claimed);
4153
- if (dependents.status !== "ready") return dependents;
4154
- const deletion = recordState.isNew ? [] : [compileDelete(modelOf(record), recordState.storedKey)];
4155
- const stage = () => [...dependents.writes(), {
4156
- statements: deletion,
4157
- commit: () => recordState.markDestroyed(),
4158
- after: () => runAfterCallbacks(record, "afterDestroy", "destroy")
4159
- }];
4160
- return {
4161
- status: "ready",
4162
- stages: [stage]
4163
- };
4164
- }
4165
- /** Loads the record's row again by its stored primary key, discarding unsaved changes. */
4166
- async function reloadRecord(record) {
4167
- const recordState = record[state];
4168
- recordState.requireLive("be reloaded");
4169
- const { executor } = recordState;
4170
- const model = modelOf(record);
4171
- if (recordState.isNew) throw new RecordNotFound(`${model.name} record hasn't been saved, so there's nothing to reload`);
4172
- const key = recordState.storedKeyValue;
4173
- const query = {
4174
- model,
4175
- conditions: [{ [model.primaryKey]: key }],
4176
- order: [],
4177
- limit: 1
4178
- };
4179
- const [row] = await executor.all(compileSelect(executor.dialect, query));
4180
- if (row === void 0) throw new RecordNotFound(`${model.name} with ${model.primaryKey} ${shownKey(model, key)} not found`);
4181
- recordState.clearAssociations();
4182
- recordState.loadRow(row);
4183
- }
4184
- //#endregion
4185
- //#region src/batch.ts
4186
- /** The Executor an entry was built on: its Relation's, or its record's. */
4187
- function executorOf(entry) {
4188
- return entry instanceof RecordStatement ? entry[recordStatementParts].record[state].executor : entry[statementParts].executor;
4189
- }
4190
- /** The records a batch entry writes: a save's whole autosave graph, or a destroy's record. */
4191
- function recordsOf(entry) {
4192
- if (!(entry instanceof RecordStatement)) return [];
4193
- const { record, kind } = entry[recordStatementParts];
4194
- return kind === "save" ? recordsSaving(record) : [record];
4195
- }
4196
- /**
4197
- * A batch's steps: its one database found and every record pinned to it, before anything runs
4198
- * (#93); then before-callbacks, one atomic write, then after-callbacks. Records a callback added
4199
- * on the way are pinned too, before the write.
4200
- */
4201
- async function runBatch(entries, needs, handles = []) {
4202
- const statements = entries.filter((entry) => !(entry instanceof RecordStatement));
4203
- const all = [...handles, ...statements.map(executorOf)];
4204
- const records = entries.flatMap(recordsOf);
4205
- if (all.length === 0 && records.length === 0) return [];
4206
- const database = await pinBefore(linksOf(records), needs, all);
4207
- const claimed = /* @__PURE__ */ new Set();
4208
- const prepared = [];
4209
- for (const entry of entries) prepared.push(entry instanceof RecordStatement ? await recordEntry(entry, claimed) : statementEntry(entry));
4210
- await pinClaimed(linksOf(claimed), database, needs);
4211
- const writes = prepared.flatMap(({ writes }) => writes());
4212
- await writeAll(database, writes);
4213
- await runAfter(writes);
4214
- return prepared.map(({ result }) => result());
4215
- }
4216
- /**
4217
- * `db.batch`, on the database the entries were built on: the current one, for statements and
4218
- * records from a Model's statics (`Product.toUpdateAll(…)`, `Product.build(…).toSave()`), or one
4219
- * explicit `db`. Atomic, as `db.batch` is; entries from two databases throw `IncompatibleRelation`.
4220
- */
4221
- async function batch(entries) {
4222
- return runBatch(entries, "batch() needs its statements and records");
4223
- }
4224
- function statementEntry(statement) {
4225
- let written;
4226
- const { query, landed, resultOf } = statement[statementParts];
4227
- const write = {
4228
- statements: [query],
4229
- commit: ([result]) => {
4230
- if (result !== void 0) written = resultOf(result);
4231
- landed();
4232
- },
4233
- after: async () => {}
4234
- };
4235
- return {
4236
- writes: () => [write],
4237
- result: () => written
4238
- };
4239
- }
4240
- /** A record's prepared save or destroy; a refusal throws, as a Rails transaction's `save!` does. */
4241
- async function recordEntry(statement, claimed) {
4242
- const { record, kind } = statement[recordStatementParts];
4243
- const plan = await (kind === "save" ? prepareSave(record, claimed) : prepareDestroy(record, claimed));
4244
- if (plan.status !== "ready") throw refusalError(record, plan, kind);
4245
- if (plan.stages.length > 1) {
4246
- const { name } = record.constructor;
4247
- throw new RecordNotSaved(`${name} can't be saved in a batch with the new records it autosaves: one of them needs a key D1 only generates when a record is written (the ${name}'s, or a new record it points at). Generate keys in code, or save it on its own`);
4248
- }
4249
- return {
4250
- writes: () => plan.stages.flatMap((stage) => stage()),
4251
- result: () => record
4252
- };
4253
- }
4254
- //#endregion
4255
- export { hasMany as _, databaseExecutor as a, valueMark as c, between as d, gt as f, belongsTo as g, lte as h, AnyDatabase as i, column as l, lt as m, Model as n, Relation as o, gte as p, withDatabase as r, DatabaseExecutor as s, batch as t, sql as u, hasOne as v };