dynamo-bao 0.7.3 → 0.8.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.
@@ -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,598 @@ 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
- }
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
+ // Nothing to backfill when one half is the modelPrefix constant:
635
+ // if the field half is in the update both halves are known, and
636
+ // if it is not, the index key does not change.
637
+ if (pkField === "modelPrefix" || skField === "modelPrefix") {
638
+ return;
639
+ }
640
+ const pkInUpdate = indexComputationData[pkField] !== undefined;
641
+ const skInUpdate = indexComputationData[skField] !== undefined;
468
642
 
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;
643
+ if (pkInUpdate && !skInUpdate) {
644
+ const currentValue = currentItem._dyData[skField];
645
+ if (currentValue !== undefined) {
646
+ indexComputationData[skField] = currentValue;
481
647
  }
482
648
  }
483
- }
649
+ if (skInUpdate && !pkInUpdate) {
650
+ const currentValue = currentItem._dyData[pkField];
651
+ if (currentValue !== undefined) {
652
+ indexComputationData[pkField] = currentValue;
653
+ }
654
+ }
655
+ });
484
656
  }
657
+ }
485
658
 
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];
659
+ if (isNew) {
660
+ primaryId = this._createNewPrimaryId(jsUpdates);
661
+
662
+ // validate required fields
663
+ for (const [fieldName, field] of Object.entries(this.fields)) {
497
664
  if (
498
- !(field instanceof CounterFieldClass) ||
499
- typeof dyValue !== "string"
500
- ) {
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
- )
665
+ field.required &&
666
+ (jsUpdates[fieldName] === undefined || jsUpdates[fieldName] === null)
513
667
  ) {
514
- const loadedValue = currentItem._loadedDyData[key];
515
- value = Number(loadedValue ?? 0) + delta;
516
- counterGuards.push({ fieldName: key, loadedValue });
517
- } else {
518
- continue;
668
+ throw new ValidationError(
669
+ `Field is required: ${fieldName}`,
670
+ fieldName,
671
+ jsUpdates[fieldName],
672
+ );
519
673
  }
520
- dyUpdatesToSave[key] = value;
521
- indexComputationData[key] = value;
522
674
  }
675
+ }
523
676
 
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
- }
677
+ Object.entries(jsUpdates).forEach(([fieldName, value]) => {
678
+ const field = this._getField(fieldName);
679
+ if (field) {
680
+ field.validate(value, fieldName);
564
681
  }
682
+ });
565
683
 
