@forestfuture/active-record 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { $ as FilteredMark, A as authenticateBy, B as RecordState, C as Filtered, Ct as isIgnoringColumns, D as isFiltered, Dt as requireModelName, E as filteredValues, Et as rejectAbstract, F as rejectMissingDigests, G as columnOf, H as state, I as resetPurposeOf, J as requireDefined, K as define, L as resetTokenDefinitions, M as hashPasswords, Mt as staticBelow, N as passwordConfirmations, O as shownKey, Ot as requireTableName, P as passwordFailures, Q as fullMessageOf, R as secretAttributeNames, S as FILTERED, St as inferTableNames, T as defaultFilterAttributes, U as attributeOf, V as linksOf, W as attributesForColumn, X as addFailure, Z as clearErrors, _ as isLocking, _t as declared, a as isGenerated, at as specProblem, b as isThenable, bt as defineModelName, c as methodsOffFixes, ct as generateTokens, d as enumNameProblem, et as inspectCustom, ft as aliasesIn, g as withArticle, gt as declare, h as noMatch, ht as withAttributeNames, i as isBase, it as humanAttributeName, j as defineSecurePasswordMethods, jt as ancestors, k as shownValue$1, kt as tableOwnerModelName, l as defineEnumMethods, lt as expiryAfter, m as castInherited, mt as isAlias, n as defineGeneratedStatics, nt as styled, o as schemaAdapter, ot as defineSecureTokenMethods, p as attributeFor, pt as attributeName, q as initialValues, r as hasSettledAttributes, rt as attributesNamedInMessages, s as settleGenerated, t as defineAttributeAccessors, tt as printed, u as defineEnumStatics, ut as secondsOf, v as lockVersion, vt as declaredByClass, w as boundValue, x as refuseThenable, xt as explainMissingTable, y as checkNormalizedName, yt as seal, z as withSecurePasswords } from "./generated-model-CKIciUat.mjs";
2
- import { $ as StaleRecord, A as AssociationNotLoaded, C as pluralize, D as underscore, F as IncompatibleRelation, G as ReadonlyRecord, H as NotNullViolation, I as InvalidForeignKey, J as RecordNotDestroyed, L as InvalidModel, M as CheckViolation, O as AbortAfterPersistence, P as DeleteRestriction, Q as SoleRecordExceeded, R as InvalidToken, T as camelize, U as ReadonlyAssociation, V as NoDatabase, W as ReadonlyAttribute, X as RecordNotSaved, Y as RecordNotFound, Z as RecordNotUnique, b as enumValuesOf, c as castValue, d as uncastable, et as StrictValidationFailed, f as writeUntypedValue, g as orderDecimal, i as hexOf, it as abort, j as CallbackAbort, k as ActiveRecordError, m as zonelessDateTime, q as RecordInvalid, rt as UnknownModelName, tt as UnknownAssociation, w as singularize, y as enumValidations, z as IrreversibleOrder } from "./identifiers-BP6aRwew.mjs";
1
+ import { $ as FilteredMark, A as authenticateBy, B as RecordState, C as Filtered, Ct as isIgnoringColumns, D as isFiltered, Dt as requireModelName, E as filteredValues, Et as rejectAbstract, F as rejectMissingDigests, G as columnOf, H as state, I as resetPurposeOf, J as requireDefined, K as define, L as resetTokenDefinitions, M as hashPasswords, Mt as staticBelow, N as passwordConfirmations, O as shownKey, Ot as requireTableName, P as passwordFailures, Q as fullMessageOf, R as secretAttributeNames, S as FILTERED, St as inferTableNames, T as defaultFilterAttributes, U as attributeOf, V as linksOf, W as attributesForColumn, X as addFailure, Z as clearErrors, _ as isLocking, _t as declared, a as isGenerated, at as specProblem, b as isThenable, bt as defineModelName, c as methodsOffFixes, ct as generateTokens, d as enumNameProblem, et as inspectCustom, ft as aliasesIn, g as withArticle, gt as declare, h as noMatch, ht as withAttributeNames, i as isBase, it as humanAttributeName, j as defineSecurePasswordMethods, jt as ancestors, k as shownValue$1, kt as tableOwnerModelName, l as defineEnumMethods, lt as expiryAfter, m as castInherited, mt as isAlias, n as defineGeneratedStatics, nt as styled, o as schemaAdapter, ot as defineSecureTokenMethods, p as attributeFor, pt as attributeName, q as initialValues, r as hasSettledAttributes, rt as attributesNamedInMessages, s as settleGenerated, t as defineAttributeAccessors, tt as printed, u as defineEnumStatics, ut as secondsOf, v as lockVersion, vt as declaredByClass, w as boundValue, x as refuseThenable, xt as explainMissingTable, y as checkNormalizedName, yt as seal, z as withSecurePasswords } from "./generated-model-DiQb9_3C.mjs";
2
+ import { $ as IrreversibleOrder, A as orderDecimal, C as incoming, D as refuseReferenceValue, G as CallbackAbort, H as AbortAfterPersistence, J as DeleteRestriction, K as CheckViolation, L as pluralize, N as enumValidations, O as sql, P as enumValuesOf, Q as InvalidToken, R as singularize, S as column, T as isAttributeReference, U as ActiveRecordError, V as underscore, W as AssociationNotLoaded, X as InvalidForeignKey, Y as IncompatibleRelation, Z as InvalidModel, _ as refuseNestedReference, _t as UnknownModelName, at as ReadonlyRecord, b as IncomingReference, c as castValue, ct as RecordNotDestroyed, d as uncastable, dt as RecordNotUnique, f as writeUntypedValue, ft as SoleRecordExceeded, ht as UnknownAssociation, i as hexOf, it as ReadonlyAttribute, lt as RecordNotFound, m as zonelessDateTime, mt as StrictValidationFailed, nt as NotNullViolation, pt as StaleRecord, rt as ReadonlyAssociation, st as RecordInvalid, tt as NoDatabase, ut as RecordNotSaved, v as ColumnReference, vt as abort, w as incomingRefusal, x as SafeSql, y as ColumnValue, z as camelize } from "./identifiers-DRLEguFD.mjs";
3
3
  // src/foreign-keys.ts
