dynamo-bao 0.10.0 → 0.12.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,21 @@ const {
18
18
  } = require("../exceptions");
19
19
  const { computeSearchTextUpdate } = require("../utils/search-text");
20
20
  const { SEARCH_TEXT_FIELD, GID_SEPARATOR } = require("../constants");
21
+ const { TRANSACT_OP } = require("../transact");
22
+
23
+ function withReturnValuesOnFailure(transactItem) {
24
+ const [action] = Object.keys(transactItem);
25
+ const params = transactItem[action];
26
+ if (params && params.ConditionExpression) {
27
+ return {
28
+ [action]: {
29
+ ...params,
30
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
31
+ },
32
+ };
33
+ }
34
+ return transactItem;
35
+ }
21
36
 
22
37
  /**
23
38
  * AND a guard onto an optional ConditionExpression. The existing expression
@@ -51,16 +66,31 @@ const MutationMethods = {
51
66
  * @param {Object} jsUpdates - The data to create the item with.
52
67
  * @returns {Promise<Object>} Returns a promise that resolves to the created item.
53
68
  */
54
- async create(jsUpdates) {
55
- await pluginManager.executeHooks(this.name, "beforeSave", jsUpdates, {
69
+ async create(jsUpdates, options = {}) {
70
+ if (options.quiet) {
71
+ throw new ValidationError(
72
+ "quiet: true is only supported on update and updateOp",
73
+ );
74
+ }
75
+ const createOptions = {
56
76
  isNew: true,
57
- });
58
- const result = await this._saveItem(null, jsUpdates, { isNew: true });
77
+ ...options,
78
+ };
79
+ await pluginManager.executeHooks(
80
+ this.name,
81
+ "beforeSave",
82
+ jsUpdates,
83
+ createOptions,
84
+ );
85
+ const result = await this._saveItem(null, jsUpdates, createOptions);
59
86
 
60
87
  logger.debug("create() - result", result);
61
- await pluginManager.executeHooks(this.name, "afterSave", result, {
62
- isNew: true,
63
- });
88
+ await pluginManager.executeHooks(
89
+ this.name,
90
+ "afterSave",
91
+ result,
92
+ createOptions,
93
+ );
64
94
  return result;
65
95
  },
66
96
 
@@ -79,37 +109,136 @@ const MutationMethods = {
79
109
  * - Existence check: { fieldName: { $exists: true|false } }
80
110
  * - Logical operators: $and, $or, $not
81
111
  * @param {boolean} [options.forceReindex=false] - When true, repopulates all index attributes even if the source fields are unchanged.
112
+ * @param {boolean} [options.quiet=false] - When true, writes only the named plain attributes: skips `beforeSave`/`afterSave` hooks, `updateBeforeSave` field stamps (`ModifiedDateField`, `VersionField`, ...), and `_iter_*` rewrites. Refused for primary key, index key, unique-constraint, search-text source, server-generated, or immutable fields.
82
113
  * @returns {Promise<Object>} Returns a promise that resolves to the updated item.
83
114
  * @throws {Error} "Item not found" if the item doesn't exist
84
115
  * @throws {Error} "Condition check failed" if the condition isn't satisfied
85
116
  */
86
117
  async update(primaryId, jsUpdates, options = {}) {
118
+ if (options.quiet) {
119
+ if (options.isNew) {
120
+ throw new ValidationError(
121
+ "quiet: true is only supported on update and updateOp",
122
+ );
123
+ }
124
+ this._assertQuietUpdateAllowed(jsUpdates, options);
125
+ }
126
+
87
127
  const updateOptions = {
88
128
  isNew: false,
89
129
  ...options,
90
130
  };
91
131
 
92
- await pluginManager.executeHooks(
93
- this.name,
94
- "beforeSave",
95
- jsUpdates,
96
- updateOptions,
97
- );
132
+ if (!updateOptions.quiet) {
133
+ await pluginManager.executeHooks(
134
+ this.name,
135
+ "beforeSave",
136
+ jsUpdates,
137
+ updateOptions,
138
+ );
139
+ }
98
140
 
99
141
  const result = await this._saveItem(primaryId, jsUpdates, updateOptions);
100
142
 
101
143
  logger.debug("update() - result", result);
102
144
 
103
- await pluginManager.executeHooks(
104
- this.name,
105
- "afterSave",
106
- result,
107
- updateOptions,
108
- );
145
+ if (!updateOptions.quiet) {
146
+ await pluginManager.executeHooks(
147
+ this.name,
148
+ "afterSave",
149
+ result,
150
+ updateOptions,
151
+ );
152
+ }
109
153
 
110
154
  return result;
111
155
  },
112
156
 
157
+ /**
158
+ * @private
159
+ */
160
+ async _prepareDelete(primaryId, options = {}) {
161
+ const canonicalId = this._canonicalPrimaryId(primaryId);
162
+
163
+ // The row is read first only when the delete needs its contents: to
164
+ // find unique-constraint values to clean up, or (mid key migration) to
165
+ // learn which key shape the row actually lives at. Otherwise the key is
166
+ // derived from the id and a single conditional DeleteItem does the work.
167
+ const uniqueConstraints = Object.values(this.uniqueConstraints || {});
168
+ const needsRead =
169
+ uniqueConstraints.length > 0 || this._writesInPlaceWhileMigrating();
170
+
171
+ let item = null;
172
+ let key;
173
+ if (needsRead) {
174
+ item = await this.find(primaryId, { batchDelay: 0 });
175
+ if (!item.exists()) {
176
+ throw new ItemNotFoundError("Item not found", primaryId);
177
+ }
178
+ key = { _pk: item._dyData._pk, _sk: item._dyData._sk };
179
+ } else {
180
+ key = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
181
+ }
182
+
183
+ const deleteParams = {
184
+ TableName: this.table,
185
+ Key: key,
186
+ };
187
+
188
+ if (options.condition) {
189
+ const builder = new FilterExpressionBuilder();
190
+ const filterExpression = builder.build(options.condition, this);
191
+
192
+ if (filterExpression) {
193
+ deleteParams.ConditionExpression = filterExpression.FilterExpression;
194
+ deleteParams.ExpressionAttributeNames =
195
+ filterExpression.ExpressionAttributeNames;
196
+ deleteParams.ExpressionAttributeValues =
197
+ filterExpression.ExpressionAttributeValues;
198
+ }
199
+ }
200
+
201
+ let existsGuard = false;
202
+ if (!item) {
203
+ this._addExistsGuard(deleteParams);
204
+ existsGuard = true;
205
+ }
206
+
207
+ const uniqueTransactItems = [];
208
+ const uniqueItemMeta = [];
209
+ if (item !== null) {
210
+ for (const constraint of uniqueConstraints) {
211
+ const value = item[constraint.field];
212
+ if (value) {
213
+ const constraintOp = await this._removeUniqueConstraint(
214
+ constraint.field,
215
+ value,
216
+ item.getPrimaryId(),
217
+ constraint.constraintId,
218
+ );
219
+ uniqueTransactItems.push(constraintOp);
220
+ uniqueItemMeta.push({
221
+ role: "unique_delete",
222
+ constraintField: constraint.field,
223
+ hasExistsGuard: false,
224
+ });
225
+ }
226
+ }
227
+ }
228
+
229
+ const hasConstraintsToClean = uniqueTransactItems.length > 0;
230
+
231
+ return {
232
+ canonicalId,
233
+ item,
234
+ hasConstraintsToClean,
235
+ deleteParams,
236
+ existsGuard,
237
+ uniqueTransactItems,
238
+ uniqueItemMeta,
239
+ };
240
+ },
241
+
113
242
  /**
114
243
  *@memberof BaoModel
115
244
  * @description
@@ -150,33 +279,8 @@ const MutationMethods = {
150
279
  options,
151
280
  );
152
281
 
153
- // The row is read first only when the delete needs its contents: to
154
- // find unique-constraint values to clean up, or (mid key migration) to
155
- // learn which key shape the row actually lives at. Otherwise the key is
156
- // derived from the id and a single conditional DeleteItem does the work.
157
- const uniqueConstraints = Object.values(this.uniqueConstraints || {});
158
- const needsRead =
159
- uniqueConstraints.length > 0 || this._writesInPlaceWhileMigrating();
160
-
161
- let item = null;
162
- let key;
163
- if (needsRead) {
164
- item = await this.find(primaryId, { batchDelay: 0 });
165
- if (!item.exists()) {
166
- throw new ItemNotFoundError("Item not found", primaryId);
167
- }
168
- key = { _pk: item._dyData._pk, _sk: item._dyData._sk };
169
- } else {
170
- key = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
171
- }
172
-
173
- // Check if we need to clean up any unique constraints
174
- const hasConstraintsToClean =
175
- item !== null &&
176
- uniqueConstraints.some((constraint) => {
177
- const value = item[constraint.field];
178
- return value != null;
179
- });
282
+ const { item, hasConstraintsToClean, deleteParams, uniqueTransactItems } =
283
+ await this._prepareDelete(primaryId, options);
180
284
 
181
285
  try {
182
286
  let response;
@@ -184,45 +288,10 @@ const MutationMethods = {
184
288
  if (hasConstraintsToClean) {
185
289
  // Transaction path - handle unique constraint cleanup
186
290
  const transactItems = [
187
- {
188
- Delete: {
189
- TableName: this.table,
190
- Key: key,
191
- },
192
- },
291
+ { Delete: deleteParams },
292
+ ...uniqueTransactItems,
193
293
  ];
194
294
 
195
- // Add condition if specified
196
- if (options.condition) {
197
- const builder = new FilterExpressionBuilder();
198
- const filterExpression = builder.build(options.condition, this);
199
-
200
- if (filterExpression) {
201
- transactItems[0].Delete = {
202
- ...transactItems[0].Delete,
203
- ConditionExpression: filterExpression.FilterExpression,
204
- ExpressionAttributeNames:
205
- filterExpression.ExpressionAttributeNames,
206
- ExpressionAttributeValues:
207
- filterExpression.ExpressionAttributeValues,
208
- };
209
- }
210
- }
211
-
212
- // Add unique constraint cleanup operations
213
- for (const constraint of uniqueConstraints) {
214
- const value = item[constraint.field];
215
- if (value) {
216
- const constraintOp = await this._removeUniqueConstraint(
217
- constraint.field,
218
- value,
219
- item.getPrimaryId(),
220
- constraint.constraintId,
221
- );
222
- transactItems.push(constraintOp);
223
- }
224
- }
225
-
226
295
  // The token makes a retry after a lost response a no-op instead of
227
296
  // applying the transaction twice.
228
297
  const clientRequestToken = ulid();
@@ -237,36 +306,14 @@ const MutationMethods = {
237
306
  );
238
307
  } else {
239
308
  // Fast path - simple delete
240
- const deleteParams = {
241
- TableName: this.table,
242
- Key: key,
243
- ReturnValues: "ALL_OLD",
244
- ReturnConsumedCapacity: "TOTAL",
245
- };
246
-
247
- // Add condition if specified
248
- if (options.condition) {
249
- const builder = new FilterExpressionBuilder();
250
- const filterExpression = builder.build(options.condition, this);
251
-
252
- if (filterExpression) {
253
- deleteParams.ConditionExpression =
254
- filterExpression.FilterExpression;
255
- deleteParams.ExpressionAttributeNames =
256
- filterExpression.ExpressionAttributeNames;
257
- deleteParams.ExpressionAttributeValues =
258
- filterExpression.ExpressionAttributeValues;
259
- }
260
- }
261
-
262
- // Without a pre-read, the item's existence is checked by the delete
263
- // itself; a failure is mapped to ItemNotFoundError in the catch below.
264
- if (!item) {
265
- this._addExistsGuard(deleteParams);
266
- }
267
-
268
309
  response = await retryOperation(() =>
269
- this.documentClient.send(new DeleteCommand(deleteParams)),
310
+ this.documentClient.send(
311
+ new DeleteCommand({
312
+ ...deleteParams,
313
+ ReturnValues: "ALL_OLD",
314
+ ReturnConsumedCapacity: "TOTAL",
315
+ }),
316
+ ),
270
317
  );
271
318
  }
272
319
 
@@ -545,19 +592,479 @@ const MutationMethods = {
545
592
  },
546
593
 
547
594
  /**
548
- *@memberof BaoModel
549
- * @private
595
+ * @memberof BaoModel
550
596
  * @description
551
- * Save an item to the database.
552
- * @param {string} primaryId - The primary ID of the item to save.
553
- * @param {Object} jsUpdates - The data to save the item with.
554
- * @param {Object} [options] - Additional options for the save operation.
555
- * @param {boolean} [options.isNew=false] - Whether this is a new item being created. Internal use only.
556
- * @param {Object} [options.instanceObj=null] - Existing model instance, if any. Internal use only.
557
- * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
597
+ * Build a deferred create operation for use with {@link transact}.
598
+ * @param {Object} jsUpdates - Data to create the item with.
599
+ * @param {Object} [options] - Optional condition options.
600
+ * @returns {Object} Op descriptor for transact().
558
601
  */
559
- async _saveItem(primaryId, jsUpdates, options = {}) {
560
- const { isNew = false, instanceObj = null, forceReindex = false } = options;
602
+ createOp(jsUpdates, options = {}) {
603
+ if (!jsUpdates || typeof jsUpdates !== "object" || Array.isArray(jsUpdates)) {
604
+ throw new ValidationError("createOp() requires a data object");
605
+ }
606
+ if (options.quiet) {
607
+ throw new ValidationError(
608
+ "quiet: true is only supported on update and updateOp",
609
+ );
610
+ }
611
+ const tenantId = this.manager.getTenantId();
612
+ const model = this;
613
+ const table = this.table;
614
+ const documentClient = this.documentClient;
615
+ const dataCopy = { ...jsUpdates };
616
+ const opOptions = { ...options };
617
+
618
+ return {
619
+ [TRANSACT_OP]: true,
620
+ type: "create",
621
+ model,
622
+ tenantId,
623
+ table,
624
+ documentClient,
625
+ async _prepare() {
626
+ const hookOptions = { isNew: true, ...opOptions };
627
+ const working = { ...dataCopy };
628
+ await pluginManager.executeHooks(
629
+ model.name,
630
+ "beforeSave",
631
+ working,
632
+ hookOptions,
633
+ );
634
+ const prepared = await model._prepareSave(null, working, hookOptions);
635
+ const transactItems = [
636
+ ...prepared.uniqueTransactItems.map(withReturnValuesOnFailure),
637
+ withReturnValuesOnFailure({ Update: prepared.updateParams }),
638
+ ];
639
+ const itemMeta = [
640
+ ...prepared.uniqueItemMeta,
641
+ { role: "main", hasExistsGuard: false },
642
+ ];
643
+ const localResult = model._buildLocalSavedItem(
644
+ true,
645
+ null,
646
+ prepared.dyKey,
647
+ prepared.dyUpdatesToSave,
648
+ );
649
+ return {
650
+ type: "create",
651
+ model,
652
+ tenantId,
653
+ primaryId: prepared.primaryId,
654
+ transactItems,
655
+ itemMeta,
656
+ localResult,
657
+ hookOptions,
658
+ hasAtomicOps: prepared.hasAtomicOps,
659
+ };
660
+ },
661
+ };
662
+ },
663
+
664
+ /**
665
+ * @memberof BaoModel
666
+ * @description
667
+ * Build a deferred update operation for use with {@link transact}.
668
+ * @param {string|Object} primaryId - Primary ID of the item to update.
669
+ * @param {Object} jsUpdates - Changes to apply.
670
+ * @param {Object} [options] - Same options as {@link BaoModel.update}.
671
+ * @returns {Object} Op descriptor for transact().
672
+ */
673
+ updateOp(primaryId, jsUpdates, options = {}) {
674
+ if (primaryId === undefined || primaryId === null) {
675
+ throw new ValidationError("updateOp() requires a primaryId");
676
+ }
677
+ if (!jsUpdates || typeof jsUpdates !== "object" || Array.isArray(jsUpdates)) {
678
+ throw new ValidationError("updateOp() requires an updates object");
679
+ }
680
+ if (options.quiet) {
681
+ this._assertQuietUpdateAllowed(jsUpdates, options);
682
+ }
683
+ const tenantId = this.manager.getTenantId();
684
+ const model = this;
685
+ const table = this.table;
686
+ const documentClient = this.documentClient;
687
+ const updatesCopy = { ...jsUpdates };
688
+ const opOptions = { ...options };
689
+
690
+ return {
691
+ [TRANSACT_OP]: true,
692
+ type: "update",
693
+ model,
694
+ tenantId,
695
+ table,
696
+ documentClient,
697
+ async _prepare() {
698
+ const hookOptions = { isNew: false, ...opOptions };
699
+ const working = { ...updatesCopy };
700
+ if (!opOptions.quiet) {
701
+ await pluginManager.executeHooks(
702
+ model.name,
703
+ "beforeSave",
704
+ working,
705
+ hookOptions,
706
+ );
707
+ }
708
+ const prepared = await model._prepareSave(
709
+ primaryId,
710
+ working,
711
+ hookOptions,
712
+ );
713
+ const mainTransactItem = prepared.updateParams.UpdateExpression
714
+ ? withReturnValuesOnFailure({ Update: prepared.updateParams })
715
+ : {
716
+ ConditionCheck: model._updateParamsToConditionCheck(
717
+ prepared.updateParams,
718
+ ),
719
+ };
720
+ const transactItems = [
721
+ ...prepared.uniqueTransactItems.map(withReturnValuesOnFailure),
722
+ mainTransactItem,
723
+ ];
724
+ const itemMeta = [
725
+ ...prepared.uniqueItemMeta,
726
+ {
727
+ role: "main",
728
+ hasExistsGuard:
729
+ prepared.existsGuard ||
730
+ (!prepared.updateParams.UpdateExpression &&
731
+ !prepared.updateParams.ConditionExpression),
732
+ },
733
+ ];
734
+ const localResult =
735
+ prepared.currentItem && !prepared.hasAtomicOps
736
+ ? model._buildLocalSavedItem(
737
+ false,
738
+ prepared.currentItem,
739
+ prepared.dyKey,
740
+ prepared.dyUpdatesToSave,
741
+ )
742
+ : null;
743
+ return {
744
+ type: "update",
745
+ model,
746
+ tenantId,
747
+ primaryId: prepared.primaryId,
748
+ transactItems,
749
+ itemMeta,
750
+ localResult,
751
+ hookOptions,
752
+ hasAtomicOps: prepared.hasAtomicOps,
753
+ quiet: Boolean(opOptions.quiet),
754
+ };
755
+ },
756
+ };
757
+ },
758
+
759
+ /**
760
+ * @memberof BaoModel
761
+ * @description
762
+ * Build a deferred delete operation for use with {@link transact}.
763
+ * @param {string|Object} primaryId - Primary ID of the item to delete.
764
+ * @param {Object} [options] - Same options as {@link BaoModel.delete}.
765
+ * @returns {Object} Op descriptor for transact().
766
+ */
767
+ deleteOp(primaryId, options = {}) {
768
+ if (primaryId === undefined || primaryId === null) {
769
+ throw new ValidationError("deleteOp() requires a primaryId");
770
+ }
771
+ const tenantId = this.manager.getTenantId();
772
+ const model = this;
773
+ const table = this.table;
774
+ const documentClient = this.documentClient;
775
+ const opOptions = { ...options };
776
+
777
+ return {
778
+ [TRANSACT_OP]: true,
779
+ type: "delete",
780
+ model,
781
+ tenantId,
782
+ table,
783
+ documentClient,
784
+ async _prepare() {
785
+ const canonicalId = model._canonicalPrimaryId(primaryId);
786
+ await pluginManager.executeHooks(
787
+ model.name,
788
+ "beforeDelete",
789
+ canonicalId,
790
+ opOptions,
791
+ );
792
+ const prepared = await model._prepareDelete(primaryId, opOptions);
793
+ const transactItems = [
794
+ withReturnValuesOnFailure({ Delete: prepared.deleteParams }),
795
+ ...prepared.uniqueTransactItems.map(withReturnValuesOnFailure),
796
+ ];
797
+ const itemMeta = [
798
+ { role: "main", hasExistsGuard: prepared.existsGuard },
799
+ ...prepared.uniqueItemMeta,
800
+ ];
801
+ return {
802
+ type: "delete",
803
+ model,
804
+ tenantId,
805
+ primaryId: prepared.canonicalId,
806
+ transactItems,
807
+ itemMeta,
808
+ localResult: prepared.item,
809
+ hookOptions: opOptions,
810
+ hasAtomicOps: false,
811
+ };
812
+ },
813
+ };
814
+ },
815
+
816
+ /**
817
+ * @memberof BaoModel
818
+ * @description
819
+ * Build a deferred ConditionCheck (read-only assertion) for use with {@link transact}.
820
+ * @param {string|Object} primaryId - Primary ID of the item to check.
821
+ * @param {Object} condition - Filter-style condition that must hold.
822
+ * @returns {Object} Op descriptor for transact().
823
+ */
824
+ conditionCheckOp(primaryId, condition) {
825
+ if (primaryId === undefined || primaryId === null) {
826
+ throw new ValidationError("conditionCheckOp() requires a primaryId");
827
+ }
828
+ if (
829
+ !condition ||
830
+ typeof condition !== "object" ||
831
+ Array.isArray(condition) ||
832
+ Object.keys(condition).length === 0
833
+ ) {
834
+ throw new ValidationError(
835
+ "conditionCheckOp() requires a non-empty condition object",
836
+ );
837
+ }
838
+ const tenantId = this.manager.getTenantId();
839
+ const model = this;
840
+ const table = this.table;
841
+ const documentClient = this.documentClient;
842
+
843
+ return {
844
+ [TRANSACT_OP]: true,
845
+ type: "conditionCheck",
846
+ model,
847
+ tenantId,
848
+ table,
849
+ documentClient,
850
+ async _prepare() {
851
+ const canonicalId = model._canonicalPrimaryId(primaryId);
852
+ let key;
853
+ if (model._writesInPlaceWhileMigrating()) {
854
+ const existing = await model.find(canonicalId, { batchDelay: 0 });
855
+ key = existing.exists()
856
+ ? { _pk: existing._dyData._pk, _sk: existing._dyData._sk }
857
+ : model._getDyKeyForPkSk(model._parsePrimaryId(canonicalId));
858
+ } else {
859
+ key = model._getDyKeyForPkSk(model._parsePrimaryId(canonicalId));
860
+ }
861
+
862
+ const builder = new FilterExpressionBuilder();
863
+ const filterExpression = builder.build(condition, model);
864
+ if (!filterExpression) {
865
+ throw new ValidationError(
866
+ "conditionCheckOp() requires a non-empty condition object",
867
+ );
868
+ }
869
+
870
+ const checkParams = {
871
+ TableName: model.table,
872
+ Key: key,
873
+ ConditionExpression: filterExpression.FilterExpression,
874
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
875
+ };
876
+ if (Object.keys(filterExpression.ExpressionAttributeNames).length > 0) {
877
+ checkParams.ExpressionAttributeNames =
878
+ filterExpression.ExpressionAttributeNames;
879
+ }
880
+ if (
881
+ Object.keys(filterExpression.ExpressionAttributeValues).length > 0
882
+ ) {
883
+ checkParams.ExpressionAttributeValues =
884
+ filterExpression.ExpressionAttributeValues;
885
+ }
886
+
887
+ return {
888
+ type: "conditionCheck",
889
+ model,
890
+ tenantId,
891
+ primaryId: canonicalId,
892
+ transactItems: [{ ConditionCheck: checkParams }],
893
+ itemMeta: [{ role: "main", hasExistsGuard: false }],
894
+ localResult: null,
895
+ hookOptions: null,
896
+ hasAtomicOps: false,
897
+ };
898
+ },
899
+ };
900
+ },
901
+
902
+ /**
903
+ * Convert an updateParams with an empty UpdateExpression (e.g. a quiet
904
+ * update on an unchanged StringSetField) into a ConditionCheck that enforces
905
+ * the caller's condition and/or item existence without writing attributes.
906
+ * @private
907
+ */
908
+ _updateParamsToConditionCheck(updateParams) {
909
+ const checkParams = {
910
+ TableName: updateParams.TableName,
911
+ Key: updateParams.Key,
912
+ };
913
+ if (updateParams.ConditionExpression) {
914
+ checkParams.ConditionExpression = updateParams.ConditionExpression;
915
+ }
916
+ if (updateParams.ExpressionAttributeNames) {
917
+ checkParams.ExpressionAttributeNames = {
918
+ ...updateParams.ExpressionAttributeNames,
919
+ };
920
+ }
921
+ if (updateParams.ExpressionAttributeValues) {
922
+ checkParams.ExpressionAttributeValues = {
923
+ ...updateParams.ExpressionAttributeValues,
924
+ };
925
+ }
926
+ if (!checkParams.ConditionExpression) {
927
+ this._addExistsGuard(checkParams);
928
+ } else {
929
+ checkParams.ReturnValuesOnConditionCheckFailure = "ALL_OLD";
930
+ }
931
+ return checkParams;
932
+ },
933
+
934
+ /**
935
+ * @private
936
+ */
937
+ _buildLocalSavedItem(isNew, currentItem, dyKey, dyUpdatesToSave) {
938
+ const base = isNew
939
+ ? {}
940
+ : currentItem.isLoaded()
941
+ ? currentItem._loadedDyData
942
+ : currentItem._dyData;
943
+ const storedItem = { ...base, ...dyKey };
944
+ for (const [key, value] of Object.entries(dyUpdatesToSave)) {
945
+ if (value === undefined) continue;
946
+ if (value === null) {
947
+ delete storedItem[key];
948
+ } else {
949
+ storedItem[key] = value;
950
+ }
951
+ }
952
+ return this._createFromDyItem(storedItem);
953
+ },
954
+
955
+ /**
956
+ * Validate that a `quiet: true` update touches only plain writable
957
+ * attributes — refusing primary keys, index keys, unique-constraint fields,
958
+ * search-text source fields, server-generated/immutable fields, unknown
959
+ * fields, empty updates, and `forceReindex`.
960
+ * @private
961
+ */
962
+ _assertQuietUpdateAllowed(jsUpdates, options = {}) {
963
+ if (options.forceReindex) {
964
+ throw new ValidationError(
965
+ "quiet: true cannot be combined with forceReindex: true",
966
+ );
967
+ }
968
+
969
+ if (!jsUpdates || typeof jsUpdates !== "object" || Array.isArray(jsUpdates)) {
970
+ throw new ValidationError("quiet: true requires an updates object");
971
+ }
972
+
973
+ const fieldNames = Object.keys(jsUpdates).filter(
974
+ (k) => jsUpdates[k] !== undefined,
975
+ );
976
+ if (fieldNames.length === 0) {
977
+ throw new ValidationError(
978
+ "quiet: true requires at least one named field to update",
979
+ );
980
+ }
981
+
982
+ const pkFields = new Set(
983
+ [this.primaryKey?.pk, this.primaryKey?.sk].filter(
984
+ (f) => f && f !== "modelPrefix",
985
+ ),
986
+ );
987
+ const indexFields = new Set();
988
+ for (const index of Object.values(this.indexes || {})) {
989
+ if (index.indexId === undefined) continue;
990
+ if (index.pk && index.pk !== "modelPrefix") indexFields.add(index.pk);
991
+ if (index.sk && index.sk !== "modelPrefix") indexFields.add(index.sk);
992
+ }
993
+ const uniqueFields = new Set(
994
+ Object.values(this.uniqueConstraints || {}).map((c) => c.field),
995
+ );
996
+ const searchFields = new Set(
997
+ this.searchable && this.searchConfig?.fields
998
+ ? this.searchConfig.fields
999
+ : [],
1000
+ );
1001
+
1002
+ for (const fieldName of fieldNames) {
1003
+ if (!Object.prototype.hasOwnProperty.call(this.fields, fieldName)) {
1004
+ throw new ValidationError(
1005
+ `Unknown field "${fieldName}" on ${this.name} cannot be updated with quiet: true`,
1006
+ fieldName,
1007
+ );
1008
+ }
1009
+ const field = this.fields[fieldName];
1010
+ if (pkFields.has(fieldName)) {
1011
+ throw new ValidationError(
1012
+ `Primary key field "${fieldName}" cannot be updated with quiet: true`,
1013
+ fieldName,
1014
+ );
1015
+ }
1016
+ if (indexFields.has(fieldName)) {
1017
+ throw new ValidationError(
1018
+ `Index key field "${fieldName}" cannot be updated with quiet: true`,
1019
+ fieldName,
1020
+ );
1021
+ }
1022
+ if (uniqueFields.has(fieldName)) {
1023
+ throw new ValidationError(
1024
+ `Unique constraint field "${fieldName}" cannot be updated with quiet: true`,
1025
+ fieldName,
1026
+ );
1027
+ }
1028
+ if (searchFields.has(fieldName)) {
1029
+ throw new ValidationError(
1030
+ `Search-text source field "${fieldName}" cannot be updated with quiet: true`,
1031
+ fieldName,
1032
+ );
1033
+ }
1034
+ if (field.serverGenerated) {
1035
+ throw new ValidationError(
1036
+ `Server-generated field "${fieldName}" cannot be updated with quiet: true`,
1037
+ fieldName,
1038
+ );
1039
+ }
1040
+ if (field.immutable) {
1041
+ throw new ValidationError(
1042
+ `Immutable field "${fieldName}" cannot be updated with quiet: true`,
1043
+ fieldName,
1044
+ );
1045
+ }
1046
+ }
1047
+ },
1048
+
1049
+ /**
1050
+ * @private
1051
+ */
1052
+ async _prepareSave(primaryId, jsUpdates, options = {}) {
1053
+ const {
1054
+ isNew = false,
1055
+ instanceObj = null,
1056
+ forceReindex = false,
1057
+ quiet = false,
1058
+ } = options;
1059
+
1060
+ if (quiet) {
1061
+ if (isNew) {
1062
+ throw new ValidationError(
1063
+ "quiet: true is only supported on update and updateOp",
1064
+ );
1065
+ }
1066
+ this._assertQuietUpdateAllowed(jsUpdates, options);
1067
+ }
561
1068
 
562
1069
  // The id is used as a string below (iteration keys, the relatedId on
563
1070
  // unique constraint rows), so accept an object id by normalizing it.
@@ -570,7 +1077,8 @@ const MutationMethods = {
570
1077
 
571
1078
  let currentItem = isNew ? null : instanceObj;
572
1079
 
573
- const transactItems = [];
1080
+ const uniqueTransactItems = [];
1081
+ const uniqueItemMeta = [];
574
1082
  const dyUpdatesToSave = {};
575
1083
  const indexComputationData = {};
576
1084
  let hasUniqueConstraintChanges = false;
@@ -600,7 +1108,7 @@ const MutationMethods = {
600
1108
  const dyValue = field.toDy(jsUpdates[key]);
601
1109
  dyUpdatesToSave[key] = dyValue;
602
1110
  indexComputationData[key] = dyValue;
603
- } else {
1111
+ } else if (!quiet) {
604
1112
  if (typeof field.updateBeforeSave === "function") {
605
1113
  const newValue = field.updateBeforeSave(jsUpdates[key]);
606
1114
  if (newValue !== jsUpdates[key]) {
@@ -760,7 +1268,7 @@ const MutationMethods = {
760
1268
 
761
1269
  // Remove old constraint if updating
762
1270
  if (currentItem && dyCurrentValue) {
763
- transactItems.push(
1271
+ uniqueTransactItems.push(
764
1272
  await this._removeUniqueConstraint(
765
1273
  fieldName,
766
1274
  dyCurrentValue,
@@ -768,11 +1276,16 @@ const MutationMethods = {
768
1276
  constraint.constraintId,
769
1277
  ),
770
1278
  );
1279
+ uniqueItemMeta.push({
1280
+ role: "unique_delete",
1281
+ constraintField: fieldName,
1282
+ hasExistsGuard: false,
1283
+ });
771
1284
  }
772
1285
 
773
1286
  // Add new constraint unless value is null (clearing field removes constraint)
774
1287
  if (dyNewValue !== null) {
775
- transactItems.push(
1288
+ uniqueTransactItems.push(
776
1289
  await this._createUniqueConstraint(
777
1290
  fieldName,
778
1291
  dyNewValue,
@@ -780,6 +1293,11 @@ const MutationMethods = {
780
1293
  constraint.constraintId,
781
1294
  ),
782
1295
  );
1296
+ uniqueItemMeta.push({
1297
+ role: "unique_create",
1298
+ constraintField: fieldName,
1299
+ hasExistsGuard: false,
1300
+ });
783
1301
  }
784
1302
  } else if (dyNewValue !== undefined && currentItem) {
785
1303
  // Re-sending the unchanged value writes no constraint rows, so guard
@@ -793,35 +1311,41 @@ const MutationMethods = {
793
1311
  }
794
1312
  }
795
1313
 
796
- // Add GSI keys
797
- const indexSourceData = Object.keys(indexComputationData).length
798
- ? indexComputationData
799
- : dyUpdatesToSave;
1314
+ // Add GSI keys, iteration keys, and _searchText (skipped on quiet updates,
1315
+ // which are validated to touch only plain non-indexed, non-searchable fields).
1316
+ if (!quiet) {
1317
+ const indexSourceData = Object.keys(indexComputationData).length
1318
+ ? indexComputationData
1319
+ : dyUpdatesToSave;
800
1320
 
801
- const indexKeys = this._getIndexKeys(indexSourceData, {
802
- isUpdate: !isNew,
803
- });
804
- logger.debug("indexKeys", indexKeys);
805
- Object.assign(dyUpdatesToSave, indexKeys);
806
-
807
- // Add iteration keys if model is iterable
808
- if (this.iterable) {
809
- const iterationKeys = this._getIterationKeys(primaryId, dyUpdatesToSave);
810
- Object.assign(dyUpdatesToSave, iterationKeys);
811
- }
812
-
813
- // Compute _searchText if the model is searchable. Returns undefined to
814
- // skip the write entirely, null to REMOVE, or a string to SET.
815
- if (this.searchable && this.searchConfig) {
816
- const searchTextValue = computeSearchTextUpdate({
817
- searchConfig: this.searchConfig,
818
- dyUpdatesToSave,
819
- currentItem,
820
- isNew,
821
- forceReindex,
1321
+ const indexKeys = this._getIndexKeys(indexSourceData, {
1322
+ isUpdate: !isNew,
822
1323
  });
823
- if (searchTextValue !== undefined) {
824
- dyUpdatesToSave[SEARCH_TEXT_FIELD] = searchTextValue;
1324
+ logger.debug("indexKeys", indexKeys);
1325
+ Object.assign(dyUpdatesToSave, indexKeys);
1326
+
1327
+ // Add iteration keys if model is iterable
1328
+ if (this.iterable) {
1329
+ const iterationKeys = this._getIterationKeys(
1330
+ primaryId,
1331
+ dyUpdatesToSave,
1332
+ );
1333
+ Object.assign(dyUpdatesToSave, iterationKeys);
1334
+ }
1335
+
1336
+ // Compute _searchText if the model is searchable. Returns undefined to
1337
+ // skip the write entirely, null to REMOVE, or a string to SET.
1338
+ if (this.searchable && this.searchConfig) {
1339
+ const searchTextValue = computeSearchTextUpdate({
1340
+ searchConfig: this.searchConfig,
1341
+ dyUpdatesToSave,
1342
+ currentItem,
1343
+ isNew,
1344
+ forceReindex,
1345
+ });
1346
+ if (searchTextValue !== undefined) {
1347
+ dyUpdatesToSave[SEARCH_TEXT_FIELD] = searchTextValue;
1348
+ }
825
1349
  }
826
1350
  }
827
1351
 
@@ -855,7 +1379,6 @@ const MutationMethods = {
855
1379
  TableName: this.table,
856
1380
  Key: writeKey,
857
1381
  UpdateExpression: updateExpression,
858
- ReturnValues: "ALL_NEW",
859
1382
  };
860
1383
 
861
1384
  if (Object.keys(names).length > 0) {
@@ -956,14 +1479,84 @@ const MutationMethods = {
956
1479
  const dyKey = writeKey;
957
1480
  logger.debug("dyKey", dyKey);
958
1481
 
1482
+ return {
1483
+ primaryId,
1484
+ dyKey,
1485
+ dyUpdatesToSave,
1486
+ currentItem,
1487
+ consumedCapacity,
1488
+ hasUniqueConstraintChanges,
1489
+ uniqueTransactItems,
1490
+ uniqueItemMeta,
1491
+ updateParams,
1492
+ hasAtomicOps,
1493
+ existsGuard,
1494
+ };
1495
+ },
1496
+
1497
+ /**
1498
+ *@memberof BaoModel
1499
+ * @private
1500
+ * @description
1501
+ * Save an item to the database.
1502
+ * @param {string} primaryId - The primary ID of the item to save.
1503
+ * @param {Object} jsUpdates - The data to save the item with.
1504
+ * @param {Object} [options] - Additional options for the save operation.
1505
+ * @param {boolean} [options.isNew=false] - Whether this is a new item being created. Internal use only.
1506
+ * @param {Object} [options.instanceObj=null] - Existing model instance, if any. Internal use only.
1507
+ * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
1508
+ */
1509
+ async _saveItem(primaryId, jsUpdates, options = {}) {
1510
+ const { isNew = false } = options;
1511
+ const prepared = await this._prepareSave(primaryId, jsUpdates, options);
1512
+ const {
1513
+ dyKey,
1514
+ dyUpdatesToSave,
1515
+ currentItem,
1516
+ consumedCapacity,
1517
+ hasUniqueConstraintChanges,
1518
+ uniqueTransactItems,
1519
+ updateParams,
1520
+ hasAtomicOps,
1521
+ existsGuard,
1522
+ } = prepared;
1523
+ primaryId = prepared.primaryId;
1524
+
959
1525
  try {
960
1526
  let response;
961
1527
 
1528
+ if (!updateParams.UpdateExpression) {
1529
+ // A quiet update whose diff produced no write expression (for example,
1530
+ // an unchanged StringSetField). Evaluate any caller condition via
1531
+ // ConditionCheck without mutating the item.
1532
+ if (updateParams.ConditionExpression) {
1533
+ const checkParams = this._updateParamsToConditionCheck(updateParams);
1534
+ const clientRequestToken = ulid();
1535
+ const checkResp = await retryOperation(() =>
1536
+ this.documentClient.send(
1537
+ new TransactWriteCommand({
1538
+ TransactItems: [{ ConditionCheck: checkParams }],
1539
+ ClientRequestToken: clientRequestToken,
1540
+ ReturnConsumedCapacity: "TOTAL",
1541
+ }),
1542
+ ),
1543
+ );
1544
+ currentItem._addConsumedCapacity(
1545
+ checkResp.ConsumedCapacity,
1546
+ "write",
1547
+ false,
1548
+ );
1549
+ }
1550
+ this._primeLoaderContext(primaryId, currentItem);
1551
+ return currentItem;
1552
+ }
1553
+
962
1554
  if (hasUniqueConstraintChanges) {
963
1555
  // Use transaction if we have unique constraint changes
964
- transactItems.push({
965
- Update: updateParams,
966
- });
1556
+ const transactItems = [
1557
+ ...uniqueTransactItems,
1558
+ { Update: updateParams },
1559
+ ];
967
1560
 
968
1561
  if (logger.isDebugEnabled()) {
969
1562
  logger.debug("transactItems", JSON.stringify(transactItems, null, 2));
@@ -995,21 +1588,12 @@ const MutationMethods = {
995
1588
  // loader cache, which still holds the pre-update row.
996
1589
  let savedItem;
997
1590
  if (isNew || !hasAtomicOps) {
998
- const base = isNew
999
- ? {}
1000
- : currentItem.isLoaded()
1001
- ? currentItem._loadedDyData
1002
- : currentItem._dyData;
1003
- const storedItem = { ...base, ...dyKey };
1004
- for (const [key, value] of Object.entries(dyUpdatesToSave)) {
1005
- if (value === undefined) continue;
1006
- if (value === null) {
1007
- delete storedItem[key];
1008
- } else {
1009
- storedItem[key] = value;
1010
- }
1011
- }
1012
- savedItem = this._createFromDyItem(storedItem);
1591
+ savedItem = this._buildLocalSavedItem(
1592
+ isNew,
1593
+ currentItem,
1594
+ dyKey,
1595
+ dyUpdatesToSave,
1596
+ );
1013
1597
  } else {
1014
1598
  const readOptions = { batchDelay: 0, bypassCache: true };
1015
1599
  savedItem = await this.find(primaryId, readOptions);
@@ -1052,6 +1636,7 @@ const MutationMethods = {
1052
1636
  this.documentClient.send(
1053
1637
  new UpdateCommand({
1054
1638
  ...updateParams,
1639
+ ReturnValues: "ALL_NEW",
1055
1640
  ReturnConsumedCapacity: "TOTAL",
1056
1641
  }),
1057
1642
  );