566
- if (isNew) {
567
- primaryId = this._createNewPrimaryId(jsUpdates);
684
+ // No pre-save uniqueness read: each constraint Put in the transaction
685
+ // carries attribute_not_exists, and the catch block below runs
686
+ // _validateUniqueConstraints to name the colliding field.
568
687
 
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}`,
688
+ // Handle unique constraints
689
+ for (const constraint of Object.values(this.uniqueConstraints || {})) {
690
+ const fieldName = constraint.field;
691
+ const field = this._getField(fieldName);
692
+ const dyNewValue = dyUpdatesToSave[fieldName];
693
+ const dyCurrentValue = currentItem?._loadedDyData[fieldName];
694
+
695
+ logger.debug("uniqueConstraint", field, dyCurrentValue, dyNewValue);
696
+
697
+ if (dyNewValue !== undefined && dyNewValue !== dyCurrentValue) {
698
+ hasUniqueConstraintChanges = true;
699
+
700
+ // Remove old constraint if updating
701
+ if (currentItem && dyCurrentValue) {
702
+ transactItems.push(
703
+ await this._removeUniqueConstraint(
578
704
  fieldName,
579
- jsUpdates[fieldName],
580
- );
581
- }
705
+ dyCurrentValue,
706
+ primaryId,
707
+ constraint.constraintId,
708
+ ),
709
+ );
582
710
  }
583
- }
584
711
 
585
- Object.entries(jsUpdates).forEach(([fieldName, value]) => {
586
- const field = this._getField(fieldName);
587
- if (field) {
588
- field.validate(value, fieldName);
712
+ // Add new constraint unless value is null (clearing field removes constraint)
713
+ if (dyNewValue !== null) {
714
+ transactItems.push(
715
+ await this._createUniqueConstraint(
716
+ fieldName,
717
+ dyNewValue,
718
+ primaryId,
719
+ constraint.constraintId,
720
+ ),
721
+ );
589
722
  }
590
- });
723
+ }
724
+ }
591
725
 
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
- }
726
+ // Add GSI keys
727
+ const indexSourceData = Object.keys(indexComputationData).length
728
+ ? indexComputationData
729
+ : dyUpdatesToSave;
619
730
 
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
- }
731
+ const indexKeys = this._getIndexKeys(indexSourceData, {
732
+ isUpdate: !isNew,
733
+ });
734
+ logger.debug("indexKeys", indexKeys);
735
+ Object.assign(dyUpdatesToSave, indexKeys);
633
736
 
634
- // Add GSI keys
635
- const indexSourceData = Object.keys(indexComputationData).length
636
- ? indexComputationData
637
- : dyUpdatesToSave;
737
+ // Add iteration keys if model is iterable
738
+ if (this.iterable) {
739
+ const iterationKeys = this._getIterationKeys(primaryId, dyUpdatesToSave);
740
+ Object.assign(dyUpdatesToSave, iterationKeys);
741
+ }
638
742
 
639
- const indexKeys = this._getIndexKeys(indexSourceData, {
640
- isUpdate: !isNew,
743
+ // Compute _searchText if the model is searchable. Returns undefined to
744
+ // skip the write entirely, null to REMOVE, or a string to SET.
745
+ if (this.searchable && this.searchConfig) {
746
+ const searchTextValue = computeSearchTextUpdate({
747
+ searchConfig: this.searchConfig,
748
+ dyUpdatesToSave,
749
+ currentItem,
750
+ isNew,
751
+ forceReindex,
641
752
  });
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);
753
+ if (searchTextValue !== undefined) {
754
+ dyUpdatesToSave[SEARCH_TEXT_FIELD] = searchTextValue;
652
755
  }
756
+ }
653
757
 
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
- }
758
+ // Build the update expression first
759
+ const { updateExpression, names, values, hasAtomicOps } =
760
+ this._buildUpdateExpression(dyUpdatesToSave, currentItem);
761
+
762
+ // Key to write to. Normally the canonical key. But for an EXISTING
763
+ // `pk === "modelPrefix"` row in "migrating" mode, write in place at the
764
+ // row's current (possibly legacy) key so we update the full row rather
765
+ // than create a partial duplicate at the canonical key. The backfill is
766
+ // what relocates rows to the canonical key; deletes already target the
767
+ // loaded key. New items always use the canonical key.
768
+ let writeKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
769
+ let inPlaceMigratingUpdate = false;
770
+ if (
771
+ !isNew &&
772
+ this.primaryKey.pk === "modelPrefix" &&
773
+ this._modelPrefixPkMode() === "migrating" &&
774
+ currentItem?._dyData?._pk
775
+ ) {
776
+ writeKey = {
777
+ _pk: currentItem._dyData._pk,
778
+ _sk: currentItem._dyData._sk,
779
+ };
780
+ inPlaceMigratingUpdate = true;
781
+ }
668
782
 
669
- // Build the update expression first
670
- const { updateExpression, names, values } = this._buildUpdateExpression(
671
- dyUpdatesToSave,
672
- currentItem,
673
- );
783
+ // Create the base update params
784
+ const updateParams = {
785
+ TableName: this.table,
786
+ Key: writeKey,
787
+ UpdateExpression: updateExpression,
788
+ ReturnValues: "ALL_NEW",
789
+ };
674
790
 
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
- }
791
+ if (Object.keys(names).length > 0) {
792
+ updateParams.ExpressionAttributeNames = {
793
+ ...names,
794
+ };
795
+ }
695
796
 
696
- // Create the base update params
697
- const updateParams = {
698
- TableName: this.table,
699
- Key: writeKey,
700
- UpdateExpression: updateExpression,
701
- ReturnValues: "ALL_NEW",
797
+ if (Object.keys(values).length > 0) {
798
+ updateParams.ExpressionAttributeValues = {
799
+ ...values,
702
800
  };
801
+ }
802
+
803
+ // Build the condition expression for the update/put
804
+ const conditionExpressions = [];
805
+ const conditionNames = {};
806
+ const conditionValues = {};
807
+
808
+ if (options.condition) {
809
+ const builder = new FilterExpressionBuilder();
810
+ const filterExpression = builder.build(options.condition, this);
703
811
 
704
- if (Object.keys(names).length > 0) {
812
+ if (filterExpression) {
813
+ updateParams.ConditionExpression = filterExpression.FilterExpression;
705
814
  updateParams.ExpressionAttributeNames = {
706
- ...names,
815
+ ...updateParams.ExpressionAttributeNames,
816
+ ...filterExpression.ExpressionAttributeNames,
707
817
  };
708
- }
709
-
710
- if (Object.keys(values).length > 0) {
711
818
  updateParams.ExpressionAttributeValues = {
712
- ...values,
819
+ ...updateParams.ExpressionAttributeValues,
820
+ ...filterExpression.ExpressionAttributeValues,
713
821
  };
714
822
  }
823
+ }
715
824
 
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
- }
825
+ if (isNew) {
826
+ // For new items, ensure they don't already exist, ANDed with any
827
+ // caller-supplied condition. _buildUpdateExpression maps each field
828
+ // to "#<fieldName>"; user field names can't start with "_" and no
829
+ // system field starts with "__", so a "#__" placeholder can't clobber
830
+ // one.
831
+ updateParams.ConditionExpression = andCondition(
832
+ updateParams.ConditionExpression,
833
+ "attribute_not_exists(#__newItemPk)",
834
+ );
835
+ updateParams.ExpressionAttributeNames = {
836
+ ...updateParams.ExpressionAttributeNames,
837
+ "#__newItemPk": "_pk",
838
+ };
839
+ }
737
840
 
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
- }
841
+ if (existsGuard) {
842
+ this._addExistsGuard(updateParams);
843
+ }
752
844
 
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
- }
845
+ if (inPlaceMigratingUpdate) {
846
+ // Updating the row in place at its current (legacy) key. Guard with
847
+ // attribute_exists so a concurrent backfill that relocated/deleted the
848
+ // legacy row can't make this UpdateItem upsert a partial row — it fails
849
+ // loudly (ConditionalError) instead, and the caller can retry, which
850
+ // will then find and update the relocated canonical row. ANDed with any
851
+ // caller-supplied condition.
852
+ //
853
+ // Use a "#__" placeholder so we never clobber a field placeholder
854
+ // (see the new-item guard above).
855
+ updateParams.ExpressionAttributeNames = {
856
+ ...updateParams.ExpressionAttributeNames,
857
+ "#__migExistsPk": "_pk",
858
+ };
859
+ updateParams.ConditionExpression = andCondition(
860
+ updateParams.ConditionExpression,
861
+ "attribute_exists(#__migExistsPk)",
862
+ );
863
+ }
771
864
 
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,
865
+ for (const { fieldName, loadedValue } of counterGuards) {
866
+ const name = `#__counterGuard_${fieldName}`;
867
+ const value = `:__counterGuard_${fieldName}`;
868
+ updateParams.ExpressionAttributeNames = {
869
+ ...updateParams.ExpressionAttributeNames,
870
+ [name]: fieldName,
871
+ };
872
+ let guard = `attribute_not_exists(${name})`;
873
+ if (loadedValue != null) {
874
+ guard = `${name} = ${value}`;
875
+ updateParams.ExpressionAttributeValues = {
876
+ ...updateParams.ExpressionAttributeValues,
877
+ [value]: loadedValue,
778
878
  };
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
879
  }
