@atscript/db-mongo 0.1.180 → 0.1.182

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.
package/dist/index.cjs CHANGED
@@ -155,6 +155,111 @@ function containsAggregationExpr(v) {
155
155
  return false;
156
156
  }
157
157
  /**
158
+ * Whether `value` holds a plain object at any depth. Only then can BSON
159
+ * equality (`$in` / `$eq`, which follows stored property order) differ from
160
+ * the comparison of the other adapters, which ignores property order.
161
+ */
162
+ function holdsObject(value) {
163
+ return Array.isArray(value) ? value.some(holdsObject) : (0, _atscript_db.isPlainObject)(value);
164
+ }
165
+ /**
166
+ * The form two operator items are the same by: JSON text with every object's
167
+ * keys sorted (as `stableJson` writes it) — what the other adapters compare
168
+ * elements without key props by — except that a value JSON cannot represent
169
+ * (an `ObjectId`, a `Date`, …) keeps its BSON type, as `$in` / `$eq` compare
170
+ * it: an `ObjectId` never equals its hex string, nor a `Date` its ISO text.
171
+ */
172
+ function itemForm(item) {
173
+ return JSON.stringify([item], function(key, value) {
174
+ const raw = this[key];
175
+ if (raw !== null && typeof raw === "object" && !Array.isArray(raw) && !(0, _atscript_db.isPlainObject)(raw)) return `\u0000${raw.constructor?.name}:${JSON.stringify(value)}`;
176
+ return (0, _atscript_db.isPlainObject)(value) ? Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : value;
177
+ });
178
+ }
179
+ /**
180
+ * `items` without those the same as an earlier one ({@link itemForm}) — what
181
+ * an operator that skips repeated items drops before it reaches the server.
182
+ */
183
+ function distinctItems(items) {
184
+ const seen = /* @__PURE__ */ new Set();
185
+ return items.filter((item) => {
186
+ const form = itemForm(item);
187
+ if (seen.has(form)) return false;
188
+ seen.add(form);
189
+ return true;
190
+ });
191
+ }
192
+ const allOf = (checks) => checks.length === 1 ? checks[0] : { $and: checks };
193
+ const anyOf = (checks) => checks.length === 1 ? checks[0] : { $or: checks };
194
+ /** Whether a property name can follow a variable in a field path (`$$el.<name>`). */
195
+ const isPathSegment = (name) => name !== "" && !name.includes(".") && !name.startsWith("$") && !name.includes("\0");
196
+ /**
197
+ * Appends to `checks` aggregation conditions that all hold exactly when the
198
+ * value of `expr` equals `item` the way the other adapters compare elements
199
+ * without key props: an object whatever the order of its properties, at
200
+ * every depth; an array element by element, in order; a scalar as BSON
201
+ * compares it; a missing property is not `null`. The conditions follow the
202
+ * item's structure — stored structure deeper than the item cannot equal it —
203
+ * and each one is safe to evaluate on any stored value.
204
+ *
205
+ * `depth` names the variables a nested array element is bound to (`v0`,
206
+ * `v1`, … from the outside in). Item values are `$literal`s.
207
+ */
208
+ function equalityChecks(expr, item, depth, checks = []) {
209
+ if (item === null || item === void 0) checks.push({ $eq: [{ $type: expr }, "null"] });
210
+ else if (!holdsObject(item)) checks.push({ $eq: [expr, { $literal: item }] });
211
+ else if (typeof expr !== "string") {
212
+ const name = `v${depth}`;
213
+ checks.push({ $let: {
214
+ vars: { [name]: expr },
215
+ in: allOf(equalityChecks(`$$${name}`, item, depth + 1))
216
+ } });
217
+ } else if (Array.isArray(item)) {
218
+ const elements = item.flatMap((el, i) => equalityChecks({ $arrayElemAt: [expr, i] }, el, depth));
219
+ checks.push({ $cond: [
220
+ { $isArray: expr },
221
+ allOf([{ $eq: [{ $size: expr }, item.length] }, ...elements]),
222
+ false
223
+ ] });
224
+ } else {
225
+ const entries = Object.entries(item).filter(([, v]) => v !== void 0);
226
+ const isObject = { $eq: [{ $type: expr }, "object"] };
227
+ checks.push({ $eq: [{ $cond: [
228
+ isObject,
229
+ { $size: { $objectToArray: expr } },
230
+ -1
231
+ ] }, entries.length] });
232
+ for (const [name, value] of entries) if (isPathSegment(name)) equalityChecks(`${expr}.${name}`, value, depth, checks);
233
+ else {
234
+ const field = { $getField: {
235
+ field: { $literal: name },
236
+ input: expr
237
+ } };
238
+ checks.push({ $cond: [
239
+ isObject,
240
+ allOf(equalityChecks(field, value, depth)),
241
+ false
242
+ ] });
243
+ }
244
+ }
245
+ return checks;
246
+ }
247
+ /** Condition: the value of `expr` equals `item` (see {@link equalityChecks}). */
248
+ function equalsItem(expr, item) {
249
+ return allOf(equalityChecks(expr, item, 0));
250
+ }
251
+ /**
252
+ * Condition: array `arr` has an element equal to `item` — BSON `$in` when
253
+ * the item holds no object (it is exact then), else {@link equalsItem}.
254
+ */
255
+ function holdsItem(arr, item) {
256
+ return holdsObject(item) ? { $anyElementTrue: { $map: {
257
+ input: arr,
258
+ as: "el",
259
+ in: equalsItem("$$el", item)
260
+ } } } : { $in: [{ $literal: item }, arr] };
261
+ }
262
+ /**
158
263
  * A field's current value in an aggregation pipeline update — a missing field
159
264
  * counts as `0`, like the `$inc` / `$mul` update operators (the pipeline
160
265
  * `$add` / `$multiply` would yield `null`) — so a document written before an
@@ -394,6 +499,32 @@ var CollectionPatcher = class {
394
499
  } });
395
500
  }
396
501
  /**
502
+ * Key-less `$upsert` / unique `$insert`: each item is appended, as sent and
503
+ * in the order sent, unless a stored element or an earlier item equals it.
504
+ * One rule for every item (since 0.1.182): an item that holds an object
505
+ * equals whatever the order of the objects' properties, as on the other
506
+ * adapters — before, BSON equality, which follows stored property order,
507
+ * appended a re-ordered item next to the equal element; a scalar as BSON
508
+ * compares it, so an `ObjectId` never equals its hex string (see
509
+ * {@link itemForm}; before, it did when another item held an object).
510
+ * Stored elements stay as they are.
511
+ */
512
+ _appendAbsent(key, input) {
513
+ if (!input.some(holdsObject)) {
514
+ this._appendUnless(key, input, { $in: ["$$this", "$$value"] });
515
+ return;
516
+ }
517
+ const added = distinctItems(input).map((item) => ({ $cond: [
518
+ holdsItem("$$arr", item),
519
+ [],
520
+ literal([item])
521
+ ] }));
522
+ this._set(key, { $let: {
523
+ vars: { arr: { $ifNull: [`$${key}`, []] } },
524
+ in: { $concatArrays: ["$$arr", ...added] }
525
+ } });
526
+ }
527
+ /**
397
528
  * `$insert` — what the read-modify-write of the other adapters does (since
398
529
  * 0.1.180; before, a keyed or unique insert was an upsert / a set union):
399
530
  * - keyed → append, skipping an item whose key is already stored
@@ -403,7 +534,7 @@ var CollectionPatcher = class {
403
534
  _insert(key, input, keys, flatType) {
404
535
  if (!input?.length) return;
405
536
  if (keys.length > 0) this._appendUnless(key, input, this._keyStored(keys));
406
- else if (flatType.metadata?.has("expect.array.uniqueItems")) this._appendUnless(key, input, { $in: ["$$this", "$$value"] });
537
+ else if (flatType.metadata?.has("expect.array.uniqueItems")) this._appendAbsent(key, input);
407
538
  else this._set(key, { $concatArrays: [{ $ifNull: [`$${key}`, []] }, literal(input)] });
408
539
  }
409
540
  /**
@@ -417,7 +548,7 @@ var CollectionPatcher = class {
417
548
  _upsert(key, input, keys, flatType) {
418
549
  if (!input?.length) return;
419
550
  if (keys.length === 0) {
420
- this._appendUnless(key, input, { $in: ["$$this", "$$value"] });
551
+ this._appendAbsent(key, input);
421
552
  return;
422
553
  }
423
554
  const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
@@ -477,11 +608,16 @@ var CollectionPatcher = class {
477
608
  } } } }
478
609
  } }
479
610
  } });
480
- else this._set(key, { $filter: {
481
- input: stored,
482
- as: "el",
483
- cond: { $not: { $in: ["$$el", literal(input)] } }
484
- } });
611
+ else {
612
+ const scalars = input.filter((item) => !holdsObject(item));
613
+ const equal = distinctItems(input.filter(holdsObject)).map((item) => equalsItem("$$el", item));
614
+ if (scalars.length > 0) equal.unshift({ $in: ["$$el", literal(scalars)] });
615
+ this._set(key, { $filter: {
616
+ input: stored,
617
+ as: "el",
618
+ cond: { $not: anyOf(equal) }
619
+ } });
620
+ }
485
621
  }
486
622
  };
487
623
  /**
@@ -2809,7 +2945,52 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2809
2945
  matchedCount: 0,
2810
2946
  modifiedCount: 0
2811
2947
  };
2812
- const versionColumn = this._versionColumnFor(opts, expectedVersion);
2948
+ const { updateFilter, updateOptions } = this._patchPipeline(patch, ops, this._versionColumnFor(opts, expectedVersion));
2949
+ if (updateFilter.length === 0) return this._countUnpatched(mongoFilter, { limit: 1 });
2950
+ this._log("updateOne (patch)", mongoFilter, updateFilter);
2951
+ return this._wrapUpdate(() => this.collection.updateOne(mongoFilter, updateFilter, {
2952
+ ...updateOptions,
2953
+ ...this._getSessionOpts()
2954
+ }));
2955
+ }
2956
+ /**
2957
+ * `updateMany` with array operators (since 0.1.182): the pipeline
2958
+ * {@link nativePatch} builds, in one `updateMany` over every matching
2959
+ * document — per batch of matching `_id`s for a filter holding relational
2960
+ * predicates. Never CAS-checks; bumps the version unless `opts.keepVersion`.
2961
+ */
2962
+ async nativePatchMany(filter, patch, ops, opts) {
2963
+ const { updateFilter, updateOptions } = this._patchPipeline(patch, ops, this._versionColumnFor(opts));
2964
+ return this._updateMatching(filter, (mongoFilter) => {
2965
+ if (updateFilter.length === 0) return this._countUnpatched(mongoFilter);
2966
+ this._log("updateMany (patch)", mongoFilter, updateFilter);
2967
+ return this._wrapUpdate(() => this.collection.updateMany(mongoFilter, updateFilter, {
2968
+ ...updateOptions,
2969
+ ...this._getSessionOpts()
2970
+ }));
2971
+ });
2972
+ }
2973
+ /**
2974
+ * A patch with nothing to set: the driver rejects an empty pipeline, so the
2975
+ * matching documents are only counted.
2976
+ */
2977
+ async _countUnpatched(mongoFilter, opts) {
2978
+ this._log("countDocuments (empty patch)", mongoFilter);
2979
+ return {
2980
+ matchedCount: await this.collection.countDocuments(mongoFilter, {
2981
+ ...opts,
2982
+ ...this._getSessionOpts()
2983
+ }),
2984
+ modifiedCount: 0
2985
+ };
2986
+ }
2987
+ /**
2988
+ * The update pipeline of a patch (`CollectionPatcher`), with the version
2989
+ * auto-bump injected into `ops.inc` so the patcher emits it as a
2990
+ * `version = version + 1` aggregation expression alongside any
2991
+ * user-supplied `$inc` / `$mul` ops.
2992
+ */
2993
+ _patchPipeline(patch, ops, versionColumn) {
2813
2994
  const effectiveOps = versionColumn !== void 0 ? {
2814
2995
  ...ops,
2815
2996
  inc: {
@@ -2817,22 +2998,7 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2817
2998
  [versionColumn]: 1
2818
2999
  }
2819
3000
  } : ops;
2820
- const { updateFilter, updateOptions } = new CollectionPatcher(this.getPatcherContext(), patch, effectiveOps).preparePatch();
2821
- if (updateFilter.length === 0) {
2822
- this._log("countDocuments (empty patch)", mongoFilter);
2823
- return {
2824
- matchedCount: await this.collection.countDocuments(mongoFilter, {
2825
- limit: 1,
2826
- ...this._getSessionOpts()
2827
- }),
2828
- modifiedCount: 0
2829
- };
2830
- }
2831
- this._log("updateOne (patch)", mongoFilter, updateFilter);
2832
- return this._wrapUpdate(() => this.collection.updateOne(mongoFilter, updateFilter, {
2833
- ...updateOptions,
2834
- ...this._getSessionOpts()
2835
- }));
3001
+ return new CollectionPatcher(this.getPatcherContext(), patch, effectiveOps).preparePatch();
2836
3002
  }
