@forestfuture/active-record 0.8.0 → 0.8.2

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.
@@ -1,5 +1,5 @@
1
- import { A as CallbackAbort, B as NotNullViolation, C as pluralize, D as AbortAfterPersistence, E as underscore, F as InvalidForeignKey, G as RecordNotFound, I as InvalidModel, J as SoleRecordExceeded, K as RecordNotSaved, L as IrreversibleOrder, N as DeleteRestriction, P as IncompatibleRelation, Q as UnknownModelName, T as camelize, U as RecordInvalid, V as ReadonlyAssociation, W as RecordNotDestroyed, X as UnknownAssociation, Y as StrictValidationFailed, b as enumValuesOf, f as zonelessDateTime, j as CheckViolation, k as AssociationNotLoaded, l as uncastable, o as castValue, p as hexOf, q as RecordNotUnique, r as orderDecimal, u as writeUntypedValue, w as singularize, y as enumValidations, z as NoDatabase } from "./epoch-storage-CDlQZcBB.mjs";
2
- import { A as FILTERED, B as define, C as declared, D as castInherited, E as attributeFor, F as isFiltered, G as defineEnumMethods, H as requireDefined, I as shownKey, K as defineEnumStatics, L as shownValue$1, M as boundValue, N as defaultFilterAttributes, O as noMatch, P as filteredValues, Q as isIgnoringColumns, R as attributeOf, S as declare, T as seal, V as initialValues, W as specProblem, X as explainMissingTable, Y as defineModelName, Z as inferTableNames, _ as inspectCustom, a as isGenerated, b as attributesNamedInMessages, c as methodsOffFixes, d as state, g as FilteredMark, h as fullMessageOf, i as isBase, it as tableOwnerModelName, j as Filtered, k as withArticle, l as RecordState, m as clearErrors, n as defineGeneratedStatics, nt as requireModelName, o as schemaAdapter, ot as ancestors, p as addFailure, q as enumNameProblem, r as hasSettledAttributes, rt as requireTableName, s as settleGenerated, st as staticBelow, t as defineAttributeAccessors, tt as rejectAbstract, u as linksOf, v as printed, w as declaredByClass, x as humanAttributeName, y as styled, z as attributesForColumn } from "./generated-model-g5oWsDKE.mjs";
1
+ import { A as filteredValues, B as specProblem, C as castInherited, D as Filtered, E as FILTERED, F as attributesForColumn, G as declare, H as defineEnumStatics, I as define, J as seal, K as declared, L as initialValues, M as shownKey, N as shownValue$1, O as boundValue, P as attributeOf, Q as isIgnoringColumns, R as requireDefined, S as attributeFor, T as withArticle, U as enumNameProblem, V as defineEnumMethods, X as explainMissingTable, Y as defineModelName, Z as inferTableNames, _ as inspectCustom, a as isGenerated, b as attributesNamedInMessages, c as methodsOffFixes, d as state, g as FilteredMark, h as fullMessageOf, i as isBase, it as tableOwnerModelName, j as isFiltered, k as defaultFilterAttributes, l as RecordState, m as clearErrors, n as defineGeneratedStatics, nt as requireModelName, o as schemaAdapter, ot as ancestors, p as addFailure, q as declaredByClass, r as hasSettledAttributes, rt as requireTableName, s as settleGenerated, st as staticBelow, t as defineAttributeAccessors, tt as rejectAbstract, u as linksOf, v as printed, w as noMatch, x as humanAttributeName, y as styled } from "./generated-model-FB7oT7V1.mjs";
2
+ import { $ as abort, A as CallbackAbort, B as NotNullViolation, C as pluralize, D as AbortAfterPersistence, E as underscore, F as InvalidForeignKey, G as RecordNotFound, I as InvalidModel, J as SoleRecordExceeded, K as RecordNotSaved, L as IrreversibleOrder, N as DeleteRestriction, O as ActiveRecordError, P as IncompatibleRelation, Q as UnknownModelName, T as camelize, U as RecordInvalid, V as ReadonlyAssociation, W as RecordNotDestroyed, X as UnknownAssociation, Y as StrictValidationFailed, b as enumValuesOf, f as zonelessDateTime, j as CheckViolation, k as AssociationNotLoaded, l as uncastable, o as castValue, p as hexOf, q as RecordNotUnique, r as orderDecimal, u as writeUntypedValue, w as singularize, y as enumValidations, z as NoDatabase } from "./epoch-storage-C7186hd1.mjs";
3
3
  // src/foreign-keys.ts
4
4
  /**
5
5
  * Gives each declaration its foreign key: the one passed, or else inferred by Rails'
@@ -249,6 +249,34 @@ function conversionsFor(model, attribute) {
249
249
  deserialize: (stored) => resolved.read(stored)
250
250
  });
251
251
  }
252
+ // src/load-callbacks.ts
253
+ /** Runs a record's `afterFind`, then its `afterInitialize`: it was just loaded from a row. */
254
+ function runLoadedCallbacks(record) {
255
+ runSyncCallbacks(record, "afterFind");
256
+ runSyncCallbacks(record, "afterInitialize");
257
+ }
258
+ /** Runs a record's `afterInitialize`: it was just built, and handed to any `init`. */
259
+ function runBuiltCallbacks(record) {
260
+ runSyncCallbacks(record, "afterInitialize");
261
+ }
262
+ /** Runs the Model's callbacks of `kind` in declaration order; none may return a promise. */
263
+ function runSyncCallbacks(record, kind) {
264
+ const model = modelOf(record);
265
+ for (const callback of declared(model, kind)) refuseThenable(callback(record), `${model.name}.${kind}: a callback returned a promise, which nothing awaits; ${kind} runs synchronously`);
266
+ }
267
+ /**
268
+ * Throws `TypeError` with `message` if `result` is a promise or another thenable, which the code
269
+ * that ran it can't await. Its rejection, if it has one, is handled here, so the `TypeError` is
270
+ * the only error.
271
+ */
272
+ function refuseThenable(result, message) {
273
+ if (!isThenable$1(result)) return;
274
+ Promise.resolve(result).catch(() => {});
275
+ throw new TypeError(message);
276
+ }
277
+ function isThenable$1(value) {
278
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
279
+ }
252
280
  // src/validation-context.ts
253
281
  /** The contexts every Model has: a new record's, and a saved one's. */
254
282
  const BUILT_IN_CONTEXTS = ["create", "update"];
@@ -1541,23 +1569,31 @@ function violation({ kind, table, columns }, models, cause) {
1541
1569
  cause
1542
1570
  });
1543
1571
  }
1572
+ // src/async-storage.ts
1573
+ /** The Wrangler settings that give a Worker Node.js compatibility, for the errors that need it. */
1574
+ const NODE_COMPATIBILITY = "a compatibility_date of 2026-08-04 or later, or the nodejs_compat flag, in your Wrangler config";
1575
+ /** A new AsyncLocalStorage, or `undefined` without Node.js compatibility. */
1576
+ function newAsyncStorage() {
1577
+ const hooks = globalThis.process?.getBuiltinModule?.("node:async_hooks");
1578
+ return hooks === void 0 ? void 0 : new hooks.AsyncLocalStorage();
1579
+ }
1544
1580
  // src/request-store.ts
1545
1581
  /** The storage, once `withDatabase` has been called. */
1546
- let storage;
1547
- /** Node's AsyncLocalStorage, loaded when it's first needed, so Workers without Node.js compatibility still build. */
1582
+ let storage$1;
1583
+ /** The storage `withDatabase` keeps its databases in. */
1548
1584
  function newStorage() {
1549
- const hooks = globalThis.process?.getBuiltinModule?.("node:async_hooks");
1550
- if (hooks === void 0) throw new NoDatabase("withDatabase needs Node.js compatibility: a compatibility_date of 2026-08-04 or later, or the nodejs_compat flag, in your Wrangler config");
1551
- return new hooks.AsyncLocalStorage();
1585
+ const created = newAsyncStorage();
1586
+ if (created === void 0) throw new NoDatabase(`withDatabase needs Node.js compatibility: ${NODE_COMPATIBILITY}`);
1587
+ return created;
1552
1588
  }
1553
1589
  /** What the current `withDatabase` keeps, if code runs inside one. */
1554
1590
  function requestStore() {
1555
- return storage?.getStore();
1591
+ return storage$1?.getStore();
1556
1592
  }
1557
1593
  /** Runs `fn` with `store` as the request's. */
1558
1594
  function runWithStore(store, fn) {
1559
- storage ??= newStorage();
1560
- return storage.run(store, fn);
1595
+ storage$1 ??= newStorage();
1596
+ return storage$1.run(store, fn);
1561
1597
  }
1562
1598
  // src/executor.ts
1563
1599
  /**
@@ -1812,25 +1848,24 @@ var JointExecutor = class extends ForwardingExecutor {
1812
1848
  };
1813
1849
  // src/counters.ts
1814
1850
  /**
1815
- * What `touch` sets, each to now: `updatedAt` when the Model has it, and those named, each a
1851
+ * What `touch` sets, each to `now`: `updatedAt` when the Model has it, and those named, each a
1816
1852
  * datetime attribute (a `TypeError` naming `method` otherwise).
1817
1853
  */