880
+ updateParams.ConditionExpression = andCondition(
881
+ updateParams.ConditionExpression,
882
+ guard,
883
+ );
884
+ }
791
885
 
792
- const dyKey = writeKey;
793
- logger.debug("dyKey", dyKey);
886
+ const dyKey = writeKey;
887
+ logger.debug("dyKey", dyKey);
794
888
 
795
- try {
796
- let response;
889
+ try {
890
+ let response;
797
891
 
798
- if (hasUniqueConstraintChanges) {
799
- // Use transaction if we have unique constraint changes
800
- transactItems.push({
801
- Update: updateParams,
802
- });
892
+ if (hasUniqueConstraintChanges) {
893
+ // Use transaction if we have unique constraint changes
894
+ transactItems.push({
895
+ Update: updateParams,
896
+ });
803
897
 
898
+ if (logger.isDebugEnabled()) {
804
899
  logger.debug("transactItems", JSON.stringify(transactItems, null, 2));
900
+ }
805
901
 
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);
902
+ response = await retryOperation(() =>
903
+ this.documentClient.send(
904
+ new TransactWriteCommand({
905
+ TransactItems: transactItems,
906
+ ReturnConsumedCapacity: "TOTAL",
907
+ }),
908
+ ),
909
+ );
834
910
 
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);
911
+ logger.debug("transactItems response", response);
912
+ logger.debug("primaryId to load", primaryId);
913
+
914
+ // transactWrite doesn't return values. When the expression is only
915
+ // SET/REMOVE the written row is fully determined: a new item is its
916
+ // key plus what we wrote, and an update is the row we loaded with
917
+ // our writes applied, so build it locally and save a round trip.
918
+ // Fields this write didn't touch reflect the row as loaded, which
919
+ // is the same staleness a caller-held instance already has. Only
920
+ // an ADD/DELETE (counter, set diff) needs a read-back, bypassing the
921
+ // loader cache, which still holds the pre-update row.
922
+ let savedItem;
923
+ if (isNew || !hasAtomicOps) {
924
+ const base = isNew
925
+ ? {}
926
+ : currentItem.isLoaded()
927
+ ? currentItem._loadedDyData
928
+ : currentItem._dyData;
929
+ const storedItem = { ...base, ...dyKey };
930
+ for (const [key, value] of Object.entries(dyUpdatesToSave)) {
931
+ if (value === undefined) continue;
932
+ if (value === null) {
933
+ delete storedItem[key];
934
+ } else {
935
+ storedItem[key] = value;
839
936
  }
840
937
  }
938
+ savedItem = this._createFromDyItem(storedItem);
939
+ } else {
940
+ const readOptions = { batchDelay: 0, bypassCache: true };
941
+ savedItem = await this.find(primaryId, readOptions);
841
942
 
842
- logger.debug("savedItem", savedItem);
843
-
943
+ // if the item doesn't exist, sleep for 200ms and try again
844
944
  if (!savedItem.exists()) {
845
- throw new ConditionalError("Failed to fetch saved item", "update");
945
+ await new Promise((resolve) => setTimeout(resolve, 200));
946
+ savedItem = await this.find(primaryId, readOptions);
846
947
  }
847
- logger.debug("savedItem.getPrimaryId()", savedItem.getPrimaryId());
948
+ }
848
949
 
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);
950
+ logger.debug("savedItem", savedItem);
858
951
 
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));
952
+ if (!savedItem.exists()) {
953
+ throw new ConditionalError("Failed to fetch saved item", "update");
954
+ }
955
+ logger.debug("savedItem.getPrimaryId()", savedItem.getPrimaryId());
864
956
 
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
- }
957
+ // Set the consumed capacity from the transaction
958
+ savedItem._addConsumedCapacity(
959
+ response.ConsumedCapacity,
960
+ "write",
961
+ false,
962
+ );
963
+ // The loaded row's capacity was counted in the request total when
964
+ // it was consumed, so don't count it again.
965
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
878
966
 