2837
3003
  onBeforeFlatten(_type) {
2838
3004
  const typeMeta = _type.metadata;
package/dist/index.d.cts CHANGED
@@ -139,6 +139,18 @@ declare class CollectionPatcher {
139
139
  * array as it is) is the result.
140
140
  */
141
141
  private _appendUnless;
142
+ /**
143
+ * Key-less `$upsert` / unique `$insert`: each item is appended, as sent and
144
+ * in the order sent, unless a stored element or an earlier item equals it.
145
+ * One rule for every item (since 0.1.182): an item that holds an object
146
+ * equals whatever the order of the objects' properties, as on the other
147
+ * adapters — before, BSON equality, which follows stored property order,
148
+ * appended a re-ordered item next to the equal element; a scalar as BSON
149
+ * compares it, so an `ObjectId` never equals its hex string (see
150
+ * {@link itemForm}; before, it did when another item held an object).
151
+ * Stored elements stay as they are.
152
+ */
153
+ private _appendAbsent;
142
154
  /**
143
155
  * `$insert` — what the read-modify-write of the other adapters does (since
144
156
  * 0.1.180; before, a keyed or unique insert was an upsert / a set union):
@@ -506,6 +518,25 @@ declare class MongoAdapter extends BaseDbAdapter {
506
518
  */
507
519
  private _patcherFlatMap;
508
520
  nativePatch(filter: FilterExpr, patch: unknown, ops?: TFieldOps, expectedVersion?: number, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
521
+ /**
522
+ * `updateMany` with array operators (since 0.1.182): the pipeline
523
+ * {@link nativePatch} builds, in one `updateMany` over every matching
524
+ * document — per batch of matching `_id`s for a filter holding relational
525
+ * predicates. Never CAS-checks; bumps the version unless `opts.keepVersion`.
526
+ */
527
+ nativePatchMany(filter: FilterExpr, patch: unknown, ops?: TFieldOps, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
528
+ /**
529
+ * A patch with nothing to set: the driver rejects an empty pipeline, so the
530
+ * matching documents are only counted.
531
+ */
532
+ private _countUnpatched;
533
+ /**
534
+ * The update pipeline of a patch (`CollectionPatcher`), with the version
535
+ * auto-bump injected into `ops.inc` so the patcher emits it as a
536
+ * `version = version + 1` aggregation expression alongside any
537
+ * user-supplied `$inc` / `$mul` ops.
538
+ */
539
+ private _patchPipeline;
509
540
  onBeforeFlatten(_type: unknown): void;
510
541
  onFieldScanned(field: string, _type: unknown, metadata: TMetadataMap<AtscriptMetadata>): void;
511
542
  getMetadataOverrides(meta: TableMetadata): TMetadataOverrides;
package/dist/index.d.mts CHANGED
@@ -139,6 +139,18 @@ declare class CollectionPatcher {
139
139
  * array as it is) is the result.
140
140
  */
141
141
  private _appendUnless;
142
+ /**
143
+ * Key-less `$upsert` / unique `$insert`: each item is appended, as sent and
144
+ * in the order sent, unless a stored element or an earlier item equals it.
145
+ * One rule for every item (since 0.1.182): an item that holds an object
146
+ * equals whatever the order of the objects' properties, as on the other
147
+ * adapters — before, BSON equality, which follows stored property order,
148
+ * appended a re-ordered item next to the equal element; a scalar as BSON
149
+ * compares it, so an `ObjectId` never equals its hex string (see
150
+ * {@link itemForm}; before, it did when another item held an object).
151
+ * Stored elements stay as they are.
152
+ */
153
+ private _appendAbsent;
142
154
  /**
143
155
  * `$insert` — what the read-modify-write of the other adapters does (since
144
156
  * 0.1.180; before, a keyed or unique insert was an upsert / a set union):
@@ -506,6 +518,25 @@ declare class MongoAdapter extends BaseDbAdapter {
506
518
  */
507
519
  private _patcherFlatMap;
508
520
  nativePatch(filter: FilterExpr, patch: unknown, ops?: TFieldOps, expectedVersion?: number, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
521
+ /**
522
+ * `updateMany` with array operators (since 0.1.182): the pipeline
523
+ * {@link nativePatch} builds, in one `updateMany` over every matching
524
+ * document — per batch of matching `_id`s for a filter holding relational
525
+ * predicates. Never CAS-checks; bumps the version unless `opts.keepVersion`.
526
+ */
527
+ nativePatchMany(filter: FilterExpr, patch: unknown, ops?: TFieldOps, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
528
+ /**
529
+ * A patch with nothing to set: the driver rejects an empty pipeline, so the
530
+ * matching documents are only counted.
531
+ */
532
+ private _countUnpatched;
533
+ /**
534
+ * The update pipeline of a patch (`CollectionPatcher`), with the version
535
+ * auto-bump injected into `ops.inc` so the patcher emits it as a
536
+ * `version = version + 1` aggregation expression alongside any
537
+ * user-supplied `$inc` / `$mul` ops.
538
+ */
539
+ private _patchPipeline;
509
540
  onBeforeFlatten(_type: unknown): void;
510
541
  onFieldScanned(field: string, _type: unknown, metadata: TMetadataMap<AtscriptMetadata>): void;
511
542
  getMetadataOverrides(meta: TableMetadata): TMetadataOverrides;
package/dist/index.mjs CHANGED
@@ -154,6 +154,111 @@ function containsAggregationExpr(v) {
154
154
  return false;
155
155
  }
156
156
  /**
157
+ * Whether `value` holds a plain object at any depth. Only then can BSON
158
+ * equality (`$in` / `$eq`, which follows stored property order) differ from
159
+ * the comparison of the other adapters, which ignores property order.
160
+ */
161
+ function holdsObject(value) {
162
+ return Array.isArray(value) ? value.some(holdsObject) : isPlainObject(value);
163
+ }
164
+ /**
165
+ * The form two operator items are the same by: JSON text with every object's
166
+ * keys sorted (as `stableJson` writes it) — what the other adapters compare
167
+ * elements without key props by — except that a value JSON cannot represent
168
+ * (an `ObjectId`, a `Date`, …) keeps its BSON type, as `$in` / `$eq` compare
169
+ * it: an `ObjectId` never equals its hex string, nor a `Date` its ISO text.
170
+ */
171
+ function itemForm(item) {
172
+ return JSON.stringify([item], function(key, value) {
173
+ const raw = this[key];
174
+ if (raw !== null && typeof raw === "object" && !Array.isArray(raw) && !isPlainObject(raw)) return `\u0000${raw.constructor?.name}:${JSON.stringify(value)}`;
175
+ return isPlainObject(value) ? Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : value;
176
+ });
177
+ }
178
+ /**
179
+ * `items` without those the same as an earlier one ({@link itemForm}) — what
180
+ * an operator that skips repeated items drops before it reaches the server.
181
+ */
182
+ function distinctItems(items) {
183
+ const seen = /* @__PURE__ */ new Set();
184
+ return items.filter((item) => {
185
+ const form = itemForm(item);
186
+ if (seen.has(form)) return false;
187
+ seen.add(form);
188
+ return true;
189
+ });
190
+ }
191
+ const allOf = (checks) => checks.length === 1 ? checks[0] : { $and: checks };
192
+ const anyOf = (checks) => checks.length === 1 ? checks[0] : { $or: checks };
193
+ /** Whether a property name can follow a variable in a field path (`$$el.<name>`). */
194
+ const isPathSegment = (name) => name !== "" && !name.includes(".") && !name.startsWith("$") && !name.includes("\0");
195
+ /**
196
+ * Appends to `checks` aggregation conditions that all hold exactly when the
197
+ * value of `expr` equals `item` the way the other adapters compare elements
198
+ * without key props: an object whatever the order of its properties, at
199
+ * every depth; an array element by element, in order; a scalar as BSON
200
+ * compares it; a missing property is not `null`. The conditions follow the
201
+ * item's structure — stored structure deeper than the item cannot equal it —
202
+ * and each one is safe to evaluate on any stored value.
203
+ *
204
+ * `depth` names the variables a nested array element is bound to (`v0`,
205
+ * `v1`, … from the outside in). Item values are `$literal`s.
206
+ */
207
+ function equalityChecks(expr, item, depth, checks = []) {
208
+ if (item === null || item === void 0) checks.push({ $eq: [{ $type: expr }, "null"] });
209
+ else if (!holdsObject(item)) checks.push({ $eq: [expr, { $literal: item }] });
210
+ else if (typeof expr !== "string") {
211
+ const name = `v${depth}`;
212
+ checks.push({ $let: {
213
+ vars: { [name]: expr },
214
+ in: allOf(equalityChecks(`$$${name}`, item, depth + 1))
215
+ } });
216
+ } else if (Array.isArray(item)) {
217
+ const elements = item.flatMap((el, i) => equalityChecks({ $arrayElemAt: [expr, i] }, el, depth));
218
+ checks.push({ $cond: [
219
+ { $isArray: expr },
220
+ allOf([{ $eq: [{ $size: expr }, item.length] }, ...elements]),
221
+ false
222
+ ] });
223
+ } else {
224
+ const entries = Object.entries(item).filter(([, v]) => v !== void 0);
225
+ const isObject = { $eq: [{ $type: expr }, "object"] };
226
+ checks.push({ $eq: [{ $cond: [
227
+ isObject,
228
+ { $size: { $objectToArray: expr } },
229
+ -1
230
+ ] }, entries.length] });
231
+ for (const [name, value] of entries) if (isPathSegment(name)) equalityChecks(`${expr}.${name}`, value, depth, checks);
232
+ else {
233
+ const field = { $getField: {
234
+ field: { $literal: name },
235
+ input: expr
236
+ } };
237
+ checks.push({ $cond: [
238
+ isObject,
239
+ allOf(equalityChecks(field, value, depth)),
240
+ false
241
+ ] });
242
+ }
243
+ }
244
+ return checks;
245
+ }
246
+ /** Condition: the value of `expr` equals `item` (see {@link equalityChecks}). */
247
+ function equalsItem(expr, item) {
248
+ return allOf(equalityChecks(expr, item, 0));
249
+ }
250
+ /**
251
+ * Condition: array `arr` has an element equal to `item` — BSON `$in` when
252
+ * the item holds no object (it is exact then), else {@link equalsItem}.
253
+ */
254
+ function holdsItem(arr, item) {
255
+ return holdsObject(item) ? { $anyElementTrue: { $map: {
256
+ input: arr,
257
+ as: "el",
258
+ in: equalsItem("$$el", item)
259
+ } } } : { $in: [{ $literal: item }, arr] };
260
+ }
261
+ /**
157
262
  * A field's current value in an aggregation pipeline update — a missing field
158
263
  * counts as `0`, like the `$inc` / `$mul` update operators (the pipeline
159
264
  * `$add` / `$multiply` would yield `null`) — so a document written before an
@@ -393,6 +498,32 @@ var CollectionPatcher = class {
393
498
  } });
394
499
  }
395
500
  /**
501
+ * Key-less `$upsert` / unique `$insert`: each item is appended, as sent and
502
+ * in the order sent, unless a stored element or an earlier item equals it.
503
+ * One rule for every item (since 0.1.182): an item that holds an object
504
+ * equals whatever the order of the objects' properties, as on the other
505
+ * adapters — before, BSON equality, which follows stored property order,
506
+ * appended a re-ordered item next to the equal element; a scalar as BSON
507
+ * compares it, so an `ObjectId` never equals its hex string (see
508
+ * {@link itemForm}; before, it did when another item held an object).
509
+ * Stored elements stay as they are.
510
+ */
511
+ _appendAbsent(key, input) {
512
+ if (!input.some(holdsObject)) {
513
+ this._appendUnless(key, input, { $in: ["$$this", "$$value"] });
514
+ return;
515
+ }
516
+ const added = distinctItems(input).map((item) => ({ $cond: [
517
+ holdsItem("$$arr", item),
518
+ [],
519
+ literal([item])
520
+ ] }));
521
+ this._set(key, { $let: {
522
+ vars: { arr: { $ifNull: [`$${key}`, []] } },
523
+ in: { $concatArrays: ["$$arr", ...added] }
524
+ } });
525
+ }
526
+ /**
396
527
  * `$insert` — what the read-modify-write of the other adapters does (since
397
528
  * 0.1.180; before, a keyed or unique insert was an upsert / a set union):
398
529
  * - keyed → append, skipping an item whose key is already stored
@@ -402,7 +533,7 @@ var CollectionPatcher = class {
402
533
  _insert(key, input, keys, flatType) {
403
534
  if (!input?.length) return;
404
535
  if (keys.length > 0) this._appendUnless(key, input, this._keyStored(keys));
405
- else if (flatType.metadata?.has("expect.array.uniqueItems")) this._appendUnless(key, input, { $in: ["$$this", "$$value"] });
536
+ else if (flatType.metadata?.has("expect.array.uniqueItems")) this._appendAbsent(key, input);
406
537
  else this._set(key, { $concatArrays: [{ $ifNull: [`$${key}`, []] }, literal(input)] });
407
538
  }
408
539
  /**
@@ -416,7 +547,7 @@ var CollectionPatcher = class {
416
547
  _upsert(key, input, keys, flatType) {
417
548
  if (!input?.length) return;
418
549
  if (keys.length === 0) {
419
- this._appendUnless(key, input, { $in: ["$$this", "$$value"] });
550
+ this._appendAbsent(key, input);
420
551
  return;
421
552
  }
422
553
  const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
@@ -476,11 +607,16 @@ var CollectionPatcher = class {
476
607
  } } } }
477
608
  } }
478
609
  } });
479
- else this._set(key, { $filter: {
480
- input: stored,
481
- as: "el",
482
- cond: { $not: { $in: ["$$el", literal(input)] } }
483
- } });
610
+ else {
611
+ const scalars = input.filter((item) => !holdsObject(item));
612
+ const equal = distinctItems(input.filter(holdsObject)).map((item) => equalsItem("$$el", item));
613
+ if (scalars.length > 0) equal.unshift({ $in: ["$$el", literal(scalars)] });
614
+ this._set(key, { $filter: {
615
+ input: stored,
616
+ as: "el",
617
+ cond: { $not: anyOf(equal) }
618
+ } });
619
+ }
484
620
  }
485
621
  };
486
622
  /**
@@ -2808,7 +2944,52 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2808
2944
  matchedCount: 0,
2809
2945
  modifiedCount: 0
2810
2946
  };
2811
- const versionColumn = this._versionColumnFor(opts, expectedVersion);
2947
+ const { updateFilter, updateOptions } = this._patchPipeline(patch, ops, this._versionColumnFor(opts, expectedVersion));
2948
+ if (updateFilter.length === 0) return this._countUnpatched(mongoFilter, { limit: 1 });
2949
+ this._log("updateOne (patch)", mongoFilter, updateFilter);
2950
+ return this._wrapUpdate(() => this.collection.updateOne(mongoFilter, updateFilter, {
2951
+ ...updateOptions,
2952
+ ...this._getSessionOpts()
2953
+ }));
2954
+ }
2955
+ /**
2956
+ * `updateMany` with array operators (since 0.1.182): the pipeline
2957
+ * {@link nativePatch} builds, in one `updateMany` over every matching
2958
+ * document — per batch of matching `_id`s for a filter holding relational
2959
+ * predicates. Never CAS-checks; bumps the version unless `opts.keepVersion`.
2960
+ */
2961
+ async nativePatchMany(filter, patch, ops, opts) {
2962
+ const { updateFilter, updateOptions } = this._patchPipeline(patch, ops, this._versionColumnFor(opts));
2963
+ return this._updateMatching(filter, (mongoFilter) => {
2964
+ if (updateFilter.length === 0) return this._countUnpatched(mongoFilter);
2965
+ this._log("updateMany (patch)", mongoFilter, updateFilter);
2966
+ return this._wrapUpdate(() => this.collection.updateMany(mongoFilter, updateFilter, {
2967
+ ...updateOptions,
2968
+ ...this._getSessionOpts()
2969
+ }));
2970
+ });
2971
+ }
2972
+ /**
2973
+ * A patch with nothing to set: the driver rejects an empty pipeline, so the
2974
+ * matching documents are only counted.
2975
+ */
2976
+ async _countUnpatched(mongoFilter, opts) {
2977
+ this._log("countDocuments (empty patch)", mongoFilter);
2978
+ return {
2979
+ matchedCount: await this.collection.countDocuments(mongoFilter, {
2980
+ ...opts,
2981
+ ...this._getSessionOpts()
2982
+ }),
2983
+ modifiedCount: 0
2984
+ };
2985
+ }
2986
+ /**
2987
+ * The update pipeline of a patch (`CollectionPatcher`), with the version
2988
+ * auto-bump injected into `ops.inc` so the patcher emits it as a
2989
+ * `version = version + 1` aggregation expression alongside any
2990
+ * user-supplied `$inc` / `$mul` ops.
2991
+ */
2992
+ _patchPipeline(patch, ops, versionColumn) {
2812
2993
  const effectiveOps = versionColumn !== void 0 ? {
2813
2994
  ...ops,
2814
2995
  inc: {
@@ -2816,22 +2997,7 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2816
2997
  [versionColumn]: 1
2817
2998
  }
2818
2999
  } : ops;
2819
- const { updateFilter, updateOptions } = new CollectionPatcher(this.getPatcherContext(), patch, effectiveOps).preparePatch();
2820
- if (updateFilter.length === 0) {
2821
- this._log("countDocuments (empty patch)", mongoFilter);
2822
- return {
2823
- matchedCount: await this.collection.countDocuments(mongoFilter, {
2824
- limit: 1,
2825
- ...this._getSessionOpts()
2826
- }),
2827
- modifiedCount: 0
2828
- };
2829
- }
2830
- this._log("updateOne (patch)", mongoFilter, updateFilter);
2831
- return this._wrapUpdate(() => this.collection.updateOne(mongoFilter, updateFilter, {
2832
- ...updateOptions,
2833
- ...this._getSessionOpts()
2834
- }));
3000
+ return new CollectionPatcher(this.getPatcherContext(), patch, effectiveOps).preparePatch();
2835
3001
  }
2836
3002
  onBeforeFlatten(_type) {
2837
3003
  const typeMeta = _type.metadata;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-mongo",
3
- "version": "0.1.180",
3
+ "version": "0.1.182",
4
4
  "description": "Mongodb plugin for atscript.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -46,19 +46,19 @@
46
46
  "access": "public"
47
47
  },
48
48
  "devDependencies": {
49
- "@atscript/core": "^0.2.12",
50
- "@atscript/typescript": "^0.2.12",
49
+ "@atscript/core": "^0.2.13",
50
+ "@atscript/typescript": "^0.2.13",
51
51
  "@uniqu/core": "^0.2.2",
52
52
  "mongodb": "^6.17.0",
53
53
  "mongodb-memory-server-core": "^10.0.0",
54
- "unplugin-atscript": "^0.2.12"
54
+ "unplugin-atscript": "^0.2.13"
55
55
  },
56
56
  "peerDependencies": {
57
- "@atscript/core": "^0.2.12",
58
- "@atscript/typescript": "^0.2.12",
57
+ "@atscript/core": "^0.2.13",
58
+ "@atscript/typescript": "^0.2.13",
59
59
  "@uniqu/core": "^0.2.2",
60
60
  "mongodb": "^6.17.0",
61
- "@atscript/db": "^0.1.180"
61
+ "@atscript/db": "^0.1.182"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "vp pack",