dynamo-bao 0.7.2 → 0.8.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.
@@ -18,6 +18,30 @@ const {
18
18
  const { computeSearchTextUpdate } = require("../utils/search-text");
19
19
  const { SEARCH_TEXT_FIELD } = require("../constants");
20
20
 
21
+ /**
22
+ * AND a guard onto an optional ConditionExpression. The existing expression
23
+ * is parenthesized so a top-level OR in it can't swallow the guard, except
24
+ * when it is already one parenthesized group: DynamoDB rejects redundant
25
+ * parentheses, and the filter builder emits "$and"/"$or" groups that way.
26
+ * @private
27
+ */
28
+ function andCondition(existing, guard) {
29
+ if (!existing) return guard;
30
+ return `${isOneParenGroup(existing) ? existing : `(${existing})`} AND ${guard}`;
31
+ }
32
+
33
+ function isOneParenGroup(expr) {
34
+ if (!expr.startsWith("(") || !expr.endsWith(")")) return false;
35
+ let depth = 0;
36
+ for (let i = 0; i < expr.length; i++) {
37
+ if (expr[i] === "(") depth++;
38
+ else if (expr[i] === ")") depth--;
39
+ // The opening paren closed before the end: not a single group.
40
+ if (depth === 0 && i < expr.length - 1) return false;
41
+ }
42
+ return true;
43
+ }
44
+
21
45
  const MutationMethods = {
22
46
  /**
23
47
  *@memberof BaoModel
@@ -125,17 +149,33 @@ const MutationMethods = {
125
149
  options,
126
150
  );
127
151
 
128
- const item = await this.find(primaryId, { batchDelay: 0 });
129
- if (!item.exists()) {
130
- throw new ItemNotFoundError("Item not found", primaryId);
152
+ // The row is read first only when the delete needs its contents: to
153
+ // find unique-constraint values to clean up, or (mid key migration) to
154
+ // learn which key shape the row actually lives at. Otherwise the key is
155
+ // derived from the id and a single conditional DeleteItem does the work.
156
+ const uniqueConstraints = Object.values(this.uniqueConstraints || {});
157
+ const needsRead =
158
+ uniqueConstraints.length > 0 || this._writesInPlaceWhileMigrating();
159
+
160
+ let item = null;
161
+ let key;
162
+ if (needsRead) {
163
+ item = await this.find(primaryId, { batchDelay: 0 });
164
+ if (!item.exists()) {
165
+ throw new ItemNotFoundError("Item not found", primaryId);
166
+ }
167
+ key = { _pk: item._dyData._pk, _sk: item._dyData._sk };
168
+ } else {
169
+ key = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
131
170
  }
132
171
 
133
172
  // Check if we need to clean up any unique constraints
134
- const uniqueConstraints = Object.values(this.uniqueConstraints || {});
135
- const hasConstraintsToClean = uniqueConstraints.some((constraint) => {
136
- const value = item[constraint.field];
137
- return value != null;
138
- });
173
+ const hasConstraintsToClean =
174
+ item !== null &&
175
+ uniqueConstraints.some((constraint) => {
176
+ const value = item[constraint.field];
177
+ return value != null;
178
+ });
139
179
 
140
180
  try {
141
181
  let response;
@@ -146,10 +186,7 @@ const MutationMethods = {
146
186
  {
147
187
  Delete: {
148
188
  TableName: this.table,
149
- Key: {
150
- _pk: item._dyData._pk,
151
- _sk: item._dyData._sk,
152
- },
189
+ Key: key,
153
190
  },
154
191
  },
155
192
  ];
@@ -197,10 +234,7 @@ const MutationMethods = {
197
234
  // Fast path - simple delete
198
235
  const deleteParams = {
199
236
  TableName: this.table,
200
- Key: {
201
- _pk: item._dyData._pk,
202
- _sk: item._dyData._sk,
203
- },
237
+ Key: key,
204
238
  ReturnValues: "ALL_OLD",
205
239
  ReturnConsumedCapacity: "TOTAL",
206
240
  };
@@ -220,6 +254,12 @@ const MutationMethods = {
220
254
  }
221
255
  }
222
256
 
257
+ // Without a pre-read, the item's existence is checked by the delete
258
+ // itself; a failure is mapped to ItemNotFoundError in the catch below.
259
+ if (!item) {
260
+ this._addExistsGuard(deleteParams);
261
+ }
262
+
223
263
  response = await retryOperation(() =>
224
264
  this.documentClient.send(new DeleteCommand(deleteParams)),
225
265
  );
@@ -252,6 +292,12 @@ const MutationMethods = {
252
292
  (error.name === "TransactionCanceledException" &&
253
293
  error.CancellationReasons?.[0]?.Code === "ConditionalCheckFailed")
254
294
  ) {
295
+ if (
296
+ !item &&
297
+ !(await this._existsAfterGuardFailure(primaryId, options))
298
+ ) {
299
+ throw new ItemNotFoundError("Item not found", primaryId);
300
+ }
255
301
  throw new ConditionalError(
256
302
  "Delete condition not met",
257
303
  "delete",
@@ -262,6 +308,53 @@ const MutationMethods = {
262
308
  }
263
309
  },
264
310
 
311
+ /**
312
+ * Whether an existing `pk === "modelPrefix"` row must be written at the
313
+ * key it was loaded from rather than the canonical key (mid-migration).
314
+ * Such writes need the row read first to learn that key.
315
+ * @private
316
+ */
317
+ _writesInPlaceWhileMigrating() {
318
+ return (
319
+ this.primaryKey.pk === "modelPrefix" &&
320
+ this._modelPrefixPkMode() === "migrating"
321
+ );
322
+ },
323
+
324
+ /**
325
+ * AND an `attribute_exists(_pk)` guard into a write's ConditionExpression.
326
+ * Uses a "#__" placeholder so it can't clobber a field placeholder (user
327
+ * field names can't start with "_"; filter placeholders are "#nN").
328
+ * @private
329
+ */
330
+ _addExistsGuard(params) {
331
+ params.ExpressionAttributeNames = {
332
+ ...params.ExpressionAttributeNames,
333
+ "#__existsPk": "_pk",
334
+ };
335
+ params.ConditionExpression = andCondition(
336
+ params.ConditionExpression,
337
+ "attribute_exists(#__existsPk)",
338
+ );
339
+ },
340
+
341
+ /**
342
+ * After a guarded write fails its condition check, decide whether the row
343
+ * exists. With no caller condition the guard is the only thing that could
344
+ * have failed, so no read is needed; otherwise one GetItem (cache
345
+ * bypassed) tells a missing row apart from an unmet condition. Only the
346
+ * failure path pays for this read.
347
+ * @private
348
+ */
349
+ async _existsAfterGuardFailure(primaryId, options) {
350
+ if (!options.condition) return false;
351
+ const existing = await this.find(primaryId, {
352
+ batchDelay: 0,
353
+ bypassCache: true,
354
+ });
355
+ return existing.exists();
356
+ },
357
+
265
358
  /**
266
359
  * @memberof BaoModel
267
360
  * @description
@@ -414,522 +507,596 @@ const MutationMethods = {
414
507
  * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
415
508
  */
416
509
  async _saveItem(primaryId, jsUpdates, options = {}) {
417
- try {
418
- const {
419
- isNew = false,
420
- instanceObj = null,
421
- forceReindex = false,
422
- } = options;
423
-
424
- // The id is used as a string below (iteration keys, the relatedId on
425
- // unique constraint rows), so accept an object id by normalizing it.
426
- if (!isNew) {
427
- primaryId = this._canonicalPrimaryId(primaryId);
510
+ const { isNew = false, instanceObj = null, forceReindex = false } = options;
511
+
512
+ // The id is used as a string below (iteration keys, the relatedId on
513
+ // unique constraint rows), so accept an object id by normalizing it.
514
+ if (!isNew) {
515
+ primaryId = this._canonicalPrimaryId(primaryId);
516
+ }
517
+
518
+ logger.debug("saveItem", primaryId, isNew, instanceObj);
519
+ let consumedCapacity = [];
520
+
521
+ let currentItem = isNew ? null : instanceObj;
522
+
523
+ const transactItems = [];
524
+ const dyUpdatesToSave = {};
525
+ const indexComputationData = {};
526
+ let hasUniqueConstraintChanges = false;
527
+
528
+ logger.debug("jsUpdates", jsUpdates);
529
+
530
+ // Generate Dynamo Updates to save
531
+ for (const [key, field] of Object.entries(this.fields)) {
532
+ if (isNew && jsUpdates[key] === undefined) {
533
+ // Only set initial values during creation
534
+ const initialValue = field.getInitialValue();
535
+ if (initialValue !== undefined) {
536
+ jsUpdates[key] = initialValue;
537
+ }
428
538
  }
429
539
 
430
- logger.debug("saveItem", primaryId, isNew, instanceObj);
431
- let consumedCapacity = [];
540
+ if (jsUpdates[key] !== undefined) {
541
+ field.validate(jsUpdates[key]);
542
+ const dyValue = field.toDy(jsUpdates[key]);
543
+ dyUpdatesToSave[key] = dyValue;
544
+ indexComputationData[key] = dyValue;
545
+ } else {
546
+ if (typeof field.updateBeforeSave === "function") {
547
+ const newValue = field.updateBeforeSave(jsUpdates[key]);
548
+ if (newValue !== jsUpdates[key]) {
549
+ const dyValue = field.toDy(newValue);
550
+ dyUpdatesToSave[key] = dyValue;
551
+ indexComputationData[key] = dyValue;
552
+ }
553
+ }
554
+ }
555
+ }
432
556
 
433
- let currentItem = instanceObj;
434
- if (isNew) {
435
- currentItem = null;
436
- } else if (!currentItem) {
557
+ // An update by id reads the current row only when the write depends on
558
+ // it (see _updateNeedsCurrentItem). Otherwise the UpdateItem carries an
559
+ // attribute_exists guard instead, so a missing row still surfaces as
560
+ // ItemNotFoundError rather than being upserted as a partial row.
561
+ let existsGuard = false;
562
+ if (!isNew && !currentItem) {
563
+ if (this._updateNeedsCurrentItem(dyUpdatesToSave, { forceReindex })) {
437
564
  currentItem = await this.find(primaryId, { batchDelay: 0 });
438
- if (currentItem && currentItem.exists()) {
439
- consumedCapacity = [
440
- ...consumedCapacity,
441
- ...currentItem.getConsumedCapacity(),
442
- ];
443
- } else {
565
+ if (!currentItem.exists()) {
444
566
  throw new ItemNotFoundError("Item not found", primaryId);
445
567
  }
568
+ consumedCapacity = [
569
+ ...consumedCapacity,
570
+ ...currentItem.getConsumedCapacity(),
571
+ ];
572
+ } else {
573
+ existsGuard = true;
446
574
  }
575
+ }
447
576
 
448
- if (!isNew && !currentItem) {
449
- throw new ItemNotFoundError("Item not found", primaryId);
577
+ // A relative counter ("+3") is written with ADD, which DynamoDB applies
578
+ // at write time, but an index key built from it needs the resulting
579
+ // number. On a new item ADD just stores the delta, so write that. On an
580
+ // existing item, a counter that's part of an index key is written as
581
+ // the loaded value plus the delta, guarded on the loaded value, so a
582
+ // concurrent change fails the update (ConditionalError) instead of
583
+ // leaving the index key stale. Other counters keep the atomic ADD.
584
+ const counterGuards = [];
585
+ const { CounterFieldClass } = require("../fields");
586
+ for (const [key, field] of Object.entries(this.fields)) {
587
+ const dyValue = dyUpdatesToSave[key];
588
+ if (
589
+ !(field instanceof CounterFieldClass) ||
590
+ typeof dyValue !== "string"
591
+ ) {
592
+ continue;
450
593
  }
594
+ const delta = parseInt(dyValue, 10);
595
+ let value;
596
+ if (isNew) {
597
+ value = delta;
598
+ } else if (
599
+ Object.values(this.indexes).some(
600
+ (index) =>
601
+ index.indexId !== undefined &&
602
+ (index.pk === key || index.sk === key),
603
+ )
604
+ ) {
605
+ const loadedValue = currentItem._loadedDyData[key];
606
+ value = Number(loadedValue ?? 0) + delta;
607
+ counterGuards.push({ fieldName: key, loadedValue });
608
+ } else {
609
+ continue;
610
+ }
611
+ dyUpdatesToSave[key] = value;
612
+ indexComputationData[key] = value;
613
+ }
451
614
 
452
- const transactItems = [];
453
- const dyUpdatesToSave = {};
454
- const indexComputationData = {};
455
- let hasUniqueConstraintChanges = false;
456
-
457
- logger.debug("jsUpdates", jsUpdates);
458
-
459
- // Generate Dynamo Updates to save
460
- for (const [key, field] of Object.entries(this.fields)) {
461
- if (isNew && jsUpdates[key] === undefined) {
462
- // Only set initial values during creation
463
- const initialValue = field.getInitialValue();
464
- if (initialValue !== undefined) {
465
- jsUpdates[key] = initialValue;
615
+ // Backfill from currentItem for GSI consistency
616
+ if (!isNew && currentItem) {
617
+ if (forceReindex) {
618
+ // forceReindex: backfill all fields from current item
619
+ Object.keys(this.fields).forEach((fieldName) => {
620
+ const currentValue = currentItem._dyData[fieldName];
621
+ if (
622
+ currentValue !== undefined &&
623
+ indexComputationData[fieldName] === undefined
624
+ ) {
625
+ indexComputationData[fieldName] = currentValue;
466
626
  }
467
- }
468
-
469
- if (jsUpdates[key] !== undefined) {
470
- field.validate(jsUpdates[key]);
471
- const dyValue = field.toDy(jsUpdates[key]);
472
- dyUpdatesToSave[key] = dyValue;
473
- indexComputationData[key] = dyValue;
474
- } else {
475
- if (typeof field.updateBeforeSave === "function") {
476
- const newValue = field.updateBeforeSave(jsUpdates[key]);
477
- if (newValue !== jsUpdates[key]) {
478
- const dyValue = field.toDy(newValue);
479
- dyUpdatesToSave[key] = dyValue;
480
- indexComputationData[key] = dyValue;
627
+ });
628
+ } else {
629
+ // Regular update: backfill GSI counterpart fields so indexes
630
+ // stay consistent when only one field of a key pair is updated
631
+ Object.entries(this.indexes).forEach(([, index]) => {
632
+ const pkField = index.pk;
633
+ const skField = index.sk;
634
+ const pkInUpdate =
635
+ pkField === "modelPrefix" ||
636
+ indexComputationData[pkField] !== undefined;
637
+ const skInUpdate =
638
+ skField === "modelPrefix" ||
639
+ indexComputationData[skField] !== undefined;
640
+
641
+ if (pkInUpdate && !skInUpdate && skField !== "modelPrefix") {
642
+ const currentValue = currentItem._dyData[skField];
643
+ if (currentValue !== undefined) {
644
+ indexComputationData[skField] = currentValue;
481
645
  }
482
646
  }
483
- }
647
+ if (skInUpdate && !pkInUpdate && pkField !== "modelPrefix") {
648
+ const currentValue = currentItem._dyData[pkField];
649
+ if (currentValue !== undefined) {
650
+ indexComputationData[pkField] = currentValue;
651
+ }
652
+ }
653
+ });
484
654
  }
655
+ }
656
+
657
+ if (isNew) {
658
+ primaryId = this._createNewPrimaryId(jsUpdates);
485
659
 
486
- // A relative counter ("+3") is written with ADD, which DynamoDB applies
487
- // at write time, but an index key built from it needs the resulting
488
- // number. On a new item ADD just stores the delta, so write that. On an
489
- // existing item, a counter that's part of an index key is written as
490
- // the loaded value plus the delta, guarded on the loaded value, so a
491
- // concurrent change fails the update (ConditionalError) instead of
492
- // leaving the index key stale. Other counters keep the atomic ADD.
493
- const counterGuards = [];
494
- const { CounterFieldClass } = require("../fields");
495
- for (const [key, field] of Object.entries(this.fields)) {
496
- const dyValue = dyUpdatesToSave[key];
660
+ // validate required fields
661
+ for (const [fieldName, field] of Object.entries(this.fields)) {
497
662
  if (
498
- !(field instanceof CounterFieldClass) ||
499
- typeof dyValue !== "string"
663
+ field.required &&
664
+ (jsUpdates[fieldName] === undefined || jsUpdates[fieldName] === null)
500
665
  ) {
501
- continue;
502
- }
503
- const delta = parseInt(dyValue, 10);
504
- let value;
505
- if (isNew) {
506
- value = delta;
507
- } else if (
508
- Object.values(this.indexes).some(
509
- (index) =>
510
- index.indexId !== undefined &&
511
- (index.pk === key || index.sk === key),
512
- )
513
- ) {
514
- const loadedValue = currentItem._loadedDyData[key];
515
- value = Number(loadedValue ?? 0) + delta;
516
- counterGuards.push({ fieldName: key, loadedValue });
517
- } else {
518
- continue;
666
+ throw new ValidationError(
667
+ `Field is required: ${fieldName}`,
668
+ fieldName,
669
+ jsUpdates[fieldName],
670
+ );
519
671
  }
520
- dyUpdatesToSave[key] = value;
521
- indexComputationData[key] = value;
522
672
  }
673
+ }
523
674
 
524
- // Backfill from currentItem for GSI consistency
525
- if (!isNew && currentItem) {
526
- if (forceReindex) {
527
- // forceReindex: backfill all fields from current item
528
- Object.keys(this.fields).forEach((fieldName) => {
529
- const currentValue = currentItem._dyData[fieldName];
530
- if (
531
- currentValue !== undefined &&
532
- indexComputationData[fieldName] === undefined
533
- ) {
534
- indexComputationData[fieldName] = currentValue;
535
- }
536
- });
537
- } else {
538
- // Regular update: backfill GSI counterpart fields so indexes
539
- // stay consistent when only one field of a key pair is updated
540
- Object.entries(this.indexes).forEach(([, index]) => {
541
- const pkField = index.pk;
542
- const skField = index.sk;
543
- const pkInUpdate =
544
- pkField === "modelPrefix" ||
545
- indexComputationData[pkField] !== undefined;
546
- const skInUpdate =
547
- skField === "modelPrefix" ||
548
- indexComputationData[skField] !== undefined;
549
-
550
- if (pkInUpdate && !skInUpdate && skField !== "modelPrefix") {
551
- const currentValue = currentItem._dyData[skField];
552
- if (currentValue !== undefined) {
553
- indexComputationData[skField] = currentValue;
554
- }
555
- }
556
- if (skInUpdate && !pkInUpdate && pkField !== "modelPrefix") {
557
- const currentValue = currentItem._dyData[pkField];
558
- if (currentValue !== undefined) {
559
- indexComputationData[pkField] = currentValue;
560
- }
561
- }
562
- });
563
- }
675
+ Object.entries(jsUpdates).forEach(([fieldName, value]) => {
676
+ const field = this._getField(fieldName);
677
+ if (field) {
678
+ field.validate(value, fieldName);
564
679
  }
680
+ });
565
681
 
566
- if (isNew) {
567
- primaryId = this._createNewPrimaryId(jsUpdates);
682
+ // No pre-save uniqueness read: each constraint Put in the transaction
683
+ // carries attribute_not_exists, and the catch block below runs
684
+ // _validateUniqueConstraints to name the colliding field.
568
685
 
569
- // validate required fields
570
- for (const [fieldName, field] of Object.entries(this.fields)) {
571
- if (
572
- field.required &&
573
- (jsUpdates[fieldName] === undefined ||
574
- jsUpdates[fieldName] === null)
575
- ) {
576
- throw new ValidationError(
577
- `Field is required: ${fieldName}`,
686
+ // Handle unique constraints
687
+ for (const constraint of Object.values(this.uniqueConstraints || {})) {
688
+ const fieldName = constraint.field;
689
+ const field = this._getField(fieldName);
690
+ const dyNewValue = dyUpdatesToSave[fieldName];
691
+ const dyCurrentValue = currentItem?._loadedDyData[fieldName];
692
+
693
+ logger.debug("uniqueConstraint", field, dyCurrentValue, dyNewValue);
694
+
695
+ if (dyNewValue !== undefined && dyNewValue !== dyCurrentValue) {
696
+ hasUniqueConstraintChanges = true;
697
+
698
+ // Remove old constraint if updating
699
+ if (currentItem && dyCurrentValue) {
700
+ transactItems.push(
701
+ await this._removeUniqueConstraint(
578
702
  fieldName,
579
- jsUpdates[fieldName],
580
- );
581
- }
703
+ dyCurrentValue,
704
+ primaryId,
705
+ constraint.constraintId,
706
+ ),
707
+ );
582
708
  }
583
- }
584
709
 
585
- Object.entries(jsUpdates).forEach(([fieldName, value]) => {
586
- const field = this._getField(fieldName);
587
- if (field) {
588
- field.validate(value, fieldName);
710
+ // Add new constraint unless value is null (clearing field removes constraint)
711
+ if (dyNewValue !== null) {
712
+ transactItems.push(
713
+ await this._createUniqueConstraint(
714
+ fieldName,
715
+ dyNewValue,
716
+ primaryId,
717
+ constraint.constraintId,
718
+ ),
719
+ );
589
720
  }
590
- });
721
+ }
722
+ }
591
723
 
592
- // No pre-save uniqueness read: each constraint Put in the transaction
593
- // carries attribute_not_exists, and the catch block below runs
594
- // _validateUniqueConstraints to name the colliding field.
595
-
596
- // Handle unique constraints
597
- for (const constraint of Object.values(this.uniqueConstraints || {})) {
598
- const fieldName = constraint.field;
599
- const field = this._getField(fieldName);
600
- const dyNewValue = dyUpdatesToSave[fieldName];
601
- const dyCurrentValue = currentItem?._loadedDyData[fieldName];
602
-
603
- logger.debug("uniqueConstraint", field, dyCurrentValue, dyNewValue);
604
-
605
- if (dyNewValue !== undefined && dyNewValue !== dyCurrentValue) {
606
- hasUniqueConstraintChanges = true;
607
-
608
- // Remove old constraint if updating
609
- if (currentItem && dyCurrentValue) {
610
- transactItems.push(
611
- await this._removeUniqueConstraint(
612
- fieldName,
613
- dyCurrentValue,
614
- primaryId,
615
- constraint.constraintId,
616
- ),
617
- );
618
- }
724
+ // Add GSI keys
725
+ const indexSourceData = Object.keys(indexComputationData).length
726
+ ? indexComputationData
727
+ : dyUpdatesToSave;
619
728
 
620
- // Add new constraint unless value is null (clearing field removes constraint)
621
- if (dyNewValue !== null) {
622
- transactItems.push(
623
- await this._createUniqueConstraint(
624
- fieldName,
625
- dyNewValue,
626
- primaryId,
627
- constraint.constraintId,
628
- ),
629
- );
630
- }
631
- }
632
- }
729
+ const indexKeys = this._getIndexKeys(indexSourceData, {
730
+ isUpdate: !isNew,
731
+ });
732
+ logger.debug("indexKeys", indexKeys);
733
+ Object.assign(dyUpdatesToSave, indexKeys);
633
734
 
634
- // Add GSI keys
635
- const indexSourceData = Object.keys(indexComputationData).length
636
- ? indexComputationData
637
- : dyUpdatesToSave;
735
+ // Add iteration keys if model is iterable
736
+ if (this.iterable) {
737
+ const iterationKeys = this._getIterationKeys(primaryId, dyUpdatesToSave);
738
+ Object.assign(dyUpdatesToSave, iterationKeys);
739
+ }
638
740
 
639
- const indexKeys = this._getIndexKeys(indexSourceData, {
640
- isUpdate: !isNew,
741
+ // Compute _searchText if the model is searchable. Returns undefined to
742
+ // skip the write entirely, null to REMOVE, or a string to SET.
743
+ if (this.searchable && this.searchConfig) {
744
+ const searchTextValue = computeSearchTextUpdate({
745
+ searchConfig: this.searchConfig,
746
+ dyUpdatesToSave,
747
+ currentItem,
748
+ isNew,
749
+ forceReindex,
641
750
  });
642
- logger.debug("indexKeys", indexKeys);
643
- Object.assign(dyUpdatesToSave, indexKeys);
644
-
645
- // Add iteration keys if model is iterable
646
- if (this.iterable) {
647
- const iterationKeys = this._getIterationKeys(
648
- primaryId,
649
- dyUpdatesToSave,
650
- );
651
- Object.assign(dyUpdatesToSave, iterationKeys);
751
+ if (searchTextValue !== undefined) {
752
+ dyUpdatesToSave[SEARCH_TEXT_FIELD] = searchTextValue;
652
753
  }
754
+ }
653
755
 
654
- // Compute _searchText if the model is searchable. Returns undefined to
655
- // skip the write entirely, null to REMOVE, or a string to SET.
656
- if (this.searchable && this.searchConfig) {
657
- const searchTextValue = computeSearchTextUpdate({
658
- searchConfig: this.searchConfig,
659
- dyUpdatesToSave,
660
- currentItem,
661
- isNew,
662
- forceReindex,
663
- });
664
- if (searchTextValue !== undefined) {
665
- dyUpdatesToSave[SEARCH_TEXT_FIELD] = searchTextValue;
666
- }
667
- }
756
+ // Build the update expression first
757
+ const { updateExpression, names, values, hasAtomicOps } =
758
+ this._buildUpdateExpression(dyUpdatesToSave, currentItem);
759
+
760
+ // Key to write to. Normally the canonical key. But for an EXISTING
761
+ // `pk === "modelPrefix"` row in "migrating" mode, write in place at the
762
+ // row's current (possibly legacy) key so we update the full row rather
763
+ // than create a partial duplicate at the canonical key. The backfill is
764
+ // what relocates rows to the canonical key; deletes already target the
765
+ // loaded key. New items always use the canonical key.
766
+ let writeKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
767
+ let inPlaceMigratingUpdate = false;
768
+ if (
769
+ !isNew &&
770
+ this.primaryKey.pk === "modelPrefix" &&
771
+ this._modelPrefixPkMode() === "migrating" &&
772
+ currentItem?._dyData?._pk
773
+ ) {
774
+ writeKey = {
775
+ _pk: currentItem._dyData._pk,
776
+ _sk: currentItem._dyData._sk,
777
+ };
778
+ inPlaceMigratingUpdate = true;
779
+ }
668
780
 
669
- // Build the update expression first
670
- const { updateExpression, names, values } = this._buildUpdateExpression(
671
- dyUpdatesToSave,
672
- currentItem,
673
- );
781
+ // Create the base update params
782
+ const updateParams = {
783
+ TableName: this.table,
784
+ Key: writeKey,
785
+ UpdateExpression: updateExpression,
786
+ ReturnValues: "ALL_NEW",
787
+ };
674
788
 
675
- // Key to write to. Normally the canonical key. But for an EXISTING
676
- // `pk === "modelPrefix"` row in "migrating" mode, write in place at the
677
- // row's current (possibly legacy) key so we update the full row rather
678
- // than create a partial duplicate at the canonical key. The backfill is
679
- // what relocates rows to the canonical key; deletes already target the
680
- // loaded key. New items always use the canonical key.
681
- let writeKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
682
- let inPlaceMigratingUpdate = false;
683
- if (
684
- !isNew &&
685
- this.primaryKey.pk === "modelPrefix" &&
686
- this._modelPrefixPkMode() === "migrating" &&
687
- currentItem?._dyData?._pk
688
- ) {
689
- writeKey = {
690
- _pk: currentItem._dyData._pk,
691
- _sk: currentItem._dyData._sk,
692
- };
693
- inPlaceMigratingUpdate = true;
694
- }
789
+ if (Object.keys(names).length > 0) {
790
+ updateParams.ExpressionAttributeNames = {
791
+ ...names,
792
+ };
793
+ }
695
794
 
696
- // Create the base update params
697
- const updateParams = {
698
- TableName: this.table,
699
- Key: writeKey,
700
- UpdateExpression: updateExpression,
701
- ReturnValues: "ALL_NEW",
795
+ if (Object.keys(values).length > 0) {
796
+ updateParams.ExpressionAttributeValues = {
797
+ ...values,
702
798
  };
799
+ }
800
+
801
+ // Build the condition expression for the update/put
802
+ const conditionExpressions = [];
803
+ const conditionNames = {};
804
+ const conditionValues = {};
703
805
 
704
- if (Object.keys(names).length > 0) {
806
+ if (options.condition) {
807
+ const builder = new FilterExpressionBuilder();
808
+ const filterExpression = builder.build(options.condition, this);
809
+
810
+ if (filterExpression) {
811
+ updateParams.ConditionExpression = filterExpression.FilterExpression;
705
812
  updateParams.ExpressionAttributeNames = {
706
- ...names,
813
+ ...updateParams.ExpressionAttributeNames,
814
+ ...filterExpression.ExpressionAttributeNames,
707
815
  };
708
- }
709
-
710
- if (Object.keys(values).length > 0) {
711
816
  updateParams.ExpressionAttributeValues = {
712
- ...values,
817
+ ...updateParams.ExpressionAttributeValues,
818
+ ...filterExpression.ExpressionAttributeValues,
713
819
  };
714
820
  }
821
+ }
715
822
 
716
- // Build the condition expression for the update/put
717
- const conditionExpressions = [];
718
- const conditionNames = {};
719
- const conditionValues = {};
720
-
721
- if (options.condition) {
722
- const builder = new FilterExpressionBuilder();
723
- const filterExpression = builder.build(options.condition, this);
724
-
725
- if (filterExpression) {
726
- updateParams.ConditionExpression = filterExpression.FilterExpression;
727
- updateParams.ExpressionAttributeNames = {
728
- ...updateParams.ExpressionAttributeNames,
729
- ...filterExpression.ExpressionAttributeNames,
730
- };
731
- updateParams.ExpressionAttributeValues = {
732
- ...updateParams.ExpressionAttributeValues,
733
- ...filterExpression.ExpressionAttributeValues,
734
- };
735
- }
736
- }
823
+ if (isNew) {
824
+ // For new items, ensure they don't already exist, ANDed with any
825
+ // caller-supplied condition. _buildUpdateExpression maps each field
826
+ // to "#<fieldName>"; user field names can't start with "_" and no
827
+ // system field starts with "__", so a "#__" placeholder can't clobber
828
+ // one.
829
+ updateParams.ConditionExpression = andCondition(
830
+ updateParams.ConditionExpression,
831
+ "attribute_not_exists(#__newItemPk)",
832
+ );
833
+ updateParams.ExpressionAttributeNames = {
834
+ ...updateParams.ExpressionAttributeNames,
835
+ "#__newItemPk": "_pk",
836
+ };
837
+ }
737
838
 
738
- if (isNew) {
739
- // For new items, ensure they don't already exist, ANDed with any
740
- // caller-supplied condition. _buildUpdateExpression maps each field
741
- // to "#<fieldName>"; user field names can't start with "_" and no
742
- // system field starts with "__", so a "#__" placeholder can't clobber
743
- // one.
744
- updateParams.ConditionExpression = updateParams.ConditionExpression
745
- ? `(${updateParams.ConditionExpression}) AND attribute_not_exists(#__newItemPk)`
746
- : "attribute_not_exists(#__newItemPk)";
747
- updateParams.ExpressionAttributeNames = {
748
- ...updateParams.ExpressionAttributeNames,
749
- "#__newItemPk": "_pk",
750
- };
751
- }
839
+ if (existsGuard) {
840
+ this._addExistsGuard(updateParams);
841
+ }
752
842
 
753
- if (inPlaceMigratingUpdate) {
754
- // Updating the row in place at its current (legacy) key. Guard with
755
- // attribute_exists so a concurrent backfill that relocated/deleted the
756
- // legacy row can't make this UpdateItem upsert a partial row — it fails
757
- // loudly (ConditionalError) instead, and the caller can retry, which
758
- // will then find and update the relocated canonical row. ANDed with any
759
- // caller-supplied condition.
760
- //
761
- // Use a "#__" placeholder so we never clobber a field placeholder
762
- // (see the new-item guard above).
763
- updateParams.ExpressionAttributeNames = {
764
- ...updateParams.ExpressionAttributeNames,
765
- "#__migExistsPk": "_pk",
766
- };
767
- updateParams.ConditionExpression = updateParams.ConditionExpression
768
- ? `(${updateParams.ConditionExpression}) AND attribute_exists(#__migExistsPk)`
769
- : "attribute_exists(#__migExistsPk)";
770
- }
843
+ if (inPlaceMigratingUpdate) {
844
+ // Updating the row in place at its current (legacy) key. Guard with
845
+ // attribute_exists so a concurrent backfill that relocated/deleted the
846
+ // legacy row can't make this UpdateItem upsert a partial row — it fails
847
+ // loudly (ConditionalError) instead, and the caller can retry, which
848
+ // will then find and update the relocated canonical row. ANDed with any
849
+ // caller-supplied condition.
850
+ //
851
+ // Use a "#__" placeholder so we never clobber a field placeholder
852
+ // (see the new-item guard above).
853
+ updateParams.ExpressionAttributeNames = {
854
+ ...updateParams.ExpressionAttributeNames,
855
+ "#__migExistsPk": "_pk",
856
+ };
857
+ updateParams.ConditionExpression = andCondition(
858
+ updateParams.ConditionExpression,
859
+ "attribute_exists(#__migExistsPk)",
860
+ );
861
+ }
771
862
 
772
- for (const { fieldName, loadedValue } of counterGuards) {
773
- const name = `#__counterGuard_${fieldName}`;
774
- const value = `:__counterGuard_${fieldName}`;
775
- updateParams.ExpressionAttributeNames = {
776
- ...updateParams.ExpressionAttributeNames,
777
- [name]: fieldName,
863
+ for (const { fieldName, loadedValue } of counterGuards) {
864
+ const name = `#__counterGuard_${fieldName}`;
865
+ const value = `:__counterGuard_${fieldName}`;
866
+ updateParams.ExpressionAttributeNames = {
867
+ ...updateParams.ExpressionAttributeNames,
868
+ [name]: fieldName,
869
+ };
870
+ let guard = `attribute_not_exists(${name})`;
871
+ if (loadedValue != null) {
872
+ guard = `${name} = ${value}`;
873
+ updateParams.ExpressionAttributeValues = {
874
+ ...updateParams.ExpressionAttributeValues,
875
+ [value]: loadedValue,
778
876
  };
779
- let guard = `attribute_not_exists(${name})`;
780
- if (loadedValue != null) {
781
- guard = `${name} = ${value}`;
782
- updateParams.ExpressionAttributeValues = {
783
- ...updateParams.ExpressionAttributeValues,
784
- [value]: loadedValue,
785
- };
786
- }
787
- updateParams.ConditionExpression = updateParams.ConditionExpression
788
- ? `(${updateParams.ConditionExpression}) AND ${guard}`
789
- : guard;
790
877
  }
878
+ updateParams.ConditionExpression = andCondition(
879
+ updateParams.ConditionExpression,
880
+ guard,
881
+ );
882
+ }
791
883
 
792
- const dyKey = writeKey;
793
- logger.debug("dyKey", dyKey);
884
+ const dyKey = writeKey;
885
+ logger.debug("dyKey", dyKey);
794
886
 
795
- try {
796
- let response;
887
+ try {
888
+ let response;
797
889
 
798
- if (hasUniqueConstraintChanges) {
799
- // Use transaction if we have unique constraint changes
800
- transactItems.push({
801
- Update: updateParams,
802
- });
890
+ if (hasUniqueConstraintChanges) {
891
+ // Use transaction if we have unique constraint changes
892
+ transactItems.push({
893
+ Update: updateParams,
894
+ });
803
895
 
896
+ if (logger.isDebugEnabled()) {
804
897
  logger.debug("transactItems", JSON.stringify(transactItems, null, 2));
898
+ }
805
899
 
806
- response = await retryOperation(() =>
807
- this.documentClient.send(
808
- new TransactWriteCommand({
809
- TransactItems: transactItems,
810
- ReturnConsumedCapacity: "TOTAL",
811
- }),
812
- ),
813
- );
814
-
815
- logger.debug("transactItems response", response);
816
- logger.debug("primaryId to load", primaryId);
817
-
818
- // transactWrite doesn't return values. A new item is exactly its key
819
- // plus what we wrote (REMOVEd nulls aside), so build it locally. An
820
- // update must be read back, bypassing the loader cache, which still
821
- // holds the pre-update row.
822
- let savedItem;
823
- if (isNew) {
824
- const storedItem = { ...dyKey };
825
- for (const [key, value] of Object.entries(dyUpdatesToSave)) {
826
- if (value !== undefined && value !== null) {
827
- storedItem[key] = value;
828
- }
829
- }
830
- savedItem = this._createFromDyItem(storedItem);
831
- } else {
832
- const readOptions = { batchDelay: 0, bypassCache: true };
833
- savedItem = await this.find(primaryId, readOptions);
900
+ response = await retryOperation(() =>
901
+ this.documentClient.send(
902
+ new TransactWriteCommand({
903
+ TransactItems: transactItems,
904
+ ReturnConsumedCapacity: "TOTAL",
905
+ }),
906
+ ),
907
+ );
834
908
 
835
- // if the item doesn't exist, sleep for 200ms and try again
836
- if (!savedItem.exists()) {
837
- await new Promise((resolve) => setTimeout(resolve, 200));
838
- savedItem = await this.find(primaryId, readOptions);
909
+ logger.debug("transactItems response", response);
910
+ logger.debug("primaryId to load", primaryId);
911
+
912
+ // transactWrite doesn't return values. When the expression is only
913
+ // SET/REMOVE the written row is fully determined: a new item is its
914
+ // key plus what we wrote, and an update is the row we loaded with
915
+ // our writes applied, so build it locally and save a round trip.
916
+ // Fields this write didn't touch reflect the row as loaded, which
917
+ // is the same staleness a caller-held instance already has. Only
918
+ // an ADD/DELETE (counter, set diff) needs a read-back, bypassing the
919
+ // loader cache, which still holds the pre-update row.
920
+ let savedItem;
921
+ if (isNew || !hasAtomicOps) {
922
+ const base = isNew
923
+ ? {}
924
+ : currentItem.isLoaded()
925
+ ? currentItem._loadedDyData
926
+ : currentItem._dyData;
927
+ const storedItem = { ...base, ...dyKey };
928
+ for (const [key, value] of Object.entries(dyUpdatesToSave)) {
929
+ if (value === undefined) continue;
930
+ if (value === null) {
931
+ delete storedItem[key];
932
+ } else {
933
+ storedItem[key] = value;
839
934
  }
840
935
  }
936
+ savedItem = this._createFromDyItem(storedItem);
937
+ } else {
938
+ const readOptions = { batchDelay: 0, bypassCache: true };
939
+ savedItem = await this.find(primaryId, readOptions);
841
940
 
842
- logger.debug("savedItem", savedItem);
843
-
941
+ // if the item doesn't exist, sleep for 200ms and try again
844
942
  if (!savedItem.exists()) {
845
- throw new ConditionalError("Failed to fetch saved item", "update");
943
+ await new Promise((resolve) => setTimeout(resolve, 200));
944
+ savedItem = await this.find(primaryId, readOptions);
846
945
  }
847
- logger.debug("savedItem.getPrimaryId()", savedItem.getPrimaryId());
946
+ }
848
947
 
849
- // Set the consumed capacity from the transaction
850
- savedItem._addConsumedCapacity(
851
- response.ConsumedCapacity,
852
- "write",
853
- false,
854
- );
855
- // The loaded row's capacity was counted in the request total when
856
- // it was consumed, so don't count it again.
857
- savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
948
+ logger.debug("savedItem", savedItem);
858
949
 
859
- this._primeLoaderContext(primaryId, savedItem);
860
- return savedItem;
861
- } else {
862
- // Use simple update if no unique constraints are changing
863
- logger.debug("updateParams", JSON.stringify(updateParams, null, 2));
950
+ if (!savedItem.exists()) {
951
+ throw new ConditionalError("Failed to fetch saved item", "update");
952
+ }
953
+ logger.debug("savedItem.getPrimaryId()", savedItem.getPrimaryId());
864
954
 
865
- try {
866
- response = await retryOperation(() =>
867
- this.documentClient.send(
868
- new UpdateCommand({
869
- ...updateParams,
870
- ReturnConsumedCapacity: "TOTAL",
871
- }),
872
- ),
873
- );
874
- } catch (error) {
875
- logger.error(`DynamoDB update failed for ${primaryId}:`, error);
876
- throw error;
877
- }
955
+ // Set the consumed capacity from the transaction
956
+ savedItem._addConsumedCapacity(
957
+ response.ConsumedCapacity,
958
+ "write",
959
+ false,
960
+ );
961
+ // The loaded row's capacity was counted in the request total when
962
+ // it was consumed, so don't count it again.
963
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
878
964
 
879
- const savedItem = this._createFromDyItem(response.Attributes);
880
- logger.debug("savedItem", savedItem);
965
+ this._primeLoaderContext(primaryId, savedItem);
966
+ return savedItem;
967
+ } else {
968
+ // Use simple update if no unique constraints are changing
969
+ if (logger.isDebugEnabled()) {
970
+ logger.debug("updateParams", JSON.stringify(updateParams, null, 2));
971
+ }
881
972
 
882
- savedItem._setConsumedCapacity(
883
- response.ConsumedCapacity,
884
- "write",
885
- false,
886
- );
887
- // The loaded row's capacity was counted in the request total when
888
- // it was consumed, so don't count it again.
889
- savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
973
+ response = await retryOperation(() =>
974
+ this.documentClient.send(
975
+ new UpdateCommand({
976
+ ...updateParams,
977
+ ReturnConsumedCapacity: "TOTAL",
978
+ }),
979
+ ),
980
+ );
890
981
 
891
- if (!savedItem.exists()) {
892
- throw new ConditionalError("Failed to fetch saved item", "update");
893
- }
982
+ const savedItem = this._createFromDyItem(response.Attributes);
983
+ logger.debug("savedItem", savedItem);
984
+
985
+ savedItem._setConsumedCapacity(
986
+ response.ConsumedCapacity,
987
+ "write",
988
+ false,
989
+ );
990
+ // The loaded row's capacity was counted in the request total when
991
+ // it was consumed, so don't count it again.
992
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
894
993
 
895
- this._primeLoaderContext(primaryId, savedItem);
896
- return savedItem;
994
+ if (!savedItem.exists()) {
995
+ throw new ConditionalError("Failed to fetch saved item", "update");
897
996
  }
898
- } catch (error) {
899
- logger.error("Error in _saveItem", error);
900
- if (error.name === "ConditionalCheckFailedException") {
901
- throw new ConditionalError("Condition check failed", "update", error);
997
+
998
+ this._primeLoaderContext(primaryId, savedItem);
999
+ return savedItem;
1000
+ }
1001
+ } catch (error) {
1002
+ // A failed condition (caller condition, duplicate key, missing row,
1003
+ // taken unique value) is an expected outcome that is mapped to a
1004
+ // typed error below, so it is only worth a debug line. Anything
1005
+ // else is logged once, here, and rethrown as-is.
1006
+ const isConditionFailure =
1007
+ error.name === "ConditionalCheckFailedException" ||
1008
+ (error.name === "TransactionCanceledException" &&
1009
+ error.CancellationReasons?.some(
1010
+ (reason) => reason.Code === "ConditionalCheckFailed",
1011
+ ));
1012
+ if (isConditionFailure) {
1013
+ logger.debug(`${this.name} save condition failed for`, primaryId);
1014
+ } else {
1015
+ logger.error(`${this.name} save failed for ${primaryId}:`, error);
1016
+ }
1017
+
1018
+ if (error.name === "ConditionalCheckFailedException") {
1019
+ if (
1020
+ existsGuard &&
1021
+ !(await this._existsAfterGuardFailure(primaryId, options))
1022
+ ) {
1023
+ throw new ItemNotFoundError("Item not found", primaryId);
902
1024
  }
1025
+ throw new ConditionalError("Condition check failed", "update", error);
1026
+ }
903
1027
 
904
- if (error.name === "TransactionCanceledException") {
905
- // A taken unique value cancels the transaction; this read throws a
906
- // ConditionalError naming the field if that's the cause.
907
- await this._validateUniqueConstraints(
908
- jsUpdates,
909
- isNew ? null : primaryId,
910
- );
1028
+ if (error.name === "TransactionCanceledException") {
1029
+ // A taken unique value cancels the transaction; this read throws a
1030
+ // ConditionalError naming the field if that's the cause.
1031
+ await this._validateUniqueConstraints(
1032
+ jsUpdates,
1033
+ isNew ? null : primaryId,
1034
+ );
911
1035
 
912
- // Check if it's due to conditional check failure
913
- if (
914
- error.CancellationReasons?.some(
915
- (reason) => reason.Code === "ConditionalCheckFailed",
916
- )
917
- ) {
918
- throw new ConditionalError(
919
- "Transaction cancelled due to condition check failure",
920
- "update",
921
- error,
922
- );
923
- }
1036
+ // Check if it's due to conditional check failure
1037
+ if (
1038
+ error.CancellationReasons?.some(
1039
+ (reason) => reason.Code === "ConditionalCheckFailed",
1040
+ )
1041
+ ) {
1042
+ throw new ConditionalError(
1043
+ "Transaction cancelled due to condition check failure",
1044
+ "update",
1045
+ error,
1046
+ );
924
1047
  }
925
- throw error;
926
1048
  }
927
- } catch (error) {
928
- logger.error(`Error in _saveItem for ${primaryId}:`, error);
929
1049
  throw error;
930
1050
  }
931
1051
  },
932
1052
 
1053
+ /**
1054
+ * Whether an update by id has to read the current row before writing.
1055
+ * The row is needed to backfill the other half of a GSI key pair, to
1056
+ * diff a StringSet, to guard an indexed counter, to compare a unique
1057
+ * constraint's old value, to rebuild _searchText from untouched source
1058
+ * fields, to reindex everything, or (mid key migration) to find the key
1059
+ * the row lives at. A write touching none of those is a plain SET/REMOVE
1060
+ * of the given attributes and can go straight to DynamoDB.
1061
+ * @private
1062
+ * @param {Object} dyUpdatesToSave - Attributes the write will touch
1063
+ * @param {{forceReindex: boolean}} options
1064
+ * @returns {boolean}
1065
+ */
1066
+ _updateNeedsCurrentItem(dyUpdatesToSave, { forceReindex = false } = {}) {
1067
+ if (forceReindex || this._writesInPlaceWhileMigrating()) {
1068
+ return true;
1069
+ }
1070
+
1071
+ const { StringSetFieldClass } = require("../fields");
1072
+ const indexes = Object.values(this.indexes).filter(
1073
+ (index) => index.indexId !== undefined,
1074
+ );
1075
+ for (const fieldName of Object.keys(dyUpdatesToSave)) {
1076
+ if (
1077
+ indexes.some(
1078
+ (index) => index.pk === fieldName || index.sk === fieldName,
1079
+ )
1080
+ ) {
1081
+ return true;
1082
+ }
1083
+ if (this.fields[fieldName] instanceof StringSetFieldClass) {
1084
+ return true;
1085
+ }
1086
+ }
1087
+
1088
+ for (const constraint of Object.values(this.uniqueConstraints || {})) {
1089
+ if (constraint.field in dyUpdatesToSave) return true;
1090
+ }
1091
+
1092
+ if (this.searchable && this.searchConfig) {
1093
+ const searchFields = this.searchConfig.fields || [];
1094
+ if (searchFields.some((f) => f in dyUpdatesToSave)) return true;
1095
+ }
1096
+
1097
+ return false;
1098
+ },
1099
+
933
1100
  _buildUpdateExpression(dyUpdatesToSave, currentItem = null) {
934
1101
  const names = {};
935
1102
  const values = {};
@@ -1018,6 +1185,9 @@ const MutationMethods = {
1018
1185
  updateExpression: parts.join(" "),
1019
1186
  names,
1020
1187
  values,
1188
+ // ADD/DELETE are applied by DynamoDB against the stored value, so the
1189
+ // written row can't be predicted locally; SET/REMOVE can.
1190
+ hasAtomicOps: addExpressions.length > 0 || deleteExpressions.length > 0,
1021
1191
  };
1022
1192
  },
1023
1193