879
- const savedItem = this._createFromDyItem(response.Attributes);
880
- logger.debug("savedItem", savedItem);
967
+ this._primeLoaderContext(primaryId, savedItem);
968
+ return savedItem;
969
+ } else {
970
+ // Use simple update if no unique constraints are changing
971
+ if (logger.isDebugEnabled()) {
972
+ logger.debug("updateParams", JSON.stringify(updateParams, null, 2));
973
+ }
881
974
 
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);
975
+ response = await retryOperation(() =>
976
+ this.documentClient.send(
977
+ new UpdateCommand({
978
+ ...updateParams,
979
+ ReturnConsumedCapacity: "TOTAL",
980
+ }),
981
+ ),
982
+ );
890
983
 
891
- if (!savedItem.exists()) {
892
- throw new ConditionalError("Failed to fetch saved item", "update");
893
- }
984
+ const savedItem = this._createFromDyItem(response.Attributes);
985
+ logger.debug("savedItem", savedItem);
986
+
987
+ savedItem._setConsumedCapacity(
988
+ response.ConsumedCapacity,
989
+ "write",
990
+ false,
991
+ );
992
+ // The loaded row's capacity was counted in the request total when
993
+ // it was consumed, so don't count it again.
994
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
894
995
 
895
- this._primeLoaderContext(primaryId, savedItem);
896
- return savedItem;
996
+ if (!savedItem.exists()) {
997
+ throw new ConditionalError("Failed to fetch saved item", "update");
897
998
  }
