effect-dynamodb 1.41.0 → 1.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/Aggregate.d.ts +18 -1
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +21 -3
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/DynamoClient.d.ts.map +1 -1
  6. package/dist/DynamoClient.js +45 -29
  7. package/dist/DynamoClient.js.map +1 -1
  8. package/dist/Entity.d.ts +10 -4
  9. package/dist/Entity.d.ts.map +1 -1
  10. package/dist/Entity.js +243 -42
  11. package/dist/Entity.js.map +1 -1
  12. package/dist/Query.d.ts +4 -3
  13. package/dist/Query.d.ts.map +1 -1
  14. package/dist/Query.js.map +1 -1
  15. package/dist/Table.d.ts +5 -2
  16. package/dist/Table.d.ts.map +1 -1
  17. package/dist/Table.js +6 -4
  18. package/dist/Table.js.map +1 -1
  19. package/dist/Transaction.d.ts.map +1 -1
  20. package/dist/Transaction.js +4 -3
  21. package/dist/Transaction.js.map +1 -1
  22. package/dist/internal/BoundCrud.d.ts +33 -22
  23. package/dist/internal/BoundCrud.d.ts.map +1 -1
  24. package/dist/internal/BoundCrud.js +4 -1
  25. package/dist/internal/BoundCrud.js.map +1 -1
  26. package/dist/internal/BoundQuery.d.ts +3 -2
  27. package/dist/internal/BoundQuery.d.ts.map +1 -1
  28. package/dist/internal/BoundQuery.js +3 -2
  29. package/dist/internal/BoundQuery.js.map +1 -1
  30. package/dist/internal/BoundVectorQuery.d.ts +2 -1
  31. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  32. package/dist/internal/BoundVectorQuery.js.map +1 -1
  33. package/dist/internal/EntityCombinators.d.ts +12 -0
  34. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  35. package/dist/internal/EntityCombinators.js +9 -0
  36. package/dist/internal/EntityCombinators.js.map +1 -1
  37. package/dist/internal/EntityOps.d.ts +6 -0
  38. package/dist/internal/EntityOps.d.ts.map +1 -1
  39. package/dist/internal/EntityOps.js.map +1 -1
  40. package/dist/internal/Expr.d.ts +20 -9
  41. package/dist/internal/Expr.d.ts.map +1 -1
  42. package/dist/internal/Expr.js +25 -11
  43. package/dist/internal/Expr.js.map +1 -1
  44. package/dist/internal/PathBuilder.d.ts +15 -1
  45. package/dist/internal/PathBuilder.d.ts.map +1 -1
  46. package/dist/internal/PathBuilder.js +49 -32
  47. package/dist/internal/PathBuilder.js.map +1 -1
  48. package/package.json +2 -2