4
4
  /**
5
5
  * Gives each declaration its foreign key: the one passed, or else inferred from
@@ -493,92 +493,6 @@ function requireKnownContexts(record, given) {
493
493
  if (name === void 0) return;
494
494
  throw new TypeError(`${nameOf$1(model)} has no validation context "${name}"; list it in static validationContexts`);
495
495
  }
496
- // src/bulk-rows.ts
497
- /** The "[" and "]" around a JSON value's rows. */
498
- const brackets = 2;
499
- /** The "," between two rows of a JSON value. */
500
- const comma = 1;
501
- /**
502
- * `rows` of `names`' values, assigned, in groups whose JSON value is at most `maxBytes` long in
503
- * UTF-8 (all in one when it's undefined); listeners see a filtered attribute as "[FILTERED]".
504
- */
505
- function rowGroups(model, names, rows, maxBytes) {
506
- const jsonRows = rows.map(jsonRowOf(model, names));
507
- if (maxBytes === void 0) return [{
508
- kind: "json",
509
- value: jsonValue(jsonRows)
510
- }];
511
- const groups = [];
512
- let pending = [];
513
- let bytes = brackets;
514
- const flush = () => {
515
- if (pending.length > 0) groups.push({
516
- kind: "json",
517
- value: jsonValue(pending)
518
- });
519
- pending = [];
520
- };
521
- for (const row of jsonRows) {
522
- const size = utf8Length(row.text);
523
- if (brackets + size > maxBytes) {
524
- flush();
525
- groups.push({
526
- kind: "values",
527
- row: row.values
528
- });
529
- continue;
530
- }
531
- if (pending.length > 0 && bytes + comma + size > maxBytes) flush();
532
- bytes = pending.length === 0 ? brackets + size : bytes + comma + size;
533
- pending.push(row);
534
- }
535
- flush();
536
- return groups;
537
- }
538
- /** A function that writes a row of `names`' values as JSON, and as listeners see it. */
539
- function jsonRowOf(model, names) {
540
- const attributes = names.map((name) => attributeFor(model, name));
541
- const filtered = names.map((name) => isFiltered(model, name));
542
- const hiding = filtered.includes(true);
543
- return (values) => {
544
- const stored = values.map((value, index) => inJson(attributes[index].store(value)));
545
- const text = JSON.stringify(stored);
546
- if (!hiding) return {
547
- values,
548
- text,
549
- shown: text
550
- };
551
- return {
552
- values,
553
- text,
554
- shown: JSON.stringify(stored.map((cell, index) => filtered[index] ? FILTERED : cell))
555
- };
556
- };
557
- }
558
- /** Rows as one JSON value, which listeners see with filtered attributes hidden. */
559
- function jsonValue(rows) {
560
- const json = `[${rows.map(({ text }) => text).join(",")}]`;
561
- if (rows.every(({ text, shown }) => text === shown)) return json;
562
- return new Filtered(json, `[${rows.map(({ shown }) => shown).join(",")}]`);
563
- }
564
- /**
565
- * `text`'s length in UTF-8 bytes, counted without encoding a copy of it. A code unit below
566
- * U+0080 is one byte, below U+0800 two, and any other three, except that a surrogate pair is four
567
- * between its two units. JSON text has no lone surrogates: `JSON.stringify` escapes them.
568
- */
569
- function utf8Length(text) {
570
- let bytes = text.length;
571
- for (let index = 0; index < text.length; index++) {
572
- const unit = text.charCodeAt(index);
573
- if (unit < 128) continue;
574
- bytes += unit < 2048 || unit >= 55296 && unit <= 57343 ? 1 : 2;
575
- }
576
- return bytes;
577
- }
578
- /** A stored cell as a bulk write's JSON holds it: bytes as hex text, which JSON has no form for (#20). */
579
- function inJson(cell) {
580
- return cell instanceof Uint8Array ? hexOf(cell) : cell;
581
- }
582
496
  // src/comparisons.ts
583
497
  /** @internal The library's key for reading a Comparison's parts. */
584
498
  const comparisonParts = Symbol("comparisonParts");
@@ -685,59 +599,6 @@ function compileEquality(dialect, { column, attribute }, value, params) {
685
599
  if (value.includes(null)) parts.push(`${column} IS NULL`);
686
600
  return parts.length > 0 ? `(${parts.join(" OR ")})` : NOTHING;
687
601
  }
688
- // src/sql.ts
689
- /**
690
- * A SQL fragment built with the `sql` tagged template (ADR-0006). The template
691
- * text is written by the developer; every interpolated value is bound as a
692
- * parameter and never becomes SQL text.
693
- */
694
- var SafeSql = class {
695
- strings;
696
- values;
697
- /** @internal Use the `sql` tag instead. */
698
- constructor(strings, values) {
699
- this.strings = strings;
700
- this.values = values;
701
- }
702
- };
703
- function sql(strings, ...values) {
704
- return new SafeSql([...strings], values);
705
- }
706
- /** A reference to an attribute's column, resolved against the query's Model when compiled. */
707
- var ColumnReference = class {
708
- attribute;
709
- /** @internal Use `column()` instead. */
710
- constructor(attribute) {
711
- this.attribute = attribute;
712
- }
713
- /**
714
- * A value of this attribute for a fragment, converted as the attribute stores it: a `Date`
715
- * as the integer of an attribute kept as a Unix time, a boolean as 0 or 1, and so on. It's
716
- * still a bound parameter. Without it, a value has no attribute to say how it's stored (#142).
717
- */
718
- value(value) {
719
- return new ColumnValue(this.attribute, value);
720
- }
721
- };
722
- /** A value of an attribute, from `column(attribute).value(value)`, converted when compiled. */
723
- var ColumnValue = class {
724
- attribute;
725
- /** What was given, before it's cast as an assigned value of the attribute. */
726
- assigned;
727
- /** @internal Use `column(attribute).value(value)` instead. */
728
- constructor(attribute, assigned) {
729
- this.attribute = attribute;
730
- this.assigned = assigned;
731
- }
732
- };
733
- /** Whether a fragment's interpolated value names an attribute: a column, or a typed value. */
734
- function isAttributeReference(value) {
735
- return value instanceof ColumnReference || value instanceof ColumnValue;
736
- }
737
- /** Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004). */
738
- function column(attribute) {
739
- return new ColumnReference(attribute);
740
- }
741
602
  // src/query.ts
742
603
  /** @internal The library's key for the query a Relation describes. */
743
604
  const queryOf = Symbol("queryOf");
@@ -1205,54 +1066,6 @@ function compileReturning(model, attributes) {
1205
1066
  return ` RETURNING ${columnsIn(unqualifiedSource(model), attributes)}`;
1206
1067
  }