898
- } catch (error) {
899
- logger.error("Error in _saveItem", error);
900
- if (error.name === "ConditionalCheckFailedException") {
901
- throw new ConditionalError("Condition check failed", "update", error);
999
+
1000
+ this._primeLoaderContext(primaryId, savedItem);
1001
+ return savedItem;
1002
+ }
1003
+ } catch (error) {
1004
+ // A failed condition (caller condition, duplicate key, missing row,
1005
+ // taken unique value) is an expected outcome that is mapped to a
1006
+ // typed error below, so it is only worth a debug line. Anything
1007
+ // else is logged once, here, and rethrown as-is.
1008
+ const isConditionFailure =
1009
+ error.name === "ConditionalCheckFailedException" ||
1010
+ (error.name === "TransactionCanceledException" &&
1011
+ error.CancellationReasons?.some(
1012
+ (reason) => reason.Code === "ConditionalCheckFailed",
1013
+ ));
1014
+ if (isConditionFailure) {
1015
+ logger.debug(`${this.name} save condition failed for`, primaryId);
1016
+ } else {
1017
+ logger.error(`${this.name} save failed for ${primaryId}:`, error);
1018
+ }
1019
+
1020
+ if (error.name === "ConditionalCheckFailedException") {
1021
+ if (
1022
+ existsGuard &&
1023
+ !(await this._existsAfterGuardFailure(primaryId, options))
1024
+ ) {
1025
+ throw new ItemNotFoundError("Item not found", primaryId);
902
1026
  }
1027
+ throw new ConditionalError("Condition check failed", "update", error);
1028
+ }
903
1029
 
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
- );
1030
+ if (error.name === "TransactionCanceledException") {
1031
+ // A taken unique value cancels the transaction; this read throws a
1032
+ // ConditionalError naming the field if that's the cause.
1033
+ await this._validateUniqueConstraints(
1034
+ jsUpdates,
1035
+ isNew ? null : primaryId,
1036
+ );
911
1037
 
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
- }
1038
+ // Check if it's due to conditional check failure
1039
+ if (
1040
+ error.CancellationReasons?.some(
1041
+ (reason) => reason.Code === "ConditionalCheckFailed",
1042
+ )
1043
+ ) {
1044
+ throw new ConditionalError(
1045
+ "Transaction cancelled due to condition check failure",
1046
+ "update",
1047
+ error,
1048
+ );
924
1049
  }
925
- throw error;
926
1050
  }
927
- } catch (error) {
928
- logger.error(`Error in _saveItem for ${primaryId}:`, error);
929
1051
  throw error;
930
1052
  }
931
1053
  },
