@forestfuture/active-record 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -231,6 +231,11 @@ interface SpecObject {
231
231
  * `regenerate…()` (#355): `true`, or its options. Only a string has one.
232
232
  */
233
233
  secureToken?: boolean | SecureTokenOptions;
234
+ /**
235
+ * Written when a record is created, and refused once it's persisted (#358): assigning it a value
236
+ * other than the one it holds throws `ReadonlyAttribute`.
237
+ */
238
+ readonly?: boolean;
234
239
  }
235
240
  /** How an enum's value is validated: `true`, or `{ allowNull: true }` to let it be null. */
236
241
  type EnumValidation = boolean | {
@@ -262,6 +267,14 @@ type NoDigits = {
262
267
  type NoToken = {
263
268
  secureToken?: never;
264
269
  };
270
+ /** A string's secure token, which `regenerate…()` changes, so it's never read-only (#358). */
271
+ type TokenOrReadonly = {
272
+ secureToken?: boolean | SecureTokenOptions;
273
+ readonly?: false;
274
+ } | {
275
+ secureToken?: false;
276
+ readonly: true;
277
+ };
265
278
  /** The spec's keys that only some types have, each written by the type's own branch below. */
266
279
  type PerTypeKeys = "type" | "generateId" | "storage" | "enum" | "precision" | "scale" | "secureToken";
267
280
  type AttributeSpec = AttributeType | AnyCustomType | (SpecObjectByType & Placement);
@@ -271,14 +284,14 @@ type Placement = {
271
284
  } | {
272
285
  virtual: true;
273
286
  column?: never;
287
+ readonly?: never;
274
288
  };
275
289
  /** A spec written out, by its type: the keys each type may have. */
276
290
  type SpecObjectByType = (Omit<SpecObject, "default" | PerTypeKeys> & {
277
291
  type: "string";
278
292
  storage?: never;
279
293
  enum?: TextEnum;
280
- secureToken?: boolean | SecureTokenOptions;
281
- } & ValueSource & NoDigits) | (Omit<SpecObject, PerTypeKeys> & NoDigits & NoToken & {
294
+ } & TokenOrReadonly & ValueSource & NoDigits) | (Omit<SpecObject, PerTypeKeys> & NoDigits & NoToken & {
282
295
  type: "integer";
283
296
  generateId?: false;
284
297
  storage?: never;
@@ -342,6 +355,8 @@ interface AttributeDefinition {
342
355
  securePassword?: true | SecurePasswordOptions;
343
356
  /** A secure token, generated for a new record (#355). */
344
357
  secureToken?: true | SecureTokenOptions;
358
+ /** Written on create, and not changed once persisted (#358). */
359
+ readonly?: true;
345
360
  }
346
361
  /** The JavaScript value an attribute of a built-in type holds: a `Date` for a `datetime`. */
347
362
  type BuiltInValue<T extends AttributeType> = T extends "string" ? string : T extends "integer" | "real" ? number : T extends "boolean" ? boolean : T extends "datetime" ? Date : T extends "binary" ? Uint8Array : T extends "decimal" | "date" | "time" ? string : unknown;
@@ -1,6 +1,6 @@
1
- import { i as attributeName, n as castDefault, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-yF2NT5ST.mjs";
2
- import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-D35a5x3t.mjs";
3
- import { D as underscore } from "./identifiers-CzqYL_nC.mjs";
1
+ import { i as attributeName, n as castDefault, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-BDgUIPQu.mjs";
2
+ import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-DvtC7L8N.mjs";
3
+ import { V as underscore } from "./identifiers-DRLEguFD.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
@@ -1,6 +1,6 @@
1
- import { i as attributeName, n as castDefault, p as byVersion, r as isCastDefaultType, u as parseJsonc } from "./storage-override-yF2NT5ST.mjs";
2
- import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, t as generatedSchema } from "./for-adapters-D35a5x3t.mjs";
3
- import { D as underscore } from "./identifiers-CzqYL_nC.mjs";
1
+ import { i as attributeName, n as castDefault, p as byVersion, r as isCastDefaultType, u as parseJsonc } from "./storage-override-BDgUIPQu.mjs";
2
+ import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, t as generatedSchema } from "./for-adapters-DvtC7L8N.mjs";
3
+ import { V as underscore } from "./identifiers-DRLEguFD.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { existsSync, readFileSync, readdirSync } from "node:fs";
6
6
  import { basename, dirname, join } from "node:path";
@@ -1,4 +1,4 @@
1
- import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-CKPJoSj4.mjs";
1
+ import { O as SchemaAdapter, S as CacheOptions, T as QueryListener$1, k as AnyDatabase, w as QueryEvent$1 } from "./validations-BUn_5T-8.mjs";
2
2
  import pg from "pg";
3
3
  /** The Postgres database a generated schema's Models query: `adapter: postgresql({ binding: "HYPERDRIVE" })`. */
4
4
  export declare function postgresql({ binding }: {
@@ -49,6 +49,11 @@ type QueryListener = QueryListener$1<PostgreSQLMeta>;
49
49
  interface ConnectOptions {
50
50
  /** Called once for every statement sent to Postgres, with Postgres's `meta`. */
51
51
  onQuery?: QueryListener;
52
+ /**
53
+ * Inside a `withDatabase` call, a read identical to one already sent there is answered from
54
+ * memory, until a write; `cache: { request: false }` turns that off.
55
+ */
56
+ cache?: CacheOptions;
52
57
  }
53
58
  /** Where a Database's Postgres is: a Hyperdrive binding (`env.HYPERDRIVE`), a connection string, or a `pg` Pool. */
54
59
  type PostgreSQLSource = Hyperdrive | string | Pool;
@@ -1,7 +1,7 @@
1
- import { a as databaseExecutor, i as AnyDatabase, l as workersEnv, u as DatabaseExecutor } from "./batch-Ca1JtVcK.mjs";
2
- import { t as onlyRequested } from "./for-adapters-Bl6BCiR1.mjs";
3
- import { V as NoDatabase } from "./identifiers-CzqYL_nC.mjs";
4
- import { w as boundValue } from "./generated-model-L4WAqgOZ.mjs";
1
+ import { a as databaseExecutor, i as AnyDatabase, l as workersEnv, u as DatabaseExecutor } from "./batch-vRCbt-jV.mjs";
2
+ import { t as onlyRequested } from "./for-adapters-CIUvPeas.mjs";
3
+ import { tt as NoDatabase } from "./identifiers-DRLEguFD.mjs";
4
+ import { w as boundValue } from "./generated-model-DiQb9_3C.mjs";
5
5
  import pg from "pg";
6
6
  // src/adapters/postgresql/connect-timeout.ts
7
7
  /** The limit when the connection string sets none, in milliseconds. */
@@ -558,6 +558,11 @@ const pgAdapter = {
558
558
  model: write.model
559
559
  }];
560
560
  },
561
+ /** `json` has no equality operator, so a json attribute's values are compared as text. */
562
+ sameValue(left, right, { isJson }) {
563
+ if (isJson) return `CAST(${left} AS TEXT) IS NOT DISTINCT FROM CAST(${right} AS TEXT)`;
564
+ return `${left} IS NOT DISTINCT FROM ${right}`;
565
+ },
561
566
  /**
562
567
  * The removal returns a row for each row it removed, which the counters' UPDATEs count, and the
563
568
  * statement selects how many as `removed`: a COUNT sent before it could miss a row another
@@ -611,7 +616,8 @@ function clientsFor(source) {
611
616
  var Database = class extends AnyDatabase {
612
617
  #connectionString;
613
618
  constructor(source, options = {}) {
614
- super(new DatabaseExecutor(pgAdapter, new PgDriver(clientsFor(source)), options.onQuery));
619
+ const { onQuery, cache } = options;
620
+ super(new DatabaseExecutor(pgAdapter, new PgDriver(clientsFor(source)), onQuery, cache));
615
621
  this.#connectionString = connectionStringOf(source) ?? source.options?.connectionString;
616
622
  }
617
623
  /**
@@ -1,5 +1,5 @@
1
- import { n as Model, o as readyModel, s as isReservedScopeName } from "./batch-Ca1JtVcK.mjs";
2
- import { Mt as staticBelow, Tt as ownValueSetter, jt as ancestors, wt as modelNameOf } from "./generated-model-L4WAqgOZ.mjs";
1
+ import { n as Model, o as readyModel, s as isReservedScopeName } from "./batch-vRCbt-jV.mjs";
2
+ import { Mt as staticBelow, Tt as ownValueSetter, jt as ancestors, wt as modelNameOf } from "./generated-model-DiQb9_3C.mjs";
3
3
  // src/define-schema.ts
4
4
  const listed = /* @__PURE__ */ new Set();
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { D as underscore, T as camelize, c as castValue, d as uncastable, n as reservedWords, r as epochStorages } from "./identifiers-CzqYL_nC.mjs";
1
+ import { V as underscore, c as castValue, d as uncastable, n as reservedWords, r as epochStorages, z as camelize } from "./identifiers-DRLEguFD.mjs";
2
2
  import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  // cli/project/paths.ts
@@ -1,4 +1,4 @@
1
- import { D as Duration, M as AttributeAlias, N as DefinedSpecs, O as AnyCustomType, P as WithoutAliases, S as SecurePasswordMethods, T as WithSecurePasswords, _ as SecureTokenOptions, a as AttributeType, b as PasswordResetTokenArgument, c as SpecObject, d as EnumMapping, f as EnumNames, g as SecureTokenMethods, h as TextEnum, i as AttributeSpecs, j as AliasSpecs, k as CustomType, l as ValueSource, m as IntegerEnum, n as AttributeProperties, o as DeclaredAttributes, p as EnumValues, s as ExactSpecs, t as AttributeDefinition, w as SecurePasswordSpecs, x as SecurePasswordDeclaration, y as AuthenticateByAttributes } from "./metadata-BIUbGJlS.mjs";
1
+ import { D as Duration, M as AttributeAlias, N as DefinedSpecs, O as AnyCustomType, P as WithoutAliases, S as SecurePasswordMethods, T as WithSecurePasswords, _ as SecureTokenOptions, a as AttributeType, b as PasswordResetTokenArgument, c as SpecObject, d as EnumMapping, f as EnumNames, g as SecureTokenMethods, h as TextEnum, i as AttributeSpecs, j as AliasSpecs, k as CustomType, l as ValueSource, m as IntegerEnum, n as AttributeProperties, o as DeclaredAttributes, p as EnumValues, s as ExactSpecs, t as AttributeDefinition, w as SecurePasswordSpecs, x as SecurePasswordDeclaration, y as AuthenticateByAttributes } from "./metadata-nKZ_6DzA.mjs";
2
2
  /** What `comparison` compares: numbers with numbers, strings with strings, Dates by their time. */
3
3
  type Comparable = number | string | Date;
4
4
  /** A bound: a value, or a function of the record being validated (`(event) => event.startsAt`). */
@@ -42,40 +42,6 @@ type ScopeStems<A> = { [K in keyof A]: A[K] extends {
42
42
  type EnumMethods<A> = { [P in `is${RecordStems<A>}`]: () => boolean; } & { [P in `saveAs${RecordStems<A>}`]: () => Promise<boolean>; } & { [P in `saveAs${RecordStems<A>}OrThrow`]: () => Promise<true>; };
43
43
  /** What the enums of the specs `A` add to a Model: a scope for each name, and a `not…` scope. */
44
44
  type EnumStatics<A> = { [P in Uncapitalize<ScopeStems<A>> | `not${ScopeStems<A>}`]: ScopeStatic<[]>; };
45
- /**
46
- * A SQL fragment built with the `sql` tagged template (ADR-0006). The template
47
- * text is written by the developer; every interpolated value is bound as a
48
- * parameter and never becomes SQL text.
49
- */
50
- declare class SafeSql {
51
- readonly strings: readonly string[];
52
- readonly values: readonly unknown[];
53
- }
54
- declare function sql$1(strings: TemplateStringsArray, ...values: unknown[]): SafeSql;
55
- /** A reference to an attribute's column, resolved against the query's Model when compiled. */
56
- declare class ColumnReference {
57
- readonly attribute: string;
58
- /**
59
- * A value of this attribute for a fragment, converted as the attribute stores it: a `Date`
60
- * as the integer of an attribute kept as a Unix time, a boolean as 0 or 1, and so on. It's
61
- * still a bound parameter. Without it, a value has no attribute to say how it's stored (#142).
62
- */
63
- value(value: unknown): ColumnValue;
64
- }
65
- /** A value of an attribute, from `column(attribute).value(value)`, converted when compiled. */
66
- declare class ColumnValue {
67
- readonly attribute: string;
68
- /** What was given, before it's cast as an assigned value of the attribute. */
69
- readonly assigned: unknown;
70
- }
71
- /** Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004). */
72
- declare function column(attribute: string): ColumnReference;
73
- type OrderDirection = "asc" | "desc";
74
- type NullsPlacement = "first" | "last";
75
- /** A part of a query `unscope()` drops: one by name, or the conditions on some attributes. */
76
- type UnscopedPart = "where" | "order" | "limit" | "offset" | "select" | "distinct" | "includes" | "joins" | "leftJoins" | "createWith" | {
77
- readonly where: readonly string[];
78
- };
79
45
  /**
80
46
  * One attribute's value path, resolved once per Model class by `attributeFor` (#163). Which
81
47
  * Model and attribute a refusal names, whether the attribute is filtered, and how its type is
@@ -161,6 +127,52 @@ declare class Attribute {
161
127
  */
162
128
  bindCells(params: unknown[], ...cells: unknown[]): void;
163
129
  }
130
+ /**
131
+ * A SQL fragment built with the `sql` tagged template (ADR-0006). The template
132
+ * text is written by the developer; every interpolated value is bound as a
133
+ * parameter and never becomes SQL text.
134
+ */
135
+ declare class SafeSql {
136
+ readonly strings: readonly string[];
137
+ readonly values: readonly unknown[];
138
+ }
139
+ declare function sql$1(strings: TemplateStringsArray, ...values: unknown[]): SafeSql;
140
+ /** A reference to an attribute's column, resolved against the query's Model when compiled. */
141
+ declare class ColumnReference {
142
+ readonly attribute: string;
143
+ /**
144
+ * A value of this attribute for a fragment, converted as the attribute stores it: a `Date`
145
+ * as the integer of an attribute kept as a Unix time, a boolean as 0 or 1, and so on. It's
146
+ * still a bound parameter. Without it, a value has no attribute to say how it's stored (#142).
147
+ */
148
+ value(value: unknown): ColumnValue;
149
+ }
150
+ /** A value of an attribute, from `column(attribute).value(value)`, converted when compiled. */
151
+ declare class ColumnValue {
152
+ readonly attribute: string;
153
+ /** What was given, before it's cast as an assigned value of the attribute. */
154
+ readonly assigned: unknown;
155
+ }
156
+ /**
157
+ * The value a row an upsert writes has for an attribute, in its `onDuplicate` (#531): what the
158
+ * row that clashed would have been given.
159
+ */
160
+ declare class IncomingReference {
161
+ readonly attribute: string;
162
+ }
163
+ /** Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004). */
164
+ declare function column(attribute: string): ColumnReference;
165
+ /**
166
+ * Names, inside an upsert's `onDuplicate` fragment, the value the row being written has for
167
+ * `attribute`, where `column(attribute)` names the clashing row's (#531).
168
+ */
169
+ declare function incoming(attribute: string): IncomingReference;
170
+ type OrderDirection = "asc" | "desc";
171
+ type NullsPlacement = "first" | "last";
172
+ /** A part of a query `unscope()` drops: one by name, or the conditions on some attributes. */
173
+ type UnscopedPart = "where" | "order" | "limit" | "offset" | "select" | "distinct" | "includes" | "joins" | "leftJoins" | "createWith" | {
174
+ readonly where: readonly string[];
175
+ };
164
176
  /**
165
177
  * Where compiled SQL binds a value, in its own order. A dialect writes each as its database's
166
178
  * placeholder once the SQL is complete, so a `?` in a raw `sql` fragment's text (Postgres's jsonb
@@ -214,6 +226,12 @@ interface Dialect {
214
226
  * result first.
215
227
  */
216
228
  staleGuard(write: CompiledSql, marker: string): CompiledSql[];
229
+ /**
230
+ * Whether `left` and `right` (SQL, of `attribute`) hold the same value, NULL the same as NULL:
231
+ * `IS NOT DISTINCT FROM` without it. An upsert keeps a clashing row's `updatedAt` when it
232
+ * is (#36).
233
+ */
234
+ sameValue?(left: string, right: string, attribute: Attribute): string;
217
235
  /**
218
236
  * A bulk removal (a DELETE, or an UPDATE nullifying a key) and the counter caches it changes
219
237
  * (#61), as one statement: `decrements` writes the counters' UPDATEs, given SQL counting the rows
@@ -260,6 +278,58 @@ interface InOrderOfOptions {
260
278
  /** Keep only the records whose value is in the list (the default); `false` keeps every one, those not in it last. */
261
279
  filter?: boolean;
262
280
  }
281
+ /** What a signed id is for, and how long it lasts: forever unless given. */
282
+ interface SignedIdOptions {
283
+ /** How long it lasts: `{ minutes: 15 }`. Give this or `expiresAt`. */
284
+ readonly expiresIn?: Duration;
285
+ /** When it stops finding its record. */
286
+ readonly expiresAt?: Date;
287
+ /** What it's for (`"login"`): `findSigned` finds its record only given the same. */
288
+ readonly purpose?: string;
289
+ }
290
+ /** What `findSigned` takes: the purpose the signed id was made for. */
291
+ interface FindSignedOptions {
292
+ readonly purpose?: string;
293
+ }
294
+ /** The finders by token every Relation has. */
295
+ declare abstract class TokenFinders<M extends Model> {
296
+ #private;
297
+ abstract findBy(conditions: never): Promise<M | null>;
298
+ /**
299
+ * The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for
300
+ * the same `purpose` and it hasn't expired, and this Relation matches it; or null.
301
+ */
302
+ findSigned(signedId: unknown, options?: FindSignedOptions): Promise<M | null>;
303
+ /** Like `findSigned`, but throws `InvalidToken` for a signed id that isn't valid, and `RecordNotFound` when its record is gone. */
304
+ findSignedOrThrow(signedId: unknown, options?: FindSignedOptions): Promise<M>;
305
+ /**
306
+ * The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this
307
+ * Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this
308
+ * Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
309
+ */
310
+ findByTokenFor(purpose: string, token: unknown): Promise<M | null>;
311
+ /**
312
+ * Like `findByTokenFor`, but throws `InvalidToken` for a token that isn't valid, and
313
+ * `RecordNotFound` when its record is gone or the value it depends on changed.
314
+ */
315
+ findByTokenForOrThrow(purpose: string, token: unknown): Promise<M>;
316
+ }
317
+ /** The questions about how many records every Relation has. */
318
+ declare abstract class CountQuestions<M extends Model> extends TokenFinders<M> {
319
+ /**
320
+ * The number of records: a loaded association's (built records included) without a query;
321
+ * otherwise a `COUNT(*)`, plus an association's unsaved built records.
322
+ */
323
+ size(): Promise<number>;
324
+ /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
325
+ isEmpty(): Promise<boolean>;
326
+ /** Whether there are any records: the opposite of `isEmpty()`. */
327
+ hasAny(): Promise<boolean>;
328
+ /** Whether more than one record matches: one `COUNT` of at most two rows. */
329
+ hasMoreThanOne(): Promise<boolean>;
330
+ /** Whether exactly one record matches: one `COUNT` of at most two rows. */
331
+ hasExactlyOne(): Promise<boolean>;
332
+ }
263
333
  /** A part of a query `unscope` drops by name: `unscope("order")`. */
264
334
  type QueryPart = Exclude<UnscopedPart, object>;
265
335
  /** One attribute's name, or several: what `unscope({ where })` takes. */
@@ -314,11 +384,26 @@ interface InsertOptions<M = unknown> {
314
384
  onDuplicate?: "skip";
315
385
  returning?: Returning<M>;
316
386
  }
317
- /** `upsert`/`upsertAll` options: the attributes of the unique index to match on. */
318
- interface UpsertOptions<M> {
387
+ /**
388
+ * `upsert`/`upsertAll` options: the attributes of the unique index to match on, and the
389
+ * attributes a clashing row has updated (every one written, by default), or what `onDuplicate`
390
+ * sets them to (#531).
391
+ */
392
+ type UpsertOptions<M> = {
319
393
  uniqueBy?: (keyof AttributesOf<M> & string) | readonly (keyof AttributesOf<M> & string)[];
320
394
  returning?: Returning<M>;
321
- }
395
+ } & ({
396
+ updateOnly?: (keyof AttributesOf<M> & string) | readonly (keyof AttributesOf<M> & string)[];
397
+ onDuplicate?: never;
398
+ } | {
399
+ onDuplicate?: OnDuplicate<M>;
400
+ updateOnly?: never;
401
+ });
402
+ /**
403
+ * What a clashing row's attributes become (#531): each an `sql` fragment, where `column()`
404
+ * names the clashing row's value and `incoming()` the new row's, or a value.
405
+ */
406
+ type OnDuplicate<M> = { [K in keyof AttributesOf<M>]?: SafeSql | AttributesOf<M>[K]; };
322
407
  /** `{ attribute: "asc" | "desc" }`; key order sets precedence. */
323
408
  type OrderSpec<M> = { [K in keyof AttributesOf<M>]?: OrderDirection | {
324
409
  direction: OrderDirection;
@@ -540,42 +625,6 @@ declare class Statement<Row = never> {
540
625
  * `create({ email }, (user) => { user.role = "member" })`. Awaited where it's saved.
541
626
  */
542
627
  type Init<M> = (record: M) => void | Promise<void>;
543
- /** What a signed id is for, and how long it lasts: forever unless given. */
544
- interface SignedIdOptions {
545
- /** How long it lasts: `{ minutes: 15 }`. Give this or `expiresAt`. */
546
- readonly expiresIn?: Duration;
547
- /** When it stops finding its record. */
548
- readonly expiresAt?: Date;
549
- /** What it's for (`"login"`): `findSigned` finds its record only given the same. */
550
- readonly purpose?: string;
551
- }
552
- /** What `findSigned` takes: the purpose the signed id was made for. */
553
- interface FindSignedOptions {
554
- readonly purpose?: string;
555
- }
556
- /** The finders by token every Relation has. */
557
- declare abstract class TokenFinders<M extends Model> {
558
- #private;
559
- abstract findBy(conditions: never): Promise<M | null>;
560
- /**
561
- * The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for
562
- * the same `purpose` and it hasn't expired, and this Relation matches it; or null.
563
- */
564
- findSigned(signedId: unknown, options?: FindSignedOptions): Promise<M | null>;
565
- /** Like `findSigned`, but throws `InvalidToken` for a signed id that isn't valid, and `RecordNotFound` when its record is gone. */
566
- findSignedOrThrow(signedId: unknown, options?: FindSignedOptions): Promise<M>;
567
- /**
568
- * The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this
569
- * Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this
570
- * Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
571
- */
572
- findByTokenFor(purpose: string, token: unknown): Promise<M | null>;
573
- /**
574
- * Like `findByTokenFor`, but throws `InvalidToken` for a token that isn't valid, and
575
- * `RecordNotFound` when its record is gone or the value it depends on changed.
576
- */
577
- findByTokenForOrThrow(purpose: string, token: unknown): Promise<M>;
578
- }
579
628
  /** Two or more of a Model's attributes, as `pluck` and `pick` take them for tuples. */
580
629
  type AttributeList<M extends Model> = readonly [keyof AttributesOf<M> & string, keyof AttributesOf<M> & string, ...(keyof AttributesOf<M> & string)[]];
581
630
  /** The types a sum or an average takes; a custom type stored as one of them too. */
@@ -717,7 +766,7 @@ type ScopeMethods<M extends Model, S> = { [K in keyof S]: S[K] extends ((this: n
717
766
  /** A Relation of Model records `M` with the Model's scope methods `S`. */
718
767
  type Scoped<M extends Model, S = {}> = [keyof S] extends [never] ? Relation<M, S> : Relation<M, S> & ScopeMethods<M, S>;
719
768
  /** A lazy, immutable description of a query against one Model. */
720
- declare class Relation<M extends Model, S = {}> extends TokenFinders<M> {
769
+ declare class Relation<M extends Model, S = {}> extends CountQuestions<M> {
721
770
  #private;
722
771
  /** Type-only: the Model's scopes, so chained calls keep their scope methods. */
723
772
  readonly [scopeTypes]?: S;
@@ -781,6 +830,12 @@ declare class Relation<M extends Model, S = {}> extends TokenFinders<M> {
781
830
  select(...attributes: (keyof AttributesOf<M> & string)[]): Scoped<M, S>;
782
831
  /** Removes duplicate rows (of the selected attributes). */
783
832
  distinct(): Scoped<M, S>;
833
+ /**
834
+ * Makes the records this Relation loads read-only (#358): saving or destroying one throws
835
+ * `ReadonlyRecord`. Records it preloads, builds or creates aren't, and its bulk writes ignore it.
836
+ * `readonly(false)` undoes it.
837
+ */
838
+ readonly(flag?: boolean): Scoped<M, S>;
784
839
  /**
785
840
  * Preloads associations for every record this Relation loads, so reading them afterwards
786
841
  * sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
@@ -827,7 +882,8 @@ declare class Relation<M extends Model, S = {}> extends TokenFinders<M> {
827
882
  /**
828
883
  * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
829
884
  * primary key by default): every given attribute and every value this Relation writes into the
830
- * row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set.
885
+ * row (#475), except the `uniqueBy` ones and `createdAt`, or only those `updateOnly` names
886
+ * (#36), with `updatedAt` set when one of them changes.
831
887
  * Resolves as `insert` does, returning inserted and updated rows.
832
888
  */
833
889
  upsert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: UpsertOptions<M> & {
@@ -959,19 +1015,6 @@ declare class Relation<M extends Model, S = {}> extends TokenFinders<M> {
959
1015
  calculate<K extends OrderedAttribute<M> | SafeSql>(operation: "minimum" | "maximum", attribute: K): Promise<CalculatedValue<M, K, unknown> | null>;
960
1016
  /** Groups the rows by attributes or `sql` fragments, for each group's calculations (#345). */
961
1017
  group<const G extends GroupTerms<M>>(...terms: G): GroupedRelation<M, G>;
962
- /**
963
- * The number of records: a loaded association's (built records included) without a query;
964
- * otherwise a `COUNT(*)`, plus an association's unsaved built records.
965
- */
966
- size(): Promise<number>;
967
- /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
968
- isEmpty(): Promise<boolean>;
969
- /** Whether there are any records: the opposite of `isEmpty()`. */
970
- hasAny(): Promise<boolean>;
971
- /** Whether more than one record matches: one `COUNT` of at most two rows. */
972
- hasMoreThanOne(): Promise<boolean>;
973
- /** Whether exactly one record matches: one `COUNT` of at most two rows. */
974
- hasExactlyOne(): Promise<boolean>;
975
1018
  /** Whether any record matches, optionally with extra conditions. */
976
1019
  exists(conditions?: Conditions<M> | SafeSql): Promise<boolean>;
977
1020
  /** Converted values of one attribute, or tuples of several, in this Relation's order. */
@@ -1057,7 +1100,7 @@ interface SaveOptions {
1057
1100
  /** A Model's Relation, as its statics return them: `Product.where(…)` is `Product.all().where(…)`. */
1058
1101
  type RelationOf<C extends ModelClass> = Scoped<InstanceType<C>, ScopesOf<C>>;
1059
1102
  /** The Relation methods every Model has as statics (besides the overloaded ones). */
1060
- declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "touchAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findSigned", "findSignedOrThrow", "findByTokenFor", "findByTokenForOrThrow", "findOrCreateBy", "findOrCreateByOrThrow", "findOrInitializeBy", "createOrFindBy", "createOrFindByOrThrow", "first", "last", "take", "firstOrThrow", "lastOrThrow", "takeOrThrow", "sole", "count", "average", "size", "isEmpty", "hasAny", "hasMoreThanOne", "hasExactlyOne", "exists", "ids", "toArray", "toSql", "findEach", "findInBatches", "inBatches"];
1103
+ declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "readonly", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "touchAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findSigned", "findSignedOrThrow", "findByTokenFor", "findByTokenForOrThrow", "findOrCreateBy", "findOrCreateByOrThrow", "findOrInitializeBy", "createOrFindBy", "createOrFindByOrThrow", "first", "last", "take", "firstOrThrow", "lastOrThrow", "takeOrThrow", "sole", "count", "average", "size", "isEmpty", "hasAny", "hasMoreThanOne", "hasExactlyOne", "exists", "ids", "toArray", "toSql", "findEach", "findInBatches", "inBatches"];
1061
1104
  /** A Relation method with no overloads, by name. */
1062
1105
  type RelationMethod = (typeof relationMethods)[number];
1063
1106
  /**
@@ -1423,6 +1466,12 @@ declare class AnyDatabase {
1423
1466
  model<C extends ModelClass<Model>>(model: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1424
1467
  /** Request-bound relations for several models at once: `db.models({ User }).User`. */
1425
1468
  models<const T extends Record<string, ModelClass<Model>>>(models: T): RelationsFor<T>;
1469
+ /**
1470
+ * Empties the request cache of the running `withDatabase` call, every database's in it, so each
1471
+ * read after it is sent. Call it after a write the library didn't send, such as SQL sent on the
1472
+ * binding or client yourself, which it can't see. Outside `withDatabase` it does nothing.
1473
+ */
1474
+ clearRequestCache(): void;
1426
1475
  /**
1427
1476
  * Runs the writes `build` prepares atomically, on this Database: all of them are written, or
1428
1477
  * none. `db.batch((b) => [b.insert(Post, { title }), b.save(user)])`. The callback can't await,
@@ -1487,6 +1536,11 @@ interface QueryEvent<Meta = unknown> {
1487
1536
  durationMs: number;
1488
1537
  meta?: Meta;
1489
1538
  error?: unknown;
1539
+ /**
1540
+ * Answered from the request cache (#218): a read identical to one already sent in the same
1541
+ * `withDatabase` call, with no round trip. Its `durationMs` is 0, and it has no `meta`.
1542
+ */
1543
+ cached?: true;
1490
1544
  }
1491
1545
  /**
1492
1546
  * Hears each statement's `QueryEvent`. Declared as a method's type, so a listener typed for one
@@ -1516,6 +1570,14 @@ interface Executor {
1516
1570
  /** Runs statements atomically: one on its own, several as one batch. */
1517
1571
  write(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
1518
1572
  }
1573
+ /** What a Database caches: `request: false` turns off the request cache, on by default (#218). */
1574
+ interface CacheOptions {
1575
+ /**
1576
+ * Answer a read identical to one already sent, inside the same `withDatabase` call, from
1577
+ * memory. On unless `false`.
1578
+ */
1579
+ request?: boolean;
1580
+ }
1519
1581
  /** Where a database came from, for errors to name it: `connect()`'s, the request's, or a binding's. */
1520
1582
  type Origin = "connect" | "request" | {
1521
1583
  binding: string;
@@ -1527,7 +1589,7 @@ type Origin = "connect" | "request" | {
1527
1589
  declare class DatabaseExecutor implements Executor {
1528
1590
  #private;
1529
1591
  readonly adapter: Adapter;
1530
- constructor(adapter: Adapter, driver: Driver, onQuery?: QueryListener);
1592
+ constructor(adapter: Adapter, driver: Driver, onQuery?: QueryListener, cache?: CacheOptions);
1531
1593
  get dialect(): Dialect;
1532
1594
  [resolve](): Promise<DatabaseExecutor>;
1533
1595
  /** Where this database came from; errors name it by this. */
@@ -1597,9 +1659,10 @@ type EnumOptions = Pick<SpecOverride, "prefix" | "suffix" | "scopes" | "instance
1597
1659
  /**
1598
1660
  * A change to a generated attribute: its type alone, or its type, nullability, default and
1599
1661
  * `generateId`, typed so `generateId` goes only with a string, and never with a default (#99); and
1600
- * an enum on a string or an integer, whose stored values are of its type (#340).
1662
+ * an enum on a string or an integer, whose stored values are of its type (#340); and `readonly`
1663
+ * on a column (#358).
1601
1664
  */
1602
- type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "null"> & {
1665
+ type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "null" | "readonly"> & {
1603
1666
  type?: "string";
1604
1667
  storage?: never;
1605
1668
  virtual?: false;
@@ -1607,24 +1670,24 @@ type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "nu
1607
1670
  enum?: TextEnum | boolean;
1608
1671
  /** A random token, generated for a new record (#355). */
1609
1672
  secureToken?: boolean | SecureTokenOptions;
1610
- } & EnumOptions & ValueSource) | (Pick<SpecOverride, "null" | "default"> & {
1673
+ } & EnumOptions & ValueSource) | (Pick<SpecOverride, "null" | "default" | "readonly"> & {
1611
1674
  type?: "integer";
1612
1675
  generateId?: false;
1613
1676
  storage?: never;
1614
1677
  virtual?: false;
1615
1678
  enum: IntegerEnum;
1616
- } & EnumOptions) | (Pick<SpecOverride, "null" | "default"> & {
1679
+ } & EnumOptions) | (Pick<SpecOverride, "null" | "default" | "readonly"> & {
1617
1680
  type: Exclude<AttributeType, "string" | "datetime">;
1618
1681
  generateId?: false;
1619
1682
  storage?: never;
1620
1683
  enum?: never;
1621
1684
  virtual?: false;
1622
- }) | (Pick<SpecOverride, "null" | "default" | "storage"> & {
1685
+ }) | (Pick<SpecOverride, "null" | "default" | "storage" | "readonly"> & {
1623
1686
  type: "datetime";
1624
1687
  generateId?: false;
1625
1688
  enum?: never;
1626
1689
  virtual?: false;
1627
- }) | (Pick<SpecOverride, "null" | "default"> & {
1690
+ }) | (Pick<SpecOverride, "null" | "default" | "readonly"> & {
1628
1691
  type: AnyCustomType;
1629
1692
  generateId?: false;
1630
1693
  storage?: never;
@@ -1723,6 +1786,16 @@ interface DatabaseSchema {
1723
1786
  }
1724
1787
  /** `{ attribute: [before, after] }` */
1725
1788
  type Changes = Record<string, [before: unknown, after: unknown]>;
1789
+ /** The read-only mark Model's records have. */
1790
+ declare abstract class ReadonlyMarks extends AttributeWrites {
1791
+ /**
1792
+ * Marks the record read-only: saving, destroying, touching it or writing its columns throws
1793
+ * `ReadonlyRecord`, sending nothing. It can still be changed in memory and reloaded.
1794
+ */
1795
+ markReadonly<R extends Model>(this: R): R;
1796
+ /** Whether it's read-only: marked by `markReadonly()`, or loaded through a `readonly()` Relation. */
1797
+ isReadonly(this: Model): boolean;
1798
+ }
1726
1799
  /** Type-only brand on a scope static (`static newest = this.scope(…)`); never set at runtime. */
1727
1800
  declare const scopeBrand: unique symbol;
1728
1801
  /**
@@ -1799,7 +1872,7 @@ type AttributesOf<M> = M extends {
1799
1872
  * methods, statics, callbacks and scopes declared there are shared by every Model built on it.
1800
1873
  * It has no table, so it's never used as a Model itself.
1801
1874
  */
1802
- declare class Model extends AttributeWrites {
1875
+ declare class Model extends ReadonlyMarks {
1803
1876
  /** The table's name: inferred from `modelName` (`BlogPost` → `blog_posts`) unless set. */
1804
1877
  static table: string;
1805
1878
  /**
@@ -2259,4 +2332,4 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
2259
2332
  }
2260
2333
  /** The options of a `validatesAssociated(association, options)` call. */
2261
2334
  type AssociatedValidationOptions<R = never, X extends string = ValidationContext> = Pick<ValidationOptions<R, X>, "message" | "strict" | "if" | "unless" | "on" | "exceptOn">;
2262
- export { TouchOptions as $, databaseExecutor as A, lt as At, SaveOptions as B, ColumnValue as Bt, QueryEvent as C, OrderSpec as Ct, SchemaAdapter as D, between as Dt, ConstraintFailure as E, Comparison as Et, RecordStatement as F, QuerySql as Ft, Relation as G, ComparisonBound as Gt, ValidationContext as H, column as Ht, DatetimeAttributeKey as I, Dialect as It, Scoped as J, Scope as K, ComparisonOptions as Kt, NumberAttributeKey as L, valueMark as Lt, BatchResults as M, QueryPart as Mt, batch as N, InOrderOfOptions as Nt, AnyDatabase as O, gt as Ot, Batch as P, CompiledSql as Pt, PageOptions as Q, SigningEnv as R, Attribute as Rt, DatabaseExecutor as S, InsertOptions as St, Adapter as T, UpsertOptions as Tt, ValidationContexts as U, sql$1 as Ut, ValidationCallbackOptions as V, SafeSql as Vt, TokenForOptions as W, Comparable as Wt, CountlessPage as X, IterationOptions as Y, Page as Z, TableSchema as _, HasOneThrough as _t, ValidationOptions as a, Statement as at, boundValue as b, ThroughOptions as bt, AttributeErrorMessages as c, StatementResult as ct, RestrictMessages as d, HasMany as dt, GroupedRelation as et, Model as f, HasManyCollection as ft, DatabaseSchema as g, HasOneDependent as gt, TableAttributes as h, HasOne as ht, UniquenessOptions as i, ReturnedRow as it, BatchEntry as j, lte as jt, RelationsFor as k, gte as kt, ErrorMessage as l, AssociationOptions as lt, ScopeStatic as m, HasManyThrough as mt, LengthOptions as n, SignedIdOptions as nt, Errors as o, WriteResult as ot, ModelClass as p, HasManyDependent as pt, ScopeMethods as q, NumericalityOptions as r, Init as rt, ValidationError as s, Driver as st, AssociatedValidationOptions as t, FindSignedOptions as tt, ErrorMessages as u, BelongsTo as ut, TableSchemas as v, PolymorphicBelongsTo as vt, QueryListener as w, Returning as wt, AttributeConversions as x, Conditions as xt, FilterAttribute as y, ThroughDependent as yt, SigningSecrets as z, ColumnReference as zt };
2335
+ export { PageOptions as $, RelationsFor as A, lt as At, SigningSecrets as B, ColumnReference as Bt, DatabaseExecutor as C, OrderSpec as Ct, ConstraintFailure as D, between as Dt, Adapter as E, Comparison as Et, Batch as F, InOrderOfOptions as Ft, TokenForOptions as G, incoming as Gt, ValidationCallbackOptions as H, IncomingReference as Ht, RecordStatement as I, CompiledSql as It, ScopeMethods as J, Comparable as Jt, Relation as K, sql$1 as Kt, DatetimeAttributeKey as L, QuerySql as Lt, BatchEntry as M, QueryPart as Mt, BatchResults as N, FindSignedOptions as Nt, SchemaAdapter as O, gt as Ot, batch as P, SignedIdOptions as Pt, Page as Q, NumberAttributeKey as R, Dialect as Rt, CacheOptions as S, OnDuplicate as St, QueryListener as T, UpsertOptions as Tt, ValidationContext as U, SafeSql as Ut, SaveOptions as V, ColumnValue as Vt, ValidationContexts as W, column as Wt, IterationOptions as X, ComparisonOptions as Xt, Scoped as Y, ComparisonBound as Yt, CountlessPage as Z, TableSchema as _, PolymorphicBelongsTo as _t, ValidationOptions as a, WriteResult as at, boundValue as b, Conditions as bt, AttributeErrorMessages as c, AssociationOptions as ct, RestrictMessages as d, HasManyCollection as dt, TouchOptions as et, Model as f, HasManyDependent as ft, DatabaseSchema as g, HasOneThrough as gt, TableAttributes as h, HasOneDependent as ht, UniquenessOptions as i, Statement as it, databaseExecutor as j, lte as jt, AnyDatabase as k, gte as kt, ErrorMessage as l, BelongsTo as lt, ScopeStatic as m, HasOne as mt, LengthOptions as n, Init as nt, Errors as o, Driver as ot, ModelClass as p, HasManyThrough as pt, Scope as q, Attribute as qt, NumericalityOptions as r, ReturnedRow as rt, ValidationError as s, StatementResult as st, AssociatedValidationOptions as t, GroupedRelation as tt, ErrorMessages as u, HasMany as ut, TableSchemas as v, ThroughDependent as vt, QueryEvent as w, Returning as wt, AttributeConversions as x, InsertOptions as xt, FilterAttribute as y, ThroughOptions as yt, SigningEnv as z, valueMark as zt };