1207
1068
  /**
1208
- * `INSERT` of several rows, all with the attributes `names`, bound as one JSON parameter, which
1209
- * the dialect reads them from: one statement and one bound value, whatever the number of rows,
1210
- * within D1's limit of 100 bound parameters per statement. Rows whose JSON would pass the
1211
- * dialect's `maxValueBytes` take several statements, and a row whose JSON alone would pass it
1212
- * binds each of its values apart, as `compileInsert` does (#392).
1213
- */
1214
- function compileInsertRows(dialect, model, { names, rows, conflict, returning }) {
1215
- const attributes = names.map((name) => attributeFor(model, name));
1216
- const columns = attributes.map(({ column }) => quoteIdentifier(column)).join(", ");
1217
- const table = quoteIdentifier(model.table);
1218
- const { select, from } = dialect.bulkRows(table, attributes);
1219
- const end = compileConflict(model, names, conflict) + compileReturning(model, returning);
1220
- return rowGroups(model, names, rows, dialect.maxValueBytes).map((group) => {
1221
- if (group.kind === "json") return {
1222
- sql: `INSERT INTO ${table} (${columns}) SELECT ${select} FROM ${from} WHERE true${end}`,
1223
- params: [group.value],
1224
- model
1225
- };
1226
- const params = [];
1227
- const values = compileValues(attributes, group.row, params);
1228
- return {
1229
- sql: `INSERT INTO ${table} ${values}${end}`,
1230
- params,
1231
- model
1232
- };
1233
- });
1234
- }
1235
- /**
1236
- * `ON CONFLICT DO NOTHING`, or `ON CONFLICT (…) DO UPDATE SET` the `update` attributes (every
1237
- * inserted one by default) except the `uniqueBy` ones and `createdAt`,
1238
- * `WHERE` the clashing row already has the new row's `ownedBy` values (#451).
1239
- */
1240
- function compileConflict(model, names, conflict) {
1241
- if (conflict === void 0) return "";
1242
- if (conflict.kind === "skip") return " ON CONFLICT DO NOTHING";
1243
- const column = (name) => quoteIdentifier(attributeFor(model, name).column);
1244
- const target = conflict.uniqueBy.map(column).join(", ");
1245
- const updated = (conflict.update ?? names).filter((name) => !conflict.uniqueBy.includes(name) && name !== "createdAt");
1246
- if (updated.length === 0) return ` ON CONFLICT (${target}) DO NOTHING`;
1247
- return ` ON CONFLICT (${target}) DO UPDATE SET ${updated.map((name) => `${column(name)} = excluded.${column(name)}`).join(", ")}${compileOwnedBy(model, conflict.ownedBy, column)}`;
1248
- }
1249
- /** ` WHERE "t"."a" = excluded."a" AND …`: the clashing row already has the new row's values. */
1250
- function compileOwnedBy(model, ownedBy, column) {
1251
- if (ownedBy.length === 0) return "";
1252
- const table = quoteIdentifier(model.table);
1253
- return ` WHERE ${ownedBy.map((name) => `${table}.${column(name)} = excluded.${column(name)}`).join(" AND ")}`;
1254
- }
1255
- /**
1256
1069
  * `UPDATE … SET … WHERE <primary key> = ?` for the given attribute values, or an `sql`
1257
1070
  * fragment's sets, `RETURNING` the `returning` attributes. `storedKey` is the key as stored in
1258
1071
  * D1 (the row's key before any change to it), so it's bound as-is.
@@ -1533,20 +1346,30 @@ function compilePagination(dialect, { limit, offset }, params) {
1533
1346
  function compileFragment(fragment, source, params) {
1534
1347
  let text = fragment.strings[0] ?? "";
1535
1348
  fragment.values.forEach((value, index) => {
1536
- if (value instanceof ColumnReference) text += columnIn(source, value.attribute);
1537
- else if (value instanceof ColumnValue) {
1538
- const attribute = attributeFor(source.model, value.attribute);
1539
- attribute.bindCells(params, attribute.storeNormalized(value.assigned));
1540
- text += "\0";
1541
- } else {
1542
- params.push(writeUntypedValue(value));
1543
- text += "\0";
1544
- }
1349
+ text += compileFragmentValue(value, source, params);
1545
1350
  text += fragment.strings[index + 1] ?? "";
1546
1351
  });
1547
1352
  return text;
1548
1353
  }
1354
+ /** One of a fragment's values: a column, or an incoming value, as SQL, or a value bound. */
1355
+ function compileFragmentValue(value, source, params) {
1356
+ if (value instanceof ColumnReference) return columnIn(source, value.attribute);
1357
+ if (value instanceof IncomingReference) return incomingColumn(source, value.attribute);
1358
+ if (value instanceof ColumnValue) {
1359
+ const attribute = attributeFor(source.model, value.attribute);
1360
+ attribute.bindCells(params, attribute.storeNormalized(value.assigned));
1361
+ } else params.push(writeUntypedValue(value));
1362
+ return "\0";
1363
+ }
1364
+ /** `excluded."column"`: the row an upsert writes, which only its `onDuplicate` reads (#531). */
1365
+ function incomingColumn(source, attribute) {
1366
+ if (source.allowsIncoming !== true) throw incomingRefusal(attribute);
1367
+ return `excluded.${quoteIdentifier(attributeFor(source.model, attribute).column)}`;
1368
+ }
1549
1369
  // src/fragment-guard.ts
1370
+ function isRowValueReference(value) {
1371
+ return value instanceof ColumnReference || value instanceof IncomingReference;
1372
+ }
1550
1373
  /** A comparison operator, alone between two interpolations. */
1551
1374
  const comparison$1 = /^\s*(?:=|==|<>|!=|<=|>=|<|>)\s*$/;
1552
1375
  /** `BETWEEN` or `NOT BETWEEN`, alone before the first bound. */
@@ -1559,23 +1382,23 @@ function bareDatetimeKind(value) {
1559
1382
  if (typeof value !== "string") return void 0;
1560
1383
  return castValue({ type: "datetime" }, value) !== uncastable || zonelessDateTime.test(value) ? "string" : void 0;
1561
1384
  }