932
1054
 
1055
+ /**
1056
+ * Whether an update by id has to read the current row before writing.
1057
+ * The row is needed to backfill the other half of a GSI key pair, to
1058
+ * diff a StringSet, to guard an indexed counter, to compare a unique
1059
+ * constraint's old value, to rebuild _searchText from untouched source
1060
+ * fields, to reindex everything, or (mid key migration) to find the key
1061
+ * the row lives at. A write touching none of those is a plain SET/REMOVE
1062
+ * of the given attributes and can go straight to DynamoDB.
1063
+ * @private
1064
+ * @param {Object} dyUpdatesToSave - Attributes the write will touch
1065
+ * @param {{forceReindex: boolean}} options
1066
+ * @returns {boolean}
1067
+ */
1068
+ _updateNeedsCurrentItem(dyUpdatesToSave, { forceReindex = false } = {}) {
1069
+ if (forceReindex || this._writesInPlaceWhileMigrating()) {
1070
+ return true;
1071
+ }
1072
+
1073
+ const { StringSetFieldClass } = require("../fields");
1074
+ const indexes = Object.values(this.indexes).filter(
1075
+ (index) => index.indexId !== undefined,
1076
+ );
1077
+ for (const fieldName of Object.keys(dyUpdatesToSave)) {
1078
+ if (
1079
+ indexes.some(
1080
+ (index) => index.pk === fieldName || index.sk === fieldName,
1081
+ )
1082
+ ) {
1083
+ return true;
1084
+ }
1085
+ if (this.fields[fieldName] instanceof StringSetFieldClass) {
1086
+ return true;
1087
+ }
1088
+ }
1089
+
1090
+ for (const constraint of Object.values(this.uniqueConstraints || {})) {
1091
+ if (constraint.field in dyUpdatesToSave) return true;
1092
+ }
1093
+
1094
+ if (this.searchable && this.searchConfig) {
1095
+ const searchFields = this.searchConfig.fields || [];
1096
+ if (searchFields.some((f) => f in dyUpdatesToSave)) return true;
1097
+ }
1098
+
1099
+ return false;
1100
+ },
1101
+
933
1102
  _buildUpdateExpression(dyUpdatesToSave, currentItem = null) {
934
1103
  const names = {};
935
1104
  const values = {};
@@ -1018,6 +1187,9 @@ const MutationMethods = {
1018
1187
  updateExpression: parts.join(" "),
1019
1188
  names,
1020
1189
  values,
1190
+ // ADD/DELETE are applied by DynamoDB against the stored value, so the
1191
+ // written row can't be predicted locally; SET/REMOVE can.
1192
+ hasAtomicOps: addExpressions.length > 0 || deleteExpressions.length > 0,
1021
1193
  };
1022
1194
  },
1023
1195
 
@@ -1049,10 +1221,19 @@ const MutationMethods = {
1049
1221
  }
1050
1222
  }
1051
1223
 
1052
- // Detect partial GSI key updates that would cause index staleness
1224
+ // Detect partial GSI key updates that would cause index staleness.
1225
+ // A "modelPrefix" half is a constant, so an update that leaves the
1226
+ // other half alone leaves the index key unchanged: skip it rather
1227
+ // than treat the constant as a newly provided key.
1053
1228
  if (isUpdate && index.indexId !== undefined) {
1054
- const pkProvided = index.pk === "modelPrefix" || pkValue !== undefined;
1055
- const skProvided = index.sk === "modelPrefix" || skValue !== undefined;
1229
+ if (
1230
+ (index.pk === "modelPrefix" && skValue === undefined) ||
1231
+ (index.sk === "modelPrefix" && pkValue === undefined)
1232
+ ) {
1233
+ return;
1234
+ }
1235
+ const pkProvided = pkValue !== undefined;
1236
+ const skProvided = skValue !== undefined;
1056
1237
  if (pkProvided && !skProvided) {
1057
1238
  throw new Error(
1058
1239
  `Update includes GSI partition key "${index.pk}" for index "${indexName}" ` +