package/dist/Entity.js CHANGED
@@ -36,7 +36,7 @@ import { isBoundOp, makeBoundAppend, makeBoundDelete, makeBoundGet, makeBoundIns
36
36
  import { BoundQueryImpl, entityNaming, wholeRowsOf, } from "./internal/BoundQuery.js";
37
37
  import * as Capacity from "./internal/Capacity.js";
38
38
  import { isNumeric, memberKind, numberSum, setDifference, setUnion, } from "./internal/DynamoArithmetic.js";
39
- import { compileExpr, createConditionOps, emptyPartProblem, isExpr, nonEmptyCondition, operandsAsStored, parseShorthand, parseSimpleShorthand, splitByForms, toExpr, } from "./internal/Expr.js";
39
+ import { compileExpr, createConditionOps, ExprTag, emptyPartProblem, isExpr, nonEmptyCondition, operandsAsStored, parseShorthand, parseSimpleShorthand, splitByForms, toExpr, } from "./internal/Expr.js";
40
40
  import { asReadGuard, countOperators, expressionFits, substitutionsFit, wholeRowGuard, } from "./internal/ExpressionLimits.js";
41
41
  import { formGuard, formGuardName, rejectedBy } from "./internal/FormGuard.js";
42
42
  import { BASE_DELAY_MS, MAX_RETRIES } from "./internal/Hydrate.js";
@@ -58,8 +58,8 @@ import { resolveTtlAttributeName, } from "./Table.js";
58
58
  export { EntityDeleteImpl, EntityDeleteTypeId, EntityGetImpl, EntityOpTypeId, EntityPutImpl, EntityUpdateImpl, EntityUpdateTypeId, emptyUpdateState, returnValuesMap, } from "./internal/EntityOps.js";
59
59
  import * as Projection from "@effect-dynamodb/schema/Projection.js";
60
60
  import { EntityDeleteImpl, EntityDeleteTypeId, EntityGetImpl, EntityOpTypeId, EntityPutImpl, EntityUpdateImpl, emptyUpdateState, withGuard, } from "./internal/EntityOps.js";
61
- export { add, append, asItem, asModel, asNative, asRecord, cascade, clearMap, consistentRead, deleteFromSet, expectedVersion, pathAdd, pathAppend, pathDelete, pathIfNotExists, pathPrepend, pathRemove, pathSet, pathSubtract, project, remove, removeEntries, returnValues, set, subtract, } from "./internal/EntityCombinators.js";
62
- import { allCompositeAttributes, allKeyFieldNames, getSchemaFields, inferDefaultEncoding, makePathValueEncoder, primaryKeyComposites, resolveUniqueFields, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
61
+ export { add, append, asItem, asModel, asNative, asRecord, cascade, clearMap, consistentRead, deleteFromSet, expectedVersion, keepRefs, pathAdd, pathAppend, pathDelete, pathIfNotExists, pathPrepend, pathRemove, pathSet, pathSubtract, project, remove, removeEntries, returnValues, set, subtract, } from "./internal/EntityCombinators.js";
62
+ import { allCompositeAttributes, allKeyFieldNames, getSchemaFields, heldStorageOf, inferDefaultEncoding, makePathValueEncoder, primaryKeyComposites, resolveUniqueFields, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
63
63
  import { asModel, condition as conditionCombinator, expectedVersion, set, } from "./internal/EntityCombinators.js";
64
64
  // ---------------------------------------------------------------------------
65
65
  // Sparse-aware unique sentinel composition
@@ -86,7 +86,8 @@ import { asModel, condition as conditionCombinator, expectedVersion, set, } from
86
86
  */
87
87
  import { buildEntityDefinition, normalizeTtlSeconds, resolveUniqueTtl, zorderInCollection, } from "@effect-dynamodb/schema/Entity.js";
88
88
  export { normalizeTtlSeconds };
89
- const composeUniqueSentinel = (schema, entityType, constraintName, constraintDef, source,
89
+ /** The sentinel of `source`'s values; an entity composes each through its `composeUniqueSentinel`. */
90
+ const composeSentinelFrom = (schema, entityType, constraintName, constraintDef, source,
90
91
  /**
91
92
  * The value a field held when it was stored (`storedNumericForm`), or `undefined` when it is
92
93
  * that already. A sentinel is composed from the Encoded value `put` stores, and a row read back
@@ -477,6 +478,18 @@ export const storedRefIdOf = (ref, stored) => {
477
478
  };
478
479
  /** @internal {@link storedRefIdOf}, or the value as it's stored when it's no value of the key. */
479
480
  const storedRefId = (ref, stored) => Option.getOrElse(storedRefIdOf(ref, stored), () => stored);
481
+ /**
482
+ * @internal {@link storedRefIdOf}'s inverse (#263): a ref's id as the stored ref holds it, encoded
483
+ * through the referenced entity's own field, as {@link refDataOf} encodes the item a ref stores
484
+ * (`5` of a `NumberFromString` is `"5"`). The id as given where that field is unknown or doesn't
485
+ * take it.
486
+ */
487
+ const storedRefKeyOf = (ref, id) => {
488
+ const field = getSchemaFields(ref.refEntity.schemas.modelSchema)?.[ref.keyField];
489
+ return field === undefined
490
+ ? Effect.succeed(id)
491
+ : Schema.encodeUnknownEffect(field)(id).pipe(Effect.orElseSucceed(() => id));
492
+ };
480
493
  /**
481
494
  * @internal What a ref stores of the item it names: the referenced entity's domain item encoded
482
495
  * through that entity's `modelSchema`, so transform fields are in their wire form (a
@@ -692,23 +705,26 @@ const makeImpl = (config, precomputedData) => {
692
705
  * of a renamed sparse map where the row holds it.
693
706
  */
694
707
  const compileOwnCondition = (cond) => compileCondition(cond === undefined ? undefined : entryForms(operandsAsStored(toExpr(cond), storedFormAt)), resolveDbName, storedFormAt, storedBelow);
708
+ /** Each ref's field and the model it is denormalised from (a `configure` wrapper as given). */
709
+ const refModels = data.resolvedRefs.flatMap((ref) => ref.refEntity?.model === undefined ? [] : [[ref.fieldName, ref.refEntity.model]]);
695
710
  // Encoders for path-addressed update values (`pathSet`, `pathAppend`, …) and
696
711
  // record-based `append`, which bypass the update schema (#133).
697
712
  const pathValues = makePathValueEncoder(data.modelFields, schemas.writeModelSchema.fields,
698
713
  // A `DynamoModel.ref` field's own schema is opaque; paths under it follow
699
714
  // the model it is denormalised from.
700
- Object.fromEntries(data.resolvedRefs
701
- .filter((ref) => ref.refEntity?.model !== undefined)
702
- .map((ref) => {
703
- const model = ref.refEntity.model;
704
- return [
705
- ref.fieldName,
706
- isConfiguredModel(model) ? model.model : model,
707
- ];
708
- })),
715
+ Object.fromEntries(refModels.map(([field, model]) => [
716
+ field,
717
+ (isConfiguredModel(model) ? model.model : model),
718
+ ])),
709
719
  // An operand DynamoDB can't store in its stored form is sent as given (`operand`).
710
720
  (encoded) => unstorableIn({ stored: encoded }) === undefined, schemas.modelSchema
711
- .fields);
721
+ .fields,
722
+ // ...in the storage the target's `configure` gives its fields, which the ref holds them in, and
723
+ // its own refs' fields in theirs.
724
+ Object.fromEntries(data.resolvedRefs.flatMap((ref) => {
725
+ const storage = heldStorageOf(ref.refEntity);
726
+ return storage === undefined ? [] : [[ref.fieldName, storage]];
727
+ })));
712
728
  /**
713
729
  * Encode a path-addressed update value and check it against the write schema
714
730
  * at its path — container checks included (#133). `undefined` issue = valid. A
@@ -2924,6 +2940,38 @@ const makeImpl = (config, precomputedData) => {
2924
2940
  return forms.get(field)?.(value);
2925
2941
  };
2926
2942
  })();
2943
+ /** The refs whose id a unique constraint names (`teamId` for `refs: { team }`, #266). */
2944
+ const uniqueRefs = resolvedRefs.filter((ref) => Object.values((config.unique ?? {})).some((def) => resolveUniqueFields(def).includes(ref.idFieldName)));
2945
+ const uniqueRefIds = new Set(uniqueRefs.map((ref) => ref.idFieldName));
2946
+ /**
2947
+ * Every unique sentinel of this entity, composed from `source`'s values ({@link composeSentinelFrom}).
2948
+ * A ref's id a constraint names (#266) is the referenced item's key as the ref holds it
2949
+ * ({@link storedRefId}), in the key form an index composite of it takes. Every path composes it
2950
+ * from there, a row read back and a write's item alike (a write hydrates the ref first), so a
2951
+ * sentinel a write reserves is the one a later delete, restore or `rekey` composes. A source
2952
+ * holding no ref (a put's input, checked before hydration) gives the id as given. An entity whose
2953
+ * constraints name no ref's id composes exactly as it did.
2954
+ */
2955
+ const composeUniqueSentinel = (under, _entityType, constraintName, constraintDef, source, stored) => {
2956
+ if (uniqueRefs.length === 0) {
2957
+ return composeSentinelFrom(under, entityType, constraintName, constraintDef, source, stored);
2958
+ }
2959
+ const values = { ...source };
2960
+ for (const ref of uniqueRefs) {
2961
+ const held = ownValue(source, ref.fieldName);
2962
+ const id = held === undefined || held === null
2963
+ ? given(source, ref.idFieldName)
2964
+ : (() => {
2965
+ const key = ownValue(held, ref.keyField);
2966
+ return key === undefined || key === null ? undefined : storedRefId(ref, key);
2967
+ })();
2968
+ values[ref.idFieldName] =
2969
+ id === undefined || id === null ? id : compositeKeyForm(ref.idFieldName, id);
2970
+ }
2971
+ return composeSentinelFrom(under, entityType, constraintName, constraintDef, values,
2972
+ // The id is in its key form already, which no stored form of the field changes.
2973
+ (field, value) => (uniqueRefIds.has(field) ? undefined : stored(field, value)));
2974
+ };
2927
2975
  /**
2928
2976
  * `keyForm` of a caller's DOMAIN key record: each composite first put into
2929
2977
  * the form `put` stores it in, as `put`'s encode and `get`'s `encodeKey` do,
@@ -4169,7 +4217,7 @@ const makeImpl = (config, precomputedData) => {
4169
4217
  for (const key of Object.keys(values))
4170
4218
  if (key.startsWith(":dg"))
4171
4219
  delete values[key];
4172
- const uniqueAttrs = Object.values(config.unique ?? {}).flatMap((def) => resolveUniqueFields(def).map(resolveDbName));
4220
+ const uniqueAttrs = Object.values(config.unique ?? {}).flatMap((def) => resolveUniqueFields(def).map(compositeAttribute));
4173
4221
  const modelAttrs = Object.keys(data.modelFields).map(resolveDbName);
4174
4222
  const ordered = [
4175
4223
  ...new Set([
@@ -4830,7 +4878,8 @@ const makeImpl = (config, precomputedData) => {
4830
4878
  const uniqueAttrs = [
4831
4879
  ...new Set(Object.values((config.unique ?? {}))
4832
4880
  .flatMap((def) => [...resolveUniqueFields(def)])
4833
- .map(resolveDbName)),
4881
+ // A ref's id is held by the ref.
4882
+ .map(compositeAttribute)),
4834
4883
  ];
4835
4884
  const userCondition = args.userCondition;
4836
4885
  const guard = current === undefined
@@ -5056,6 +5105,121 @@ const makeImpl = (config, precomputedData) => {
5056
5105
  }
5057
5106
  return keyed;
5058
5107
  };
5108
+ /**
5109
+ * The refs an update holding the whole row keys its indexes from as the row holds them (#263):
5110
+ * each whose id an index half holds that also holds a composite the update gives or removes, so
5111
+ * the half composes from the ref the row holds, as a `put` of the row would, rather than
5112
+ * stopping before the id. Not a ref whose id the update has otherwise (given, kept, or a
5113
+ * primary key composite), nor one only a half the update doesn't touch holds: the id the row
5114
+ * holds may be spelled other than the one that half was composed from (a ref read through a key
5115
+ * that folds case). An id read here is guarded as read (`heldRefGuard`).
5116
+ */
5117
+ const heldRefsOf = (row, payload, removed, kept) => {
5118
+ if (!hasRefs)
5119
+ return [];
5120
+ const touched = (attr) => (Object.hasOwn(payload, attr) && payload[attr] !== undefined) || removed?.has(attr) === true;
5121
+ const beside = new Set();
5122
+ for (const [name, index] of Object.entries(allIndexes)) {
5123
+ if (name === "primary")
5124
+ continue;
5125
+ for (const [, composites] of halvesOf(index)) {
5126
+ if (composites.some(touched))
5127
+ for (const attr of composites)
5128
+ beside.add(attr);
5129
+ }
5130
+ }
5131
+ return resolvedRefs.flatMap((ref) => {
5132
+ const name = ref.idFieldName;
5133
+ if (!beside.has(name) || touched(name) || isPrimaryComposite(name))
5134
+ return [];
5135
+ if (kept !== undefined && Object.hasOwn(kept.ids, name))
5136
+ return [];
5137
+ const held = ownValue(row, ref.fieldName);
5138
+ if (held === null || typeof held !== "object")
5139
+ return [];
5140
+ const id = ownValue(held, ref.keyField);
5141
+ return id === undefined ? [] : [{ ref, id: storedRefId(ref, id) }];
5142
+ });
5143
+ };
5144
+ /** A row's index key record with the ids `heldRefsOf` read beside their refs. A copy. */
5145
+ const withHeldRefIds = (row, held) => held.length === 0
5146
+ ? row
5147
+ : { ...row, ...Object.fromEntries(held.map(({ ref, id }) => [ref.idFieldName, id])) };
5148
+ /**
5149
+ * The guard that a ref `heldRefsOf` read is still the one read (#263): its id inside the stored
5150
+ * ref (`#team.#id = :id`), as read. An unversioned update guards each composite it read as read;
5151
+ * a ref's id isn't an attribute of the row, so a guard on it would hold whatever the ref is.
5152
+ * `undefined` where the stored ref has no id to compare (the update then guards as before).
5153
+ */
5154
+ const heldRefGuard = (ref, read) => {
5155
+ const attribute = compositeAttribute(ref.idFieldName);
5156
+ const stored = ownValue(read, attribute);
5157
+ const id = stored?.M === undefined ? undefined : ownValue(stored.M, ref.keyField);
5158
+ return id === undefined ? undefined : { attribute, key: ref.keyField, id: id };
5159
+ };
5160
+ /**
5161
+ * What `.keepRefs()` keeps (#263): the ids it names, encoded as `.set()` encodes them (`ids`, which
5162
+ * key the indexes each is a composite of), and the condition that the row holds each of those refs
5163
+ * (`guard`: the stored ref's key is the id). `undefined` without `.keepRefs()`. A name that is no
5164
+ * ref id an update can give ([EDD-9166]), or the id of a ref the same update sets or removes
5165
+ * ([EDD-9167]), is refused before anything is read or sent.
5166
+ */
5167
+ const keptRefsOf = (uState) => Effect.gen(function* () {
5168
+ const given = uState.keepRefs;
5169
+ if (given === undefined)
5170
+ return undefined;
5171
+ const named = Object.keys(given).filter((name) => given[name] !== undefined);
5172
+ if (named.length === 0)
5173
+ return undefined;
5174
+ const primaryComposites = new Set([
5175
+ ...config.indexes.primary.pk.composite,
5176
+ ...config.indexes.primary.sk.composite,
5177
+ ]);
5178
+ const updates = (uState.updates ?? {});
5179
+ const removed = new Set(uState.remove ?? []);
5180
+ const kept = [];
5181
+ for (const name of named) {
5182
+ const ref = resolvedRefs.find((candidate) => candidate.idFieldName === name);
5183
+ if (ref === undefined || primaryComposites.has(name)) {
5184
+ const ids = resolvedRefs
5185
+ .map((candidate) => candidate.idFieldName)
5186
+ .filter((id) => !primaryComposites.has(id));
5187
+ return yield* new ValidationError({
5188
+ entityType,
5189
+ operation: "update.keepRefs",
5190
+ cause: `[EDD-9166] .keepRefs() names "${name}", which is no ref id this update can keep. ` +
5191
+ (ids.length === 0
5192
+ ? `Entity "${entityType}" has no ref an update can reassign.`
5193
+ : `It takes ${ids.map((id) => `"${id}"`).join(", ")}.`) +
5194
+ " Nothing was sent.",
5195
+ });
5196
+ }
5197
+ if ((hasOwnName(updates, name) && updates[name] !== undefined) ||
5198
+ removed.has(ref.fieldName)) {
5199
+ return yield* new ValidationError({
5200
+ entityType,
5201
+ operation: "update.keepRefs",
5202
+ cause: `[EDD-9167] .keepRefs() keeps "${ref.fieldName}", which the same update ` +
5203
+ `${removed.has(ref.fieldName) ? "removes" : `reassigns with .set({ ${name} })`}. ` +
5204
+ "Keep it or change it, not both. Nothing was sent.",
5205
+ });
5206
+ }
5207
+ kept.push(ref);
5208
+ }
5209
+ const ids = (yield* encodeForWrite(schemas.updateSchema, Object.fromEntries(named.map((name) => [name, given[name]])), "update.keepRefs"));
5210
+ // The row holds the ref when its stored key is the id: the id in the form the stored ref
5211
+ // holds it (`"5"` of a `NumberFromString`), not the key form the index keys take.
5212
+ const holds = yield* Effect.forEach(kept, (ref) => Effect.map(storedRefKeyOf(ref, Option.getOrElse(keyValueOf(ref.keySchema, ids[ref.idFieldName]), () => ids[ref.idFieldName])), (value) => ({
5213
+ [ExprTag]: ExprTag,
5214
+ _tag: "eq",
5215
+ left: { _tag: "path", segments: [ref.fieldName, ref.keyField] },
5216
+ right: { _tag: "value", value },
5217
+ })));
5218
+ const guard = holds.length === 1 ? holds[0] : { [ExprTag]: ExprTag, _tag: "and", exprs: holds };
5219
+ return { ids, guard };
5220
+ });
5221
+ /** An update's index key record, with the ids of the refs it keeps (`.keepRefs()`, #263). */
5222
+ const withKeptRefIds = (record, kept) => kept === undefined ? record : { ...record, ...kept.ids };
5059
5223
  /**
5060
5224
  * What an update's `.remove()` removes, as the index key composer is told (`removedSet`): the
5061
5225
  * fields named, and the id of each ref removed, which is the composite a cascade index is keyed
@@ -5867,9 +6031,11 @@ const makeImpl = (config, precomputedData) => {
5867
6031
  "is no version to check. Add `versioned: true`, or use a `.condition()`. Nothing was sent.",
5868
6032
  });
5869
6033
  }
6034
+ // `.keepRefs()` (#263): the refs this update keeps, and the guard that the row holds them.
6035
+ const kept = yield* keptRefsOf(uState);
5870
6036
  // The caller's condition, ANDed onto `patch`'s exists guard — a guard
5871
- // no `.condition()` can replace (#133).
5872
- const userCond = withGuard(uState.patch ? { attributeExists: [config.indexes.primary.pk.field] } : undefined, uState.condition);
6037
+ // no `.condition()` can replace (#133) — and onto `.keepRefs()`'s.
6038
+ const userCond = withGuard(withGuard(uState.patch ? { attributeExists: [config.indexes.primary.pk.field] } : undefined, kept?.guard), uState.condition);
5873
6039
  yield* checkWithVectorNames(uState.withVectors, "update");
5874
6040
  // Caller key: Type side in, ENCODED out (see `encodeKey`).
5875
6041
  const encodedKey = encoded ?? (yield* encodeKey(key, "update.decodeKey"));
@@ -5910,7 +6076,7 @@ const makeImpl = (config, precomputedData) => {
5910
6076
  }
5911
6077
  }
5912
6078
  const checked = refsToHydrate.length === 0
5913
- ? yield* checkUpdatePayload(uState, needsBothImages, encodedKey, encodedUpdates, encodedUpdates)
6079
+ ? yield* checkUpdatePayload(uState, needsBothImages, encodedKey, encodedUpdates, encodedUpdates, kept)
5914
6080
  : undefined;
5915
6081
  // The operands written as values of a field, in the form they're written: refused here if
5916
6082
  // the schema refuses one, before anything is read or sent, and written as encoded here.
@@ -5941,6 +6107,7 @@ const makeImpl = (config, precomputedData) => {
5941
6107
  encodedUpdates,
5942
6108
  refsToHydrate,
5943
6109
  checked,
6110
+ kept,
5944
6111
  };
5945
6112
  });
5946
6113
  /**
@@ -6014,6 +6181,11 @@ const makeImpl = (config, precomputedData) => {
6014
6181
  ...Object.keys(uState.append ?? {}),
6015
6182
  ...Object.keys(uState.deleteFromSet ?? {}),
6016
6183
  ]);
6184
+ // A ref's id is written as the ref (`team`, hydrated from `teamId`), and removed by its field.
6185
+ for (const ref of uniqueRefs) {
6186
+ if (allUpdatedFields.has(ref.fieldName))
6187
+ allUpdatedFields.add(ref.idFieldName);
6188
+ }
6017
6189
  return [...uniqueFieldSet].some((f) => allUpdatedFields.has(f));
6018
6190
  };
6019
6191
  /**
@@ -6021,13 +6193,15 @@ const makeImpl = (config, precomputedData) => {
6021
6193
  * no key text or level, and path operations no read-then-write can carry. Returns the primary key
6022
6194
  * and what decides the write's path.
6023
6195
  */
6024
- const checkUpdatePayload = (uState, needsBothImages, encodedKey, encodedUpdates, hydratedUpdates) => Effect.gen(function* () {
6196
+ const checkUpdatePayload = (uState, needsBothImages, encodedKey, encodedUpdates, hydratedUpdates,
6197
+ /** The refs the update keeps (`.keepRefs()`, #263): their ids key the indexes too. */
6198
+ kept) => Effect.gen(function* () {
6025
6199
  // The index keys the payload feeds, composed once before anything is
6026
6200
  // marshalled: a composite with no key text (`NaN`, `[EDD-9096]`) or
6027
6201
  // Z-order level (`[EDD-9092]`) fails the update with a
6028
6202
  // `ValidationError`. Each branch below composes the keys it writes itself.
6029
6203
  // A payload value a key composed here holds is the write's own (`ownSchema`, `EDD-9162`).
6030
- yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(ownPayload(hydratedUpdates), entityType, entityVersion, allIndexes, keyForm(withRefIds(hydratedUpdates, encodedUpdates)), keyForm(encodedKey),
6204
+ yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(ownPayload(hydratedUpdates), entityType, entityVersion, allIndexes, keyForm(withRefIds(hydratedUpdates, encodedUpdates)), keyForm(withKeptRefIds(encodedKey, kept)),
6031
6205
  // The branches below know more: the retain path reads the whole item
6032
6206
  // first, so a shard it can compute is not refused here (#183).
6033
6207
  {
@@ -6118,7 +6292,7 @@ const makeImpl = (config, precomputedData) => {
6118
6292
  ? yield* hydrateRefs(encodedUpdates, prepared.refsToHydrate)
6119
6293
  : encodedUpdates;
6120
6294
  const { primaryKey, marshalledKey, touchesUniqueFields, computedComposites, pathOpsPresent } = prepared.checked ??
6121
- (yield* checkUpdatePayload(uState, needsBothImages, encodedKey, encodedUpdates, hydratedUpdates));
6295
+ (yield* checkUpdatePayload(uState, needsBothImages, encodedKey, encodedUpdates, hydratedUpdates, prepared.kept));
6122
6296
  if (rewritesWholeItem(uState, needsBothImages, {
6123
6297
  touchesUniqueFields,
6124
6298
  computedComposites,
@@ -6361,8 +6535,13 @@ const makeImpl = (config, precomputedData) => {
6361
6535
  // here. Recompose all keys with the updated attributes.
6362
6536
  //
6363
6537
  // Primary key always recomposes from `newItem` (Put-style), a ref's id in it the caller's:
6364
- // a row stores the ref, not the id.
6365
- const keyedItem = withRefIds(newItem, encodedKey);
6538
+ // a row stores the ref, not the id. In an index half the update touches, a ref's id the
6539
+ // update doesn't give is the one the row holds (`heldRefsOf`, #263), so the half composes
6540
+ // as a `put` of the row would, guarded as read below. Up to 1.41.0 those ids were missing
6541
+ // here, so such a half was truncated before the first.
6542
+ const retainRemovedSet = removedSetOf(uState.remove);
6543
+ const heldRefs = heldRefsOf(newItem, withRefIds(hydratedUpdates, encodedUpdates), retainRemovedSet, prepared.kept);
6544
+ const keyedItem = withKeptRefIds(withRefIds(withHeldRefIds(newItem, heldRefs), encodedKey), prepared.kept);
6366
6545
  const primaryKeyMap = composePrimaryKey(keyedItem);
6367
6546
  Object.assign(newItem, primaryKeyMap);
6368
6547
  // GSI keys: route through the policy-aware composer so the
@@ -6378,7 +6557,6 @@ const makeImpl = (config, precomputedData) => {
6378
6557
  // EDD-9024 was deprecated in v1.7.1 — hole patterns don't throw. A
6379
6558
  // Z-order value the composer can't place (EDD-9092, #171) fails the
6380
6559
  // update with a `ValidationError`.
6381
- const retainRemovedSet = removedSetOf(uState.remove);
6382
6560
  // The payload's values are the write's own; the rest of `newItem` is the row as stored.
6383
6561
  const ownUpdate = ownPayload(hydratedUpdates);
6384
6562
  const gsiUpdate = yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(ownUpdate, entityType, entityVersion, allIndexes, keyForm(withRefIds(hydratedUpdates, encodedUpdates)), keyForm(keyedItem), {
@@ -6530,6 +6708,8 @@ const makeImpl = (config, precomputedData) => {
6530
6708
  // and a concurrent change to an input is refused.
6531
6709
  const condParts = [];
6532
6710
  const inputs = [];
6711
+ // The refs whose ids a key was composed from as read, guarded by the id in the ref.
6712
+ const heldGuards = [];
6533
6713
  if (systemFields.version) {
6534
6714
  condParts.push(versionIs(currentVersion, writeNames, writeValues, "#ver", ":expectedVer"));
6535
6715
  const incarnation = incarnationGuard(currentItem, writeNames, writeValues);
@@ -6569,7 +6749,8 @@ const makeImpl = (config, precomputedData) => {
6569
6749
  add(asRead(indexDef.sk.composite));
6570
6750
  }
6571
6751
  for (const rotation of sentinelRotations) {
6572
- add(resolveUniqueFields(config.unique[rotation.constraintName]), true);
6752
+ // A ref's id is read from the ref, which is what's guarded.
6753
+ add(resolveUniqueFields(config.unique[rotation.constraintName]).map((field) => uniqueRefs.find((ref) => ref.idFieldName === field)?.fieldName ?? field), true);
6573
6754
  }
6574
6755
  for (const [, definition] of vectorIndexEntries) {
6575
6756
  if (written.has(definition.vectorField))
@@ -6578,6 +6759,16 @@ const makeImpl = (config, precomputedData) => {
6578
6759
  add(definition.partition);
6579
6760
  }
6580
6761
  for (const [i, field] of inputs.entries()) {
6762
+ const held = heldRefs.find(({ ref }) => ref.idFieldName === field);
6763
+ const asRead = held === undefined ? undefined : heldRefGuard(held.ref, currentItem);
6764
+ if (asRead !== undefined) {
6765
+ writeNames[`#g${i}`] = asRead.attribute;
6766
+ writeNames[`#g${i}k`] = asRead.key;
6767
+ writeValues[`:g${i}`] = asRead.id;
6768
+ condParts.push(`#g${i}.#g${i}k = :g${i}`);
6769
+ heldGuards.push(asRead);
6770
+ continue;
6771
+ }
6581
6772
  const attr = resolveDbName(field);
6582
6773
  writeNames[`#g${i}`] = attr;
6583
6774
  const read = ownValue(currentItem, attr);
@@ -6667,14 +6858,24 @@ const makeImpl = (config, precomputedData) => {
6667
6858
  }
6668
6859
  if (stored === undefined)
6669
6860
  return missingItem();
6670
- const changed = guardedAttrs.filter((attr) => !attributeValueEquals(ownValue(stored, attr), ownValue(currentItem, attr)));
6671
- if (changed.length === 0 && userCond) {
6861
+ const changed = new Set([
6862
+ ...guardedAttrs.filter((attr) => !attributeValueEquals(ownValue(stored, attr), ownValue(currentItem, attr))),
6863
+ // A ref is guarded by its id: another ref is a change, a refreshed copy isn't.
6864
+ ...heldGuards
6865
+ .filter((guard) => {
6866
+ const ref = ownValue(stored, guard.attribute);
6867
+ const id = ref?.M === undefined ? undefined : ownValue(ref.M, guard.key);
6868
+ return !attributeValueEquals(id, guard.id);
6869
+ })
6870
+ .map((guard) => guard.attribute),
6871
+ ]);
6872
+ if (changed.size === 0 && userCond) {
6672
6873
  return new ConditionalCheckFailed({ entityType, key: encodedKey });
6673
6874
  }
6674
6875
  return new ConcurrentModification({
6675
6876
  entityType,
6676
6877
  key: encodedKey,
6677
- attributes: changed.map(domainNameOf),
6878
+ attributes: [...changed].map(domainNameOf),
6678
6879
  current: Option.none(),
6679
6880
  });
6680
6881
  };
@@ -7215,7 +7416,7 @@ const makeImpl = (config, precomputedData) => {
7215
7416
  // EDD-9024 was deprecated in v1.7.1 — hole patterns collapse into the
7216
7417
  // unified can't-compose rule and don't throw. A Z-order value the
7217
7418
  // composer can't place (EDD-9092, #171) fails with a `ValidationError`.
7218
- const gsiUpdate = yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(ownPayload(hydratedUpdates), entityType, entityVersion, allIndexes, keyForm(withRefIds(hydratedUpdates, encodedUpdates)), keyForm(encodedKey), {
7419
+ const gsiUpdate = yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(ownPayload(hydratedUpdates), entityType, entityVersion, allIndexes, keyForm(withRefIds(hydratedUpdates, encodedUpdates)), keyForm(withKeptRefIds(encodedKey, prepared.kept)), {
7219
7420
  ...(removedSet === undefined ? {} : { removedSet }),
7220
7421
  stamped: keyForm(writeStamps(stampedUpdatedAt, retainSnapshot === undefined ? undefined : retainSnapshot.version + 1)),
7221
7422
  }));
@@ -7513,8 +7714,8 @@ const makeImpl = (config, precomputedData) => {
7513
7714
  condParts.push("(attribute_exists(#intVer) OR attribute_not_exists(#intInc))");
7514
7715
  }
7515
7716
  // A plain write already requires the item (`attribute_exists(#exists)`
7516
- // below), so `patch`'s own exists guard would only repeat it.
7517
- const sentCond = plainWrite ? uState.condition : userCond;
7717
+ // below), so `patch`'s own exists guard would only repeat it; `.keepRefs()`'s is sent.
7718
+ const sentCond = plainWrite ? withGuard(prepared.kept?.guard, uState.condition) : userCond;
7518
7719
  const uc = sentCond ? compileOwnCondition(sentCond) : undefined;
7519
7720
  if (uc) {
7520
7721
  condParts.push(`(${uc.expression})`);
@@ -8019,7 +8220,8 @@ const makeImpl = (config, precomputedData) => {
8019
8220
  ...uState.add,
8020
8221
  ...Object.fromEntries(Object.entries(uState.subtract ?? {}).map(([field, by]) => [field, -by])),
8021
8222
  },
8022
- callerCondition: uState.condition !== undefined,
8223
+ // `.keepRefs()`'s guard is the caller's: a row holding another ref fails it, unchanged.
8224
+ callerCondition: uState.condition !== undefined || prepared.kept !== undefined,
8023
8225
  expectedVersion: uState.expectedVersion,
8024
8226
  refuse: (row) => fallbackRefusal(prepared.operands.fallbacks, row),
8025
8227
  });
@@ -8302,7 +8504,7 @@ const makeImpl = (config, precomputedData) => {
8302
8504
  yield* checkVersion(result.Item, "delete");
8303
8505
  const hardGuard = deleteGuard(result.Item, hasUniqueConstraints
8304
8506
  ? [
8305
- ...new Set(Object.values(config.unique).flatMap((def) => resolveUniqueFields(def).map(resolveDbName))),
8507
+ ...new Set(Object.values(config.unique).flatMap((def) => resolveUniqueFields(def).map(compositeAttribute))),
8306
8508
  ]
8307
8509
  : [], userCondition?.expression);
8308
8510
  const raw = fromAttributeMap(result.Item);
@@ -12640,7 +12842,7 @@ const makeImpl = (config, precomputedData) => {
12640
12842
  */
12641
12843
  const sameOwnerValues = (now, read) => [
12642
12844
  "__edd_e__",
12643
- ...allUniqueFields().map((field) => resolveDbName(field)),
12845
+ ...allUniqueFields().map((field) => compositeAttribute(field)),
12644
12846
  UNSENTINELED_DEFAULTS,
12645
12847
  ].every((attribute) => attributeValueEquals(now[attribute], read[attribute]));
12646
12848
  /**
@@ -12762,7 +12964,7 @@ const makeImpl = (config, precomputedData) => {
12762
12964
  const guards = ["#e = :e"];
12763
12965
  const attributes = [
12764
12966
  ...new Set([
12765
- ...resolveUniqueFields(constraintDef).map((field) => resolveDbName(field)),
12967
+ ...resolveUniqueFields(constraintDef).map((field) => compositeAttribute(field)),
12766
12968
  UNSENTINELED_DEFAULTS,
12767
12969
  ]),
12768
12970
  ];
@@ -14060,13 +14262,12 @@ export const bind = (entity) => Effect.gen(function* () {
14060
14262
  if ("between" in cond)
14061
14263
  return { between: [rewrite(cond.between[0]), rewrite(cond.between[1])] };
14062
14264
  if ("beginsWith" in cond) {
14063
- // A number has no text prefix: its key text is not its digits
14064
- // (`-3` is `-9999999999999996:`), and an integer's text prefixes
14065
- // its fractions'. `beginsWith` on a numeric orderBy is `eq`.
14265
+ // A number has no text prefix (`KeyComposer.matchesTextPrefix`):
14266
+ // `beginsWith` on a numeric orderBy is `eq`.
14066
14267
  const operand = keyFormOf(cond.beginsWith);
14067
- return typeof operand === "number" || typeof operand === "bigint"
14068
- ? { eq: rewrite(cond.beginsWith) }
14069
- : { beginsWith: rewrite(cond.beginsWith) };
14268
+ return KeyComposer.matchesTextPrefix(operand)
14269
+ ? { beginsWith: rewrite(cond.beginsWith) }
14270
+ : { eq: rewrite(cond.beginsWith) };
14070
14271
  }
14071
14272
  return cond;
14072
14273
  };