1562
- /** The column a value at `index` follows, with only a comparison or `BETWEEN` between them. */
1563
- function columnBefore(fragment, index) {
1385
+ /** The column or incoming value a value at `index` follows, with only a comparison or `BETWEEN` between them. */
1386
+ function referenceBefore(fragment, index) {
1564
1387
  const { strings, values } = fragment;
1565
1388
  const between = strings[index] ?? "";
1566
1389
  const before = values[index - 1];
1567
- if (before instanceof ColumnReference && (comparison$1.test(between) || betweenLower.test(between))) return before;
1390
+ if (isRowValueReference(before) && (comparison$1.test(between) || betweenLower.test(between))) return before;
1568
1391
  const column = values[index - 2];
1569
- return betweenUpper.test(between) && betweenLower.test(strings[index - 1] ?? "") && column instanceof ColumnReference ? column : void 0;
1392
+ return betweenUpper.test(between) && betweenLower.test(strings[index - 1] ?? "") && isRowValueReference(column) ? column : void 0;
1570
1393
  }
1571
- /** The column a value at `index` precedes: after a comparison, or the bounds of `BETWEEN`. */
1572
- function columnAfter(fragment, index) {
1394
+ /** The column or incoming value a value at `index` precedes: after a comparison, or the bounds of `BETWEEN`. */
1395
+ function referenceAfter(fragment, index) {
1573
1396
  const { strings, values } = fragment;
1574
1397
  const between = strings[index + 1] ?? "";
1575
1398
  const after = values[index + 1];
1576
- if (after instanceof ColumnReference && (comparison$1.test(between) || betweenLower.test(between))) return after;
1399
+ if (isRowValueReference(after) && (comparison$1.test(between) || betweenLower.test(between))) return after;
1577
1400
  const upper = values[index + 2];
1578
- return betweenLower.test(between) && betweenUpper.test(strings[index + 2] ?? "") && upper instanceof ColumnReference ? upper : void 0;
1401
+ return betweenLower.test(between) && betweenUpper.test(strings[index + 2] ?? "") && isRowValueReference(upper) ? upper : void 0;
1579
1402
  }
1580
1403
  /**
1581
1404
  * Throws `TypeError` when a fragment puts a bare date directly beside the column of an attribute
@@ -1586,7 +1409,7 @@ function refuseBareDates(model, fragment) {
1586
1409
  fragment.values.forEach((value, index) => {
1587
1410
  const kind = bareDatetimeKind(value);
1588
1411
  if (kind === void 0) return;
1589
- const reference = columnBefore(fragment, index) ?? columnAfter(fragment, index);
1412
+ const reference = referenceBefore(fragment, index) ?? referenceAfter(fragment, index);
1590
1413
  if (reference === void 0) return;
1591
1414
  const { storage } = columnOf(model, reference.attribute);
1592
1415
  if (storage === void 0) return;
@@ -1628,11 +1451,13 @@ function attributeOrder(attribute, value, method) {
1628
1451
  * A fragment's `column()` references must name declared attributes, and so must its typed
1629
1452
  * values, which must also be values those attributes can hold, so a mistake surfaces where the
1630
1453
  * fragment is written, not when the query runs (#142). A bare date beside an integer-stored
1631
- * column is refused too (#149).
1454
+ * column is refused too (#149). So is `incoming()`, unless it's an upsert's `onDuplicate`
1455
+ * (#531).
1632
1456
  */
1633
- function checkFragment(model, fragment) {
1457
+ function checkFragment(model, fragment, { allowsIncoming = false } = {}) {
1634
1458
  for (const value of fragment.values) {
1635
1459
  if (!isAttributeReference(value)) continue;
1460
+ if (value instanceof IncomingReference && !allowsIncoming) throw incomingRefusal(value.attribute);
1636
1461
  columnOf(model, value.attribute);
1637
1462
  if (value instanceof ColumnValue) attributeFor(model, value.attribute).cast(value.assigned);
1638
1463
  }
@@ -1655,9 +1480,19 @@ function checkConditions(model, conditions, method) {
1655
1480
  for (const [name, value] of Object.entries(conditions)) {
1656
1481
  const { type } = columnOf(model, name);
1657
1482
  rejectUndefined(value, name, method);
1483
+ for (const each of conditionValues(value)) {
1484
+ refuseReferenceValue(each, `${method}() gives ${name}`);
1485
+ if (type === "json") refuseNestedReference(each, `${method}() gives ${name}`);
1486
+ }
1658
1487
  if (value instanceof Comparison) requireOrdered$1(type, name, method);
1659
1488
  }
1660
1489
  }
1490
+ /** A condition's values: a list's items, a comparison's values, or the value itself. */
1491
+ function conditionValues(value) {
1492
+ if (Array.isArray(value)) return value;
1493
+ if (value instanceof Comparison) return value[comparisonParts].values;
1494
+ return [value];
1495
+ }
1661
1496
  /** Attribute changes for `updateAll`, checked like conditions: declared, and not undefined. */
1662
1497
  function checkChanges(model, changes) {
1663
1498
  checkConditions(model, changes, "updateAll");
@@ -1691,16 +1526,89 @@ function returnedNames(model, returning) {
1691
1526
  }
1692
1527
  /**
1693
1528
  * An upsert's conflict: update, matching on `uniqueBy` (the primary key by default), a row
1694
- * that already has the new row's `ownedBy` values (#451).
1529
+ * that already has the new row's `ownedBy` values (#451), only `updateOnly`'s attributes when
1530
+ * it's given (#36).
1695
1531
  */
1696
- function updateOn(model, options, ownedBy) {
1532
+ function updateOn(model, options, { ownedBy, method }) {
1697
1533
  const uniqueBy = [options.uniqueBy ?? model.primaryKey].flat();
1698
1534
  for (const name of uniqueBy) columnOf(model, name);
1699
- return {
1535
+ if (options.onDuplicate !== void 0) {
1536
+ if (options.updateOnly !== void 0) throw new TypeError(`${method}() takes updateOnly or onDuplicate, not both`);
1537
+ return {
1538
+ kind: "update",
1539
+ uniqueBy,
1540
+ ownedBy,
1541
+ set: onDuplicateSets(model, options.onDuplicate, {
1542
+ uniqueBy,
1543
+ ownedBy,
1544
+ method
1545
+ })
1546
+ };
1547
+ }
1548
+ if (options.updateOnly === void 0) return {
1700
1549
  kind: "update",
1701
1550
  uniqueBy,
1702
1551
  ownedBy
1703
1552
  };
1553
+ return {
1554
+ kind: "update",
1555
+ uniqueBy,
1556
+ ownedBy,
1557
+ update: updatedNames(model, [options.updateOnly].flat(), {
1558
+ uniqueBy,
1559
+ method,
1560
+ option: "updateOnly",
1561
+ kept: []
1562
+ })
1563
+ };
1564
+ }
1565
+ /**
1566
+ * `onDuplicate`'s attributes, by their own names, checked as `updateOnly`'s are, and what each
1567
+ * is set to: its fragment, checked, or its value cast and normalized as an assigned value is
1568
+ * (#531). It can't name an owner's key, `ownedBy`, so it can't give a row to another owner.
1569
+ */
1570
+ function onDuplicateSets(model, given, { uniqueBy, ownedBy, method }) {
1571
+ if (typeof given !== "object" || given === null || Array.isArray(given) || given instanceof SafeSql) throw new TypeError(`${method}() onDuplicate takes an object of attributes, each an sql\`…\` fragment or a value`);
1572
+ const entries = Object.entries(given);
1573
+ const names = updatedNames(model, entries.map(([name]) => name), {
1574
+ uniqueBy,
1575
+ method,
1576
+ option: "onDuplicate",
1577
+ kept: ownedBy
1578
+ });
1579
+ return entries.map(([given, value], index) => {
1580
+ const name = names[index];
1581
+ refuseReferenceValue(value, `${method}() onDuplicate gives ${given}`);
1582
+ if (!(value instanceof SafeSql)) return {
1583
+ name,
1584
+ value: attributeFor(model, name).assigned(value)
1585
+ };
1586
+ checkFragment(model, value, { allowsIncoming: true });
1587
+ return {
1588
+ name,
1589
+ value
1590
+ };
1591
+ });
1592
+ }
1593
+ /**
1594
+ * The attributes `updateOnly` or `onDuplicate` names, by their own names, checked: each one an
1595
+ * attribute an update can write, not one of the owner's `kept` keys, and at least one (#36, #531).
1596
+ */
1597
+ function updatedNames(model, given, { uniqueBy, method, option, kept }) {
1598
+ if (given.length === 0) throw new TypeError(`${method}() ${option} names no attributes; to leave a clashing row as it is, use ${method === "upsert" ? "insert(row" : "insertAll(rows"}, { onDuplicate: "skip" })`);
1599
+ const matched = new Set(uniqueBy.map((name) => attributeName(model, name)));
1600
+ return given.map((name) => {
1601
+ const own = attributeName(model, name);
1602
+ const refusal = kept.includes(own) ? "which its owner's records keep" : updateRefusal(model, own, matched);
1603
+ if (refusal !== void 0) throw new TypeError(`${method}() ${option} can't name ${name}, ${refusal}`);
1604
+ return own;
1605
+ });
1606
+ }
1607
+ /** Why an upsert can't update `name` on a clash, if it can't. */
1608
+ function updateRefusal(model, name, matched) {
1609
+ if (columnOf(model, name).readonly === true) return "which is read-only";
1610
+ if (matched.has(name)) return "which uniqueBy matches on";
1611
+ if (name === "createdAt") return "which an update keeps";
1704
1612
  }
1705
1613
  /** The query a write statement targets; rows from `distinct()` have no identity to write to. */
1706
1614
  function writableQuery(query, method) {
@@ -1913,6 +1821,26 @@ function runWithStore(store, fn) {
1913
1821
  storage$1 ??= newStorage();
1914
1822
  return storage$1.run(store, fn);
1915
1823
  }
1824
+ /**
1825
+ * Empties every request cache in the running `withDatabase` call's request (#218), a nested call's
1826
+ * included: a write on any Database inside it may change rows another of its databases cached,
1827
+ * the same database through another handle included.
1828
+ */
1829
+ function clearRequestCaches() {
1830
+ for (const cache of requestStore()?.caches ?? []) cache.clear();
1831
+ }
1832
+ /**
1833
+ * Runs `fn` with its reads, and the reads it awaits, neither answered from the request caches nor
1834
+ * kept in them: batch iteration's, each a different query that would only fill them (#218). Its
1835
+ * writes still clear them.
1836
+ */
1837
+ function withoutRequestCache(fn) {
1838
+ const store = requestStore();
1839
+ return store === void 0 ? fn() : runWithStore({
1840
+ ...store,
1841
+ uncached: true
1842
+ }, fn);
1843
+ }
1916
1844
  // src/executor.ts
1917
1845
  /**
1918
1846
  * Calls a query listener, which never changes the query's outcome: a listener that throws is
@@ -1946,11 +1874,13 @@ var DatabaseExecutor = class {
1946
1874
  adapter;
1947
1875
  #driver;
1948
1876
  #onQuery;
1877
+ #cachesRequests;
1949
1878
  #origin = "connect";
1950
- constructor(adapter, driver, onQuery) {
1879
+ constructor(adapter, driver, onQuery, cache = {}) {
1951
1880
  this.adapter = adapter;
1952
1881
  this.#driver = driver;
1953
1882
  this.#onQuery = onQuery;
1883
+ this.#cachesRequests = cache.request !== false;
1954
1884
  }
1955
1885
  get dialect() {
1956
1886
  return this.adapter.dialect;
@@ -1984,18 +1914,55 @@ var DatabaseExecutor = class {
1984
1914
  #scope() {
1985
1915
  return requestStore()?.scopes.get(this)?.held;
1986
1916
  }
1917
+ /** The request cache of the running `withDatabase` scope a statement is sent in, if any. */
1918
+ #cache() {
1919
+ if (!this.#cachesRequests) return void 0;
1920
+ const store = requestStore();
1921
+ if (store?.uncached === true) return void 0;
1922
+ const scope = store?.scopes.get(this);
1923
+ return scope === void 0 || scope.hasEnded ? void 0 : scope.cache;
1924
+ }
1987
1925
  /** Runs one statement and resolves to its rows. */
1988
1926
  async all(query) {
1989
- return (await this.#one(this.#sendable(query))).rows;
1927
+ return (await this.#readOne(this.#sendable(query))).rows;
1928
+ }
1929
+ /** Sends one read, unless the request cache has its answer, or an identical read is in flight. */
1930
+ async #readOne(query) {
1931
+ const cache = this.#cache();
1932
+ const cached = cache?.get(query);
1933
+ if (cached === void 0) {
1934
+ const answer = this.#one(query);
1935
+ cache?.set(query, answer);
1936
+ return answer;
1937
+ }
1938
+ const result = await cached;
1939
+ this.#reportCached(query);
1940
+ return result;
1990
1941
  }
1991
1942
  /** Runs one statement for its effect and resolves to its result. */
1992
1943
  async run(query) {
1993
- return this.#one(this.#sendable(query));
1944
+ return this.#writing(() => this.#one(this.#sendable(query)));
1994
1945
  }
1995
1946
  /** Runs reads together and resolves to each one's result. */
1996
1947
  async read(statements) {
1997
1948
  const sent = statements.map((statement) => this.#sendable(statement));
1998
- return this.#together(sent, () => this.#driver.read(sent, this.#scope()));
1949
+ const cache = this.#cache();
1950
+ if (cache === void 0) return this.#readTogether(sent);
1951
+ const hits = sent.map((statement) => cache.get(statement));
1952
+ const missing = sent.filter((_, index) => hits[index] === void 0);
1953
+ const fetched = this.#readTogether(missing);
1954
+ missing.forEach((statement, index) => cache.set(statement, fetched.then((results) => results[index])));
1955
+ const answers = await Promise.all(hits.map((hit) => hit ?? Promise.resolve(null)));
1956
+ sent.forEach((statement, index) => {
1957
+ if (hits[index] !== void 0) this.#reportCached(statement);
1958
+ });
1959
+ const results = await fetched;
1960
+ let next = 0;
1961
+ return answers.map((answer) => answer ?? results[next++]);
1962
+ }
1963
+ /** Sends reads together, unless there are none. */
1964
+ #readTogether(statements) {
1965
+ return this.#together(statements, () => this.#driver.read(statements, this.#scope()));
1999
1966
  }
2000
1967
  /** `query` as it's sent and reported: with its database's placeholders. */
2001
1968
  #sendable(query) {
@@ -2031,8 +1998,20 @@ var DatabaseExecutor = class {
2031
1998
  async write(statements) {
2032
1999
  const sent = statements.map((statement) => this.#sendable(statement));
2033
2000
  const [only] = sent;
2034
- if (sent.length === 1 && only !== void 0) return [await this.#one(only)];
2035
- return this.#together(sent, () => this.#driver.write(sent, this.#scope()));
2001
+ if (sent.length === 1 && only !== void 0) return [await this.#writing(() => this.#one(only))];
2002
+ return this.#writing(() => this.#together(sent, () => this.#driver.write(sent, this.#scope())));
2003
+ }
2004
+ /**
2005
+ * Sends a write, clearing the request caches before it's sent and again once it settles, failed
2006
+ * or not: a read sent meanwhile may have read the rows before it, so its answer isn't kept.
2007
+ */
2008
+ async #writing(send) {
2009
+ clearRequestCaches();
2010
+ try {
2011
+ return await send();
2012
+ } finally {
2013
+ clearRequestCaches();
2014
+ }
2036
2015
  }
2037
2016
  async #one(query, mayRetry = true) {
2038
2017
  const started = performance.now();
@@ -2058,6 +2037,13 @@ var DatabaseExecutor = class {
2058
2037
  const { adapter } = this;
2059
2038
  return adapter.refusal(error) ?? explainMissingTable(adapter, translateConstraintError(adapter, error, models), models);
2060
2039
  }
2040
+ /** Reports a read answered from the request cache: no time, and no `meta`. */
2041
+ #reportCached(statement) {
2042
+ this.#report(statement, {
2043
+ durationMs: 0,
2044
+ cached: true
2045
+ });
2046
+ }
2061
2047
  /** Reports a statement to the database's listener, then to its Model's (`static onQuery`). */
2062
2048
  #report({ sql, params, model }, outcome) {
2063
2049
  const event = {
@@ -2483,6 +2469,198 @@ function typeCondition(owner, { attribute, value }, params) {
2483
2469
  type.bind(params, value);
2484
2470
  return `${quoteIdentifier(type.column)} = `;
2485
2471
  }
2472
+ // src/bulk-rows.ts
2473
+ /** The "[" and "]" around a JSON value's rows. */
2474
+ const brackets = 2;
2475
+ /** The "," between two rows of a JSON value. */
2476
+ const comma = 1;
2477
+ /**
2478
+ * `rows` of `names`' values, assigned, in groups whose JSON value is at most `maxBytes` long in
2479
+ * UTF-8 (all in one when it's undefined); listeners see a filtered attribute as "[FILTERED]".
2480
+ */
2481
+ function rowGroups(model, names, rows, maxBytes) {
2482
+ const jsonRows = rows.map(jsonRowOf(model, names));
2483
+ if (maxBytes === void 0) return [{
2484
+ kind: "json",
2485
+ value: jsonValue(jsonRows)
2486
+ }];
2487
+ const groups = [];
2488
+ let pending = [];
2489
+ let bytes = brackets;
2490
+ const flush = () => {
2491
+ if (pending.length > 0) groups.push({
2492
+ kind: "json",
2493
+ value: jsonValue(pending)
2494
+ });
2495
+ pending = [];
2496
+ };
2497
+ for (const row of jsonRows) {
2498
+ const size = utf8Length(row.text);
2499
+ if (brackets + size > maxBytes) {
2500
+ flush();
2501
+ groups.push({
2502
+ kind: "values",
2503
+ row: row.values
2504
+ });
2505
+ continue;
2506
+ }
2507
+ if (pending.length > 0 && bytes + comma + size > maxBytes) flush();
2508
+ bytes = pending.length === 0 ? brackets + size : bytes + comma + size;
2509
+ pending.push(row);
2510
+ }
2511
+ flush();
2512
+ return groups;
2513
+ }
2514
+ /** A function that writes a row of `names`' values as JSON, and as listeners see it. */
2515
+ function jsonRowOf(model, names) {
2516
+ const attributes = names.map((name) => attributeFor(model, name));
2517
+ const filtered = names.map((name) => isFiltered(model, name));
2518
+ const hiding = filtered.includes(true);
2519
+ return (values) => {
2520
+ const stored = values.map((value, index) => inJson(attributes[index].store(value)));
2521
+ const text = JSON.stringify(stored);
2522
+ if (!hiding) return {
2523
+ values,
2524
+ text,
2525
+ shown: text
2526
+ };
2527
+ return {
2528
+ values,
2529
+ text,
2530
+ shown: JSON.stringify(stored.map((cell, index) => filtered[index] ? FILTERED : cell))
2531
+ };
2532
+ };
2533
+ }
2534
+ /** Rows as one JSON value, which listeners see with filtered attributes hidden. */
2535
+ function jsonValue(rows) {
2536
+ const json = `[${rows.map(({ text }) => text).join(",")}]`;
2537
+ if (rows.every(({ text, shown }) => text === shown)) return json;
2538
+ return new Filtered(json, `[${rows.map(({ shown }) => shown).join(",")}]`);
2539
+ }
2540
+ /**
2541
+ * `text`'s length in UTF-8 bytes, counted without encoding a copy of it. A code unit below
2542
+ * U+0080 is one byte, below U+0800 two, and any other three, except that a surrogate pair is four
2543
+ * between its two units. JSON text has no lone surrogates: `JSON.stringify` escapes them.
2544
+ */
2545
+ function utf8Length(text) {
2546
+ let bytes = text.length;
2547
+ for (let index = 0; index < text.length; index++) {
2548
+ const unit = text.charCodeAt(index);
2549
+ if (unit < 128) continue;
2550
+ bytes += unit < 2048 || unit >= 55296 && unit <= 57343 ? 1 : 2;
2551
+ }
2552
+ return bytes;
2553
+ }
2554
+ /** A stored cell as a bulk write's JSON holds it: bytes as hex text, which JSON has no form for (#20). */
2555
+ function inJson(cell) {
2556
+ return cell instanceof Uint8Array ? hexOf(cell) : cell;
2557
+ }
2558
+ // src/bulk-insert-sql.ts
2559
+ /**
2560
+ * `INSERT` of several rows, all with the attributes `names`, bound as one JSON parameter, which
2561
+ * the dialect reads them from: one statement and one bound value, whatever the number of rows,
2562
+ * within D1's limit of 100 bound parameters per statement. Rows whose JSON would pass the
2563
+ * dialect's `maxValueBytes` take several statements, and a row whose JSON alone would pass it
2564
+ * binds each of its values apart, as `compileInsert` does (#392).
2565
+ */
2566
+ function compileInsertRows(dialect, model, { names, rows, conflict, returning }) {
2567
+ const attributes = names.map((name) => attributeFor(model, name));
2568
+ const columns = attributes.map(({ column }) => quoteIdentifier(column)).join(", ");
2569
+ const table = quoteIdentifier(model.table);
2570
+ const { select, from } = dialect.bulkRows(table, attributes);
2571
+ const endParams = [];
2572
+ const end = compileConflict(dialect, model, {
2573
+ names,
2574
+ conflict,
2575
+ params: endParams
2576
+ }) + compileReturning(model, returning);
2577
+ return rowGroups(model, names, rows, dialect.maxValueBytes).map((group) => {
2578
+ if (group.kind === "json") return {
2579
+ sql: `INSERT INTO ${table} (${columns}) SELECT ${select} FROM ${from} WHERE true${end}`,
2580
+ params: [group.value, ...endParams],
2581
+ model
2582
+ };
2583
+ const params = [];
2584
+ const values = compileValues(attributes, group.row, params);
2585
+ return {
2586
+ sql: `INSERT INTO ${table} ${values}${end}`,
2587
+ params: [...params, ...endParams],
2588
+ model
2589
+ };
2590
+ });
2591
+ }
2592
+ /**
2593
+ * `ON CONFLICT DO NOTHING`, or `ON CONFLICT (…) DO UPDATE SET` the `update` attributes (every
2594
+ * inserted one by default) except the `uniqueBy` ones and `createdAt`, or what `set` gives
2595
+ * (#531), and `touch` when one of them changes (#36), `WHERE` the clashing row already has the
2596
+ * new row's `ownedBy` values (#451). The values it binds are appended to `params`.
2597
+ */
2598
+ function compileConflict(dialect, model, { names, conflict, params }) {
2599
+ if (conflict === void 0) return "";
2600
+ if (conflict.kind === "skip") return " ON CONFLICT DO NOTHING";
2601
+ const column = (name) => quoteIdentifier(attributeFor(model, name).column);
2602
+ const target = conflict.uniqueBy.map(column).join(", ");
2603
+ const sets = conflict.set ?? copiedSets(model, names, conflict);
2604
+ if (sets.length === 0) return ` ON CONFLICT (${target}) DO NOTHING`;
2605
+ const written = sets.map((set) => `${column(set.name)} = ${setValue(model, set, params)}`);
2606
+ if (conflict.touch !== void 0) written.push(touchSet(dialect, model, sets, {
2607
+ touch: conflict.touch,
2608
+ params
2609
+ }));
2610
+ return ` ON CONFLICT (${target}) DO UPDATE SET ${written.join(", ")}${compileOwnedBy(model, conflict.ownedBy)}`;
2611
+ }
2612
+ /** What an update sets by default: each `update` attribute to its incoming value. */
2613
+ function copiedSets(model, names, conflict) {
2614
+ return (conflict.update ?? names).filter((name) => !conflict.uniqueBy.includes(name) && name !== "createdAt").map((name) => ({
2615
+ name,
2616
+ value: incoming(name)
2617
+ }));
2618
+ }
2619
+ /**
2620
+ * One value an update sets, as SQL: its incoming value, a fragment (`column()` qualified as the
2621
+ * clashing row's, which Postgres needs, and `incoming()` allowed, #531), or a value bound.
2622
+ */
2623
+ function setValue(model, { name, value }, params) {
2624
+ if (value instanceof IncomingReference) return clashingAndNew(model, value.attribute)[1];
2625
+ if (value instanceof SafeSql) return `(${compileFragment(value, clashSource(model), params)})`;
2626
+ attributeFor(model, name).bind(params, value);
2627
+ return "\0";
2628
+ }
2629
+ /** The clashing row, which an upsert's `onDuplicate` reads, with the row it writes (#531). */
2630
+ function clashSource(model) {
2631
+ return {
2632
+ model,
2633
+ name: quoteIdentifier(model.table),
2634
+ qualified: true,
2635
+ allowsIncoming: true
2636
+ };
2637
+ }
2638
+ /**
2639
+ * `touch` set to the new row's value only when a `sets` attribute's value changes: a clashing
2640
+ * row written again as it was keeps its own (#36). Each set value is compared as it's written, so
2641
+ * a fragment's values are bound again (#531).
2642
+ */
2643
+ function touchSet(dialect, model, sets, { touch, params }) {
2644
+ const same = (set) => {
2645
+ const [left] = clashingAndNew(model, set.name);
2646
+ const right = setValue(model, set, params);
2647
+ const attribute = attributeFor(model, set.name);
2648
+ return dialect.sameValue?.(left, right, attribute) ?? `${left} IS NOT DISTINCT FROM ${right}`;
2649
+ };
2650
+ const unchanged = sets.map(same).join(" AND ");
2651
+ const [kept, given] = clashingAndNew(model, touch);
2652
+ return `${quoteIdentifier(attributeFor(model, touch).column)} = CASE WHEN ${unchanged} THEN ${kept} ELSE ${given} END`;
2653
+ }
2654
+ /** ` WHERE "t"."a" = excluded."a" AND …`: the clashing row already has the new row's values. */
2655
+ function compileOwnedBy(model, ownedBy) {
2656
+ if (ownedBy.length === 0) return "";
2657
+ return ` WHERE ${ownedBy.map((name) => clashingAndNew(model, name).join(" = ")).join(" AND ")}`;
2658
+ }
2659
+ /** `name`'s column in the clashing row and in the new one: `"t"."a"` and `excluded."a"`. */
2660
+ function clashingAndNew(model, name) {
2661
+ const column = quoteIdentifier(attributeFor(model, name).column);
2662
+ return [`${quoteIdentifier(model.table)}.${column}`, `excluded.${column}`];
2663
+ }
2486
2664
  // src/timestamps.ts
2487
2665
  /** Whether the Model declares `name` as a datetime attribute, which turns its timestamp on. */
2488
2666
  function hasTimestamp(model, name) {
@@ -2604,7 +2782,8 @@ function insertAssignments(model, attributes) {
2604
2782
  * `INSERT` of `rows` into `model`'s table, as one Statement. Every row must have the same
2605
2783
  * attributes as given; `conflict` skips or updates rows that clash with a unique
2606
2784
  * index. An update sets every attribute in `rows` (the given ones and any a Relation added,
2607
- * #475) and `updatedAt`, never filled-in defaults.
2785
+ * #475), or only those `updateOnly` names, and `updatedAt` when one of them changes (#36), never
2786
+ * filled-in defaults.
2608
2787
  * It returns the attributes `returning` names of each row written.
2609
2788
  */
2610
2789
  function insertStatement(executor, model, rows, { conflict, method, landed, returning }) {
@@ -2618,10 +2797,11 @@ function insertStatement(executor, model, rows, { conflict, method, landed, retu
2618
2797
  }
2619
2798
  const values = assigned.map((row) => names.map((name) => row.get(name)));
2620
2799
  const updated = given.filter((name) => model.attributeDefinitions.get(name)?.readonly !== true);
2621
- const resolved = conflict?.kind === "update" ? {
2622
- ...conflict,
2623
- update: [...updated, ...names.includes("updatedAt") ? ["updatedAt"] : []]
2624
- } : conflict;
2800
+ const resolved = conflict?.kind === "update" ? resolvedUpdate(conflict, {
2801
+ updated,
2802
+ names,
2803
+ method
2804
+ }) : conflict;
2625
2805
  return new Statement(executor, compileInsertRows(executor.dialect, model, {
2626
2806
  names,
2627
2807
  rows: values,
@@ -2629,6 +2809,31 @@ function insertStatement(executor, model, rows, { conflict, method, landed, retu
2629
2809
  returning
2630
2810
  }), landed, read);
2631
2811
  }
2812
+ /**
2813
+ * An update conflict resolved against the rows: the attributes it updates, which are
2814
+ * `updateOnly`'s (each of them one the rows give) or else every one `updated`, and `updatedAt`
2815
+ * to touch when one of them changes, when the rows write it and it isn't updated itself (#36);
2816
+ * or what `onDuplicate` sets, and `updatedAt` likewise (#531).
2817
+ */
2818
+ function resolvedUpdate(conflict, { updated, names, method }) {
2819
+ if (conflict.set !== void 0) {
2820
+ const setsUpdatedAt = conflict.set.some(({ name }) => name === "updatedAt");
2821
+ const touches = names.includes("updatedAt") && !setsUpdatedAt;
2822
+ return {
2823
+ ...conflict,
2824
+ touch: touches ? "updatedAt" : void 0
2825
+ };
2826
+ }
2827
+ const update = conflict.update ?? updated;
2828
+ const missing = update.find((name) => !updated.includes(name));
2829
+ if (missing !== void 0) throw new TypeError(`${method}() updateOnly names ${missing}, which the rows don't give`);
2830
+ const touchesUpdatedAt = names.includes("updatedAt") && !update.includes("updatedAt");
2831
+ return {
2832
+ ...conflict,
2833
+ update,
2834
+ touch: touchesUpdatedAt ? "updatedAt" : void 0
2835
+ };
2836
+ }
2632
2837
  /** The attributes every row was given; they must be the same for all rows, in any order. */
2633
2838
  function sameAttributes(rows, method) {
2634
2839
  const [first, ...rest] = rows.map((row) => Object.keys(row));
@@ -2863,11 +3068,11 @@ function preparedWritesOf(relation) {
2863
3068
  method: "insertAll",
2864
3069
  returning: options.returning
2865
3070
  }),
2866
- upsert: (attributes, options = {}) => insertRows(relation, [attributes], ownedUpdate(relation, options), {
3071
+ upsert: (attributes, options = {}) => insertRows(relation, [attributes], ownedUpdate(relation, options, "upsert"), {
2867
3072
  method: "upsert",
2868
3073
  returning: options.returning
2869
3074
  }),
2870
- upsertAll: (rows, options = {}) => insertRows(relation, rows, ownedUpdate(relation, options), {
3075
+ upsertAll: (rows, options = {}) => insertRows(relation, rows, ownedUpdate(relation, options, "upsertAll"), {
2871
3076
  method: "upsertAll",
2872
3077
  returning: options.returning
2873
3078
  }),
@@ -2879,8 +3084,11 @@ function preparedWritesOf(relation) {
2879
3084
  * An upsert's conflict through `relation`: through an owner's hasMany, it updates a clashing
2880
3085
  * row only when that row is already the owner's, so it never takes another owner's (#451).
2881
3086
  */
2882
- function ownedUpdate(relation, options) {
2883
- return updateOn(relation.model, options, Object.keys(ownersValues(relation)));
3087
+ function ownedUpdate(relation, options, method) {
3088
+ return updateOn(relation.model, options, {
3089
+ ownedBy: Object.keys(ownersValues(relation)),
3090
+ method
3091
+ });
2884
3092
  }
2885
3093
  function insertRows(relation, rows, conflict, { method, returning }) {
2886
3094
  requireSavedOwner$1(relation, "insert");
@@ -4415,8 +4623,12 @@ function inKeyOrder(records, keys) {
4415
4623
  const byKey = new Map(records.map((record) => [primaryKeyOf(record), record]));
4416
4624
  return keys.map((key) => byKey.get(key));
4417
4625
  }
4418
- /** What `find(...args)` finds: one record for one id, else an array, in the ids' or the query's order. */
4626
+ /**
4627
+ * What `find(...args)` finds: one record for one id, else an array, in the ids' or the query's
4628
+ * order. A `column()`, typed value or `incoming()` given as an id throws `TypeError` (#546).
4629
+ */
4419
4630
  async function findByIds({ model, query, runner }, args) {
4631
+ for (const id of args.flat()) refuseReferenceValue(id, `find() gives ${model.primaryKey}`, { takesFragment: false });
4420
4632
  const [only] = args;
4421
4633
  if (args.length === 1 && (typeof only === "string" || typeof only === "number")) return findById(runner, query, only);
4422
4634
  const ids = keysToFind(model, args.flat());
@@ -6202,7 +6414,7 @@ async function* batchesOf({ model, query, runner }, { batchSize, direction, boun
6202
6414
  let pastLast = [];
6203
6415
  while (left > 0) {
6204
6416
  const limit = Math.min(batchSize, left);
6205
- const rows = await runner.load({
6417
+ const rows = await withoutRequestCache(() => runner.load({
6206
6418
  ...query,
6207
6419
  conditions: [
6208
6420
  ...query.conditions,
@@ -6214,7 +6426,7 @@ async function* batchesOf({ model, query, runner }, { batchSize, direction, boun
6214
6426
  direction
6215
6427
  }],
6216
6428
  limit
6217
- });
6429
+ }));
6218
6430
  const records = eachOnce(rows);
6219
6431
  if (records.length > 0) yield records;
6220
6432
  if (rows.length < limit) return;
@@ -6503,7 +6715,8 @@ var Relation = class Relation extends CountQuestions {
6503
6715
  /**
6504
6716
  * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
6505
6717
  * primary key by default): every given attribute and every value this Relation writes into the
6506
- * row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set.
6718
+ * row (#475), except the `uniqueBy` ones and `createdAt`, or only those `updateOnly` names
6719
+ * (#36), with `updatedAt` set when one of them changes.
6507
6720
  * Resolves as `insert` does, returning inserted and updated rows.
6508
6721
  */
6509
6722
  async upsert(attributes, options = {}) {
@@ -8590,6 +8803,14 @@ var AnyDatabase = class {
8590
8803
  return Object.fromEntries(Object.entries(models).map(([name, model]) => [name, this.model(model)]));
8591
8804
  }
8592
8805
  /**
8806
+ * Empties the request cache of the running `withDatabase` call, every database's in it, so each
8807
+ * read after it is sent. Call it after a write the library didn't send, such as SQL sent on the
8808
+ * binding or client yourself, which it can't see. Outside `withDatabase` it does nothing.
8809
+ */
8810
+ clearRequestCache() {
8811
+ clearRequestCaches();
8812
+ }
8813
+ /**
8593
8814
  * Runs the writes `build` prepares atomically, on this Database: all of them are written, or
8594
8815
  * none. `db.batch((b) => [b.insert(Post, { title }), b.save(user)])`. The callback can't await,
8595
8816
  * since the batch is sent as one. Saves and destroys (`b.save(user)`, `b.destroy(post)`) run
@@ -8602,6 +8823,66 @@ var AnyDatabase = class {
8602
8823
  return runBatch(batchEntries(build, (model) => relationFor(this.#executor, model)), "db.batch() needs its statements and records", [this.#executor]);
8603
8824
  }
8604
8825
  };
8826
+ // src/request-cache.ts
8827
+ /**
8828
+ * Whether a bound value keys a read exactly as written as JSON: text, a finite number, a boolean,
8829
+ * null, bytes, or a list of those. Anything else (an ArrayBuffer, NaN, a BigInt, an object) would
8830
+ * share its JSON with another value, or have none.
8831
+ */
8832
+ function isKeyable(value) {
8833
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
8834
+ if (typeof value === "number") return Number.isFinite(value);
8835
+ if (value instanceof Uint8Array) return true;
8836
+ return Array.isArray(value) && value.every(isKeyable);
8837
+ }
8838
+ /** Bytes as an object no other bound value can be, so they never share a key with a list. */
8839
+ function tagBytes(_, value) {
8840
+ return value instanceof Uint8Array ? { bytes: [...value] } : value;
8841
+ }
8842
+ /**
8843
+ * A read's key: its SQL and the values it binds (a filtered one's real value), which only match
8844
+ * a read that's the same. A read binding a value that can't key it has none, so it's sent, and
8845
+ * the database answers it.
8846
+ */
8847
+ function keyOf({ sql, params }) {
8848
+ const bound = params.map(boundValue);
8849
+ return bound.every(isKeyable) ? JSON.stringify([sql, bound], tagBytes) : void 0;
8850
+ }
8851
+ /** How many answers a request cache keeps: enough for a request, bounded for a long one. */
8852
+ const CAPACITY = 100;
8853
+ /**
8854
+ * The answers one scope's database gave to its reads, each kept from when it's sent, so an
8855
+ * identical read sent meanwhile waits for it. Clearing forgets those in flight too. It keeps the
8856
+ * 100 used last: a Map iterates in insertion order, so each answer used is moved to its end.
8857
+ */
8858
+ var RequestCache = class {
8859
+ #answers = /* @__PURE__ */ new Map();
8860
+ /** The answer `read` has, or will have, if it was sent before, which it marks used last. */
8861
+ get(read) {
8862
+ const key = keyOf(read);
8863
+ if (key === void 0) return void 0;
8864
+ const answer = this.#answers.get(key);
8865
+ if (answer !== void 0) {
8866
+ this.#answers.delete(key);
8867
+ this.#answers.set(key, answer);
8868
+ }
8869
+ return answer;
8870
+ }
8871
+ /** Forgets every answer: its database was written to (or may have been, by a write that failed). */
8872
+ clear() {
8873
+ this.#answers.clear();
8874
+ }
8875
+ /** Keeps `answer` as `read`'s, unless it fails, or `read` has no key. Its failure is the caller's. */
8876
+ set(read, answer) {
8877
+ const key = keyOf(read);
8878
+ answer.catch(() => {
8879
+ if (key !== void 0 && this.#answers.get(key) === answer) this.#answers.delete(key);
8880
+ });
8881
+ if (key === void 0) return;
8882
+ this.#answers.set(key, answer);
8883
+ if (this.#answers.size > CAPACITY) this.#answers.delete(this.#answers.keys().next().value);
8884
+ }
8885
+ };
8605
8886
  // src/current-database.ts
8606
8887
  /**
8607
8888
  * Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and
@@ -8618,16 +8899,20 @@ async function withDatabase(databases, fn) {
8618
8899
  const outer = requestStore();
8619
8900
  const inner = Array.isArray(databases) ? databases : [databases];
8620
8901
  const scopes = new Map(outer?.scopes);
8902
+ const caches = outer?.caches ?? /* @__PURE__ */ new Set();
8621
8903
  const opened = [];
8622
8904
  try {
8623
8905
  openScopes(inner, scopes, opened);
8906
+ for (const { scope } of opened) caches.add(scope.cache);
8624
8907
  return await runWithStore({
8625
8908
  databases: [.../* @__PURE__ */ new Set([...inner, ...outer?.databases ?? []])],
8626
- scopes
8909
+ scopes,
8910
+ caches
8627
8911
  }, fn);
8628
8912
  } finally {
8629
8913
  await Promise.all(opened.map(({ executor, scope }) => {
8630
8914
  scope.hasEnded = true;
8915
+ caches.delete(scope.cache);
8631
8916
  return executor.closeScope(scope.held);
8632
8917
  }));
8633
8918
  }
@@ -8643,7 +8928,8 @@ function openScopes(databases, scopes, opened) {
8643
8928
  if (scopes.get(executor)?.hasEnded === false) continue;
8644
8929
  const scope = {
8645
8930
  held: executor.openScope(),
8646
- hasEnded: false
8931
+ hasEnded: false,
8932
+ cache: new RequestCache()
8647
8933
  };
8648
8934
  scopes.set(executor, scope);
8649
8935
  opened.push({
@@ -10012,7 +10298,7 @@ function destroyWrite(record, wrapped) {
10012
10298
  }
10013
10299
  /**
10014
10300
  * Loads the record's row again by its stored primary key, discarding unsaved changes, then runs its
10015
- * `afterFind` and `afterInitialize` (#49).
10301
+ * `afterFind` and `afterInitialize` (#49). It clears the request caches first, so it reads the database.
10016
10302
  */
10017
10303
  async function reloadRecord(record) {
10018
10304
  const recordState = record[state];
@@ -10027,6 +10313,7 @@ async function reloadRecord(record) {
10027
10313
  order: [],
10028
10314
  limit: 1
10029
10315
  };
10316
+ clearRequestCaches();
10030
10317
  const [row] = await executor.all(compileSelect(executor.dialect, query));
10031
10318
  if (row === void 0) throw new RecordNotFound(`${model.name} with ${model.primaryKey} ${shownKey(model, key)} not found`);
10032
10319
  recordState.clearAssociations();
@@ -11223,4 +11510,4 @@ async function recordEntry(statement, claimed, needs) {
11223
11510
  result: () => record
11224
11511
  };
11225
11512
  }
11226
- export { lt as _, databaseExecutor as a, hasMany as b, Relation as c, column as d, sql as f, gte as g, gt as h, AnyDatabase as i, workersEnv as l, between as m, Model as n, readyModel as o, valueMark as p, withDatabase as r, isReservedScopeName as s, batch as t, DatabaseExecutor as u, lte as v, hasOne as x, belongsTo as y };
11513
+ export { belongsTo as _, databaseExecutor as a, Relation as c, valueMark as d, between as f, lte as g, lt as h, AnyDatabase as i, workersEnv as l, gte as m, Model as n, readyModel as o, gt as p, withDatabase as r, isReservedScopeName as s, batch as t, DatabaseExecutor as u, hasMany as v, hasOne as y };