@forestfuture/active-record 0.9.1 → 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.
@@ -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
@@ -366,11 +384,26 @@ interface InsertOptions<M = unknown> {
366
384
  onDuplicate?: "skip";
367
385
  returning?: Returning<M>;
368
386
  }
369
- /** `upsert`/`upsertAll` options: the attributes of the unique index to match on. */
370
- 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> = {
371
393
  uniqueBy?: (keyof AttributesOf<M> & string) | readonly (keyof AttributesOf<M> & string)[];
372
394
  returning?: Returning<M>;
373
- }
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]; };
374
407
  /** `{ attribute: "asc" | "desc" }`; key order sets precedence. */
375
408
  type OrderSpec<M> = { [K in keyof AttributesOf<M>]?: OrderDirection | {
376
409
  direction: OrderDirection;
@@ -849,7 +882,8 @@ declare class Relation<M extends Model, S = {}> extends CountQuestions<M> {
849
882
  /**
850
883
  * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
851
884
  * primary key by default): every given attribute and every value this Relation writes into the
852
- * 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.
853
887
  * Resolves as `insert` does, returning inserted and updated rows.
854
888
  */
855
889
  upsert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: UpsertOptions<M> & {
@@ -1432,6 +1466,12 @@ declare class AnyDatabase {
1432
1466
  model<C extends ModelClass<Model>>(model: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1433
1467
  /** Request-bound relations for several models at once: `db.models({ User }).User`. */
1434
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;
1435
1475
  /**
1436
1476
  * Runs the writes `build` prepares atomically, on this Database: all of them are written, or
1437
1477
  * none. `db.batch((b) => [b.insert(Post, { title }), b.save(user)])`. The callback can't await,
@@ -1496,6 +1536,11 @@ interface QueryEvent<Meta = unknown> {
1496
1536
  durationMs: number;
1497
1537
  meta?: Meta;
1498
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;
1499
1544
  }
1500
1545
  /**
1501
1546
  * Hears each statement's `QueryEvent`. Declared as a method's type, so a listener typed for one
@@ -1525,6 +1570,14 @@ interface Executor {
1525
1570
  /** Runs statements atomically: one on its own, several as one batch. */
1526
1571
  write(statements: readonly CompiledSql[]): Promise<StatementResult[]>;
1527
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
+ }
1528
1581
  /** Where a database came from, for errors to name it: `connect()`'s, the request's, or a binding's. */
1529
1582
  type Origin = "connect" | "request" | {
1530
1583
  binding: string;
@@ -1536,7 +1589,7 @@ type Origin = "connect" | "request" | {
1536
1589
  declare class DatabaseExecutor implements Executor {
1537
1590
  #private;
1538
1591
  readonly adapter: Adapter;
1539
- constructor(adapter: Adapter, driver: Driver, onQuery?: QueryListener);
1592
+ constructor(adapter: Adapter, driver: Driver, onQuery?: QueryListener, cache?: CacheOptions);
1540
1593
  get dialect(): Dialect;
1541
1594
  [resolve](): Promise<DatabaseExecutor>;
1542
1595
  /** Where this database came from; errors name it by this. */
@@ -2279,4 +2332,4 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
2279
2332
  }
2280
2333
  /** The options of a `validatesAssociated(association, options)` call. */
2281
2334
  type AssociatedValidationOptions<R = never, X extends string = ValidationContext> = Pick<ValidationOptions<R, X>, "message" | "strict" | "if" | "unless" | "on" | "exceptOn">;
2282
- export { TouchOptions as $, databaseExecutor as A, QueryPart as At, SaveOptions as B, ColumnValue as Bt, QueryEvent as C, UpsertOptions as Ct, SchemaAdapter as D, gte as Dt, ConstraintFailure as E, gt 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, SignedIdOptions as Mt, batch as N, InOrderOfOptions as Nt, AnyDatabase as O, lt as Ot, Batch as P, CompiledSql as Pt, PageOptions as Q, SigningEnv as R, Attribute as Rt, DatabaseExecutor as S, Returning as St, Adapter as T, between 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 _, ThroughDependent as _t, ValidationOptions as a, Driver as at, boundValue as b, InsertOptions as bt, AttributeErrorMessages as c, BelongsTo as ct, RestrictMessages as d, HasManyDependent as dt, GroupedRelation as et, Model as f, HasManyThrough as ft, DatabaseSchema as g, PolymorphicBelongsTo as gt, TableAttributes as h, HasOneThrough as ht, UniquenessOptions as i, WriteResult as it, BatchEntry as j, FindSignedOptions as jt, RelationsFor as k, lte as kt, ErrorMessage as l, HasMany as lt, ScopeStatic as m, HasOneDependent as mt, LengthOptions as n, ReturnedRow as nt, Errors as o, StatementResult as ot, ModelClass as p, HasOne as pt, ScopeMethods as q, NumericalityOptions as r, Statement as rt, ValidationError as s, AssociationOptions as st, AssociatedValidationOptions as t, Init as tt, ErrorMessages as u, HasManyCollection as ut, TableSchemas as v, ThroughOptions as vt, QueryListener as w, Comparison as wt, AttributeConversions as x, OrderSpec as xt, FilterAttribute as y, Conditions 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 };
package/llms-full.txt CHANGED
@@ -412,9 +412,9 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
412
412
  - Start queries and new records from the Model, as in Rails: `User.find(id)`, `User.where(…)`, `User.build(…)`. Each Model queries the binding named in the generated schema its base class holds, during a request. For a D1 Session, wrap the handler in `withSession(request, env.DB, fn)`. For per-request `onQuery`, or tests and scripts outside a Worker, wrap the code once in `withDatabase(connect(env.DB, { … }), fn)`. Records keep the database they came from.
413
413
  - Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL, and a list matches any of its values. `findOrCreateBy`, `findOrInitializeBy` and `createOrFindBy` throw `TypeError` for a list, a comparison or a `sql` fragment.
414
414
  - Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
415
- - Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column.
415
+ - Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column. `column()` works only inside a fragment: `where({ views: column("likes") })` and `updateAll({ views: column("likes") })` throw, as do one nested in a json value and one given as `find`'s id, so write ``where(sql`${column("views")} = ${column("likes")}`)``.
416
416
  - For a raw `env.DB.prepare(…).bind(…)` statement, bind `Post.typeForAttribute("publishedAt").serialize(date)`, which writes the value as the attribute stores it, and read a cell with `.deserialize(cell)`. A value the attribute can't hold throws `TypeError`.
417
- - Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
417
+ - Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). `upsert(…, { uniqueBy: "email", updateOnly: ["name"] })` updates only `name` on a clash; ``upsertAll(rows, { uniqueBy: "name", onDuplicate: { count: sql`${column("count")} + ${incoming("count")}` } })`` sets each named attribute to a fragment (`column()` the clashing row's value, `incoming()` the new row's) or a value. Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
418
418
  - Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
419
419
  - To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`. To keep a parent's `updatedAt` current as its children change (a cache key), declare `belongsTo(Article, { touch: true })` on the child rather than touching the parent in a callback: the parent is touched in the child's batch, runs its own touch callbacks, and touches its own parents in turn. A parent that isn't loaded costs one SELECT per level, so preload the chain (`includes({ article: "blog" })`) when saving many. `hasOne(Profile, { touch: true })` touches a user's profile the same way when the user is updated, destroyed or touched. For a bulk import, wrap it in `Article.noTouching(async () => { … })`, so no article is touched per comment, then touch each article once after it.
420
420
  - To stop two edits of one record from overwriting each other, add a `lock_version INTEGER NOT NULL DEFAULT 0` column: every save, destroy and `touch()` then checks the row still has the record's `lockVersion`, and a stale copy's throws `StaleRecord` (from `save()` too, not `false`) and writes nothing in its batch (a destroy's dependents on another database are already gone). For edits across requests, put `lockVersion` in the form as a hidden field and permit it with the other fields, and answer `StaleRecord` with a 409; to retry in code, `await record.reload()` and make the change again. A child's `touch` on a locked parent raises the parent's version, so a parent its children touch often gets conflicts: drop the `touch` or write the children inside `noTouching`.
@@ -781,7 +781,7 @@ Declare each association as a field, passing the target Model’s class, as the
781
781
  - Models can refer to each other in any order.
782
782
  - A subclass inherits its parent’s associations, and can redeclare one to change it.
783
783
 
784
- ## belongsTo
784
+ ## Using `belongsTo`
785
785
 
786
786
  Use `belongsTo` on the Model whose table holds the foreign key, as an article belongs to its author:
787
787
 
@@ -809,7 +809,7 @@ await article.save();
809
809
  | `scope` | Narrows the target, `(q) => q.where(…)`. See [Scoping associations](#scoping-associations) |
810
810
  | `optional` | Lets the record point at nothing. See [Requiring the record](#requiring-the-record) |
811
811
  | `autosave` | `true` saves the record’s changes with this record. See [Saving changed records](/autosaving#saving-changed-records) |
812
- | `inverseOf` | The target’s `hasOne` that points back, or `false`. See [Inverse associations](#inverse-associations) |
812
+ | `inverseOf` | The target’s `hasOne` that points back, or `false`. See [Inverse associations](#using-inverse-associations) |
813
813
 
814
814
  ## Requiring the record
815
815
 
@@ -819,7 +819,7 @@ Saving a record checks that each `belongsTo` points at a record that exists, unl
819
819
  - A saved record whose foreign key hasn’t changed isn’t checked again.
820
820
  - A record built through a `hasMany` or `hasOne` already points at its owner, so it passes the check before either is saved. See [Autosaving](/autosaving#saving-a-graph).
821
821
 
822
- ## hasMany
822
+ ## Using `hasMany`
823
823
 
824
824
  Use `hasMany` on the Model the other table’s foreign key points at, as an author has many articles:
825
825
 
@@ -851,9 +851,9 @@ await author.articles().where({ title: "Untitled" }).deleteAll(); // scoped to t
851
851
  | `scope` | Narrows or orders the records, `(q) => q.order(…)`. See [Scoping associations](#scoping-associations) |
852
852
  | `dependent` | What destroying the owner does to the records. See [Destroying dependent records](#destroying-dependent-records) |
853
853
  | `autosave` | `true` saves the records’ changes with the owner. See [Saving changed records](/autosaving#saving-changed-records) |
854
- | `inverseOf` | The target’s `belongsTo` that points back, or `false`. See [Inverse associations](#inverse-associations) |
854
+ | `inverseOf` | The target’s `belongsTo` that points back, or `false`. See [Inverse associations](#using-inverse-associations) |
855
855
 
856
- ## hasOne
856
+ ## Using `hasOne`
857
857
 
858
858
  Use `hasOne` like `hasMany`, when there’s at most one record, as an author has one profile:
859
859
 
@@ -894,7 +894,7 @@ await author.profile.set(Profile.build({ bio: "Novelist" })); // and deletes the
894
894
  - If the old record can’t be saved with a `NULL` foreign key, the write throws `RecordNotSaved`, and nothing is written.
895
895
  - If the new record doesn’t save, the old one stays. `set` throws `RecordNotSaved` and leaves the association as it was. `create` returns the unsaved record, and saving the owner tries again.
896
896
 
897
- ## Polymorphic associations
897
+ ## Using a polymorphic `belongsTo`
898
898
 
899
899
  A polymorphic `belongsTo` points at a record of any of several Models, listed in an array, as a like belongs to a photo or a video:
900
900
 
@@ -963,7 +963,7 @@ const again = await article.author(); // none: it's cached on the article
963
963
  - A write made another way, such as `Article.where({ authorId: author.id }).deleteAll()`, doesn’t touch a loaded collection: reload the association to see it.
964
964
  - A `belongsTo` whose foreign key is `null`, or an association on an unsaved owner, reads without a query.
965
965
 
966
- ## Inverse associations
966
+ ## Using inverse associations
967
967
 
968
968
  A record loaded through its owner’s `hasMany` or `hasOne` has the owner loaded already, so reading it back sends no query:
969
969
 
@@ -1769,6 +1769,8 @@ Source: https://active-record.forestfuture.dev/batches
1769
1769
  | update or delete every row a Relation finds | `updateAll({ … })`, `deleteAll()`, `deleteBy({ … })` |
1770
1770
  | insert rows without loading records | `insert({ … })`, `insertAll([…])` |
1771
1771
  | insert, or update a row that clashes | `upsert({ … }, { uniqueBy: "email" })`, `upsertAll([…])` |
1772
+ | update only some attributes on a clash | `upsertAll([…], { updateOnly: ["name"] })` |
1773
+ | update a clashing row with your own SQL | ``upsertAll([…], { onDuplicate: { name: sql`…` } })`` |
1772
1774
  | get attributes back from an insert | `{ returning: ["id", "body"] }` |
1773
1775
  | write several statements atomically | `batch((b) => [b.insert(…), b.updateAll(…)])` |
1774
1776
  | save or destroy records in that batch | `b.save(record)`, `b.destroy(record)` |
@@ -1932,6 +1934,7 @@ To run each record’s callbacks, destroy the records with [`destroyAll`](/persi
1932
1934
  Insert many rows at once with `insertAll`:
1933
1935
 
1934
1936
  ```ts
1937
+ import { column, incoming, sql } from "@forestfuture/active-record";
1935
1938
  import { Article } from "./models/article";
1936
1939
  import { Author } from "./models/author";
1937
1940
  import { Comment } from "./models/comment";
@@ -1942,12 +1945,25 @@ await Comment.insertAll([
1942
1945
  { articleId: article.id, body: "Two" },
1943
1946
  ]);
1944
1947
  await Author.upsert({ name: "Jane Doe", email: "jane@example.com" }, { uniqueBy: "email" }); // renames Jane
1948
+ await Author.upsert(
1949
+ { id: crypto.randomUUID(), name: "Jane Smith", email: "jane@example.com" },
1950
+ { uniqueBy: "email", updateOnly: "name" },
1951
+ ); // renames Jane, keeping her id
1952
+ await Author.upsert(
1953
+ { name: "J. Smith", email: "jane@example.com" },
1954
+ {
1955
+ uniqueBy: "email",
1956
+ onDuplicate: { name: sql`${column("name")} || ' / ' || ${incoming("name")}` },
1957
+ },
1958
+ ); // Jane Smith / J. Smith
1945
1959
  await Author.insert({ name: "Jane", email: "jane@example.com" }, { onDuplicate: "skip" }); // writes nothing
1946
1960
  ```
1947
1961
 
1948
1962
  - **`insertAll(rows)`** inserts every row, however many. Every row must have the same attributes. A duplicate throws and writes nothing.
1949
1963
  - **`{ onDuplicate: "skip" }`** skips rows that clash with a unique index.
1950
- - **`upsert(attrs)`** and **`upsertAll(rows)`** update a row that clashes with the primary key, or with the unique index named by `uniqueBy`. The attributes you give are updated. So are the values a Relation adds to each row, from its equality conditions, its default scope, and `createWith`. Defaults filled in for you aren’t updated. `updatedAt` is set.
1964
+ - **`upsert(attrs)`** and **`upsertAll(rows)`** update a row that clashes with the primary key, or with the unique index named by `uniqueBy`. The attributes you give are updated. So are the values a Relation adds to each row, from its equality conditions, its default scope, and `createWith`. Defaults filled in for you aren’t updated. `updatedAt` is set when a value changes. A row with nothing to update is left alone, and isn’t counted or returned.
1965
+ - **`{ updateOnly: ["name"] }`** updates only the attributes it names when a row clashes. The others keep their values. Each row must give every attribute it names. A row’s own `updatedAt` is written only when it’s named, or when a named attribute changes.
1966
+ - **``{ onDuplicate: { name: sql`…` } }``** sets each attribute it names to an `sql` fragment or a value when a row clashes. In a fragment, `column("name")` is the clashing row’s value and `incoming("name")` is the new row’s. The others keep their values. `updatedAt` is set when a value changes. To see whether a value changes, each fragment runs twice. Name `updatedAt` yourself to run a fragment with side effects once. You can’t give `updateOnly` with it.
1951
1967
  - **Through a Relation**, `insertAll`, `upsert`, and `upsertAll` write its equality conditions over each row’s values, as `insert` does.
1952
1968
  - **Through a `hasMany`**, an upsert only updates the owner’s records. A row that clashes with another owner’s record isn’t written, counted, or returned. See [Writing many rows](/associations#writing-many-rows).
1953
1969
 
@@ -1977,7 +1993,7 @@ await Comment.insert({ articleId: article.id, body: "Three" }, { returning: fals
1977
1993
 
1978
1994
  > **Compared with Rails**
1979
1995
  >
1980
- > These are Rails’ `insert_all`, `upsert_all`, `update_all`, and `delete_all`, with two differences. Declared defaults fill what an insert isn’t given, since on D1 defaults are where keys are generated. And skipping duplicates is something you opt in to, so an insert’s duplicate is never silently lost. The `returning` option works as Rails’ does.
1996
+ > These are Rails’ `insert_all`, `upsert_all`, `update_all`, and `delete_all`, with two differences. Declared defaults fill what an insert isn’t given, since on D1 defaults are where keys are generated. And skipping duplicates is something you opt in to, so an insert’s duplicate is never silently lost. The `returning` option works as Rails’ does, `updateOnly` is Rails’ `update_only`, and `onDuplicate` is Rails’ `on_duplicate`, given for each attribute rather than as one SQL string.
1981
1997
 
1982
1998
  ## Batching writes
1983
1999
 
@@ -3043,6 +3059,7 @@ The generators follow `rails generate model` and `rails generate migration`. A c
3043
3059
  - `dependent:` strategies run after the owner’s `beforeDestroy` callbacks, wherever they’re declared, so an `abort()` always protects the records.
3044
3060
  - Records in a batch run all their before-callbacks before any write, and their after-callbacks after all of them.
3045
3061
  - Scopes preloaded with `limit` throw, where Rails silently gives wrong results.
3062
+ - The query cache is on only inside `withDatabase`, and a Model’s queries on the binding alone are never cached. `db.clearRequestCache()` is `clear_query_cache`, and `connect(env.DB, { cache: { request: false } })` turns it off. See [Caching identical reads](/connecting#caching-identical-reads).
3046
3063
 
3047
3064
  ## Not built yet
3048
3065
 
@@ -3565,6 +3582,8 @@ const email = "Jane@Example.com";
3565
3582
  const user = await User.findBy(sql`lower(${column("email")}) = lower(${email})`);
3566
3583
  ```
3567
3584
 
3585
+ To compare two columns, write both in a fragment: ``where(sql`${column("updatedAt")} > ${column("createdAt")}`)``.
3586
+
3568
3587
  Values are always bound, as they are, so a `Date` is ISO text. To write a value the way its attribute stores it, use `column(name).value(v)`:
3569
3588
 
3570
3589
  ```ts
@@ -3643,11 +3662,11 @@ Source: https://active-record.forestfuture.dev/connecting
3643
3662
 
3644
3663
  Most apps only use the binding.
3645
3664
 
3646
- | | How | Use it for |
3647
- | -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------- |
3648
- | **The binding** | `User.find(id)`, with nothing to set up | Everyday queries |
3649
- | **The request’s database** | `withDatabase(connect(env.DB, …), fn)`, once per request | Read replicas with a Session, per-request `onQuery` logging, tests, and scripts |
3650
- | **An explicit database** | `connect(env.DB).model(User).find(id)` | Code that passes its database around, or uses two at once |
3665
+ | | How | Use it for |
3666
+ | -------------------------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
3667
+ | **The binding** | `User.find(id)`, with nothing to set up | Everyday queries |
3668
+ | **The request’s database** | `withDatabase(connect(env.DB, …), fn)`, once per request | Caching identical reads, read replicas with a Session, per-request `onQuery` logging, tests, and scripts |
3669
+ | **An explicit database** | `connect(env.DB).model(User).find(id)` | Code that passes its database around, or uses two at once |
3651
3670
 
3652
3671
  [Database resolution](/query-databases) explains why there are three, and [which one you need](/query-databases#which-do-i-need).
3653
3672
 
@@ -3804,6 +3823,69 @@ These pages use a request’s database:
3804
3823
  - **[Testing](/testing):** a database for Models outside a Worker.
3805
3824
  - **[Multiple databases](/several-databases):** `withDatabase([...])`, matched to each Model’s binding.
3806
3825
 
3826
+ ## Caching identical reads
3827
+
3828
+ Inside `withDatabase`, a read you’ve already sent is answered from memory, with no round trip:
3829
+
3830
+ ```ts
3831
+ import { withDatabase } from "@forestfuture/active-record";
3832
+ import { connect } from "@forestfuture/active-record/d1";
3833
+ import { User } from "./models/user";
3834
+
3835
+ export async function findTwice(env: Env) {
3836
+ return withDatabase(connect(env.DB), async () => {
3837
+ const user = await User.findByOrThrow({ email: "jane@example.com" }); // sent
3838
+ const again = await User.findByOrThrow({ email: "jane@example.com" }); // answered from memory
3839
+ return [user, again] as const;
3840
+ });
3841
+ }
3842
+ ```
3843
+
3844
+ - Each answer is new records, so changing one changes no other.
3845
+ - Any write Active Record sends inside the call clears the cache: a save, a destroy, a bulk write, or a batch, through any database handle. So a request always reads its own writes.
3846
+ - `reload()` always reads the database, and clears the cache too.
3847
+ - The cache ends with the `withDatabase` call. Requests never share it.
3848
+ - It keeps the 100 answers used last. [Batch iteration](/batch-iteration) doesn’t keep its batches, so walking a big table doesn’t fill it.
3849
+ - [`onQuery`](/logging#seeing-a-cached-answer) hears each cached answer, with `cached: true`.
3850
+
3851
+ :::note[Caching needs `withDatabase`]
3852
+ A Model’s queries outside `withDatabase` use the binding, which every request running at once shares, so they’re never cached. To cache a request’s reads, run it inside `withDatabase`, as the example does.
3853
+ :::
3854
+
3855
+ To send every read, turn the cache off:
3856
+
3857
+ ```ts
3858
+ import { connect } from "@forestfuture/active-record/d1";
3859
+
3860
+ export function uncachedDatabase(env: Env) {
3861
+ return connect(env.DB, { cache: { request: false } }); // every read is sent
3862
+ }
3863
+ ```
3864
+
3865
+ ### Clearing the cache
3866
+
3867
+ Active Record only sees the writes it sends. After SQL you send on the binding yourself, clear the cache with `clearRequestCache()`:
3868
+
3869
+ ```ts
3870
+ import { withDatabase } from "@forestfuture/active-record";
3871
+ import { connect } from "@forestfuture/active-record/d1";
3872
+ import { Post } from "./models/post";
3873
+
3874
+ export async function renamePost(env: Env, id: string) {
3875
+ const db = connect(env.DB);
3876
+ return withDatabase(db, async () => {
3877
+ const post = await Post.find(id);
3878
+ await env.DB.prepare("UPDATE posts SET title = ? WHERE id = ?").bind("Hello again", id).run();
3879
+ db.clearRequestCache(); // the UPDATE didn't go through Active Record
3880
+ return Post.find(post.id); // sent, so it reads "Hello again"
3881
+ });
3882
+ }
3883
+ ```
3884
+
3885
+ > **Compared with Rails**
3886
+ >
3887
+ > This is Rails’ query cache. Rails turns it on for each request with its executor; here `withDatabase` does. `clearRequestCache()` is `clear_query_cache`, and `cache: { request: false }` stands in for `uncached`. Like Rails, it keeps 100 answers, dropping the least recently used.
3888
+
3807
3889
  ## Using an explicit database
3808
3890
 
3809
3891
  Start a query from a database you hold with `db.model`. It ignores `withDatabase`:
@@ -3831,7 +3913,7 @@ export async function listPosts(env: Env) {
3831
3913
  }
3832
3914
  ```
3833
3915
 
3834
- `connect(env.DB, { session, onQuery })` takes the same options as a request’s database.
3916
+ `connect(env.DB, { session, onQuery, cache })` takes the same options as a request’s database.
3835
3917
 
3836
3918
  ## Batching writes
3837
3919
 
@@ -3881,7 +3963,7 @@ local> const admins = await User.where({ role: "admin" }).toArray()
3881
3963
 
3882
3964
  Leave with `quit`, `exit`, or Ctrl-D. Ctrl-C stops a line that’s still running. `.help` lists the console’s own commands, and `npx active-record c` is the short form.
3883
3965
 
3884
- ## What you can use
3966
+ ## Using your Models and `db`
3885
3967
 
3886
3968
  - **Your Models,** by class name, from every file in `src/models`. They query your database, local unless you pass `--remote`, with no `db` to pass.
3887
3969
  - **`db`,** your connected database, for `db.batch(...)` and `db.model(...)`.
@@ -3940,7 +4022,7 @@ The SQL comes from the database’s own `onQuery`, so a listener you set on your
3940
4022
  | `--yes` | With `--remote`, don’t ask first. It’s also how to open it without a terminal. |
3941
4023
  | `--history` | Keep what you type in a remote session, which isn’t kept unless you ask. |
3942
4024
 
3943
- ## Where your data lives
4025
+ ## Finding your local data
3944
4026
 
3945
4027
  The console opens the local database in `.wrangler/state`, beside your Wrangler config. It’s the same one `wrangler dev` and `wrangler d1 migrations apply --local` use, so apply your migrations first, and what you change in the console is what your dev server sees. With [`wranglerConfig`](/command-line#declaring-your-databases), it’s beside the config that setting names.
3946
4028
 
@@ -5762,6 +5844,7 @@ Source: https://active-record.forestfuture.dev/logging
5762
5844
  | log one request’s queries, with its ID | `withDatabase(connect(env.DB, { onQuery }), …)` |
5763
5845
  | send the database time to the browser | add up `durationMs` into a `Server-Timing` header |
5764
5846
  | keep more attributes out of the logs | `static override filterAttributes = [...Model.filterAttributes, "iban"]` |
5847
+ | tell a cached read from a sent one | `event.cached` |
5765
5848
 
5766
5849
  ## The Models
5767
5850
 
@@ -5861,6 +5944,7 @@ An `onQuery` listener is called once for every statement, writes and batches inc
5861
5944
  | `durationMs` | How long it took; in a D1 batch, D1’s own timing for each statement |
5862
5945
  | `meta` | The database’s result metadata, such as D1’s rows read and written |
5863
5946
  | `error` | The database’s error, when it failed |
5947
+ | `cached` | `true` when the read was answered from memory |
5864
5948
 
5865
5949
  Send these wherever you like. A listener never changes a query’s outcome: one that throws is logged with `console.error`, and the query’s result stands.
5866
5950
 
@@ -5873,6 +5957,10 @@ Set a listener in one of two places:
5873
5957
 
5874
5958
  If both are set, the request’s listener runs first, then the base class’s.
5875
5959
 
5960
+ ### Seeing a cached answer
5961
+
5962
+ Inside `withDatabase`, a read you’ve already sent is answered from the [request cache](/connecting#caching-identical-reads), and your listener still hears it. Its event has `cached: true`, a `durationMs` of 0, and no `meta`, since nothing reached the database.
5963
+
5876
5964
  ## Logging every query
5877
5965
 
5878
5966
  Set `onQuery` on your app’s base class, in `application-record.ts`, to see every statement of every Model:
@@ -9008,6 +9096,10 @@ export async function paidSince(db: D1Database, since: Date) {
9008
9096
 
9009
9097
  For a cache key, or the value a test expects of a raw row, `serialize` gives the stored form too.
9010
9098
 
9099
+ :::warning[Your writes don’t clear the request cache]
9100
+ Inside `withDatabase`, Active Record answers a read it has already sent from memory. It can’t see SQL you send yourself, so after a raw write, call `db.clearRequestCache()` before reading again. See [Clearing the cache](/connecting#clearing-the-cache).
9101
+ :::
9102
+
9011
9103
  ## Reading cells
9012
9104
 
9013
9105
  Turn a cell from a raw query into the attribute’s value with `deserialize`:
@@ -10488,6 +10580,10 @@ test("emails are saved in lowercase", async () => {
10488
10580
 
10489
10581
  Outside a Worker, the database given to `withDatabase` serves every Model on its adapter, whatever binding its base class names. For code that takes a database explicitly, pass it one: `connect(database.binding).model(User)`.
10490
10582
 
10583
+ :::note[Reads are cached for the whole call]
10584
+ Inside `withDatabase`, a read you’ve already sent is [answered from memory](/connecting#caching-identical-reads) until Active Record writes. A test that changes rows with raw SQL, or a long script that checks a row again and again, would read the first answer. Give each test its own `withDatabase` call, call `db.clearRequestCache()` after a raw write, or open the database with `connect(binding, { cache: { request: false } })`.
10585
+ :::
10586
+
10491
10587
  ## Testing your Worker
10492
10588
 
10493
10589
  Call your Worker’s `fetch` handler inside `withDatabase` too, and its queries use the test’s database. This calls the Worker in `src/index.ts`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forestfuture/active-record",
3
- "version": "0.9.1",
3
+ "version": "0.10.0",
4
4
  "description": "A Rails-inspired Active Record for Cloudflare Workers, with an adapter per database.",
5
5
  "keywords": [
6
6
  "active-record",
@@ -46,7 +46,7 @@
46
46
  "jiti": "^2.7.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@electric-sql/pglite": "^0.5.14",
49
+ "@electric-sql/pglite": "^0.5.16",
50
50
  "pg": "^8.23.1"
51
51
  },
52
52
  "peerDependencies": {
@@ -16,9 +16,9 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
16
16
  - Start queries and new records from the Model, as in Rails: `User.find(id)`, `User.where(…)`, `User.build(…)`. Each Model queries the binding named in the generated schema its base class holds, during a request. For a D1 Session, wrap the handler in `withSession(request, env.DB, fn)`. For per-request `onQuery`, or tests and scripts outside a Worker, wrap the code once in `withDatabase(connect(env.DB, { … }), fn)`. Records keep the database they came from.
17
17
  - Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL, and a list matches any of its values. `findOrCreateBy`, `findOrInitializeBy` and `createOrFindBy` throw `TypeError` for a list, a comparison or a `sql` fragment.
18
18
  - Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
19
- - Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column.
19
+ - Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column. `column()` works only inside a fragment: `where({ views: column("likes") })` and `updateAll({ views: column("likes") })` throw, as do one nested in a json value and one given as `find`'s id, so write ``where(sql`${column("views")} = ${column("likes")}`)``.
20
20
  - For a raw `env.DB.prepare(…).bind(…)` statement, bind `Post.typeForAttribute("publishedAt").serialize(date)`, which writes the value as the attribute stores it, and read a cell with `.deserialize(cell)`. A value the attribute can't hold throws `TypeError`.
21
- - Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
21
+ - Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). `upsert(…, { uniqueBy: "email", updateOnly: ["name"] })` updates only `name` on a clash; ``upsertAll(rows, { uniqueBy: "name", onDuplicate: { count: sql`${column("count")} + ${incoming("count")}` } })`` sets each named attribute to a fragment (`column()` the clashing row's value, `incoming()` the new row's) or a value. Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
22
22
  - Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
23
23
  - To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`. To keep a parent's `updatedAt` current as its children change (a cache key), declare `belongsTo(Article, { touch: true })` on the child rather than touching the parent in a callback: the parent is touched in the child's batch, runs its own touch callbacks, and touches its own parents in turn. A parent that isn't loaded costs one SELECT per level, so preload the chain (`includes({ article: "blog" })`) when saving many. `hasOne(Profile, { touch: true })` touches a user's profile the same way when the user is updated, destroyed or touched. For a bulk import, wrap it in `Article.noTouching(async () => { … })`, so no article is touched per comment, then touch each article once after it.
24
24
  - To stop two edits of one record from overwriting each other, add a `lock_version INTEGER NOT NULL DEFAULT 0` column: every save, destroy and `touch()` then checks the row still has the record's `lockVersion`, and a stale copy's throws `StaleRecord` (from `save()` too, not `false`) and writes nothing in its batch (a destroy's dependents on another database are already gone). For edits across requests, put `lockVersion` in the form as a hidden field and permit it with the other fields, and answer `StaleRecord` with a 409; to retry in code, `await record.reload()` and make the change again. A child's `touch` on a locked parent raises the parent's version, so a parent its children touch often gets conflicts: drop the `touch` or write the children inside `noTouching`.
@@ -84,6 +84,7 @@ export default {
84
84
  ## Where code goes wrong
85
85
 
86
86
  - **`onQuery` listeners see filtered attributes' values as `"[FILTERED]"`**: passwords, tokens, keys and emails, by Rails' default list. Add names to `static filterAttributes` on the app's base class for other secrets. Values inside `sql` fragments aren't filtered.
87
+ - **Inside `withDatabase`, an identical read is answered from memory** (the request cache), until a write the library sends inside the call, through any Database handle, clears it. After SQL you send on the binding or a `pg` client yourself, call `db.clearRequestCache()` before reading again. `reload()` always reads the database. `connect(env.DB, { cache: { request: false } })` turns it off.
87
88
  - **`relation.toSql()` shows a query's `{ sql, params }` without sending it**, to inspect it while debugging. The params are real values, filtered attributes included, so don't log them where `onQuery` wouldn't. Bulk writes and batches have no `toSql()`; `onQuery` shows what they sent.
88
89
  - **`toJSON()` sends every loaded attribute**, so `Response.json(user)` includes an `apiKey` column. List the names to leave out in `static hiddenAttributes` on the app's base class (exact names; a Model's own list replaces it). `attributes()` still has them. A secure password, its confirmation, challenge and digest, and a secure token, are left out already; send a token on purpose, as `Response.json({ token: user.authToken })`.
89
90
  - **Uniqueness validation is a friendly check, not a guarantee.** Two requests can pass it at once; the table's UNIQUE index decides, and the save then throws `RecordNotUnique`. Declare both. To create a row once where requests race, use `createOrFindBy(attrs)` (insert, then find on `RecordNotUnique`) with the index alone: a `uniqueness` validation refuses first, so it finds nothing. `findOrCreateBy` races.