1818
- function touchAssignments(model, touch, method) {
1854
+ function touchAssignments(model, touch, method, now = /* @__PURE__ */ new Date()) {
1819
1855
  if (touch === void 0 || touch === false) return [];
1820
1856
  const named = touch === true ? [] : Array.isArray(touch) ? touch : [touch];
1821
1857
  const updatedAt = model.attributeDefinitions.get("updatedAt")?.type === "datetime";
1822
- const names = [.../* @__PURE__ */ new Set([...updatedAt ? ["updatedAt"] : [], ...named.map(String)])];
1823
- const now = /* @__PURE__ */ new Date();
1824
- return names.map((name) => {
1858
+ return [.../* @__PURE__ */ new Set([...updatedAt ? ["updatedAt"] : [], ...named.map(String)])].map((name) => {
1825
1859
  if (attributeOf(model, name).type !== "datetime") throw new TypeError(`${model.name}.${method}: touch takes datetime attributes; ${name} isn't one`);
1826
1860
  return [name, now];
1827
1861
  });
1828
1862
  }
1829
1863
  /**
1830
1864
  * `x = COALESCE(x, 0) + ?, …` for each counter, so a NULL counts as zero and concurrent writes
1831
- * all count. `{}`, an attribute that isn't a number, or an amount that isn't one, is a `TypeError`.
1865
+ * all count, then the timestamps `touch` sets (or those already `touched`). `{}`, an attribute
1866
+ * that isn't a number, or an amount that isn't one, is a `TypeError`.
1832
1867
  */
1833
- function counterSets(model, counters, method, touch) {
1868
+ function counterSets(model, counters, method, { touch, touched } = {}) {
1834
1869
  const entries = Object.entries(counters);
1835
1870
  if (entries.length === 0) throw new TypeError(`${method} needs at least one counter`);
1836
1871
  const strings = [""];
@@ -1841,7 +1876,7 @@ function counterSets(model, counters, method, touch) {
1841
1876
  values.push(column(name), column(name), column(name).value(amount(by, method)));
1842
1877
  strings.push(" = COALESCE(", ", 0) + ", "");
1843
1878
  }
1844
- for (const [name, now] of touchAssignments(model, touch, method)) {
1879
+ for (const [name, now] of touched ?? touchAssignments(model, touch, method)) {
1845
1880
  strings[strings.length - 1] = ", ";
1846
1881
  values.push(column(name), column(name).value(now));
1847
1882
  strings.push(" = ", "");
@@ -1864,158 +1899,443 @@ function requireAttributeType(model, name, method, ...types) {
1864
1899
  const definition = attributeOf(model, name);
1865
1900
  if (!(definition.enum === void 0 && definition.customType === void 0) || !types.includes(definition.type)) throw new TypeError(`${model.name}.${method}("${name}") takes ${types.join(" or ")} attributes; ${name} isn't one`);
1866
1901
  }
1867
- // src/finder-order.ts
1868
- /** The same term sorting the other way; NULLs move to the other end too, as in Rails. */
1869
- function reversed(term) {
1870
- return term instanceof JoinedOrder ? new JoinedOrder(term.path, reversedTerm(term.term)) : reversedTerm(term);
1871
- }
1872
- /** An attribute's or a fragment's term, reversed. */
1873
- function reversedTerm(term) {
1874
- if (term instanceof SafeSql) throw new IrreversibleOrder("last() can't reverse an order given as an sql fragment; order by attributes, or reverse the fragment yourself and use first()");
1875
- const direction = term.direction === "asc" ? "desc" : "asc";
1876
- const nulls = term.nulls && (term.nulls === "first" ? "last" : "first");
1902
+ // src/counter-caches.ts
1903
+ /**
1904
+ * A belongsTo's `counterCache` in one shape: the attribute it names, if it names one, and
1905
+ * whether `size` reads it (not with `active: false`). Checked already, by `checkCounterValue`.
1906
+ */
1907
+ function counterCacheOf({ counterCache }) {
1908
+ if (typeof counterCache === "object") return {
1909
+ attribute: counterCache.attribute,
1910
+ isActive: counterCache.active !== false
1911
+ };
1877
1912
  return {
1878
- ...term,
1879
- direction,
1880
- ...nulls && { nulls }
1913
+ attribute: typeof counterCache === "string" ? counterCache : void 0,
1914
+ isActive: true
1881
1915
  };
1882
1916
  }
1883
- /** Up to `rows` records from the page: `limit(0)` stays empty, and `offset` is kept by the caller. */
1884
- function atMost(rows, limit) {
1885
- return Math.min(limit ?? rows, rows);
1886
- }
1887
- /** One record from the page, as `atMost` takes it. */
1888
- function atMostOne(limit) {
1889
- return atMost(1, limit);
1917
+ /**
1918
+ * The counter a belongsTo's `counterCache` keeps on its target: the attribute it names, or by
1919
+ * Rails' convention the owner's plural name + `Count` (`Reply` → `repliesCount`).
1920
+ */
1921
+ function counterAttribute(owner, definition) {
1922
+ const named = counterCacheOf(definition).attribute;
1923
+ if (named !== void 0) return named;
1924
+ const plural = pluralize(tableOwnerModelName(owner));
1925
+ return `${plural.charAt(0).toLowerCase()}${plural.slice(1)}Count`;
1890
1926
  }
1891
1927
  /**
1892
- * `query`'s order, ended with what makes a row unique, so tied rows keep their pages between
1893
- * requests: the primary key, or after `distinct()`, the selected attributes (the key isn't
1894
- * loaded). Those already in the order aren't added again.
1928
+ * A counter cache is a belongsTo's, and names, or infers, an attribute of each Model it points at.
1895
1929
  */
1896
- function stableOrder(model, query) {
1897
- const unique = query.distinct && query.select ? query.select : [model.primaryKey];
1898
- const ordered = new Set(query.order.map((term) => !(term instanceof SafeSql) && !(term instanceof JoinedOrder) && term.attribute));
1899
- const ties = unique.filter((attribute) => !ordered.has(attribute)).map((attribute) => ({
1930
+ function checkCounterCache(label, owner, definition, targets) {
1931
+ const { counterCache, kind } = definition;
1932
+ if (counterCache === void 0) return;
1933
+ if (kind !== "belongsTo") return checkCollectionCounter(label, owner, definition, targets);
1934
+ checkCounterValue(label, counterCache, targets);
1935
+ const elsewhere = targets.find((target) => isOnDifferentDatabases(owner, target));
1936
+ if (elsewhere !== void 0) throw new InvalidModel(`${label} keeps a counter cache on another database, which it can't yet: ${owner.name} and ${elsewhere.name} must be on one`);
1937
+ const attribute = counterAttribute(owner, definition);
1938
+ const hint = counterCacheOf(definition).attribute !== void 0 ? "check counterCache" : `counterCache: true infers it from ${owner.name}; declare it, or name another`;
1939
+ for (const target of targets) requireCounter(label, target, attribute, hint);
1940
+ refuseCountingTwice(label, owner, definition, {
1900
1941
  attribute,
1901
- direction: "asc"
1902
- }));
1903
- return [...query.order, ...ties];
1904
- }
1905
- /** `query`'s order, then the primary key ascending, so ties come back the same way. */
1906
- function thenPrimaryKey(model, query) {
1907
- return [...query.order, {
1908
- attribute: model.primaryKey,
1909
- direction: "asc"
1910
- }];
1942
+ targets
1943
+ });
1911
1944
  }
1912
- /** `query`'s order, or the primary key ascending without one: what `first` and `last` use. */
1913
- function finderOrder(model, query) {
1914
- const { order } = query;
1915
- return order.length > 0 ? order : [{
1916
- attribute: model.primaryKey,
1917
- direction: "asc"
1918
- }];
1945
+ /**
1946
+ * Another belongsTo on the same foreign key can't keep the same attribute on a table this one
1947
+ * points at: each record would be counted in it twice.
1948
+ */
1949
+ function refuseCountingTwice(label, owner, definition, { attribute, targets }) {
1950
+ const tables = new Set(targets.map((target) => target.table));
1951
+ for (const [name, other] of associationsOf(owner)) if (other !== definition && other.kind === "belongsTo" && other.counterCache !== void 0 && other.foreignKey === definition.foreignKey && counterAttribute(owner, other) === attribute && (other.targets?.() ?? [other.target()]).some((target) => tables.has(target.table))) throw new InvalidModel(`${label}: ${name} keeps "${attribute}" on ${targets[0].name} by ${definition.foreignKey} too, so a record would count twice (name another counterCache)`);
1919
1952
  }
1920
- /** The first record `query` gives in `order`, keeping its offset, or null: what `first`, `last` and `take` load. */
1921
- async function oneInOrder(runner, query, order) {
1922
- const [record] = await runner.load({
1923
- ...query,
1924
- order,
1925
- limit: atMostOne(query.limit)
1926
- });
1927
- return record ?? null;
1953
+ /** `target`'s `attribute` must be a plain number attribute (integer or real) to keep a count. */
1954
+ function requireCounter(label, target, attribute, hint) {
1955
+ const definition = target.attributeDefinitions.get(attribute);
1956
+ if (definition === void 0) throw new InvalidModel(`${label}: ${target.name} has no attribute "${attribute}" (${hint})`);
1957
+ if (!(definition.type === "integer" || definition.type === "real") || definition.enum !== void 0 || definition.customType !== void 0) throw new InvalidModel(`${label}: ${target.name}'s "${attribute}" can't keep a count; counterCache takes an integer or real attribute`);
1928
1958
  }
1929
1959
  /**
1930
- * The only record `query` gives, asking for two rows (keeping its order and offset): a join's
1931
- * repeated rows count as more than one, as Rails counts them.
1960
+ * A hasMany's `counterCache` names the counter a belongsTo of its records keeps on the owner, by
1961
+ * the same keys; a hasOne takes none. Read from the declarations, since the records' Model may not be ready yet.
1932
1962
  */
1933
- async function soleIn(runner, query) {
1934
- return onlyOne$1(query.model, await runner.load({
1935
- ...query,
1936
- limit: atMost(2, query.limit)
1937
- }));
1963
+ function checkCollectionCounter(label, owner, { kind, counterCache, foreignKey, primaryKey }, [target]) {
1964
+ const records = target;
1965
+ if (kind !== "hasMany") throw new InvalidModel(`${label}: a ${kind} takes no counterCache; declare it on ${records.name}'s belongsTo`);
1966
+ if (typeof counterCache !== "string") throw new InvalidModel(`${label}: a hasMany's counterCache names the attribute it reads`);
1967
+ if (![...associationsOf(records).values()].some((each) => each.kind === "belongsTo" && each.counterCache !== void 0 && each.foreignKey === foreignKey && counterAttribute(records, each) === counterCache && (each.targets?.() ?? [each.target()]).some((pointed) => (owner === pointed || owner.prototype instanceof pointed) && (each.primaryKey ?? pointed.primaryKey) === (primaryKey ?? owner.primaryKey)))) throw new InvalidModel(`${label}: no belongsTo of ${records.name} keeps "${counterCache}" on ${owner.name} (check counterCache)`);
1938
1968
  }
1939
- /** The one record in `records`; `RecordNotFound` with none, `SoleRecordExceeded` with more. */
1940
- function onlyOne$1(model, records) {
1941
- const [record] = records;
1942
- if (record === void 0) throw notFound(model);
1943
- if (records.length > 1) throw new SoleRecordExceeded(`Wanted only one ${model.name}`);
1944
- return record;
1969
+ /** `counterCache` is `true`, an attribute's name, or `{ attribute, active: false }`. */
1970
+ function checkCounterValue(label, counterCache, targets) {
1971
+ if (counterCache === true || typeof counterCache === "string") return;
1972
+ if (typeof counterCache === "object" && counterCache !== null) {
1973
+ const { attribute, active, ...rest } = counterCache;
1974
+ if (active !== void 0 && active !== false) throw new InvalidModel(`${label}: counterCache's active takes false`);
1975
+ const [unknown] = Object.keys(rest);
1976
+ if (unknown !== void 0) throw new InvalidModel(`${label}: counterCache takes no "${unknown}"; use attribute or active`);
1977
+ if (attribute === void 0 || typeof attribute === "string") return;
1978
+ }
1979
+ const names = targets.map((target) => target.name).join(" or ");
1980
+ throw new InvalidModel(`${label}: counterCache takes true, the name of ${names}'s attribute, or { attribute, active: false }`);
1945
1981
  }
1946
- /** `record`, or the `RecordNotFound` a finder that must find one throws: `firstOrThrow`'s. */
1947
- function foundOrThrow(model, record) {
1948
- if (record === null) throw notFound(model);
1949
- return record;
1982
+ /** The counter caches a Model's records keep: each belongsTo's declaring one, on each target. */
1983
+ function countersOf(owner) {
1984
+ return [...associationsOf(owner)].flatMap(([name, definition]) => {
1985
+ if (definition.kind !== "belongsTo" || definition.counterCache === void 0) return [];
1986
+ const attribute = counterAttribute(owner, definition);
1987
+ const { foreignKey } = definition;
1988
+ const { isActive } = counterCacheOf(definition);
1989
+ return resolveAssociation(owner, name).branches.map(({ target, targetAttribute, type }) => ({
1990
+ name,
1991
+ foreignKey,
1992
+ target,
1993
+ attribute,
1994
+ targetKey: targetAttribute,
1995
+ type,
1996
+ isActive
1997
+ }));
1998
+ });
1950
1999
  }
1951
- /** What a finder that must find a record throws when it finds none. */
1952
- function notFound(model) {
1953
- return new RecordNotFound(`${model.name} not found`);
2000
+ /**
2001
+ * Whether the type a record holds, as `typeIn` reads it, names `counter`'s target: always, for
2002
+ * a belongsTo that isn't polymorphic.
2003
+ */
2004
+ function isTypeOfTarget(counter, typeIn) {
2005
+ return counter.type === void 0 || typeIn(counter.type.attribute) === counter.type.value;
1954
2006
  }
1955
- // src/load.ts
1956
- /** How `query`, a Relation's, runs: on `executor`, unless it's a `none()` query. */
1957
- function runnerFor(executor, model, query) {
1958
- if (query.none) return nothing$1;
2007
+ /** A write's counter changes: `before` and `after` its own statement, then `by` on `loaded`. */
2008
+ function counterChanges(record, [before, after], loaded, by) {
1959
2009
  return {
1960
- load: (description) => loadRecords(executor, model, description),
1961
- loadCounted: (description, counted) => loadCounted(executor, model, description, counted),
1962
- loadAhead: (description) => loadAhead(executor, model, description),
1963
- rows: (sql) => executor.all(sql()),
1964
- changes: async (write) => (await write()).rowsAffected
2010
+ around: (own) => [
2011
+ ...before,
2012
+ own,
2013
+ ...after
2014
+ ],
2015
+ commit(results) {
2016
+ if ((results[before.length]?.rowsAffected ?? 0) > 0) countLoaded(record, loaded, by);
2017
+ }
1965
2018
  };
1966
2019
  }
1967
- /** A `none()` query's runner: nothing is sent, so nothing is found or changed. */
1968
- const nothing$1 = {
1969
- load: async () => [],
1970
- loadCounted: async () => ({
1971
- records: [],
1972
- count: 0
1973
- }),
1974
- loadAhead: async () => ({
1975
- records: [],
1976
- hasMore: false
1977
- }),
1978
- rows: async () => [],
1979
- changes: async () => 0
2020
+ /** A write that changes no counter: a record that was never saved has no row to delete. */
2021
+ const noCounterChanges = {
2022
+ around: (own) => [own],
2023
+ commit: () => {}
1980
2024
  };
1981
- /** One SELECT for `query`'s records, hydrated, with its includes preloaded. */
1982
- async function loadRecords(executor, model, query) {
1983
- const own = (loaded) => [selectFor(executor.dialect, model, loaded)];
1984
- return (await loadWith(executor, model, {
1985
- query,
1986
- own,
1987
- rowsOf: ([rows]) => rows
1988
- })).records;
1989
- }
1990
- /** The count of `counted` and the SELECT for `query`'s records as one batch: one round trip. */
1991
- async function loadCounted(executor, model, query, counted) {
1992
- const { dialect } = executor;
1993
- const countSql = compileCount(dialect, counted);
1994
- const own = (loaded) => [countSql, selectFor(dialect, model, loaded)];
1995
- const loaded = await loadWith(executor, model, {
1996
- query,
1997
- own,
1998
- rowsOf: ([, rows]) => rows
2025
+ /** Counting a new record in: each counter cache whose key is set, on its target by that key. */
2026
+ function countersOnInsert(record) {
2027
+ const recordState = record[state];
2028
+ const counted = countersOf(modelOf(record)).filter((counter) => {
2029
+ const key = recordState.read(counter.foreignKey);
2030
+ return key !== null && key !== void 0 && isTypeOfTarget(counter, (name) => recordState.read(name));
1999
2031
  });
2000
- const [countRows] = loaded.results;
2001
- return {
2002
- records: loaded.records,
2003
- count: Number(countRows?.[0]?.["count"] ?? 0)
2004
- };
2032
+ return counterChanges(record, [[], counted.map((counter) => {
2033
+ const key = keyed(counter, recordState.read(counter.foreignKey));
2034
+ return compileCounterChange(counter, changeBy(counter, 1), key);
2035
+ })], counted, 1);
2005
2036
  }
2006
- /** One SELECT for `query`'s records and one past its limit, which is read but not loaded. */
2007
- async function loadAhead(executor, model, query) {
2008
- const own = (loaded) => [selectFor(executor.dialect, model, {
2009
- ...loaded,
2010
- limit: query.limit + 1
2011
- })];
2012
- const rowsOf = ([rows]) => rows?.slice(0, query.limit);
2013
- const { records, results } = await loadWith(executor, model, {
2014
- query,
2015
- own,
2016
- rowsOf
2017
- });
2018
- return {
2037
+ /**
2038
+ * Counting a record out, before its row is deleted: each finds its target through the stored
2039
+ * row, so a row already gone counts nothing, and a key changed in the database since the record
2040
+ * was read counts out the target it has now.
2041
+ */
2042
+ function countersOnDestroy(record) {
2043
+ const recordState = record[state];
2044
+ const skipped = destroyedThrough.get(record);
2045
+ const counted = countersOf(modelOf(record)).filter((counter) => counter.foreignKey !== skipped && isTypeOfTarget(counter, (name) => recordState.valueInDatabase(name)));
2046
+ return counterChanges(record, [counted.map((counter) => changeThroughRow(record, counter, -1, "before")), []], counted, -1);
2047
+ }
2048
+ /**
2049
+ * Moving a record's count when its foreign key, or a polymorphic belongsTo's type, changes: out
2050
+ * of the target its stored row points at before the UPDATE, and into the one it points at after
2051
+ * it, so a row that isn't there counts nothing. A loaded new target counts it in memory, as
2052
+ * Rails' `increment!` does.
2053
+ */
2054
+ function countersOnUpdate(record) {
2055
+ const recordState = record[state];
2056
+ const moved = countersOf(modelOf(record)).filter(({ foreignKey, type }) => [foreignKey, type?.attribute].some((name) => name !== void 0 && recordState.isAttributeChanged(name)));
2057
+ const from = moved.filter((counter) => isTypeOfTarget(counter, (name) => recordState.valueInDatabase(name)));
2058
+ const to = moved.filter((counter) => isTypeOfTarget(counter, (name) => recordState.read(name)));
2059
+ return counterChanges(record, [from.map((counter) => changeThroughRow(record, counter, -1, "before")), to.map((counter) => changeThroughRow(record, counter, 1, "after"))], to, 1);
2060
+ }
2061
+ /** Each counter's target the record has loaded for its key takes the change, as stored. */
2062
+ function countLoaded(record, counters, by) {
2063
+ for (const { name, attribute } of counters) {
2064
+ const target = record[state].associations.get(name)?.value;
2065
+ if (target instanceof Model) addToCount(target, attribute, by);
2066
+ }
2067
+ }
2068
+ /**
2069
+ * A record whose counter the database changed by `by` takes the change, as stored: the
2070
+ * attribute, if loaded, changes by `by` and has no unsaved change, as after Rails' `increment!`.
2071
+ */
2072
+ function addToCount(record, attribute, by) {
2073
+ const recordState = record[state];
2074
+ if (recordState.isDestroyed || !(attribute in recordState.attributes())) return;
2075
+ const count = recordState.read(attribute);
2076
+ recordState.write(attribute, (typeof count === "number" ? count : 0) + by);
2077
+ recordState.commitColumns([attribute]);
2078
+ }
2079
+ /**
2080
+ * `counter`'s change by `by` on the target the record's row points at, found by the row's key
2081
+ * `before` its write, or `after` it (its key as the record holds it, should the write change it).
2082
+ */
2083
+ function changeThroughRow(record, counter, by, when) {
2084
+ const owner = modelOf(record);
2085
+ const recordState = record[state];
2086
+ const params = [];
2087
+ const ownerKey = attributeFor(owner, owner.primaryKey);
2088
+ if (when === "before") ownerKey.bindCells(params, recordState.storedKey);
2089
+ else ownerKey.bind(params, recordState.read(owner.primaryKey));
2090
+ const foreignKey = quoteIdentifier(attributeFor(owner, counter.foreignKey).column);
2091
+ const typed = counter.type === void 0 ? "" : ` AND ${typeCondition(owner, counter.type, params)}`;
2092
+ const row = `(SELECT ${foreignKey} FROM ${quoteIdentifier(owner.table)} WHERE ${quoteIdentifier(ownerKey.column)} = ${typed})`;
2093
+ return compileCounterChange(counter, changeBy(counter, by), {
2094
+ sql: row,
2095
+ params
2096
+ });
2097
+ }
2098
+ /**
2099
+ * The foreign key of the association each record is being destroyed through, by its owner's
2100
+ * `dependent: "destroy"`: that owner is deleted with it, so its counter isn't changed, as Rails
2101
+ * skips it (`destroyed_by_association`). Not request state: set only while a destroy is prepared.
2102
+ */
2103
+ const destroyedThrough = /* @__PURE__ */ new WeakMap();
2104
+ /**
2105
+ * Whether `record` is being destroyed through its owner's association by `foreignKey`, whose
2106
+ * owner is deleted with it, so it doesn't touch that owner either (#353).
2107
+ */
2108
+ function isDestroyedThrough(record, foreignKey) {
2109
+ return destroyedThrough.get(record) === foreignKey;
2110
+ }
2111
+ /** Prepares `record`'s destroy through its owner's association, whose `foreignKey` is given. */
2112
+ async function destroyingThrough(record, foreignKey, prepare) {
2113
+ destroyedThrough.set(record, foreignKey);
2114
+ try {
2115
+ return await prepare();
2116
+ } finally {
2117
+ destroyedThrough.delete(record);
2118
+ }
2119
+ }
2120
+ /** A target's key, `= ?` with `key` bound as the counter's target key. */
2121
+ function keyed({ target, targetKey }, key) {
2122
+ const params = [];
2123
+ attributeFor(target, targetKey).bind(params, key);
2124
+ return {
2125
+ sql: "\0",
2126
+ params
2127
+ };
2128
+ }
2129
+ /** `+ ?`, with `by` bound as the counter's value: hidden from `onQuery` if it's filtered. */
2130
+ function changeBy({ target, attribute }, by) {
2131
+ const params = [];
2132
+ attributeFor(target, attribute).bindCells(params, by);
2133
+ return {
2134
+ sql: `+ `,
2135
+ params
2136
+ };
2137
+ }
2138
+ /**
2139
+ * `UPDATE … SET counter = COALESCE(counter, 0) <change> WHERE key = <key>`: `change` an operator
2140
+ * and its operand (`+ ?`), `key` the target's key or a subquery finding it.
2141
+ */
2142
+ function compileCounterChange(counter, change, key) {
2143
+ return compileCountersChange([counter], change, key);
2144
+ }
2145
+ /**
2146
+ * `compileCounterChange` for several counters of one target, found by one key, each changed by
2147
+ * `change`, in one UPDATE: Postgres changes a row once in one statement, so two UPDATEs of it in
2148
+ * one would keep only one change.
2149
+ */
2150
+ function compileCountersChange(counters, change, key) {
2151
+ const { target, targetKey } = counters[0];
2152
+ const sets = counters.map(({ attribute }) => {
2153
+ const column = quoteIdentifier(attributeFor(target, attribute).column);
2154
+ return `${column} = COALESCE(${column}, 0) ${change.sql}`;
2155
+ });
2156
+ const keyColumn = quoteIdentifier(attributeFor(target, targetKey).column);
2157
+ return {
2158
+ sql: `UPDATE ${quoteIdentifier(target.table)} SET ${sets.join(", ")} WHERE ${keyColumn} = ${key.sql}`,
2159
+ params: [...counters.flatMap(() => change.params), ...key.params],
2160
+ model: target
2161
+ };
2162
+ }
2163
+ /** `type = ?`: a polymorphic row's type naming the counter's target, its value bound. */
2164
+ function typeCondition(owner, { attribute, value }, params) {
2165
+ const type = attributeFor(owner, attribute);
2166
+ type.bind(params, value);
2167
+ return `${quoteIdentifier(type.column)} = `;
2168
+ }
2169
+ // src/finder-order.ts
2170
+ /** The same term sorting the other way; NULLs move to the other end too, as in Rails. */
2171
+ function reversed(term) {
2172
+ return term instanceof JoinedOrder ? new JoinedOrder(term.path, reversedTerm(term.term)) : reversedTerm(term);
2173
+ }
2174
+ /** An attribute's or a fragment's term, reversed. */
2175
+ function reversedTerm(term) {
2176
+ if (term instanceof SafeSql) throw new IrreversibleOrder("last() can't reverse an order given as an sql fragment; order by attributes, or reverse the fragment yourself and use first()");
2177
+ const direction = term.direction === "asc" ? "desc" : "asc";
2178
+ const nulls = term.nulls && (term.nulls === "first" ? "last" : "first");
2179
+ return {
2180
+ ...term,
2181
+ direction,
2182
+ ...nulls && { nulls }
2183
+ };
2184
+ }
2185
+ /** Up to `rows` records from the page: `limit(0)` stays empty, and `offset` is kept by the caller. */
2186
+ function atMost(rows, limit) {
2187
+ return Math.min(limit ?? rows, rows);
2188
+ }
2189
+ /** One record from the page, as `atMost` takes it. */
2190
+ function atMostOne(limit) {
2191
+ return atMost(1, limit);
2192
+ }
2193
+ /**
2194
+ * `query`'s order, ended with what makes a row unique, so tied rows keep their pages between
2195
+ * requests: the primary key, or after `distinct()`, the selected attributes (the key isn't
2196
+ * loaded). Those already in the order aren't added again.
2197
+ */
2198
+ function stableOrder(model, query) {
2199
+ const unique = query.distinct && query.select ? query.select : [model.primaryKey];
2200
+ const ordered = new Set(query.order.map((term) => !(term instanceof SafeSql) && !(term instanceof JoinedOrder) && term.attribute));
2201
+ const ties = unique.filter((attribute) => !ordered.has(attribute)).map((attribute) => ({
2202
+ attribute,
2203
+ direction: "asc"
2204
+ }));
2205
+ return [...query.order, ...ties];
2206
+ }
2207
+ /** `query`'s order, then the primary key ascending, so ties come back the same way. */
2208
+ function thenPrimaryKey(model, query) {
2209
+ return [...query.order, {
2210
+ attribute: model.primaryKey,
2211
+ direction: "asc"
2212
+ }];
2213
+ }
2214
+ /** `query`'s order, or the primary key ascending without one: what `first` and `last` use. */
2215
+ function finderOrder(model, query) {
2216
+ const { order } = query;
2217
+ return order.length > 0 ? order : [{
2218
+ attribute: model.primaryKey,
2219
+ direction: "asc"
2220
+ }];
2221
+ }
2222
+ /** The first record `query` gives in `order`, keeping its offset, or null: what `first`, `last` and `take` load. */
2223
+ async function oneInOrder(runner, query, order) {
2224
+ const [record] = await runner.load({
2225
+ ...query,
2226
+ order,
2227
+ limit: atMostOne(query.limit)
2228
+ });
2229
+ return record ?? null;
2230
+ }
2231
+ /**
2232
+ * The only record `query` gives, asking for two rows (keeping its order and offset): a join's
2233
+ * repeated rows count as more than one, as Rails counts them.
2234
+ */
2235
+ async function soleIn(runner, query) {
2236
+ return onlyOne$1(query.model, await runner.load({
2237
+ ...query,
2238
+ limit: atMost(2, query.limit)
2239
+ }));
2240
+ }
2241
+ /** The one record in `records`; `RecordNotFound` with none, `SoleRecordExceeded` with more. */
2242
+ function onlyOne$1(model, records) {
2243
+ const [record] = records;
2244
+ if (record === void 0) throw notFound(model);
2245
+ if (records.length > 1) throw new SoleRecordExceeded(`Wanted only one ${model.name}`);
2246
+ return record;
2247
+ }
2248
+ /** `record`, or the `RecordNotFound` a finder that must find one throws: `firstOrThrow`'s. */
2249
+ function foundOrThrow(model, record) {
2250
+ if (record === null) throw notFound(model);
2251
+ return record;
2252
+ }
2253
+ /** What a finder that must find a record throws when it finds none. */
2254
+ function notFound(model) {
2255
+ return new RecordNotFound(`${model.name} not found`);
2256
+ }
2257
+ // src/load.ts
2258
+ /**
2259
+ * How `query`, a Relation's, runs: on `executor`, unless it's a `none()` query. Each record it
2260
+ * loads through a hasMany points back at its owner (#62).
2261
+ */
2262
+ function runnerFor(executor, model, query, collection) {
2263
+ if (query.none) return nothing$1;
2264
+ const pointBack = (records) => {
2265
+ for (const record of records) collection.pointBack(record);
2266
+ };
2267
+ return {
2268
+ async load(description) {
2269
+ const records = await loadRecords(executor, model, description);
2270
+ pointBack(records);
2271
+ return records;
2272
+ },
2273
+ async loadCounted(description, counted) {
2274
+ const loaded = await loadCounted(executor, model, description, counted);
2275
+ pointBack(loaded.records);
2276
+ return loaded;
2277
+ },
2278
+ async loadAhead(description) {
2279
+ const loaded = await loadAhead(executor, model, description);
2280
+ pointBack(loaded.records);
2281
+ return loaded;
2282
+ },
2283
+ rows: (sql) => executor.all(sql()),
2284
+ changes: async (write) => (await write()).rowsAffected
2285
+ };
2286
+ }
2287
+ /** A `none()` query's runner: nothing is sent, so nothing is found or changed. */
2288
+ const nothing$1 = {
2289
+ load: async () => [],
2290
+ loadCounted: async () => ({
2291
+ records: [],
2292
+ count: 0
2293
+ }),
2294
+ loadAhead: async () => ({
2295
+ records: [],
2296
+ hasMore: false
2297
+ }),
2298
+ rows: async () => [],
2299
+ changes: async () => 0
2300
+ };
2301
+ /** One SELECT for `query`'s records, hydrated, with its includes preloaded. */
2302
+ async function loadRecords(executor, model, query) {
2303
+ const own = (loaded) => [selectFor(executor.dialect, model, loaded)];
2304
+ return (await loadWith(executor, model, {
2305
+ query,
2306
+ own,
2307
+ rowsOf: ([rows]) => rows
2308
+ })).records;
2309
+ }
2310
+ /** The count of `counted` and the SELECT for `query`'s records as one batch: one round trip. */
2311
+ async function loadCounted(executor, model, query, counted) {
2312
+ const { dialect } = executor;
2313
+ const countSql = compileCount(dialect, counted);
2314
+ const own = (loaded) => [countSql, selectFor(dialect, model, loaded)];
2315
+ const loaded = await loadWith(executor, model, {
2316
+ query,
2317
+ own,
2318
+ rowsOf: ([, rows]) => rows
2319
+ });
2320
+ const [countRows] = loaded.results;
2321
+ return {
2322
+ records: loaded.records,
2323
+ count: Number(countRows?.[0]?.["count"] ?? 0)
2324
+ };
2325
+ }
2326
+ /** One SELECT for `query`'s records and one past its limit, which is read but not loaded. */
2327
+ async function loadAhead(executor, model, query) {
2328
+ const own = (loaded) => [selectFor(executor.dialect, model, {
2329
+ ...loaded,
2330
+ limit: query.limit + 1
2331
+ })];
2332
+ const rowsOf = ([rows]) => rows?.slice(0, query.limit);
2333
+ const { records, results } = await loadWith(executor, model, {
2334
+ query,
2335
+ own,
2336
+ rowsOf
2337
+ });
2338
+ return {
2019
2339
  records,
2020
2340
  hasMore: (results[0]?.length ?? 0) > query.limit
2021
2341
  };
@@ -2545,11 +2865,15 @@ function targetsOfOwner(byKey, association, owner) {
2545
2865
  const key = association.isPolymorphic ? association.keyOf(owner) : owner[state].read(ownerAttribute);
2546
2866
  return byKey.get(targetKey.condition(key)) ?? [];
2547
2867
  }
2548
- /** `records` loaded as `owner`'s `association`: all of them for a hasMany, else the first or null. */
2868
+ /**
2869
+ * `records` loaded as `owner`'s `association`: all of them for a hasMany, else the first or null,
2870
+ * each pointing back at the owner through its inverse (#62).
2871
+ */
2549
2872
  function loadedAs(owner, association, records) {
2550
2873
  const { name, definition } = association;
2551
2874
  const value = definition.kind === "hasMany" ? records : records[0] ?? null;
2552
2875
  owner[state].associations.set(name, association.keyAttributes, value);
2876
+ pointLoadedBack(owner, association, value);
2553
2877
  }
2554
2878
  /** Each owner of a through association (#59) gets the records it reaches. */
2555
2879
  function gatherReached({ association, ownersAt, reached }, found) {
@@ -2609,7 +2933,7 @@ function keysForIncludes(model, includes) {
2609
2933
  // src/joins.ts
2610
2934
  /** `query` with the joins `specs` name added, each of `kind`: `joins()` and `leftJoins()`. */
2611
2935
  function withJoins(query, specs, kind, executor) {
2612
- const added = joinsFor(query.model, specs, {
2936
+ const added = joinsFor$1(query.model, specs, {
2613
2937
  kind,
2614
2938
  root: query.model,
2615
2939
  executor
@@ -2623,7 +2947,7 @@ function withJoins(query, specs, kind, executor) {
2623
2947
  * The joins `specs` name on `model`'s associations, each of `kind`: names, or `{ name: nested }`
2624
2948
  * where `nested` is a spec or a list of them for that association's Model.
2625
2949
  */
2626
- function joinsFor(model, specs, joining) {
2950
+ function joinsFor$1(model, specs, joining) {
2627
2951
  let joins = [];
2628
2952
  for (const spec of specs) {
2629
2953
  const entries = typeof spec === "string" ? [[spec, []]] : Object.entries(spec).map(([name, nested]) => [name, Array.isArray(nested) ? nested : [nested]]);
@@ -2644,7 +2968,7 @@ function joinOf(model, name, joining, nested) {
2644
2968
  ownerAttribute: association.ownerAttribute,
2645
2969
  targetAttribute: association.targetAttribute,
2646
2970
  on: scopeConditions(association, joining.executor),
2647
- joins: joinsFor(association.target, nested, joining)
2971
+ joins: joinsFor$1(association.target, nested, joining)
2648
2972
  };
2649
2973
  }
2650
2974
  /**
@@ -3218,6 +3542,15 @@ function numberCell(cell) {
3218
3542
  return typeof cell === "string" ? Number(cell) : cell;
3219
3543
  }
3220
3544
  // src/record-counts.ts
3545
+ /** What `size` and the questions about how many records there are read from `values`. */
3546
+ function countSourceOf(values, collection) {
3547
+ const unsavedCount = () => collection.unsavedCount();
3548
+ return {
3549
+ ...values,
3550
+ unsavedCount,
3551
+ cachedCount: () => collection.cachedCount?.()
3552
+ };
3553
+ }
3221
3554
  /**
3222
3555
  * The number of records, as Rails' `size`: a loaded association's (built records included)
3223
3556
  * without a query, or its owner's counter cache's (#61); otherwise a `COUNT(*)`; plus an
@@ -3472,48 +3805,6 @@ function describedValue(value) {
3472
3805
  if (value instanceof Model) return `a ${value.constructor.name}`;
3473
3806
  return value === null ? "null" : typeof value;
3474
3807
  }
3475
- // src/point-back-at-owner.ts
3476
- /**
3477
- * Makes `owner` the loaded record of the belongsTo on `record` that is `association`'s inverse:
3478
- * the first of the target's belongsTo associations that links the same foreign key to the
3479
- * owner's Model, through the same key. Neither may have a scope, which could leave the owner
3480
- * out. So `await post.author()` on a post built through `user.posts()` is the user, with no
3481
- * query, even before either is saved, and a required belongsTo passes, as Rails' automatic
3482
- * `inverse_of` does. The rest of inverse associations (preloads, `inverseOf:`) is #62.
3483
- */
3484
- function pointBackAtOwner(owner, association, record) {
3485
- const inverse = inverseOf(owner, association);
3486
- if (inverse === void 0 || association.otherTypeOf(record) !== void 0) return;
3487
- if (!isOwnersKey(record[state].read(inverse.ownerAttribute), owner, association)) return;
3488
- record[state].associations.set(inverse.name, inverse.keyAttributes, owner);
3489
- }
3490
- /**
3491
- * Whether the record's foreign key is its owner's: the same key (an integer matching a text
3492
- * key's digits, #94), or null while the owner has none yet, which saving the owner fills in. A
3493
- * key that isn't the owner's, null included, points elsewhere. Only a pushed record can hold
3494
- * one: a record built or created through the owner always gets the owner's key (#346).
3495
- */
3496
- function isOwnersKey(key, owner, association) {
3497
- if (key === null) return association.keyOf(owner) === null;
3498
- const ownerKey = owner[state].read(association.ownerAttribute);
3499
- return ownerKey !== null && String(key) === String(ownerKey);
3500
- }
3501
- /**
3502
- * The first of the target's belongsTo associations through the same foreign key, and type (#60),
3503
- * to the owner's Model: for a hasMany or hasOne with `as`, a polymorphic belongsTo that lists it
3504
- * (Rails finds no inverse there), its branch for the owner's Model.
3505
- */
3506
- function inverseOf(owner, association) {
3507
- const { target, targetAttribute, ownerAttribute } = association;
3508
- if (association.definition.scope !== void 0) return void 0;
3509
- for (const [name, definition] of associationsOf(target)) {
3510
- if (definition.kind !== "belongsTo" || definition.foreignKey !== targetAttribute) continue;
3511
- if (definition.scope !== void 0) continue;
3512
- if (definition.foreignType !== association.definition.foreignType) continue;
3513
- const candidate = resolveAssociation(target, name).branchForRecord(owner);
3514
- if (candidate?.targetAttribute === ownerAttribute) return candidate;
3515
- }
3516
- }
3517
3808
  // src/owned-collection.ts
3518
3809
  /** A plain query's: no owner, so it holds nothing, refuses nothing, and a deleteAll deletes. */
3519
3810
  const unowned = {
@@ -3970,27 +4261,20 @@ function clearCollectionUntilWritten({ collection }) {
3970
4261
  */
3971
4262
  function buildThrough(relation, attributes, init) {
3972
4263
  const record = recordToBuild(relation, attributes);
3973
- refuseThenable(relation.model, init?.(record));
4264
+ refuseInitPromise(relation.model, init?.(record));
4265
+ runBuiltCallbacks(record);
3974
4266
  relation.collection.built(record);
3975
4267
  return record;
3976
4268
  }
3977
- /**
3978
- * Throws `TypeError` for what a `build` `init` returned if it's a promise or another thenable,
3979
- * which `build` can't await. Its rejection, if it has one, is handled here, so the `TypeError` is
3980
- * the only error.
3981
- */
3982
- function refuseThenable(model, result) {
3983
- if (!isThenable$1(result)) return;
3984
- Promise.resolve(result).catch(() => {});
3985
- throw new TypeError(`${model.name}.build(): init returned a promise, which build can't await; findOrInitializeBy and create await it`);
3986
- }
3987
- function isThenable$1(value) {
3988
- return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
4269
+ /** Throws `TypeError` if a `build` `init` returned a promise, which `build` can't await. */
4270
+ function refuseInitPromise(model, result) {
4271
+ refuseThenable(result, `${model.name}.build(): init returned a promise, which build can't await; findOrInitializeBy and create await it`);
3989
4272
  }
3990
4273
  /** @internal `buildThrough`, awaiting `init`: what `findOrInitializeBy` builds. */
3991
4274
  async function initializeThrough(relation, attributes, init) {
3992
4275
  const record = recordToBuild(relation, attributes);
3993
4276
  await init?.(record);
4277
+ runBuiltCallbacks(record);
3994
4278
  relation.collection.built(record);
3995
4279
  return record;
3996
4280
  }
@@ -4020,6 +4304,7 @@ async function recordToCreate(relation, attributes, init) {
4020
4304
  requireSavedOwner$1(relation, "create");
4021
4305
  const record = recordToBuild(relation, attributes);
4022
4306
  await init?.(record);
4307
+ runBuiltCallbacks(record);
4023
4308
  return record;
4024
4309
  }
4025
4310
  /** A new record through `relation`, pointing back at its owner if it has one. */
@@ -4138,7 +4423,7 @@ async function writeAll(executor, writes) {
4138
4423
  try {
4139
4424
  results = await send(executor, writes);
4140
4425
  } catch (refusal) {
4141
- await whileHandling(refusal, () => rollBack(writes));
4426
+ await whileHandling(refusal, () => rollBack(writes, refusal));
4142
4427
  throw refusal;
4143
4428
  }
4144
4429
  commitAll(writes, results);
@@ -4171,9 +4456,9 @@ function commitAll(writes, results) {
4171
4456
  offset += write.statements.length;
4172
4457
  }
4173
4458
  }
4174
- /** Runs each refused write's rollback callbacks, in order. */
4175
- async function rollBack(writes) {
4176
- for (const write of writes) await write.afterRollback?.();
4459
+ /** Runs each refused write's rollback callbacks, in order, handing each the refusal's error. */
4460
+ async function rollBack(writes, error) {
4461
+ for (const write of writes) await write.afterRollback?.(error);
4177
4462
  }
4178
4463
  /**
4179
4464
  * Runs `callbacks` while `error` is being handled. An error one throws replaces it, and when
@@ -4249,7 +4534,7 @@ async function runStages(stages, needs) {
4249
4534
  const failure = await writeStages(stages, databases, written);
4250
4535
  if (failure === void 0) return runAfter(written);
4251
4536
  const { error, refused } = failure;
4252
- await whileHandling(error, () => rollBack(refused));
4537
+ await whileHandling(error, () => rollBack(refused, error));
4253
4538
  await whileHandling(error, () => runAfter(written));
4254
4539
  throw error;
4255
4540
  }
@@ -4290,25 +4575,27 @@ async function pinGroups(stages, needs) {
4290
4575
  */
4291
4576
  async function destroyTogether(records, needs) {
4292
4577
  await pinBefore(linksOf(records), needs);
4293
- const refused = await writeTogether(records, prepareDestroy, needs);
4578
+ const refused = await writeTogether(records, "destroy", needs);
4294
4579
  if (refused !== void 0) throw refusalError(refused.record, refused.plan, "destroy");
4295
4580
  }
4296
4581
  /**
4297
- * Prepares each record's save or destroy, then writes them all as one: or, if one refuses, writes
4298
- * nothing and returns it, with its plan.
4582
+ * Prepares each record's save or destroy (as `kind` says), then writes them all as one: or, if one
4583
+ * refuses, writes nothing and returns it, with its plan.
4299
4584
  */
4300
- async function writeTogether(records, prepare, needs) {
4301
- const claimed = /* @__PURE__ */ new Set();
4302
- const plans = [];
4303
- for (const record of records) {
4304
- const plan = await prepare(record, claimed);
4305
- if (plan.status !== "ready") return {
4306
- record,
4307
- plan
4308
- };
4309
- plans.push(plan);
4310
- }
4311
- await runStages(together(plans), needs);
4585
+ async function writeTogether(records, kind, needs) {
4586
+ const prepare = kind === "destroy" ? prepareDestroy : prepareSave;
4587
+ return withClaimedRecords(async (claimed) => {
4588
+ const plans = [];
4589
+ for (const record of records) {
4590
+ const plan = await prepare(record, claimed);
4591
+ if (plan.status !== "ready") return {
4592
+ record,
4593
+ plan
4594
+ };
4595
+ plans.push(plan);
4596
+ }
4597
+ await runStages(together(plans), needs);
4598
+ }, (refused) => refused && refusalError(refused.record, refused.plan, kind));
4312
4599
  }
4313
4600
  /**
4314
4601
  * Several records' plans as one: what each writes on another database before, then their own
@@ -4557,12 +4844,347 @@ function refuseDropWhilePicking(query, dropped) {
4557
4844
  if (query.limit === void 0 && query.offset === void 0) return;
4558
4845
  throw new IncompatibleRelation(`group() can't drop the order by ${orderedBy(dropped)}, which isn't grouped, while a limit or offset picks groups: reorder() first`);
4559
4846
  }
4560
- /** An attribute's order term as `order()` takes it. */
4561
- function orderSpec({ attribute, direction, nulls }) {
4562
- return { [attribute]: nulls === void 0 ? direction : {
4563
- direction,
4564
- nulls
4565
- } };
4847
+ /** An attribute's order term as `order()` takes it. */
4848
+ function orderSpec({ attribute, direction, nulls }) {
4849
+ return { [attribute]: nulls === void 0 ? direction : {
4850
+ direction,
4851
+ nulls
4852
+ } };
4853
+ }
4854
+ // src/no-touching.ts
4855
+ /** The storage, once `noTouching` has been called. */
4856
+ let storage;
4857
+ /**
4858
+ * Runs `fn` with `model`'s records not touched, nor those of the Models extending it, for the
4859
+ * code it runs and everything it awaits. An outer block's Models stay covered too.
4860
+ */
4861
+ async function noTouching(model, fn) {
4862
+ storage ??= newAsyncStorage();
4863
+ if (storage === void 0) throw new ActiveRecordError(`noTouching needs Node.js compatibility: ${NODE_COMPATIBILITY}`);
4864
+ const outer = storage.getStore() ?? [];
4865
+ return await storage.run([...outer, model], fn);
4866
+ }
4867
+ /** Whether a `noTouching` block the code runs in was called on `model`, or on a Model it extends. */
4868
+ function isCoveredByNoTouching(model) {
4869
+ return (storage?.getStore() ?? []).some((each) => each === model || model.prototype instanceof each);
4870
+ }
4871
+ // src/association-touch.ts
4872
+ /**
4873
+ * A belongsTo's or hasOne's `touch` (#497) is `true` or datetime attributes' names, each Model it
4874
+ * points at has what it sets, and it's on the record's database, as the touch is written in its
4875
+ * batch.
4876
+ */
4877
+ function checkTouch(label, owner, definition, targets) {
4878
+ const { touch, kind } = definition;
4879
+ if (touch === void 0) return;
4880
+ if (kind === "hasMany") throw new InvalidModel(`${label}: a hasMany takes no touch; only a belongsTo or hasOne touches`);
4881
+ const names = touchNames(label, touch, targets);
4882
+ for (const target of targets) requireTouchable(label, target, touch === true ? [] : names);
4883
+ const elsewhere = targets.find((target) => isOnDifferentDatabases(owner, target));
4884
+ if (elsewhere !== void 0) throw new InvalidModel(`${label} touches a record on another database, which it can't yet: ${owner.name} and ${elsewhere.name} must be on one`);
4885
+ }
4886
+ /** The names `touch` gives: none for `true`, else one or a list of strings. */
4887
+ function touchNames(label, touch, targets) {
4888
+ if (touch === true) return [];
4889
+ const names = Array.isArray(touch) ? touch : [touch];
4890
+ if (names.length > 0 && names.every((name) => typeof name === "string")) return names;
4891
+ const models = targets.map((target) => target.name).join(" or ");
4892
+ throw new InvalidModel(`${label}: touch takes true, the name of a datetime attribute of ${models}, or a list of them`);
4893
+ }
4894
+ /** `target` has `updatedAt` for `touch: true`, and each named attribute as a datetime. */
4895
+ function requireTouchable(label, target, names) {
4896
+ const isDatetime = (name) => target.attributeDefinitions.get(name)?.type === "datetime";
4897
+ if (names.length === 0 && !isDatetime("updatedAt")) throw new InvalidModel(`${label}: touch: true sets ${target.name}'s updatedAt, which it doesn't have (name a datetime attribute)`);
4898
+ const wrong = names.find((name) => !isDatetime(name));
4899
+ if (wrong !== void 0) throw new InvalidModel(`${label}: touch takes ${target.name}'s datetime attributes; "${wrong}" isn't one`);
4900
+ }
4901
+ /** Each write's touch session, by the set of records it claims. */
4902
+ const sessions = /* @__PURE__ */ new WeakMap();
4903
+ /**
4904
+ * The touch session of the write claiming `claimed`, started on its first touch, at `time` when
4905
+ * it's given (as `touch()` gives it).
4906
+ */
4907
+ function sessionOf(claimed, time) {
4908
+ let session = sessions.get(claimed);
4909
+ if (session === void 0) {
4910
+ session = {
4911
+ time,
4912
+ touched: /* @__PURE__ */ new Set(),
4913
+ autosaved: /* @__PURE__ */ new Set()
4914
+ };
4915
+ sessions.set(claimed, session);
4916
+ }
4917
+ return session;
4918
+ }
4919
+ /**
4920
+ * The time the session's touches set: taken when the first is sent, after the write's saves
4921
+ * have stamped their own, so a row a save stamps isn't set back.
4922
+ */
4923
+ function timeOf(session) {
4924
+ session.time ??= /* @__PURE__ */ new Date();
4925
+ return session.time;
4926
+ }
4927
+ /**
4928
+ * What tells two touched records apart: a saved record's table and stored key, so two instances
4929
+ * of a row are one; a new record has no row yet, so it's itself.
4930
+ */
4931
+ function touchKey(record) {
4932
+ if (record[state].isNew) return record;
4933
+ return `${modelOf(record).table} ${JSON.stringify(record[state].storedKeyValue)}`;
4934
+ }
4935
+ /**
4936
+ * The touches `record.touch()` makes in turn, at the `time` it sets: the record itself counts
4937
+ * as touched, so records touching each other touch it once.
4938
+ */
4939
+ function touchesOfTouch(record, time) {
4940
+ const claimed = /* @__PURE__ */ new Set([record]);
4941
+ markTouched(record, claimed, time);
4942
+ return touchesOf(record, "touch", claimed);
4943
+ }
4944
+ /** Counts `record` as touched by the write claiming `claimed`, so no touch reaches it again. */
4945
+ function markTouched(record, claimed, time) {
4946
+ sessionOf(claimed, time).touched.add(touchKey(record));
4947
+ }
4948
+ /**
4949
+ * The touches `record`'s save makes: none for an update with nothing to write. Its own row takes
4950
+ * none of them back (#497), as its save sets its time; another entry of its batch may touch it.
4951
+ */
4952
+ async function touchesOfSave(record, isInsert, claimed) {
4953
+ if (!isInsert && record[state].updateAssignments().length === 0) return [];
4954
+ const cause = isInsert ? "insert" : "update";
4955
+ const { touched } = sessionOf(claimed);
4956
+ const key = touchKey(record);
4957
+ if (touched.has(key)) return touchesOf(record, cause, claimed);
4958
+ touched.add(key);
4959
+ try {
4960
+ return await touchesOf(record, cause, claimed);
4961
+ } finally {
4962
+ touched.delete(key);
4963
+ }
4964
+ }
4965
+ /**
4966
+ * Leaves `records`, which the write claiming `claimed` saves or destroys through their owner
4967
+ * after it, to those writes: a hasOne doesn't touch them (#497), as their saves set their time.
4968
+ */
4969
+ function leaveToAutosaves(records, claimed) {
4970
+ const { autosaved } = sessionOf(claimed);
4971
+ for (const { record } of records) autosaved.add(record);
4972
+ }
4973
+ /**
4974
+ * The touches `record`'s write makes (#353): each record a belongsTo or hasOne (#497) declaring
4975
+ * `touch` reaches, loaded if it isn't, touched by its own touch write, and the records it
4976
+ * touches in turn. A destroyed record counts as touched, so none touches it back. A
4977
+ * `noTouching` block leaves out the records it covers (#496), and an association whose every
4978
+ * Model it covers isn't read.
4979
+ */
4980
+ async function touchesOf(record, cause, claimed) {
4981
+ if (cause === "destroy") markTouched(record, claimed);
4982
+ const writes = [];
4983
+ const model = modelOf(record);
4984
+ for (const [name, definition] of associationsOf(model)) {
4985
+ if (!isTouching(record, cause, definition)) continue;
4986
+ if (isEveryTargetCovered(model, name)) continue;
4987
+ for (const target of await touchedRecords(record, name, definition, claimed)) writes.push(...await touchOne(target, definition, claimed));
4988
+ }
4989
+ return writes;
4990
+ }
4991
+ /**
4992
+ * Whether an association touches on `record`'s write: one declaring `touch`, but not a hasOne
4993
+ * on its owner's create (#497), nor on a destroy that deletes the record it reaches with its own.
4994
+ */
4995
+ function isTouching(record, cause, { kind, touch, foreignKey, dependent }) {
4996
+ if (touch === void 0) return false;
4997
+ if (kind === "hasOne" && cause === "insert") return false;
4998
+ if (cause !== "destroy") return true;
4999
+ if (kind === "belongsTo") return !isDestroyedThrough(record, foreignKey);
5000
+ return dependent !== "destroy" && dependent !== "delete";
5001
+ }
5002
+ /**
5003
+ * Whether a `noTouching` block covers every Model association `name` can reach (#496): its one
5004
+ * Model, or each a polymorphic belongsTo lists. Then nothing it reaches is touched, so it isn't read.
5005
+ */
5006
+ function isEveryTargetCovered(model, name) {
5007
+ const { branches } = resolveAssociation(model, name);
5008
+ return branches.every((branch) => isCoveredByNoTouching(branch.target));
5009
+ }
5010
+ /**
5011
+ * The records `record`'s association `name` touches: the one it reaches, and, when a belongsTo's
5012
+ * key differs from the row's, the one the row's key reaches, as the association reads it; each
5013
+ * with a row to touch once the write is sent. A hasOne's record the write saves through an owner
5014
+ * is left to that save.
5015
+ */
5016
+ async function touchedRecords(record, name, definition, claimed) {
5017
+ const current = await readAssociation(record, name);
5018
+ if (definition.kind === "hasOne") {
5019
+ const isAutosaved = current instanceof Model && sessionOf(claimed).autosaved.has(current);
5020
+ return isTouchable(current, claimed) && !isAutosaved ? [current] : [];
5021
+ }
5022
+ return [current, isMoved(record, definition) ? await readStored(record, name) : null].filter((each) => isTouchable(each, claimed));
5023
+ }
5024
+ /** Whether a saved record's belongsTo points elsewhere than its row does. */
5025
+ function isMoved(record, definition) {
5026
+ const recordState = record[state];
5027
+ if (recordState.isNew) return false;
5028
+ return belongsToKeys(definition).some((key) => recordState.isAttributeChanged(key));
5029
+ }
5030
+ /**
5031
+ * The record a belongsTo reaches by the key (and a polymorphic one's type) in the record's row,
5032
+ * found through the association, so its scope and the target's default scope apply.
5033
+ */
5034
+ async function readStored(record, name) {
5035
+ const recordState = record[state];
5036
+ const association = resolveAssociation(modelOf(record), name);
5037
+ const { foreignKey, foreignType } = association.definition;
5038
+ const type = foreignType === void 0 ? void 0 : recordState.valueInDatabase(foreignType);
5039
+ const branch = association.branches.find((each) => each.type?.value === type);
5040
+ const key = recordState.valueInDatabase(foreignKey);
5041
+ if (branch === void 0 || key === null || key === void 0) return null;
5042
+ return await branch.all(recordState.executor).findBy({ [branch.targetAttribute]: key });
5043
+ }
5044
+ /**
5045
+ * A record with a row to touch once the write is sent: one that's saved and isn't destroyed, or
5046
+ * a new one the write inserts itself, which Rails touches after its insert too.
5047
+ */
5048
+ function isTouchable(record, claimed) {
5049
+ if (!(record instanceof Model)) return false;
5050
+ const recordState = record[state];
5051
+ if (recordState.isNew) return claimed.has(record);
5052
+ return !recordState.isDestroyed;
5053
+ }
5054
+ /**
5055
+ * `target`'s touch write, setting what the association's `touch` names, then those it makes in
5056
+ * turn; nothing if this write has touched it already, or `noTouching` turned its Model's touches
5057
+ * off (#496).
5058
+ */
5059
+ async function touchOne(target, { touch }, claimed) {
5060
+ const session = sessionOf(claimed);
5061
+ const model = modelOf(target);
5062
+ const key = touchKey(target);
5063
+ if (session.touched.has(key) || isCoveredByNoTouching(model)) return [];
5064
+ session.touched.add(key);
5065
+ let values;
5066
+ const valuesOf = () => values ??= Object.fromEntries(touchAssignments(model, touch, "touch", timeOf(session)));
5067
+ return [inWrite(touchWrite(target, valuesOf, { keepsSavedChanges: () => isClaimedRow(target, claimed) }), target, claimed), ...await touchesOf(target, "touch", claimed)];
5068
+ }
5069
+ /**
5070
+ * The records the write claims that are `record`'s row, by table and key, asked once inserted
5071
+ * records have their keys: another instance of the row may be the one claimed.
5072
+ */
5073
+ function sameRow(record, claimed) {
5074
+ return [...claimed].filter((each) => touchKey(each) === touchKey(record));
5075
+ }
5076
+ /** Whether the write saves or destroys `record`'s row itself. */
5077
+ function isClaimedRow(record, claimed) {
5078
+ return sameRow(record, claimed).length > 0;
5079
+ }
5080
+ /**
5081
+ * A touch write as part of another record's write. What it does to its record is asked as each
5082
+ * step runs, when the write's records are claimed and inserted ones have their keys, by row
5083
+ * (another instance may be the one claimed): a row destroyed by then takes nothing, and a row the
5084
+ * write destroys runs no touch callback (Rails touches only a persisted record); a row the write
5085
+ * saves itself runs its commit and rollback callbacks once, from its own save.
5086
+ */
5087
+ function inWrite(write, target, claimed) {
5088
+ const isDestroyed = () => target[state].isDestroyed || sameRow(target, claimed).some((each) => each[state].isDestroyed);
5089
+ return {
5090
+ get statements() {
5091
+ return write.statements;
5092
+ },
5093
+ commit: (results) => {
5094
+ if (!isDestroyed()) write.commit(results);
5095
+ },
5096
+ after: async () => {
5097
+ if (!isDestroyed()) await write.after();
5098
+ },
5099
+ afterCommit: async () => {
5100
+ if (!isClaimedRow(target, claimed)) await write.afterCommit?.();
5101
+ },
5102
+ afterRollback: async (error) => {
5103
+ if (!isClaimedRow(target, claimed)) await write.afterRollback?.(error);
5104
+ }
5105
+ };
5106
+ }
5107
+ // src/touch.ts
5108
+ /**
5109
+ * What `touch(...args)` or `touchAll(...args)` sets: `updatedAt`, and the datetime attributes
5110
+ * named, each to now or `time`. Nothing to set (no `updatedAt`, no names) is a `TypeError`.
5111
+ */
5112
+ function touchValues(model, args, method) {
5113
+ const { names, options } = splitTouchArguments(args, `${model.name}.${method}`);
5114
+ const touched = touchAssignments(model, names.length === 0 ? true : names, method, options.time);
5115
+ if (touched.length === 0) throw new TypeError(`${model.name}.${method} has nothing to touch: ${model.name} has no updatedAt; name a datetime attribute`);
5116
+ return Object.fromEntries(touched);
5117
+ }
5118
+ /**
5119
+ * The names in `touch`'s arguments, and the options after them, checked as untyped code could
5120
+ * pass a Date for `{ time }`, or a misspelled option, which would touch at now unnoticed.
5121
+ */
5122
+ function splitTouchArguments(args, method) {
5123
+ const last = args.at(-1);
5124
+ if (last instanceof Date) throw new TypeError(`${method} takes a time as { time }; got a Date`);
5125
+ if (typeof last !== "object" || last === null) return {
5126
+ names: [...args],
5127
+ options: {}
5128
+ };
5129
+ const unknown = Object.keys(last).filter((key) => key !== "time");
5130
+ if (unknown.length > 0) throw new TypeError(`${method} takes { time }; got ${unknown.join(", ")}`);
5131
+ return {
5132
+ names: args.slice(0, -1),
5133
+ options: last
5134
+ };
5135
+ }
5136
+ /**
5137
+ * Sets the record's `updatedAt`, and the datetime attributes named, to now or `time`, straight to
5138
+ * the row, and holds them, clean; then runs `afterTouch`, and the update commit callbacks when a
5139
+ * row was written, as Rails' `touch` does. Resolves to whether there was a row to write: none
5140
+ * inside a `noTouching` block that covers its Model, which sends nothing and runs no callback.
5141
+ */
5142
+ async function touchRecord(record, args) {
5143
+ const model = modelOf(record);
5144
+ const values = touchValues(model, args, "touch");
5145
+ if (isCoveredByNoTouching(model)) return false;
5146
+ const time = Object.values(values)[0];
5147
+ const writes = [touchWrite(record, () => values), ...await touchesOfTouch(record, time)];
5148
+ const [result] = await writeAll(record[state].executor, writes);
5149
+ await runAfter(writes);
5150
+ return result?.rowsAffected === 1;
5151
+ }
5152
+ /**
5153
+ * The key a touch's UPDATE finds its record's row by: the stored key, or, for a new record the
5154
+ * same batch inserts first (#353), the key it's given.
5155
+ */
5156
+ function keyCells(record) {
5157
+ const recordState = record[state];
5158
+ if (!recordState.isNew) return recordState.storedKey;
5159
+ const { primaryKey } = modelOf(record);
5160
+ return attributeFor(modelOf(record), primaryKey).store(recordState.read(primaryKey));
5161
+ }
5162
+ /**
5163
+ * The touch's write: the values `valuesOf` gives, asked as it's sent, then assigned and held clean
5164
+ * once the row has them. The record changes only then, so a refused touch leaves it as it was,
5165
+ * and runs `afterRollback`.
5166
+ */
5167
+ function touchWrite(record, valuesOf, { keepsSavedChanges } = {}) {
5168
+ const recordState = record[state];
5169
+ const model = modelOf(record);
5170
+ let isWritten = false;
5171
+ return {
5172
+ get statements() {
5173
+ return [compileUpdate(model, Object.entries(valuesOf()), keyCells(record))];
5174
+ },
5175
+ commit: ([result]) => {
5176
+ const values = valuesOf();
5177
+ recordState.assign(values);
5178
+ if (keepsSavedChanges?.()) recordState.commitColumns(Object.keys(values));
5179
+ else recordState.commitTouch(Object.keys(values));
5180
+ isWritten = result?.rowsAffected === 1;
5181
+ },
5182
+ after: () => runAfterCallbacks(record, "afterTouch", "touch"),
5183
+ afterCommit: async () => {
5184
+ if (isWritten) await runCommitCallbacks(record, "update");
5185
+ },
5186
+ afterRollback: afterRollbackOf(record)
5187
+ };
4566
5188
  }
4567
5189
  // src/pagination.ts
4568
5190
  /**
@@ -4749,8 +5371,8 @@ var Relation = class Relation {
4749
5371
  this.#executor = executor;
4750
5372
  this.#model = model;
4751
5373
  this.#query = query ?? allOf(model);
4752
- this.#runner = runnerFor(executor, model, this.#query);
4753
5374
  this.#collection = collection ?? unowned;
5375
+ this.#runner = runnerFor(executor, model, this.#query, this.#collection);
4754
5376
  }
4755
5377
  where(conditions) {
4756
5378
  checkConditions(this.#model, conditions, "where");
@@ -4961,12 +5583,20 @@ var Relation = class Relation {
4961
5583
  return this.#countOf(() => this[preparedWrites].updateAll(changes));
4962
5584
  }
4963
5585
  /**
5586
+ * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`) in every row this
5587
+ * Relation matches, in one statement, as Rails' `touch_all` (#50). Resolves to the number of
5588
+ * rows; skips what `updateAll` skips.
5589
+ */
5590
+ async touchAll(...args) {
5591
+ return this.updateAll(touchValues(this.#model, args, "touchAll"));
5592
+ }
5593
+ /**
4964
5594
  * Adds to number attributes in every row this Relation matches, now, in one statement:
4965
5595
  * `updateCounters({ viewCount: 1 })` sets `view_count = COALESCE(view_count, 0) + 1`, so
4966
5596
  * concurrent writes all count. Resolves to the number of rows; skips what `updateAll` skips.
4967
5597
  */
4968
5598
  async updateCounters(counters, { touch } = {}) {
4969
- return this.updateAll(counterSets(this.#model, counters, "updateCounters", touch));
5599
+ return this.updateAll(counterSets(this.#model, counters, "updateCounters", { touch }));
4970
5600
  }
4971
5601
  /**
4972
5602
  * Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany
@@ -5160,7 +5790,7 @@ var Relation = class Relation {
5160
5790
  #valueSource() {
5161
5791
  return {
5162
5792
  query: this.#query,
5163
- dialect: () => this.#dialect,
5793
+ dialect: () => this.#executor.dialect,
5164
5794
  runner: this.#runner,
5165
5795
  cached: () => this.#cached()
5166
5796
  };
@@ -5190,13 +5820,7 @@ var Relation = class Relation {
5190
5820
  }
5191
5821
  /** What `size` and the questions about how many records there are read. */
5192
5822
  #countSource() {
5193
- const collection = this.#collection;
5194
- const unsavedCount = () => collection.unsavedCount();
5195
- return {
5196
- ...this.#valueSource(),
5197
- unsavedCount,
5198
- cachedCount: () => collection.cachedCount?.()
5199
- };
5823
+ return countSourceOf(this.#valueSource(), this.#collection);
5200
5824
  }
5201
5825
  /** Whether any record matches, optionally with extra conditions. */
5202
5826
  async exists(conditions) {
@@ -5241,11 +5865,11 @@ var Relation = class Relation {
5241
5865
  * are never inlined into the SQL (ADR-0006), and none are redacted, filtered attributes included.
5242
5866
  */
5243
5867
  toSql() {
5244
- return querySql(selectForToSql(this.#dialect, this.#model, this.#query));
5868
+ return querySql(selectForToSql(this.#executor.dialect, this.#model, this.#query));
5245
5869
  }
5246
5870
  /** Prints as `Relation<Model> { sql, params }`: the SELECT it would send, without sending it (#104). */
5247
5871
  [inspectCustom](depth, options, inspect) {
5248
- const compiled = selectForToSql(this.#dialect, this.#model, this.#query);
5872
+ const compiled = selectForToSql(this.#executor.dialect, this.#model, this.#query);
5249
5873
  return inspectRelation(this.#model.name, compiled, {
5250
5874
  depth,
5251
5875
  options,
@@ -5278,9 +5902,6 @@ var Relation = class Relation {
5278
5902
  runner: this.#runner
5279
5903
  };
5280
5904
  }
5281
- get #dialect() {
5282
- return this.#executor.dialect;
5283
- }
5284
5905
  /** The owner's loaded records for this hasMany, if it has them. */
5285
5906
  #cached() {
5286
5907
  return this.#collection.loaded();
@@ -5515,7 +6136,7 @@ async function push$1(hasMany, records) {
5515
6136
  for (const record of records) record[state].requireLive("be saved");
5516
6137
  await pinForSaving(records, needs);
5517
6138
  link(hasMany, records);
5518
- if (await writeTogether(records, prepareSave, needs) !== void 0) return false;
6139
+ if (await writeTogether(records, "save", needs) !== void 0) return false;
5519
6140
  for (const record of records) collection.created(record);
5520
6141
  return true;
5521
6142
  }
@@ -5597,7 +6218,7 @@ async function pinForSaving(records, needs) {
5597
6218
  */
5598
6219
  async function saveTogether(records, needs) {
5599
6220
  await pinForSaving(records, needs);
5600
- return await writeTogether(records, prepareSave, needs) === void 0;
6221
+ return await writeTogether(records, "save", needs) === void 0;
5601
6222
  }
5602
6223
  // src/through-associations.ts
5603
6224
  /**
@@ -5673,7 +6294,11 @@ function checkOptions(label, definition) {
5673
6294
  if (definition.kind === "belongsTo") throw new InvalidModel(`${label}: a belongsTo can't go through another association`);
5674
6295
  checkDependent$1(label, definition);
5675
6296
  const declaredKey = definition.inferredFrom === void 0 || definition.primaryKey !== void 0;
5676
- const refused = [[definition.autosave !== void 0, "autosave"], [declaredKey, "foreignKey or primaryKey"]];
6297
+ const refused = [
6298
+ [definition.autosave !== void 0, "autosave"],
6299
+ [declaredKey, "foreignKey or primaryKey"],
6300
+ [definition.inverseOf !== void 0, "inverseOf"]
6301
+ ];
5677
6302
  for (const [given, option] of refused) if (given) throw new InvalidModel(`${label}: a through association takes no ${option}`);
5678
6303
  }
5679
6304
  /**
@@ -5771,8 +6396,8 @@ function throughCollection(through) {
5771
6396
  const collection = ownedCollection(through.owner, through.association);
5772
6397
  const built = (record) => {
5773
6398
  requireWritableThrough(through.association);
5774
- collection.built(record);
5775
6399
  joinFor(through, record);
6400
+ collection.built(record);
5776
6401
  };
5777
6402
  const requireWritable = (write) => {
5778
6403
  if (write === "insert") throw insertError(through.association);
@@ -5820,14 +6445,28 @@ async function push(hasMany, records) {
5820
6445
  for (const record of records) collection.built(record);
5821
6446
  return true;
5822
6447
  }
5823
- const joins = records.map((record) => joinFor(hasMany, record));
5824
6448
  const viaCollection = joinsHeldBy(owner, association);
6449
+ const joins = joinsFor(hasMany, records, viaCollection);
5825
6450
  const save = () => saveTogether(joins, "push() needs its records");
5826
6451
  if (!await undoneUnless(save, isTrue, () => viaCollection.removed(joins))) return false;
5827
6452
  for (const join of joins) viaCollection.created(join);
5828
6453
  for (const record of records) collection.created(record);
5829
6454
  return true;
5830
6455
  }
6456
+ /**
6457
+ * A join record for each of `records`. When one can't be built (its afterInitialize throws, #49),
6458
+ * those built before it are forgotten, so the owner's next save doesn't link their records.
6459
+ */
6460
+ function joinsFor(hasMany, records, viaCollection) {
6461
+ const joins = [];
6462
+ try {
6463
+ for (const record of records) joins.push(joinFor(hasMany, record));
6464
+ } catch (error) {
6465
+ viaCollection.removed(joins);
6466
+ throw error;
6467
+ }
6468
+ return joins;
6469
+ }
5831
6470
  /** How `delete` removes join records: by the association's `dependent:`, deleting by default. */
5832
6471
  function removalOf({ definition: { dependent } }) {
5833
6472
  return dependent === "destroy" ? "destroy" : "deleteAll";
@@ -5967,11 +6606,12 @@ const isTrue = (saved) => saved;
5967
6606
  function joinsHeldBy(owner, association) {
5968
6607
  return ownedCollection(owner, association.hops.via);
5969
6608
  }
5970
- /** A new join record, built through the association it goes through, pointing at `record`. */
6609
+ /**
6610
+ * A new join record, built through the association it goes through, pointing at `record` as
6611
+ * `build`'s init, so its afterInitialize sees the key (#49).
6612
+ */
5971
6613
  function joinFor({ association, via }, record) {
5972
- const join = via().build();
5973
- pointOwnerAt(join, association.hops.source, record);
5974
- return join;
6614
+ return via().build(void 0, (join) => pointOwnerAt(join, association.hops.source, record));
5975
6615
  }
5976
6616
  /** A through hasOne's accessor (#434): it reads its record, and `set` links the owner to another. */
5977
6617
  function throughHasOne(read, owner, association) {
@@ -6082,7 +6722,9 @@ function withRemoval(plan, removal, record) {
6082
6722
  async function removeReplaced(replacement) {
6083
6723
  const old = await replacedRecord(null, replacement);
6084
6724
  if (old === null) return;
6085
- await runStages(stagesOf(await prepareRemoval(old, replacement.association, /* @__PURE__ */ new Set())), "set() needs its records");
6725
+ await withClaimedRecords(async (claimed) => {
6726
+ await runStages(stagesOf(await prepareRemoval(old, replacement.association, claimed)), "set() needs its records");
6727
+ });
6086
6728
  }
6087
6729
  /**
6088
6730
  * The saved record `record` replaces: the one known when it was given to the association, or the
@@ -6187,7 +6829,11 @@ function failedToRemove(name) {
6187
6829
  function belongsToAccessor(owner, association) {
6188
6830
  const read = () => cachedRead(owner, association, (key) => association.all(owner[state].executor).findBy({ [association.targetAttribute]: key }));
6189
6831
  const set = (record) => pointOwnerAt(owner, association, record);
6190
- const make = (attributes) => buildRecord(association.target, attributes, targetDatabase(owner, association));
6832
+ const make = (attributes) => {
6833
+ const record = buildRecord(association.target, attributes, targetDatabase(owner, association));
6834
+ runBuiltCallbacks(record);
6835
+ return record;
6836
+ };
6191
6837
  const create = (save) => async (attributes = {}) => {
6192
6838
  const record = make(attributes);
6193
6839
  await save(record);
@@ -6350,7 +6996,7 @@ function requireSavedOwner(owner, association) {
6350
6996
  */
6351
6997
  function buildOne(owner, association, attributes) {
6352
6998
  const { [association.definition.foreignKey]: _given, ...rest } = attributes;
6353
- const record = association.all(owner[state].executor).build(rest);
6999
+ const record = association.all(owner[state].executor).build(rest, (built) => pointAtOwner(owner, association, built));
6354
7000
  adopt(owner, association, record);
6355
7001
  return record;
6356
7002
  }
@@ -6359,19 +7005,24 @@ function buildOne(owner, association, attributes) {
6359
7005
  * and saved with it. On a saved owner, it replaces the record the association held (#40).
6360
7006
  */
6361
7007
  function adopt(owner, association, record) {
6362
- const { name, ownerAttribute, definition } = association;
7008
+ const { name } = association;
6363
7009
  const replaced = takeReplaced(owner, association);
6364
7010
  if (!owner[state].isNew) markReplacing(record, {
6365
7011
  owner,
6366
7012
  association,
6367
7013
  replaced
6368
7014
  });
6369
- record[state].writeKey(definition.foreignKey, owner[state].read(ownerAttribute), name);
6370
- association.writeOwnersType(record);
7015
+ pointAtOwner(owner, association, record);
6371
7016
  owner[state].associations.set(name, association.keyAttributes, record);
6372
7017
  owner[state].autosaves.setBuilt(name, record);
6373
7018
  pointBackAtOwner(owner, association, record);
6374
7019
  }
7020
+ /** Points a hasOne's `record` at `owner`: its foreign key, and its owner's type if polymorphic. */
7021
+ function pointAtOwner(owner, association, record) {
7022
+ const { name, ownerAttribute, definition } = association;
7023
+ record[state].writeKey(definition.foreignKey, owner[state].read(ownerAttribute), name);
7024
+ association.writeOwnersType(record);
7025
+ }
6375
7026
  /** Where a record built through `association` for `owner` is saved: its target's database. */
6376
7027
  function targetDatabase(owner, association) {
6377
7028
  return association.targetExecutor(owner[state].executor);
@@ -6934,6 +7585,12 @@ function checkAssociation(model, name, definition) {
6934
7585
  checkOptional(label, definition);
6935
7586
  checkAutosave(label, definition);
6936
7587
  checkCounterCache(label, model, definition, targets);
7588
+ checkTouch(label, model, definition, targets);
7589
+ checkInverseOf(label, {
7590
+ model,
7591
+ name,
7592
+ definition
7593
+ }, targets);
6937
7594
  }
6938
7595
  /** `autosave` is `true` or left out: `false` isn't built (#378). */
6939
7596
  function checkAutosave(label, { autosave }) {
@@ -7076,6 +7733,7 @@ async function cachedRead(owner, association, load) {
7076
7733
  const keep = owner[state].associations.startLoad(name, keyAttributes, loadedFor);
7077
7734
  const value = key === null ? null : await load(key);
7078
7735
  keep(value);
7736
+ pointLoadedBack(owner, association, value);
7079
7737
  return value;
7080
7738
  }
7081
7739
  // src/record-statement.ts
@@ -7168,7 +7826,7 @@ var Batch = class {
7168
7826
  */
7169
7827
  updateCounters(target, counters, { touch } = {}) {
7170
7828
  const rows = this.#rows(target);
7171
- const sets = counterSets(rows[queryOf].model, counters, "updateCounters", touch);
7829
+ const sets = counterSets(rows[queryOf].model, counters, "updateCounters", { touch });
7172
7830
  return rows[preparedWrites].updateAll(sets);
7173
7831
  }
7174
7832
  /** Deletes every row `target` matches, as `deleteAll` does (through a hasMany, it may nullify). */
@@ -7657,265 +8315,350 @@ function linkedToRecords(relation, attribute, owners, ownerKey) {
7657
8315
  if (owners.none) return relation.none();
7658
8316
  return relation[linkedToOwner](new LinkedTo(attribute, owners, ownerKey));
7659
8317
  }
7660
- // src/counter-caches.ts
8318
+ // src/inverse-associations.ts
7661
8319
  /**
7662
- * A belongsTo's `counterCache` in one shape: the attribute it names, if it names one, and
7663
- * whether `size` reads it (not with `active: false`). Checked already, by `checkCounterValue`.
8320
+ * The belongsTo on a hasMany's or hasOne's records that points back at `owner`: the one
8321
+ * `inverseOf` names, or else the first of the target's belongsTo associations through the same
8322
+ * foreign key, and type (#60), to the owner's Model, through the same key. A polymorphic one is
8323
+ * its branch for the owner's Model. None is inferred when either side has a scope, which could
8324
+ * leave the owner out, or the belongsTo says `inverseOf: false`; none with `inverseOf: false`,
8325
+ * or through another association, whose records hold no key of the owner's.
7664
8326
  */
7665
- function counterCacheOf({ counterCache }) {
7666
- if (typeof counterCache === "object") return {
7667
- attribute: counterCache.attribute,
7668
- isActive: counterCache.active !== false
7669
- };
7670
- return {
7671
- attribute: typeof counterCache === "string" ? counterCache : void 0,
7672
- isActive: true
7673
- };
8327
+ function inverseOf(owner, association) {
8328
+ const { target, definition } = association;
8329
+ if (definition.inverseOf === false || association.hops !== void 0) return void 0;
8330
+ if (definition.inverseOf !== void 0) return resolveAssociation(target, definition.inverseOf).branchForRecord(owner);
8331
+ if (definition.scope !== void 0) return void 0;
8332
+ for (const [name, candidate] of associationsOf(target)) {
8333
+ if (!isInferable(candidate, definition)) continue;
8334
+ const branch = resolveAssociation(target, name).branchForRecord(owner);
8335
+ if (branch?.targetAttribute === association.ownerAttribute) return branch;
8336
+ }
8337
+ }
8338
+ /** Whether `candidate` may be inferred as the inverse of a hasMany or hasOne, `definition`. */
8339
+ function isInferable(candidate, definition) {
8340
+ return candidate.kind === "belongsTo" && candidate.scope === void 0 && candidate.inverseOf !== false && candidate.foreignKey === definition.foreignKey && candidate.foreignType === definition.foreignType;
7674
8341
  }
7675
8342
  /**
7676
- * The counter a belongsTo's `counterCache` keeps on its target: the attribute it names, or by
7677
- * Rails' convention the owner's plural name + `Count` (`Reply` → `repliesCount`).
8343
+ * The hasOne on a belongsTo's record, `record`, that points back at the belongsTo's owner: the
8344
+ * one `inverseOf` names, or else the one whose own inverse is the belongsTo. A hasMany is never
8345
+ * one: the owner isn't the whole collection, as in Rails.
7678
8346
  */
7679
- function counterAttribute(owner, definition) {
7680
- const named = counterCacheOf(definition).attribute;
7681
- if (named !== void 0) return named;
7682
- const plural = pluralize(tableOwnerModelName(owner));
7683
- return `${plural.charAt(0).toLowerCase()}${plural.slice(1)}Count`;
8347
+ function inverseHasOne(record, belongsTo) {
8348
+ const { target, definition } = belongsTo;
8349
+ if (definition.inverseOf === false) return void 0;
8350
+ if (definition.inverseOf !== void 0) return resolveAssociation(target, definition.inverseOf);
8351
+ for (const [name, candidate] of associationsOf(target)) {
8352
+ if (candidate.kind !== "hasOne") continue;
8353
+ const hasOne = resolveAssociation(target, name);
8354
+ if (isSameAssociation(inverseOf(record, hasOne), belongsTo)) return hasOne;
8355
+ }
7684
8356
  }
7685
8357
  /**
7686
- * A counter cache is a belongsTo's, and names, or infers, an attribute of each Model it points at.
8358
+ * Whether `one` is `other`, or what `other` inherits: the same name and foreign key, on `other`'s
8359
+ * Model or a class it extends.
7687
8360
  */
7688
- function checkCounterCache(label, owner, definition, targets) {
7689
- const { counterCache, kind } = definition;
7690
- if (counterCache === void 0) return;
7691
- if (kind !== "belongsTo") return checkCollectionCounter(label, owner, definition, targets);
7692
- checkCounterValue(label, counterCache, targets);
7693
- const elsewhere = targets.find((target) => isOnDifferentDatabases(owner, target));
7694
- if (elsewhere !== void 0) throw new InvalidModel(`${label} keeps a counter cache on another database, which it can't yet: ${owner.name} and ${elsewhere.name} must be on one`);
7695
- const attribute = counterAttribute(owner, definition);
7696
- const hint = counterCacheOf(definition).attribute !== void 0 ? "check counterCache" : `counterCache: true infers it from ${owner.name}; declare it, or name another`;
7697
- for (const target of targets) requireCounter(label, target, attribute, hint);
7698
- refuseCountingTwice(label, owner, definition, {
7699
- attribute,
7700
- targets
7701
- });
8361
+ function isSameAssociation(one, other) {
8362
+ if (one === void 0 || one.name !== other.name) return false;
8363
+ return isOrExtends(other.owner, one.owner) && one.definition.foreignKey === other.definition.foreignKey;
7702
8364
  }
7703
8365
  /**
7704
- * Another belongsTo on the same foreign key can't keep the same attribute on a table this one
7705
- * points at: each record would be counted in it twice.
8366
+ * The association `inverseOf` names must be on each of `targets` (#62): a belongsTo for a hasMany
8367
+ * or hasOne, a hasOne for a belongsTo, linking the same keys back to the declaring Model.
8368
+ * Checked from the declarations, so no other Model is made ready while this one is.
7706
8369
  */
7707
- function refuseCountingTwice(label, owner, definition, { attribute, targets }) {
7708
- const tables = new Set(targets.map((target) => target.table));
7709
- for (const [name, other] of associationsOf(owner)) if (other !== definition && other.kind === "belongsTo" && other.counterCache !== void 0 && other.foreignKey === definition.foreignKey && counterAttribute(owner, other) === attribute && (other.targets?.() ?? [other.target()]).some((target) => tables.has(target.table))) throw new InvalidModel(`${label}: ${name} keeps "${attribute}" on ${targets[0].name} by ${definition.foreignKey} too, so a record would count twice (name another counterCache)`);
8370
+ function checkInverseOf(label, declared, targets) {
8371
+ const { inverseOf: name, through } = declared.definition;
8372
+ if (typeof name !== "string" || through !== void 0) return;
8373
+ for (const target of targets) {
8374
+ const definition = associationsOf(target).get(name);
8375
+ if (definition === void 0) throw new InvalidModel(`${label}: inverseOf names "${name}", which isn't an association of ${target.name}`);
8376
+ checkNamed(label, declared, {
8377
+ model: target,
8378
+ name,
8379
+ definition
8380
+ });
8381
+ }
7710
8382
  }
7711
- /** `target`'s `attribute` must be a plain number attribute (integer or real) to keep a count. */
7712
- function requireCounter(label, target, attribute, hint) {
7713
- const definition = target.attributeDefinitions.get(attribute);
7714
- if (definition === void 0) throw new InvalidModel(`${label}: ${target.name} has no attribute "${attribute}" (${hint})`);
7715
- if (!(definition.type === "integer" || definition.type === "real") || definition.enum !== void 0 || definition.customType !== void 0) throw new InvalidModel(`${label}: ${target.name}'s "${attribute}" can't keep a count; counterCache takes an integer or real attribute`);
8383
+ /** The named association is of the kind that points back, and links the same keys. */
8384
+ function checkNamed(label, declared, named) {
8385
+ const wanted = declared.definition.kind === "belongsTo" ? "hasOne" : "belongsTo";
8386
+ const { kind } = named.definition;
8387
+ if (kind !== wanted) {
8388
+ const collection = kind === "hasMany" ? ", and a belongsTo's record doesn't fill a collection" : "";
8389
+ throw new InvalidModel(`${label}: inverseOf must name a ${wanted} of ${named.model.name}; "${named.name}" is a ${kind}${wanted === "hasOne" ? collection : ""}`);
8390
+ }
8391
+ const [belongsTo, other] = wanted === "hasOne" ? [declared, named] : [named, declared];
8392
+ if (!isInversePair(belongsTo, other)) throw new InvalidModel(`${label}: inverseOf "${named.name}" doesn't link ${named.model.name} back to ${declared.model.name} through the same keys`);
7716
8393
  }
7717
8394
  /**
7718
- * A hasMany's `counterCache` names the counter a belongsTo of its records keeps on the owner, by
7719
- * the same keys; a hasOne takes none. Read from the declarations, since the records' Model may not be ready yet.
8395
+ * Whether a belongsTo and a hasMany or hasOne are two sides of one link: each points at the
8396
+ * other's Model, through the same foreign key, type (#60) and key, and not through another.
7720
8397
  */
7721
- function checkCollectionCounter(label, owner, { kind, counterCache, foreignKey, primaryKey }, [target]) {
7722
- const records = target;
7723
- if (kind !== "hasMany") throw new InvalidModel(`${label}: a ${kind} takes no counterCache; declare it on ${records.name}'s belongsTo`);
7724
- if (typeof counterCache !== "string") throw new InvalidModel(`${label}: a hasMany's counterCache names the attribute it reads`);
7725
- if (![...associationsOf(records).values()].some((each) => each.kind === "belongsTo" && each.counterCache !== void 0 && each.foreignKey === foreignKey && counterAttribute(records, each) === counterCache && (each.targets?.() ?? [each.target()]).some((pointed) => (owner === pointed || owner.prototype instanceof pointed) && (each.primaryKey ?? pointed.primaryKey) === (primaryKey ?? owner.primaryKey)))) throw new InvalidModel(`${label}: no belongsTo of ${records.name} keeps "${counterCache}" on ${owner.name} (check counterCache)`);
8398
+ function isInversePair(belongsTo, other) {
8399
+ const { definition: pointing } = belongsTo;
8400
+ const { definition: pointedAt } = other;
8401
+ if (pointedAt.through !== void 0 || pointing.foreignKey !== pointedAt.foreignKey) return false;
8402
+ if (pointing.foreignType !== pointedAt.foreignType) return false;
8403
+ if (!(pointing.targets?.() ?? [pointing.target()]).some((each) => isOrExtends(other.model, each))) return false;
8404
+ if (!isOrExtends(belongsTo.model, pointedAt.target())) return false;
8405
+ return linkOf(pointing, belongsTo.model, other.model).targetAttribute === linkOf(pointedAt, other.model, belongsTo.model).ownerAttribute;
7726
8406
  }
7727
- /** `counterCache` is `true`, an attribute's name, or `{ attribute, active: false }`. */
7728
- function checkCounterValue(label, counterCache, targets) {
7729
- if (counterCache === true || typeof counterCache === "string") return;
7730
- if (typeof counterCache === "object" && counterCache !== null) {
7731
- const { attribute, active, ...rest } = counterCache;
7732
- if (active !== void 0 && active !== false) throw new InvalidModel(`${label}: counterCache's active takes false`);
7733
- const [unknown] = Object.keys(rest);
7734
- if (unknown !== void 0) throw new InvalidModel(`${label}: counterCache takes no "${unknown}"; use attribute or active`);
7735
- if (attribute === void 0 || typeof attribute === "string") return;
8407
+ /** Whether `model` is `base` or one of its subclasses. */
8408
+ function isOrExtends(model, base) {
8409
+ return model === base || model.prototype instanceof base;
8410
+ }
8411
+ // src/point-back-at-owner.ts
8412
+ /**
8413
+ * Makes `owner` the loaded record of the belongsTo on `record` that is `association`'s inverse
8414
+ * (`inverseOf`). So `await post.author()` on a post built or loaded through `user.posts()` is
8415
+ * the user, with no query, even before either is saved, and a required belongsTo passes, as
8416
+ * Rails' `inverse_of` does.
8417
+ */
8418
+ function pointBackAtOwner(owner, association, record) {
8419
+ const inverse = inverseOf(owner, association);
8420
+ if (inverse === void 0 || association.otherTypeOf(record) !== void 0) return;
8421
+ if (!isOwnersKey(record[state].read(inverse.ownerAttribute), owner, association)) return;
8422
+ record[state].associations.set(inverse.name, inverse.keyAttributes, owner);
8423
+ }
8424
+ /**
8425
+ * Points what `owner` loaded through `association` back at it (#62): a hasMany's or hasOne's
8426
+ * records at the owner, through their inverse belongsTo, and a belongsTo's record at the owner,
8427
+ * through its inverse hasOne. A hasMany isn't filled from a belongsTo: one record isn't the whole
8428
+ * collection, as in Rails.
8429
+ */
8430
+ function pointLoadedBack(owner, association, value) {
8431
+ if (value === null) return;
8432
+ if (!(value instanceof Model)) {
8433
+ for (const record of value) pointBackAtOwner(owner, association, record);
8434
+ return;
7736
8435
  }
7737
- const names = targets.map((target) => target.name).join(" or ");
7738
- throw new InvalidModel(`${label}: counterCache takes true, the name of ${names}'s attribute, or { attribute, active: false }`);
8436
+ if (association.definition.kind !== "belongsTo") {
8437
+ pointBackAtOwner(owner, association, value);
8438
+ return;
8439
+ }
8440
+ const inverse = inverseHasOne(value, association.branchForRecord(value) ?? association);
8441
+ if (inverse !== void 0) value[state].associations.set(inverse.name, inverse.keyAttributes, owner);
7739
8442
  }
7740
- /** The counter caches a Model's records keep: each belongsTo's declaring one, on each target. */
7741
- function countersOf(owner) {
7742
- return [...associationsOf(owner)].flatMap(([name, definition]) => {
7743
- if (definition.kind !== "belongsTo" || definition.counterCache === void 0) return [];
7744
- const attribute = counterAttribute(owner, definition);
7745
- const { foreignKey } = definition;
7746
- const { isActive } = counterCacheOf(definition);
7747
- return resolveAssociation(owner, name).branches.map(({ target, targetAttribute, type }) => ({
7748
- name,
7749
- foreignKey,
7750
- target,
7751
- attribute,
7752
- targetKey: targetAttribute,
7753
- type,
7754
- isActive
7755
- }));
7756
- });
8443
+ /**
8444
+ * Whether the record's foreign key is its owner's: the same key (an integer matching a text
8445
+ * key's digits, #94), or null while the owner has none yet, which saving the owner fills in. A
8446
+ * key that isn't the owner's, null included, points elsewhere. Only a pushed record can hold
8447
+ * one: a record built or created through the owner always gets the owner's key (#346).
8448
+ */
8449
+ function isOwnersKey(key, owner, association) {
8450
+ if (key === null) return association.keyOf(owner) === null;
8451
+ const ownerKey = owner[state].read(association.ownerAttribute);
8452
+ return ownerKey !== null && String(key) === String(ownerKey);
7757
8453
  }
8454
+ // src/autosave.ts
7758
8455
  /**
7759
- * Whether the type a record holds, as `typeIn` reads it, names `counter`'s target: always, for
7760
- * a belongsTo that isn't polymorphic.
8456
+ * The records `owner` was pointed at through belongsTo while they were new. Its foreign keys
8457
+ * are linked to them when it's saved, even if they were saved on their own since (Rails links
8458
+ * whenever the association was set); the ones still new and not already part of the write
8459
+ * (`claimed`) are saved first. Through an `autosave: true` belongsTo, its loaded record is saved
8460
+ * first too when it changed, or destroyed after it when it's marked (#37).
7761
8461
  */
7762
- function isTypeOfTarget(counter, typeIn) {
7763
- return counter.type === void 0 || typeIn(counter.type.attribute) === counter.type.value;
8462
+ function autosavedBefore(owner, claimed) {
8463
+ const model = modelOf(owner);
8464
+ const marked = ({ association, record }) => association.definition.autosave === true && record[state].isMarkedForDestruction;
8465
+ const all = owner[state].autosaves.allBelongsTo().map(([name, record]) => linkedThrough(model, name, record));
8466
+ const pointedAt = all.filter((each) => !marked(each));
8467
+ const unsaved = (each) => each.record[state].isNew && !claimed.has(each.record);
8468
+ const loadedSaved = loadedBelongsTo(owner, claimed);
8469
+ return {
8470
+ pointedAt,
8471
+ saved: [...pointedAt.filter(unsaved), ...loadedSaved.filter((each) => !marked(each) && isChangedForAutosave(each.record))],
8472
+ destroyed: [...all.filter((each) => marked(each) && unsaved(each)), ...loadedSaved.filter(marked)].map((each) => ({
8473
+ ...each,
8474
+ destroys: true
8475
+ }))
8476
+ };
7764
8477
  }
7765
- /** A write's counter changes: `before` and `after` its own statement, then `by` on `loaded`. */
7766
- function counterChanges(record, [before, after], loaded, by) {
8478
+ /** The saved records `owner`'s `autosave: true` belongsTo associations have loaded. */
8479
+ function loadedBelongsTo(owner, claimed) {
8480
+ const model = modelOf(owner);
8481
+ return [...associationsOf(model)].flatMap(([name, { kind, autosave }]) => {
8482
+ if (kind !== "belongsTo" || autosave !== true) return [];
8483
+ return loaded(owner, name).filter((record) => !record[state].isNew && !claimed.has(record)).map((record) => linkedThrough(model, name, record));
8484
+ });
8485
+ }
8486
+ /**
8487
+ * `record`, linked through `model`'s belongsTo `name`: for a polymorphic one (#60), through the
8488
+ * branch for the record's Model, which links its key.
8489
+ */
8490
+ function linkedThrough(model, name, record) {
8491
+ const association = resolveAssociation(model, name);
7767
8492
  return {
7768
- around: (own) => [
7769
- ...before,
7770
- own,
7771
- ...after
7772
- ],
7773
- commit(results) {
7774
- if ((results[before.length]?.rowsAffected ?? 0) > 0) countLoaded(record, loaded, by);
7775
- }
8493
+ association: association.branchForRecord(record) ?? association,
8494
+ record
7776
8495
  };
7777
8496
  }
7778
- /** A write that changes no counter: a record that was never saved has no row to delete. */
7779
- const noCounterChanges = {
7780
- around: (own) => [own],
7781
- commit: () => {}
7782
- };
7783
- /** Counting a new record in: each counter cache whose key is set, on its target by that key. */
7784
- function countersOnInsert(record) {
7785
- const recordState = record[state];
7786
- const counted = countersOf(modelOf(record)).filter((counter) => {
7787
- const key = recordState.read(counter.foreignKey);
7788
- return key !== null && key !== void 0 && isTypeOfTarget(counter, (name) => recordState.read(name));
8497
+ /**
8498
+ * Clears the foreign keys that point the owner at records it destroys (Rails' `self[fk] = nil`),
8499
+ * and a polymorphic belongsTo's type with it (#60), as `set(null)` does, and forgets a new one it
8500
+ * was to save first.
8501
+ */
8502
+ function unlink(owner, destroyed) {
8503
+ for (const { association } of destroyed) {
8504
+ owner[state].writeKey(association.ownerAttribute, null, association.name);
8505
+ if (association.isPolymorphic) owner[state].write(association.type.attribute, null);
8506
+ owner[state].autosaves.setBelongsTo(association.name, void 0);
8507
+ }
8508
+ }
8509
+ /**
8510
+ * What saving `owner` writes after it, through its hasMany and hasOne associations in the order
8511
+ * they're declared, leaving out any record already claimed by the write being prepared: the
8512
+ * records built through each that are still new, or with `autosave: true` what `withAutosave`
8513
+ * says. While the owner is new, a hasMany's are every record added to it, saved ones pushed onto
8514
+ * it included, as Rails saves a new owner's whole collection, and a hasOne's is its record, saved
8515
+ * or not.
8516
+ */
8517
+ function autosavedAfter(owner, claimed) {
8518
+ const model = modelOf(owner);
8519
+ return [...associationsOf(model)].flatMap(([name, { kind, autosave, through }]) => {
8520
+ if (kind === "belongsTo" || through !== void 0) return [];
8521
+ const entries = autosave ? withAutosave(owner, name, kind, claimed) : builtToSave(owner, name, claimed).map((record) => ({ record }));
8522
+ if (entries.length === 0) return [];
8523
+ const association = resolveAssociation(model, name);
8524
+ return entries.map((entry) => ({
8525
+ association,
8526
+ ...entry
8527
+ }));
7789
8528
  });
7790
- return counterChanges(record, [[], counted.map((counter) => {
7791
- const key = keyed(counter, recordState.read(counter.foreignKey));
7792
- return compileCounterChange(counter, changeBy(counter, 1), key);
7793
- })], counted, 1);
7794
8529
  }
7795
8530
  /**
7796
- * Counting a record out, before its row is deleted: each finds its target through the stored
7797
- * row, so a row already gone counts nothing, and a key changed in the database since the record
7798
- * was read counts out the target it has now.
8531
+ * What an `autosave: true` association writes after its owner (#37), as Rails does: its saved
8532
+ * records marked for destruction are destroyed, then its loaded records that changed are saved,
8533
+ * then those built through it. Marked records never saved are left out (`dropUnsavedMarked`).
7799
8534
  */
7800
- function countersOnDestroy(record) {
7801
- const recordState = record[state];
7802
- const skipped = destroyedThrough.get(record);
7803
- const counted = countersOf(modelOf(record)).filter((counter) => counter.foreignKey !== skipped && isTypeOfTarget(counter, (name) => recordState.valueInDatabase(name)));
7804
- return counterChanges(record, [counted.map((counter) => changeThroughRow(record, counter, -1, "before")), []], counted, -1);
8535
+ function withAutosave(owner, name, kind, claimed) {
8536
+ const built = builtToSave(owner, name, claimed);
8537
+ const stored = loaded(owner, name).filter((record) => !record[state].isNew && !claimed.has(record) && !built.includes(record));
8538
+ const marked = (record) => record[state].isMarkedForDestruction;
8539
+ const keepsKey = kind === "hasMany" ? { keepsKey: true } : {};
8540
+ return [
8541
+ ...[...stored, ...built].filter((record) => marked(record) && !record[state].isNew).map((record) => ({
8542
+ record,
8543
+ destroys: true
8544
+ })),
8545
+ ...stored.filter((record) => !marked(record) && isChangedForAutosave(record)).map((record) => ({
8546
+ record,
8547
+ ...keepsKey
8548
+ })),
8549
+ ...built.filter((record) => !marked(record)).map((record) => ({ record }))
8550
+ ];
7805
8551
  }
7806
8552
  /**
7807
- * Moving a record's count when its foreign key, or a polymorphic belongsTo's type, changes: out
7808
- * of the target its stored row points at before the UPDATE, and into the one it points at after
7809
- * it, so a row that isn't there counts nothing. A loaded new target counts it in memory, as
7810
- * Rails' `increment!` does.
8553
+ * Takes the records marked for destruction that were never saved out of `owner`'s `autosave:
8554
+ * true` associations, writing nothing, as Rails does when it saves the owner.
7811
8555
  */
7812
- function countersOnUpdate(record) {
7813
- const recordState = record[state];
7814
- const moved = countersOf(modelOf(record)).filter(({ foreignKey, type }) => [foreignKey, type?.attribute].some((name) => name !== void 0 && recordState.isAttributeChanged(name)));
7815
- const from = moved.filter((counter) => isTypeOfTarget(counter, (name) => recordState.valueInDatabase(name)));
7816
- const to = moved.filter((counter) => isTypeOfTarget(counter, (name) => recordState.read(name)));
7817
- return counterChanges(record, [from.map((counter) => changeThroughRow(record, counter, -1, "before")), to.map((counter) => changeThroughRow(record, counter, 1, "after"))], to, 1);
7818
- }
7819
- /** Each counter's target the record has loaded for its key takes the change, as stored. */
7820
- function countLoaded(record, counters, by) {
7821
- for (const { name, attribute } of counters) {
7822
- const target = record[state].associations.get(name)?.value;
7823
- if (target instanceof Model) addToCount(target, attribute, by);
8556
+ function dropUnsavedMarked(owner) {
8557
+ const model = modelOf(owner);
8558
+ for (const [name, { kind, autosave }] of associationsOf(model)) {
8559
+ if (kind === "belongsTo" || autosave !== true) continue;
8560
+ const association = resolveAssociation(model, name);
8561
+ for (const record of owner[state].autosaves.built(name)) if (record[state].isNew && record[state].isMarkedForDestruction) forget(owner, association, record);
7824
8562
  }
7825
8563
  }
7826
- /**
7827
- * A record whose counter the database changed by `by` takes the change, as stored: the
7828
- * attribute, if loaded, changes by `by` and has no unsaved change, as after Rails' `increment!`.
7829
- */
7830
- function addToCount(record, attribute, by) {
7831
- const recordState = record[state];
7832
- if (recordState.isDestroyed || !(attribute in recordState.attributes())) return;
7833
- const count = recordState.read(attribute);
7834
- recordState.write(attribute, (typeof count === "number" ? count : 0) + by);
7835
- recordState.commitColumns([attribute]);
8564
+ /** Takes `record` out of what `owner`'s association holds: built through it, or loaded. */
8565
+ function forget(owner, association, record) {
8566
+ const { name } = association;
8567
+ owner[state].autosaves.removeBuilt(name, [record]);
8568
+ const value = owner[state].associations.get(name)?.value;
8569
+ if (Array.isArray(value)) {
8570
+ const kept = value.filter((each) => each !== record);
8571
+ owner[state].associations.set(name, association.keyAttributes, kept);
8572
+ } else if (value === record) owner[state].associations.set(name, association.keyAttributes, null);
8573
+ }
8574
+ /** The records built through the association that saving `owner` saves after it. */
8575
+ function builtToSave(owner, name, claimed) {
8576
+ const ownerIsNew = owner[state].isNew;
8577
+ return owner[state].autosaves.built(name).filter((record) => (ownerIsNew || record[state].isNew) && !claimed.has(record));
8578
+ }
8579
+ /** The association's loaded records, for the key the owner holds now: none when it isn't loaded. */
8580
+ function loaded(owner, name) {
8581
+ const value = owner[state].associations.get(name)?.value;
8582
+ if (value === void 0 || value === null) return [];
8583
+ return Array.isArray(value) ? value : [value];
7836
8584
  }
7837
8585
  /**
7838
- * `counter`'s change by `by` on the target the record's row points at, found by the row's key
7839
- * `before` its write, or `after` it (its key as the record holds it, should the write change it).
8586
+ * Whether saving `record` through an `autosave: true` association would write anything, as Rails'
8587
+ * `changed_for_autosave?`: it's new, changed or marked for destruction, or so is a record of one of its own `autosave:
8588
+ * true` associations, at any level. `seen` stops a loop of records loaded through each other.
7840
8589
  */
7841
- function changeThroughRow(record, counter, by, when) {
7842
- const owner = modelOf(record);
8590
+ function isChangedForAutosave(record, seen = /* @__PURE__ */ new Set()) {
8591
+ if (seen.has(record)) return false;
8592
+ seen.add(record);
7843
8593
  const recordState = record[state];
7844
- const params = [];
7845
- const ownerKey = attributeFor(owner, owner.primaryKey);
7846
- if (when === "before") ownerKey.bindCells(params, recordState.storedKey);
7847
- else ownerKey.bind(params, recordState.read(owner.primaryKey));
7848
- const foreignKey = quoteIdentifier(attributeFor(owner, counter.foreignKey).column);
7849
- const typed = counter.type === void 0 ? "" : ` AND ${typeCondition(owner, counter.type, params)}`;
7850
- const row = `(SELECT ${foreignKey} FROM ${quoteIdentifier(owner.table)} WHERE ${quoteIdentifier(ownerKey.column)} = ${typed})`;
7851
- return compileCounterChange(counter, changeBy(counter, by), {
7852
- sql: row,
7853
- params
7854
- });
8594
+ if (recordState.isNew || recordState.isMarkedForDestruction) return true;
8595
+ if (recordState.changedNames().length > 0) return true;
8596
+ return [...associationsOf(modelOf(record))].some(([name, { autosave }]) => autosave === true && loaded(record, name).some((each) => isChangedForAutosave(each, seen)));
7855
8597
  }
7856
- /**
7857
- * The foreign key of the association each record is being destroyed through, by its owner's
7858
- * `dependent: "destroy"`: that owner is deleted with it, so its counter isn't changed, as Rails
7859
- * skips it (`destroyed_by_association`). Not request state: set only while a destroy is prepared.
7860
- */
7861
- const destroyedThrough = /* @__PURE__ */ new WeakMap();
7862
- /** Prepares `record`'s destroy through its owner's association, whose `foreignKey` is given. */
7863
- async function destroyingThrough(record, foreignKey, prepare) {
7864
- destroyedThrough.set(record, foreignKey);
7865
- try {
7866
- return await prepare();
7867
- } finally {
7868
- destroyedThrough.delete(record);
7869
- }
8598
+ /** Whether every record's key is known before it's written (generated in code). */
8599
+ function isEveryKeyKnown(pointedAt) {
8600
+ return pointedAt.every(({ association, record }) => record[state].read(association.targetAttribute) !== null);
7870
8601
  }
7871
- /** A target's key, `= ?` with `key` bound as the counter's target key. */
7872
- function keyed({ target, targetKey }, key) {
7873
- const params = [];
7874
- attributeFor(target, targetKey).bind(params, key);
7875
- return {
7876
- sql: "\0",
7877
- params
7878
- };
8602
+ /** Whether the owner's key, which every record takes, is known before anything is written. */
8603
+ function isOwnerKeyKnown(owner, after) {
8604
+ return after.every(({ association }) => owner[state].read(association.ownerAttribute) !== null);
7879
8605
  }
7880
- /** `+ ?`, with `by` bound as the counter's value: hidden from `onQuery` if it's filtered. */
7881
- function changeBy({ target, attribute }, by) {
7882
- const params = [];
7883
- attributeFor(target, attribute).bindCells(params, by);
7884
- return {
7885
- sql: `+ `,
7886
- params
7887
- };
8606
+ /** Points the owner at the records it points at, now that their keys exist, keeping them loaded. */
8607
+ function linkBefore(owner, pointedAt) {
8608
+ for (const { association, record } of pointedAt) {
8609
+ owner[state].pointAt(association, record[state].read(association.targetAttribute), record);
8610
+ owner[state].autosaves.setBelongsTo(association.name, void 0);
8611
+ }
7888
8612
  }
7889
8613
  /**
7890
- * `UPDATE … SET counter = COALESCE(counter, 0) <change> WHERE key = <key>`: `change` an operator
7891
- * and its operand (`+ ?`), `key` the target's key or a subquery finding it.
8614
+ * Points every record saved after its owner at it, keeping the owner loaded as its inverse
8615
+ * (#62). A hasOne's record stays the owner's loaded association under the owner's new key.
7892
8616
  */
7893
- function compileCounterChange(counter, change, key) {
7894
- return compileCountersChange([counter], change, key);
8617
+ function linkAfter(owner, after) {
8618
+ for (const { association, record, keepsKey, destroys } of after) {
8619
+ if (keepsKey || destroys) continue;
8620
+ const { name, definition, ownerAttribute } = association;
8621
+ record[state].writeKey(definition.foreignKey, owner[state].read(ownerAttribute), name);
8622
+ association.writeOwnersType(record);
8623
+ pointBackAtOwner(owner, association, record);
8624
+ if (definition.kind === "hasOne") owner[state].associations.set(name, association.keyAttributes, record);
8625
+ }
7895
8626
  }
7896
8627
  /**
7897
- * `compileCounterChange` for several counters of one target, found by one key, each changed by
7898
- * `change`, in one UPDATE: Postgres changes a row once in one statement, so two UPDATEs of it in
7899
- * one would keep only one change.
8628
+ * The records saving `record` would write, by database (#228): it, the records it saves or
8629
+ * destroys through its associations, at every level. A record reached through an association to
8630
+ * another database starts a group of its own. Found without running any validation or callback,
8631
+ * so a save can be checked before anything runs (#93).
7900
8632
  */
7901
- function compileCountersChange(counters, change, key) {
7902
- const { target, targetKey } = counters[0];
7903
- const sets = counters.map(({ attribute }) => {
7904
- const column = quoteIdentifier(attributeFor(target, attribute).column);
7905
- return `${column} = COALESCE(${column}, 0) ${change.sql}`;
7906
- });
7907
- const keyColumn = quoteIdentifier(attributeFor(target, targetKey).column);
7908
- return {
7909
- sql: `UPDATE ${quoteIdentifier(target.table)} SET ${sets.join(", ")} WHERE ${keyColumn} = ${key.sql}`,
7910
- params: [...counters.flatMap(() => change.params), ...key.params],
7911
- model: target
8633
+ function savingGroups(record) {
8634
+ const found = /* @__PURE__ */ new Set();
8635
+ const groups = [{
8636
+ records: [],
8637
+ through: void 0
8638
+ }];
8639
+ const visit = (each, group) => {
8640
+ if (found.has(each)) return;
8641
+ found.add(each);
8642
+ group.records.push(each);
8643
+ const { saved, destroyed } = autosavedBefore(each, /* @__PURE__ */ new Set());
8644
+ const linked = [
8645
+ ...saved,
8646
+ ...destroyed,
8647
+ ...autosavedAfter(each, found)
8648
+ ];
8649
+ for (const { association, record: next } of linked) visit(next, association.isCrossDatabase ? startGroup(groups, association) : group);
7912
8650
  };
8651
+ visit(record, groups[0]);
8652
+ return groups.filter(({ records }) => records.length > 0);
7913
8653
  }
7914
- /** `type = ?`: a polymorphic row's type naming the counter's target, its value bound. */
7915
- function typeCondition(owner, { attribute, value }, params) {
7916
- const type = attributeFor(owner, attribute);
7917
- type.bind(params, value);
7918
- return `${quoteIdentifier(type.column)} = `;
8654
+ /** A new group of records, reached through `association`, added to `groups`. */
8655
+ function startGroup(groups, association) {
8656
+ const group = {
8657
+ records: [],
8658
+ through: association
8659
+ };
8660
+ groups.push(group);
8661
+ return group;
7919
8662
  }
7920
8663
  // src/dependents.ts
7921
8664
  /** A destroy with no dependents to write: a new record's. */
@@ -8215,41 +8958,6 @@ function savedElsewhere(owner, planned) {
8215
8958
  if (first === void 0) return [];
8216
8959
  return [afterLinking(first, () => linkAfter(owner, planned)), ...rest];
8217
8960
  }
8218
- // src/callbacks.ts
8219
- /** Runs the Model's callbacks of `kind` in declaration order, awaiting each. */
8220
- async function runCallbacks(record, kind) {
8221
- for (const callback of declared(modelOf(record), kind)) await callback(record);
8222
- }
8223
- /**
8224
- * Runs `run`, a callback of `kind` that runs once the write is kept. An `abort()` there can't
8225
- * refuse anything: it becomes `AbortAfterPersistence`. Any other error propagates unchanged.
8226
- */
8227
- async function tooLateToAbort(run, kind, lifecycle) {
8228
- try {
8229
- await run();
8230
- } catch (error) {
8231
- if (error instanceof CallbackAbort) throw new AbortAfterPersistence(kind, lifecycle, error);
8232
- throw error;
8233
- }
8234
- }
8235
- /** Runs after-write callbacks; an `abort()` in one is `AbortAfterPersistence`. */
8236
- async function runAfterCallbacks(record, kind, lifecycle) {
8237
- await tooLateToAbort(() => runCallbacks(record, kind), kind, lifecycle);
8238
- }
8239
- /** A write's rollback callbacks: the record's `afterRollback`, to run if the database refuses it. */
8240
- function afterRollbackOf(record) {
8241
- return () => runCallbacks(record, "afterRollback");
8242
- }
8243
- /**
8244
- * Runs the record's commit callbacks for `action`, in the order they were declared. The write is
8245
- * already kept, so an `abort()` in one is `AbortAfterPersistence`; any other error propagates.
8246
- */
8247
- async function runCommitCallbacks(record, action) {
8248
- for (const { kind, on, callback } of declared(modelOf(record), "commitCallbacks")) {
8249
- if (!on.includes(action)) continue;
8250
- await tooLateToAbort(() => callback(record), kind, action === "destroy" ? "destroy" : "save");
8251
- }
8252
- }
8253
8961
  // src/required-associations.ts
8254
8962
  /**
8255
8963
  * Adds "must exist" (type `required`) to each of the record's required belongsTo associations
@@ -8376,17 +9084,21 @@ function aborted(record) {
8376
9084
  /**
8377
9085
  * The save lifecycle, in the contract's order:
8378
9086
  * can this record be used → beforeValidation → validators → afterValidation
8379
- * → beforeSave → beforeCreate | beforeUpdate → write (skipped when clean) → commit state
8380
- * → afterCreate | afterUpdate → afterSave.
9087
+ * → beforeSave → aroundSave (to `next()`) → beforeCreate | beforeUpdate
9088
+ * → aroundCreate | aroundUpdate (to `next()`) → write (skipped when clean) → commit state
9089
+ * → aroundCreate | aroundUpdate (the rest) → afterCreate | afterUpdate → aroundSave (the rest)
9090
+ * → afterSave. An around callback still waiting when it ends has its `next()` rejected.
8381
9091
  */
8382
9092
  async function saveLifecycle(record, context) {
8383
9093
  requireKnownContexts(record, context);
8384
9094
  const needs = "save() needs its records";
8385
9095
  for (const { records } of savingGroups(record)) await pinBefore(linksOf(records), needs);
8386
- const plan = await prepareSave(record, /* @__PURE__ */ new Set(), context);
8387
- if (plan.status !== "ready") return plan;
8388
- await runStages(stagesOf(plan), needs);
8389
- return { status: "saved" };
9096
+ return withClaimedRecords(async (claimed) => {
9097
+ const plan = await prepareSave(record, claimed, context);
9098
+ if (plan.status !== "ready") return plan;
9099
+ await runStages(stagesOf(plan), needs);
9100
+ return { status: "saved" };
9101
+ }, (outcome) => outcome.status === "saved" ? void 0 : refusalError(record, outcome, "save"));
8390
9102
  }
8391
9103
  /**
8392
9104
  * Everything a save does before writing: validation (in `context`, if given) and the
@@ -8410,33 +9122,47 @@ async function prepareWrites(record, claimed) {
8410
9122
  const before = await prepareBefore(record, claimed);
8411
9123
  if ("status" in before) return before;
8412
9124
  const isInsert = record[state].isNew;
8413
- if (!await beforeWrite(record, isInsert)) return aborted(record);
9125
+ const wrapped = await beforeWrite(record, isInsert);
9126
+ if (wrapped === void 0) return aborted(record);
9127
+ waitWith(claimed, wrapped);
8414
9128
  const removal = await prepareReplacement(record, claimed);
9129
+ leaveToAutosaves(autosavedAfter(record, claimed), claimed);
9130
+ const touches = await touchesOfSave(record, isInsert, claimed);
8415
9131
  const own = stageOf(record, [record], () => {
8416
9132
  linkOwner(record, before);
8417
- return [saveWrite(record, isInsert)];
9133
+ return [saveWrite(record, isInsert, wrapped), ...touches];
8418
9134
  });
8419
9135
  const after = await prepareAfter(record, claimed);
8420
9136
  if (!Array.isArray(after)) return after;
8421
9137
  return withRemoval(assemble(record, own, before, after), removal, record);
8422
9138
  }
8423
- /** beforeSave, then beforeCreate or beforeUpdate; `false` if one aborted. */
9139
+ /**
9140
+ * beforeSave, then the around callbacks (#48), which run beforeCreate or beforeUpdate inside
9141
+ * them, up to the write; `undefined` if one aborted, with `abortReason` set.
9142
+ */
8424
9143
  async function beforeWrite(record, isInsert) {
8425
- return await runAbortableCallbacks(record, "beforeSave") && await runAbortableCallbacks(record, isInsert ? "beforeCreate" : "beforeUpdate");
9144
+ if (!await runAbortableCallbacks(record, "beforeSave")) return void 0;
9145
+ const wrapped = await startSave(record, isInsert);
9146
+ if (!(wrapped instanceof CallbackAbort)) return wrapped;
9147
+ record[state].abortReason = wrapped.reason;
8426
9148
  }
8427
9149
  /**
8428
9150
  * A save's write: INSERT the assigned attributes (`RETURNING *` loads what D1 stored), or
8429
- * UPDATE the changed ones, plus timestamps; a clean record sends nothing. Its after-callbacks
8430
- * are afterCreate or afterUpdate, then afterSave.
9151
+ * UPDATE the changed ones, plus timestamps; a clean record sends nothing. Once it's kept, its
9152
+ * around callbacks finish (afterCreate or afterUpdate inside them), then afterSave runs; once
9153
+ * it's refused, afterRollback runs, then their `next()` rejects.
8431
9154
  */
8432
- function saveWrite(record, isInsert) {
9155
+ function saveWrite(record, isInsert, wrapped) {
8433
9156
  const recordState = record[state];
8434
9157
  const model = modelOf(record);
8435
9158
  const after = async () => {
8436
- await runAfterCallbacks(record, isInsert ? "afterCreate" : "afterUpdate", "save");
9159
+ await wrapped.finish();
8437
9160
  await runAfterCallbacks(record, "afterSave", "save");
8438
9161
  };
8439
- const afterRollback = afterRollbackOf(record);
9162
+ const afterRollback = async (error) => {
9163
+ await afterRollbackOf(record)();
9164
+ await wrapped.fail(error);
9165
+ };
8440
9166
  const afterCommit = () => runCommitCallbacks(record, isInsert ? "create" : "update");
8441
9167
  if (isInsert) {
8442
9168
  const own = recordState.insertAssignments();
@@ -8480,16 +9206,18 @@ function saveWrite(record, isInsert) {
8480
9206
  }
8481
9207
  /**
8482
9208
  * The destroy lifecycle: can this record be used → beforeDestroy → its `dependent:` strategies
8483
- * → DELETE by the stored key (skipped for a never-saved record: there's no row, as in Rails)
8484
- * → mark destroyed → afterDestroy. Every write, dependents' included, is one atomic batch.
9209
+ * → aroundDestroy, wrapping the DELETE by the stored key (skipped for a never-saved record:
9210
+ * there's no row, as in Rails) → mark destroyed → afterDestroy. Every write, dependents' included, is one atomic batch.
8485
9211
  */
8486
9212
  async function destroyLifecycle(record) {
8487
9213
  const needs = "destroy() needs its records";
8488
9214
  await pinBefore(linksOf([record]), needs);
8489
- const plan = await prepareDestroy(record, /* @__PURE__ */ new Set());
8490
- if (plan.status !== "ready") return plan;
8491
- await runStages(stagesOf(plan), needs);
8492
- return { status: "destroyed" };
9215
+ return withClaimedRecords(async (claimed) => {
9216
+ const plan = await prepareDestroy(record, claimed);
9217
+ if (plan.status !== "ready") return plan;
9218
+ await runStages(stagesOf(plan), needs);
9219
+ return { status: "destroyed" };
9220
+ }, (outcome) => outcome.status === "destroyed" ? void 0 : refusalError(record, outcome, "destroy"));
8493
9221
  }
8494
9222
  /** Everything a destroy does before writing: beforeDestroy, then its dependents' plans. */
8495
9223
  async function prepareDestroy(record, claimed) {
@@ -8501,19 +9229,32 @@ async function prepareDestroy(record, claimed) {
8501
9229
  if (!await runAbortableCallbacks(record, "beforeDestroy")) return aborted(record);
8502
9230
  const dependents = recordState.isNew ? noDependents : await prepareDependents(record, claimed);
8503
9231
  if (dependents.status !== "ready") return dependents;
9232
+ const wrapped = await startDestroy(record);
9233
+ if (wrapped instanceof CallbackAbort) {
9234
+ recordState.abortReason = wrapped.reason;
9235
+ return aborted(record);
9236
+ }
9237
+ waitWith(claimed, wrapped);
8504
9238
  const hasRow = !recordState.isNew;
8505
9239
  const counters = hasRow ? countersOnDestroy(record) : noCounterChanges;
8506
9240
  const deletion = hasRow ? counters.around(compileDelete(modelOf(record), recordState.storedKey)) : [];
9241
+ const touches = hasRow ? await touchesOf(record, "destroy", claimed) : [];
8507
9242
  const own = stageOf(record, [record], () => [{
8508
9243
  statements: deletion,
8509
9244
  commit: (results) => {
8510
9245
  recordState.markDestroyed();
8511
9246
  counters.commit(results);
8512
9247
  },
8513
- after: () => runAfterCallbacks(record, "afterDestroy", "destroy"),
8514
- afterRollback: afterRollbackOf(record),
9248
+ after: async () => {
9249
+ await wrapped.finish();
9250
+ await runAfterCallbacks(record, "afterDestroy", "destroy");
9251
+ },
9252
+ afterRollback: async (error) => {
9253
+ await afterRollbackOf(record)();
9254
+ await wrapped.fail(error);
9255
+ },
8515
9256
  ...hasRow && { afterCommit: () => runCommitCallbacks(record, "destroy") }
8516
- }]);
9257
+ }, ...touches]);
8517
9258
  return {
8518
9259
  status: "ready",
8519
9260
  stages: inGroup(combine([[dependents.here], [own]]), record),
@@ -8521,7 +9262,10 @@ async function prepareDestroy(record, claimed) {
8521
9262
  after: []
8522
9263
  };
8523
9264
  }
8524
- /** Loads the record's row again by its stored primary key, discarding unsaved changes. */
9265
+ /**
9266
+ * Loads the record's row again by its stored primary key, discarding unsaved changes, then runs its
9267
+ * `afterFind` and `afterInitialize` (#49).
9268
+ */
8525
9269
  async function reloadRecord(record) {
8526
9270
  const recordState = record[state];
8527
9271
  recordState.requireLive("be reloaded");
@@ -8540,6 +9284,7 @@ async function reloadRecord(record) {
8540
9284
  recordState.clearAssociations();
8541
9285
  recordState.isMarkedForDestruction = false;
8542
9286
  recordState.loadRow(row);
9287
+ runLoadedCallbacks(record);
8543
9288
  }
8544
9289
  // src/record-inspect.ts
8545
9290
  /** An unsaved change: the new value, and the one the record was loaded or saved with, if any. */
@@ -8608,6 +9353,7 @@ const relationMethods = [
8608
9353
  "upsert",
8609
9354
  "upsertAll",
8610
9355
  "updateAll",
9356
+ "touchAll",
8611
9357
  "deleteAll",
8612
9358
  "destroyAll",
8613
9359
  "destroyBy",
@@ -8644,6 +9390,13 @@ const relationMethods = [
8644
9390
  "findInBatches",
8645
9391
  "inBatches"
8646
9392
  ];
9393
+ /** The around callback kinds, one static each; `satisfies` keeps the list and the type agreed. */
9394
+ const aroundKinds = Object.keys({
9395
+ aroundSave: true,
9396
+ aroundCreate: true,
9397
+ aroundUpdate: true,
9398
+ aroundDestroy: true
9399
+ });
8647
9400
  /**
8648
9401
  * The writes each commit callback runs for. Both `satisfies` make the list, `CommitCallbackKind` and
8649
9402
  * `CommitStatics` name the same kinds.
@@ -8674,7 +9427,10 @@ const callbackKinds = Object.keys({
8674
9427
  afterSave: true,
8675
9428
  beforeDestroy: true,
8676
9429
  afterDestroy: true,
8677
- afterRollback: true
9430
+ afterTouch: true,
9431
+ afterRollback: true,
9432
+ afterFind: true,
9433
+ afterInitialize: true
8678
9434
  });
8679
9435
  /**
8680
9436
  * The class Model extends, for its statics' types only: at runtime it's empty, and
@@ -8691,6 +9447,9 @@ function defineStatics(base) {
8691
9447
  const on = isValidationKind(kind) ? options?.on : void 0;
8692
9448
  declare(this, kind, on === void 0 ? callback : inContext(callback, on));
8693
9449
  });
9450
+ for (const kind of aroundKinds) defineStatic(base, kind, function(callback) {
9451
+ declare(this, kind, callback);
9452
+ });
8694
9453
  for (const [kind, on] of Object.entries(commitKinds)) defineStatic(base, kind, function(callback) {
8695
9454
  declare(this, "commitCallbacks", {
8696
9455
  kind,
@@ -8789,15 +9548,33 @@ var AttributeWrites = class extends ModelStatics {
8789
9548
  /**
8790
9549
  * Adds `by` to a number attribute in the row, as `SET x = COALESCE(x, 0) + by`, so concurrent
8791
9550
  * writes all count, with no validation, callback or `updatedAt`; the record then holds the
8792
- * row's new value. An unsaved change to it is added too, as Rails' `increment!`. Resolves to
8793
- * whether there was a row to write.
9551
+ * row's new value. An unsaved change to it is added too, as Rails' `increment!`. With
9552
+ * `{ touch }`, the same UPDATE sets `updatedAt` (and any datetime attributes named) to now, and
9553
+ * the record holds them (#50). Resolves to whether there was a row to write.
8794
9554
  */
8795
- async incrementColumn(name, by = 1) {
8796
- return addToColumn(this, name, amount(by, "incrementColumn"), "incrementColumn");
9555
+ async incrementColumn(name, by = 1, { touch } = {}) {
9556
+ const method = "incrementColumn";
9557
+ return addToColumn(this, name, amount(by, method), {
9558
+ method,
9559
+ touch
9560
+ });
8797
9561
  }
8798
9562
  /** `incrementColumn`, taking `by` away. */
8799
- async decrementColumn(name, by = 1) {
8800
- return addToColumn(this, name, -amount(by, "decrementColumn"), "decrementColumn");
9563
+ async decrementColumn(name, by = 1, { touch } = {}) {
9564
+ const method = "decrementColumn";
9565
+ return addToColumn(this, name, -amount(by, method), {
9566
+ method,
9567
+ touch
9568
+ });
9569
+ }
9570
+ /**
9571
+ * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to
9572
+ * the row, with no validation or save callback, as Rails' `touch`. Resolves to whether there
9573
+ * was a row to write. Inside its Model's `noTouching` block, it writes nothing (#496).
9574
+ */
9575
+ async touch(...args) {
9576
+ requireSaved(this, "touch");
9577
+ return touchRecord(this, args);
8801
9578
  }
8802
9579
  /**
8803
9580
  * Writes a boolean attribute's flipped value straight to the row, as `updateColumn` does: no
@@ -8815,18 +9592,20 @@ function isTrueOnceToggled(record, name, method) {
8815
9592
  }
8816
9593
  /**
8817
9594
  * Adds to a number attribute in memory, then sends the difference from the row's value as it
8818
- * was loaded, and holds the value the row returns.
9595
+ * was loaded, with any timestamps `touch` sets, and holds the values the row returns.
8819
9596
  */
8820
- async function addToColumn(record, name, by, method) {
9597
+ async function addToColumn(record, name, by, { method, touch }) {
8821
9598
  const recordState = record[state];
8822
9599
  requireSaved(record, method);
9600
+ const model = modelOf$1(record);
9601
+ const touched = touchAssignments(model, touch, method);
9602
+ const touchedNames = touched.map(([each]) => each);
8823
9603
  const after = (numberValue(record, name, method) ?? 0) + by;
8824
9604
  const delta = after - (recordState.valueInDatabase(name) ?? 0);
8825
9605
  recordState.write(name, after);
8826
- const model = modelOf$1(record);
8827
- const update = compileUpdate(model, counterSets(model, { [name]: delta }, method), recordState.storedKey, [name]);
9606
+ const update = compileUpdate(model, counterSets(model, { [name]: delta }, method, { touched }), recordState.storedKey, [name, ...touchedNames]);
8828
9607
  const [result] = await recordState.executor.write([update]);
8829
- recordState.commitColumns([name], result?.rows[0]);
9608
+ recordState.commitColumns([name, ...touchedNames], result?.rows[0]);
8830
9609
  return result?.rowsAffected === 1;
8831
9610
  }
8832
9611
  /** Assigns `attributes`, then UPDATEs only them by the stored key, and marks them saved. */
@@ -8880,6 +9659,14 @@ var Model = class extends AttributeWrites {
8880
9659
  * names; none by default. `attributes()` still has them (#101).
8881
9660
  */
8882
9661
  static hiddenAttributes = [];
9662
+ /**
9663
+ * Runs `fn` with this Model's records not touched, nor those of the Models extending it
9664
+ * (`Model.noTouching` covers every Model), as Rails' `no_touching`: a belongsTo's `touch`
9665
+ * leaves them alone, and their `touch()` writes nothing. Resolves to what `fn` returns.
9666
+ */
9667
+ static noTouching(fn) {
9668
+ return noTouching(this, fn);
9669
+ }
8883
9670
  /** An attribute's name as error messages show it: from `humanAttributeNames`, or "Created at". */
8884
9671
  static humanAttributeName(attribute) {
8885
9672
  return humanAttributeName(this, attribute);
@@ -9139,7 +9926,9 @@ var Model = class extends AttributeWrites {
9139
9926
  }
9140
9927
  /**
9141
9928
  * Deletes the row and resolves to this record, now a read-only destroyed snapshot.
9142
- * A row that's already gone still counts. `false` means a `beforeDestroy` callback aborted.
9929
+ * A row that's already gone still counts. `false` means a `beforeDestroy` or `aroundDestroy`
9930
+ * callback aborted (or an `aroundDestroy` didn't call `next()`), or a `restrictWithError`
9931
+ * association refused.
9143
9932
  */
9144
9933
  async destroy() {
9145
9934
  return (await destroyLifecycle(this)).status === "destroyed" ? this : false;
@@ -9186,6 +9975,14 @@ var Model = class extends AttributeWrites {
9186
9975
  isDestroyed() {
9187
9976
  return this[state].isDestroyed;
9188
9977
  }
9978
+ /**
9979
+ * Whether the record has the attribute `name` loaded (Rails' `has_attribute?`): `false` for one
9980
+ * `select(...)` left out, whose read throws `MissingAttribute`, and for a name the Model doesn't
9981
+ * declare. A callback that runs for partial records, such as `afterFind`, checks it first.
9982
+ */
9983
+ hasAttribute(name) {
9984
+ return this[state].hasAttribute(name);
9985
+ }
9189
9986
  /** The record's attributes as a plain object of JavaScript values. */
9190
9987
  attributes() {
9191
9988
  return this[state].attributes();
@@ -9235,11 +10032,12 @@ function modelOf(record) {
9235
10032
  function primaryKeyOf(record) {
9236
10033
  return record[state].read(modelOf(record).primaryKey);
9237
10034
  }
9238
- /** Builds a persisted record of `model` from a D1 row. */
10035
+ /** Builds a persisted record of `model` from a row, running its `afterFind` and `afterInitialize`. */
9239
10036
  function hydrate(model, row, executor) {
9240
10037
  const record = newRecord$1(model);
9241
10038
  record[state].belongTo(executor);
9242
10039
  record[state].loadRow(row);
10040
+ runLoadedCallbacks(record);
9243
10041
  return record;
9244
10042
  }
9245
10043
  /**
@@ -9252,213 +10050,215 @@ function buildRecord(model, attributes, executor) {
9252
10050
  record[state].build(attributes);
9253
10051
  return record;
9254
10052
  }
9255
- // src/autosave.ts
10053
+ // src/callbacks.ts
10054
+ /** Runs the Model's callbacks of `kind` in declaration order, awaiting each. */
10055
+ async function runCallbacks(record, kind) {
10056
+ for (const callback of declared(modelOf(record), kind)) await callback(record);
10057
+ }
9256
10058
  /**
9257
- * The records `owner` was pointed at through belongsTo while they were new. Its foreign keys
9258
- * are linked to them when it's saved, even if they were saved on their own since (Rails links
9259
- * whenever the association was set); the ones still new and not already part of the write
9260
- * (`claimed`) are saved first. Through an `autosave: true` belongsTo, its loaded record is saved
9261
- * first too when it changed, or destroyed after it when it's marked (#37).
10059
+ * Runs `run`, a callback of `kind` that runs once the write is kept. An `abort()` there can't
10060
+ * refuse anything: it becomes `AbortAfterPersistence`. Any other error propagates unchanged.
9262
10061
  */
9263
- function autosavedBefore(owner, claimed) {
9264
- const model = modelOf(owner);
9265
- const marked = ({ association, record }) => association.definition.autosave === true && record[state].isMarkedForDestruction;
9266
- const all = owner[state].autosaves.allBelongsTo().map(([name, record]) => linkedThrough(model, name, record));
9267
- const pointedAt = all.filter((each) => !marked(each));
9268
- const unsaved = (each) => each.record[state].isNew && !claimed.has(each.record);
9269
- const loadedSaved = loadedBelongsTo(owner, claimed);
9270
- return {
9271
- pointedAt,
9272
- saved: [...pointedAt.filter(unsaved), ...loadedSaved.filter((each) => !marked(each) && isChangedForAutosave(each.record))],
9273
- destroyed: [...all.filter((each) => marked(each) && unsaved(each)), ...loadedSaved.filter(marked)].map((each) => ({
9274
- ...each,
9275
- destroys: true
9276
- }))
9277
- };
10062
+ async function tooLateToAbort(run, kind, lifecycle) {
10063
+ try {
10064
+ await run();
10065
+ } catch (error) {
10066
+ if (error instanceof CallbackAbort) throw new AbortAfterPersistence(kind, lifecycle, error);
10067
+ throw error;
10068
+ }
9278
10069
  }
9279
- /** The saved records `owner`'s `autosave: true` belongsTo associations have loaded. */
9280
- function loadedBelongsTo(owner, claimed) {
9281
- const model = modelOf(owner);
9282
- return [...associationsOf(model)].flatMap(([name, { kind, autosave }]) => {
9283
- if (kind !== "belongsTo" || autosave !== true) return [];
9284
- return loaded(owner, name).filter((record) => !record[state].isNew && !claimed.has(record)).map((record) => linkedThrough(model, name, record));
9285
- });
10070
+ /** Runs after-write callbacks; an `abort()` in one is `AbortAfterPersistence`. */
10071
+ async function runAfterCallbacks(record, kind, lifecycle) {
10072
+ await tooLateToAbort(() => runCallbacks(record, kind), kind, lifecycle);
9286
10073
  }
9287
- /**
9288
- * `record`, linked through `model`'s belongsTo `name`: for a polymorphic one (#60), through the
9289
- * branch for the record's Model, which links its key.
9290
- */
9291
- function linkedThrough(model, name, record) {
9292
- const association = resolveAssociation(model, name);
9293
- return {
9294
- association: association.branchForRecord(record) ?? association,
9295
- record
9296
- };
10074
+ /** A write's rollback callbacks: the record's `afterRollback`, to run if the database refuses it. */
10075
+ function afterRollbackOf(record) {
10076
+ return () => runCallbacks(record, "afterRollback");
9297
10077
  }
9298
10078
  /**
9299
- * Clears the foreign keys that point the owner at records it destroys (Rails' `self[fk] = nil`),
9300
- * and a polymorphic belongsTo's type with it (#60), as `set(null)` does, and forgets a new one it
9301
- * was to save first.
10079
+ * Runs the record's commit callbacks for `action`, in the order they were declared. The write is
10080
+ * already kept, so an `abort()` in one is `AbortAfterPersistence`; any other error propagates.
9302
10081
  */
9303
- function unlink(owner, destroyed) {
9304
- for (const { association } of destroyed) {
9305
- owner[state].writeKey(association.ownerAttribute, null, association.name);
9306
- if (association.isPolymorphic) owner[state].write(association.type.attribute, null);
9307
- owner[state].autosaves.setBelongsTo(association.name, void 0);
10082
+ async function runCommitCallbacks(record, action) {
10083
+ for (const { kind, on, callback } of declared(modelOf(record), "commitCallbacks")) {
10084
+ if (!on.includes(action)) continue;
10085
+ await tooLateToAbort(() => callback(record), kind, action === "destroy" ? "destroy" : "save");
10086
+ }
10087
+ }
10088
+ // src/around-callbacks.ts
10089
+ /**
10090
+ * Where a record's write waits while its around callbacks wait at `next()`: reached as the save
10091
+ * or destroy is prepared, then opened once the write is kept, or failed when it isn't.
10092
+ */
10093
+ var WriteGate = class {
10094
+ reached;
10095
+ #reach;
10096
+ #outcome;
10097
+ #settle;
10098
+ #status = "pending";
10099
+ constructor() {
10100
+ let reach;
10101
+ this.reached = new Promise((resolve) => reach = resolve);
10102
+ this.#reach = reach;
10103
+ this.#outcome = new Promise((resolve, reject) => {
10104
+ this.#settle = {
10105
+ open: resolve,
10106
+ fail: reject
10107
+ };
10108
+ });
10109
+ }
10110
+ get isOpen() {
10111
+ return this.#status === "open";
9308
10112
  }
10113
+ get isWaiting() {
10114
+ return this.#status === "pending";
10115
+ }
10116
+ /** Marks the write reached, and waits for it to be kept (or refused). */
10117
+ wait() {
10118
+ this.#reach();
10119
+ return this.#outcome;
10120
+ }
10121
+ open() {
10122
+ this.#status = "open";
10123
+ this.#settle.open();
10124
+ }
10125
+ fail(error) {
10126
+ this.#status = "failed";
10127
+ this.#settle.fail(error);
10128
+ }
10129
+ };
10130
+ /** The around callbacks waiting at `next()` in each save or destroy, by its claimed records. */
10131
+ const waiting = /* @__PURE__ */ new WeakMap();
10132
+ /** Keeps `wrapped` with the save or destroy whose claimed records are `claimed`, to release. */
10133
+ function waitWith(claimed, wrapped) {
10134
+ waiting.set(claimed, [...waiting.get(claimed) ?? [], wrapped]);
9309
10135
  }
9310
10136
  /**
9311
- * What saving `owner` writes after it, through its hasMany and hasOne associations in the order
9312
- * they're declared, leaving out any record already claimed by the write being prepared: the
9313
- * records built through each that are still new, or with `autosave: true` what `withAutosave`
9314
- * says. While the owner is new, a hasMany's are every record added to it, saved ones pushed onto
9315
- * it included, as Rails saves a new owner's whole collection, and a hasOne's is its record, saved
9316
- * or not.
10137
+ * Runs `operation`, a save's or destroy's preparing and writing, handing it a new set for the
10138
+ * records it claims. When it ends, an around callback still waiting at `next()` (its write never
10139
+ * sent, or its after-callbacks skipped by an error) has `next()` reject with the error it threw,
10140
+ * or the one `refusal` gives for what it returned; then this waits for them, ignoring their
10141
+ * errors (#48).
9317
10142
  */
9318
- function autosavedAfter(owner, claimed) {
9319
- const model = modelOf(owner);
9320
- return [...associationsOf(model)].flatMap(([name, { kind, autosave, through }]) => {
9321
- if (kind === "belongsTo" || through !== void 0) return [];
9322
- const entries = autosave ? withAutosave(owner, name, kind, claimed) : builtToSave(owner, name, claimed).map((record) => ({ record }));
9323
- if (entries.length === 0) return [];
9324
- const association = resolveAssociation(model, name);
9325
- return entries.map((entry) => ({
9326
- association,
9327
- ...entry
9328
- }));
9329
- });
10143
+ async function withClaimedRecords(operation, refusal = () => void 0) {
10144
+ const claimed = /* @__PURE__ */ new Set();
10145
+ let result;
10146
+ try {
10147
+ result = await operation(claimed);
10148
+ } catch (error) {
10149
+ await release(claimed, error);
10150
+ throw error;
10151
+ }
10152
+ const error = refusal(result);
10153
+ if (error !== void 0) await release(claimed, error);
10154
+ return result;
10155
+ }
10156
+ async function release(claimed, error) {
10157
+ for (const wrapped of waiting.get(claimed) ?? []) await wrapped.release(error);
9330
10158
  }
9331
10159
  /**
9332
- * What an `autosave: true` association writes after its owner (#37), as Rails does: its saved
9333
- * records marked for destruction are destroyed, then its loaded records that changed are saved,
9334
- * then those built through it. Marked records never saved are left out (`dropUnsavedMarked`).
10160
+ * Starts a save's around callbacks: `aroundSave`, wrapping `beforeCreate` (or `beforeUpdate`), then
10161
+ * `aroundCreate` (or `aroundUpdate`), wrapping the write, then `afterCreate` (or `afterUpdate`).
10162
+ * Resolves once the write is reached, or to the `CallbackAbort` that stopped it.
9335
10163
  */
9336
- function withAutosave(owner, name, kind, claimed) {
9337
- const built = builtToSave(owner, name, claimed);
9338
- const stored = loaded(owner, name).filter((record) => !record[state].isNew && !claimed.has(record) && !built.includes(record));
9339
- const marked = (record) => record[state].isMarkedForDestruction;
9340
- const keepsKey = kind === "hasMany" ? { keepsKey: true } : {};
9341
- return [
9342
- ...[...stored, ...built].filter((record) => marked(record) && !record[state].isNew).map((record) => ({
9343
- record,
9344
- destroys: true
9345
- })),
9346
- ...stored.filter((record) => !marked(record) && isChangedForAutosave(record)).map((record) => ({
9347
- record,
9348
- ...keepsKey
9349
- })),
9350
- ...built.filter((record) => !marked(record)).map((record) => ({ record }))
9351
- ];
10164
+ function startSave(record, isInsert) {
10165
+ const gate = new WriteGate();
10166
+ return untilWriteReached(gate, around(record, "aroundSave", gate, async () => {
10167
+ await runCallbacks(record, isInsert ? "beforeCreate" : "beforeUpdate");
10168
+ await around(record, isInsert ? "aroundCreate" : "aroundUpdate", gate, () => gate.wait());
10169
+ await runAfterCallbacks(record, isInsert ? "afterCreate" : "afterUpdate", "save");
10170
+ }));
9352
10171
  }
9353
10172
  /**
9354
- * Takes the records marked for destruction that were never saved out of `owner`'s `autosave:
9355
- * true` associations, writing nothing, as Rails does when it saves the owner.
10173
+ * Starts a destroy's `aroundDestroy` callbacks, wrapping the write. Resolves once the write is
10174
+ * reached, or to the `CallbackAbort` that stopped it.
9356
10175
  */
9357
- function dropUnsavedMarked(owner) {
9358
- const model = modelOf(owner);
9359
- for (const [name, { kind, autosave }] of associationsOf(model)) {
9360
- if (kind === "belongsTo" || autosave !== true) continue;
9361
- const association = resolveAssociation(model, name);
9362
- for (const record of owner[state].autosaves.built(name)) if (record[state].isNew && record[state].isMarkedForDestruction) forget(owner, association, record);
9363
- }
9364
- }
9365
- /** Takes `record` out of what `owner`'s association holds: built through it, or loaded. */
9366
- function forget(owner, association, record) {
9367
- const { name } = association;
9368
- owner[state].autosaves.removeBuilt(name, [record]);
9369
- const value = owner[state].associations.get(name)?.value;
9370
- if (Array.isArray(value)) {
9371
- const kept = value.filter((each) => each !== record);
9372
- owner[state].associations.set(name, association.keyAttributes, kept);
9373
- } else if (value === record) owner[state].associations.set(name, association.keyAttributes, null);
9374
- }
9375
- /** The records built through the association that saving `owner` saves after it. */
9376
- function builtToSave(owner, name, claimed) {
9377
- const ownerIsNew = owner[state].isNew;
9378
- return owner[state].autosaves.built(name).filter((record) => (ownerIsNew || record[state].isNew) && !claimed.has(record));
9379
- }
9380
- /** The association's loaded records, for the key the owner holds now: none when it isn't loaded. */
9381
- function loaded(owner, name) {
9382
- const value = owner[state].associations.get(name)?.value;
9383
- if (value === void 0 || value === null) return [];
9384
- return Array.isArray(value) ? value : [value];
10176
+ function startDestroy(record) {
10177
+ const gate = new WriteGate();
10178
+ return untilWriteReached(gate, around(record, "aroundDestroy", gate, () => gate.wait()));
9385
10179
  }
9386
10180
  /**
9387
- * Whether saving `record` through an `autosave: true` association would write anything, as Rails'
9388
- * `changed_for_autosave?`: it's new, changed or marked for destruction, or so is a record of one of its own `autosave:
9389
- * true` associations, at any level. `seen` stops a loop of records loaded through each other.
10181
+ * Runs `record`'s around callbacks of `kind` around `inside`, the first declared outermost, each
10182
+ * handed a `next` that runs the rest. One that doesn't call it stops the write, as `abort()` does.
10183
+ * Once the write is kept, an `abort()` in one is `AbortAfterPersistence`.
9390
10184
  */
9391
- function isChangedForAutosave(record, seen = /* @__PURE__ */ new Set()) {
9392
- if (seen.has(record)) return false;
9393
- seen.add(record);
9394
- const recordState = record[state];
9395
- if (recordState.isNew || recordState.isMarkedForDestruction) return true;
9396
- if (recordState.changedNames().length > 0) return true;
9397
- return [...associationsOf(modelOf(record))].some(([name, { autosave }]) => autosave === true && loaded(record, name).some((each) => isChangedForAutosave(each, seen)));
9398
- }
9399
- /** Whether every record's key is known before it's written (generated in code). */
9400
- function isEveryKeyKnown(pointedAt) {
9401
- return pointedAt.every(({ association, record }) => record[state].read(association.targetAttribute) !== null);
9402
- }
9403
- /** Whether the owner's key, which every record takes, is known before anything is written. */
9404
- function isOwnerKeyKnown(owner, after) {
9405
- return after.every(({ association }) => owner[state].read(association.ownerAttribute) !== null);
9406
- }
9407
- /** Points the owner at the records it points at, now that their keys exist, keeping them loaded. */
9408
- function linkBefore(owner, pointedAt) {
9409
- for (const { association, record } of pointedAt) {
9410
- owner[state].pointAt(association, record[state].read(association.targetAttribute), record);
9411
- owner[state].autosaves.setBelongsTo(association.name, void 0);
9412
- }
10185
+ async function around(record, kind, gate, inside) {
10186
+ const callbacks = declared(modelOf(record), kind);
10187
+ const runFrom = (index) => {
10188
+ if (index === callbacks.length) return inside();
10189
+ return runOne({
10190
+ record,
10191
+ kind,
10192
+ gate
10193
+ }, callbacks[index], () => runFrom(index + 1));
10194
+ };
10195
+ await runFrom(0);
9413
10196
  }
9414
10197
  /**
9415
- * Points every record saved after its owner at it. A hasOne's record stays the owner's loaded
9416
- * association under the owner's new key.
10198
+ * Runs one around callback, its `next` running `rest`. One that doesn't call `next` stops the
10199
+ * write as `abort()` does, so the `next()` of a callback outside it rejects. What `next()` ran is
10200
+ * awaited once the callback returns, so the rest is finished, and a stop or refusal in it stands,
10201
+ * even when the callback didn't await it or caught its rejection (#48, decision 11). Once the
10202
+ * write is kept, an `abort()` in it is `AbortAfterPersistence`.
9417
10203
  */
9418
- function linkAfter(owner, after) {
9419
- for (const { association, record, keepsKey, destroys } of after) {
9420
- if (keepsKey || destroys) continue;
9421
- const { name, definition, ownerAttribute } = association;
9422
- record[state].writeKey(definition.foreignKey, owner[state].read(ownerAttribute), name);
9423
- association.writeOwnersType(record);
9424
- if (definition.kind === "hasOne") owner[state].associations.set(name, association.keyAttributes, record);
10204
+ async function runOne({ record, kind, gate }, callback, rest) {
10205
+ const next = nextOnce(kind, rest);
10206
+ try {
10207
+ await callback(record, next.call);
10208
+ } catch (error) {
10209
+ if (error instanceof CallbackAbort && gate.isOpen) throw new AbortAfterPersistence(kind, lifecycleOf(kind), error);
10210
+ throw error;
9425
10211
  }
10212
+ const rested = next.rested();
10213
+ if (rested === void 0) throw abort(`An ${kind} callback didn't call next()`);
10214
+ await rested;
9426
10215
  }
9427
10216
  /**
9428
- * The records saving `record` would write, by database (#228): it, the records it saves or
9429
- * destroys through its associations, at every level. A record reached through an association to
9430
- * another database starts a group of its own. Found without running any validation or callback,
9431
- * so a save can be checked before anything runs (#93).
10217
+ * `next` for one around callback: runs `rest` the first time; `TypeError` after that. `rested` is
10218
+ * what the first call returned, or `undefined` before one.
9432
10219
  */
9433
- function savingGroups(record) {
9434
- const found = /* @__PURE__ */ new Set();
9435
- const groups = [{
9436
- records: [],
9437
- through: void 0
9438
- }];
9439
- const visit = (each, group) => {
9440
- if (found.has(each)) return;
9441
- found.add(each);
9442
- group.records.push(each);
9443
- const { saved, destroyed } = autosavedBefore(each, /* @__PURE__ */ new Set());
9444
- const linked = [
9445
- ...saved,
9446
- ...destroyed,
9447
- ...autosavedAfter(each, found)
9448
- ];
9449
- for (const { association, record: next } of linked) visit(next, association.isCrossDatabase ? startGroup(groups, association) : group);
10220
+ function nextOnce(kind, rest) {
10221
+ let rested;
10222
+ return {
10223
+ call: () => {
10224
+ if (rested !== void 0) return Promise.reject(/* @__PURE__ */ new TypeError(`${kind}: next() was already called`));
10225
+ rested = rest();
10226
+ rested.catch(() => {});
10227
+ return rested;
10228
+ },
10229
+ rested: () => rested
9450
10230
  };
9451
- visit(record, groups[0]);
9452
- return groups.filter(({ records }) => records.length > 0);
9453
10231
  }
9454
- /** A new group of records, reached through `association`, added to `groups`. */
9455
- function startGroup(groups, association) {
9456
- const group = {
9457
- records: [],
9458
- through: association
10232
+ function lifecycleOf(kind) {
10233
+ return kind === "aroundDestroy" ? "destroy" : "save";
10234
+ }
10235
+ /** Waits until `run` reaches its write, or stops first: a `CallbackAbort` is returned, else thrown. */
10236
+ async function untilWriteReached(gate, run) {
10237
+ const stopped = await Promise.race([gate.reached.then(() => void 0), run.then(() => void 0, (error) => ({ error }))]);
10238
+ if (stopped !== void 0) {
10239
+ if (stopped.error instanceof CallbackAbort) return stopped.error;
10240
+ throw stopped.error;
10241
+ }
10242
+ run.catch(() => {});
10243
+ return {
10244
+ finish: async () => {
10245
+ gate.open();
10246
+ await run;
10247
+ },
10248
+ release: async (error) => {
10249
+ if (!gate.isWaiting) return;
10250
+ gate.fail(error);
10251
+ await run.catch(() => {});
10252
+ },
10253
+ fail: async (error) => {
10254
+ gate.fail(error);
10255
+ try {
10256
+ await run;
10257
+ } catch (thrown) {
10258
+ if (thrown !== error) throw thrown;
10259
+ }
10260
+ }
9459
10261
  };
9460
- groups.push(group);
9461
- return group;
9462
10262
  }
9463
10263
  // src/batch.ts
9464
10264
  /** The Executor an entry was built on: its Relation's, or its record's. */
@@ -9507,7 +10307,14 @@ async function runBatch(entries, needs, handles = []) {
9507
10307
  const records = entries.flatMap(recordsOf);
9508
10308
  if (all.length === 0 && records.length === 0) return [];
9509
10309
  const database = await pinBefore(linksOf(records), needs, all);
9510
- const claimed = /* @__PURE__ */ new Set();
10310
+ return withClaimedRecords((claimed) => prepareAndWrite(entries, {
10311
+ claimed,
10312
+ database,
10313
+ needs
10314
+ }));
10315
+ }
10316
+ /** A batch's records and statements prepared, then written as one, then its after-callbacks. */
10317
+ async function prepareAndWrite(entries, { claimed, database, needs }) {
9511
10318
  const prepared = [];
9512
10319
  for (const entry of entries) prepared.push(entry instanceof RecordStatement ? await recordEntry(entry, claimed, needs) : statementEntry(entry));
9513
10320
  await pinClaimed(linksOf(claimed), database, needs);