@atscript/db-mongo 0.1.207 → 0.1.209

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
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_mongo_accumulator = require("./mongo-accumulator-DLHfj5bv.cjs");
2
+ const require_mongo_accumulator = require("./mongo-accumulator-Chn-xOiV.cjs");
3
3
  const require_search_messages = require("./search-messages-BqLxxrb8.cjs");
4
4
  let _atscript_db = require("@atscript/db");
5
5
  let mongodb = require("mongodb");
@@ -384,7 +384,7 @@ var CollectionPatcher = class {
384
384
  const flatType = this.collection.flatMap.get(key);
385
385
  const topLevelArray = flatType?.metadata?.get("db.__topLevelArray");
386
386
  const isObjectValue = typeof value === "object" && value !== null && !Array.isArray(value);
387
- if (isObjectValue && topLevelArray && !flatType?.metadata?.has("db.json")) this.parseArrayPatch(key, value, flatType);
387
+ if (isObjectValue && topLevelArray && !flatType?.metadata?.has("db.json") && !isGeoJsonPoint(value)) this.parseArrayPatch(key, value, flatType);
388
388
  else if (isObjectValue && this.collection.mergePaths.has(key)) this.flattenPayload(value, key);
389
389
  else if (isObjectValue && (0, _atscript_db.storedObjectType)(flatType) && !flatType.metadata?.has("db.json")) this._flattenReplaceObject(value, key, flatType);
390
390
  else if (key !== "_id") this._setLeaf(key, value, flatType);
@@ -408,7 +408,7 @@ var CollectionPatcher = class {
408
408
  const childIsObject = typeof childValue === "object" && childValue !== null && !Array.isArray(childValue);
409
409
  const propIsJson = propType.metadata?.has("db.json");
410
410
  const childFlatType = this.collection.flatMap.get(childKey);
411
- if (childIsObject && !propIsJson && childFlatType?.metadata?.get("db.__topLevelArray")) {
411
+ if (childIsObject && !propIsJson && childFlatType?.metadata?.get("db.__topLevelArray") && !isGeoJsonPoint(childValue)) {
412
412
  this.parseArrayPatch(childKey, childValue, childFlatType);
413
413
  continue;
414
414
  }
@@ -625,13 +625,24 @@ var CollectionPatcher = class {
625
625
  /**
626
626
  * Whether a plain-object patch value replaces the stored object instead of
627
627
  * merging into it: a `@db.json` object, or a union of objects / `T | null`
628
- * whose member may switch (since 0.1.155). A field the patcher cannot type
629
- * (e.g. under a `@db.column` name) keeps the merge.
628
+ * whose member may switch (since 0.1.155); a `db.geoPoint` in its GeoJSON
629
+ * storage form (since 0.1.209 — it may replace a stored coordinate pair). A
630
+ * field the patcher cannot type (e.g. under a `@db.column` name) keeps the
631
+ * merge.
630
632
  */
631
633
  function replacesWhole(value, type) {
634
+ if (isGeoJsonPoint(value)) return true;
632
635
  if (!type || !(0, _atscript_db.isPlainObject)(value)) return false;
633
636
  return type.metadata?.has("db.json") || type.type.kind === "union";
634
637
  }
638
+ /**
639
+ * A `db.geoPoint` as the adapter's formatter stores it — a GeoJSON Point:
640
+ * one value, never an array patch (since 0.1.209; before, a patched point was
641
+ * read as an operator object without operators, and nothing was written).
642
+ */
643
+ function isGeoJsonPoint(value) {
644
+ return (0, _atscript_db.isPlainObject)(value) && value.type === "Point" && Array.isArray(value.coordinates) && Object.keys(value).length === 2;
645
+ }
635
646
  //#endregion
636
647
  //#region src/lib/mongo-types.ts
637
648
  const INDEX_PREFIX = "atscript__";
@@ -681,9 +692,14 @@ function joinedAs(table) {
681
692
  * 3. aggregates → `$group` (+ `$addFields` turning `countDistinct` sets into
682
693
  * their sizes, + `@db.view.having` → `$match`) + `$project`, otherwise a
683
694
  * flat `$project`. A conditional aggregate's predicate reads the same
684
- * pipeline paths (SQL null semantics — `queryNodeToExpr`). A `sum` /
685
- * `avg` / `min` / `max` of a decimal (`decimal` mapping) aggregates the
686
- * text as a `Decimal128` and projects the result's text (since 0.1.207).
695
+ * pipeline paths (SQL null semantics — `queryNodeToExpr`).
696
+ *
697
+ * Decimals and longs (since 0.1.209): the view keeps the stored `Decimal128`
698
+ * / `Long` (the view's field formatters read them as text); a `sum` / `avg`
699
+ * of one aggregates it as a `Decimal128` (exact); a `number` view column over
700
+ * one projects a double; a predicate literal compared with one is a
701
+ * `Decimal128`. An unconditional `sum` over no (non-null) value is null, as
702
+ * in SQL — a conditional one stays 0 (SQL's `COALESCE(…, 0)`).
687
703
  *
688
704
  * All field paths are PHYSICAL document paths (`@db.column` renames), joined
689
705
  * tables live under `__joined_<scope>` — the physical collection, or the
@@ -700,6 +716,10 @@ function buildViewPipeline(view, variant) {
700
716
  const plan = variant?.plan ?? view.viewPlan;
701
717
  const columns = variant?.columns ?? view.getViewColumnMappings();
702
718
  const pipeline = [];
719
+ const literalOf = (ref, value) => {
720
+ const { source } = view.resolveRefSource(ref);
721
+ return !source.inJsonValue && (0, _atscript_db.exactKindOf)(source.designType) ? require_mongo_accumulator.exactLiteral(value, ref.field) : value;
722
+ };
703
723
  const prefixes = new Map([[plan.entryTable, ""]]);
704
724
  const pathOf = (ref) => {
705
725
  const { table, source } = view.resolveRefSource(ref);
@@ -708,17 +728,20 @@ function buildViewPipeline(view, variant) {
708
728
  return prefix + source.column;
709
729
  };
710
730
  for (const join of plan.joins) {
711
- pipeline.push(buildLookup(view, join, prefixes));
731
+ pipeline.push(buildLookup(view, join, prefixes, literalOf));
712
732
  pipeline.push({ $unwind: {
713
733
  path: `$${joinedAs(join.scope)}`,
714
734
  preserveNullAndEmptyArrays: join.kind === "left"
715
735
  } });
716
736
  prefixes.set(join.scope, `${joinedAs(join.scope)}.`);
717
737
  }
718
- if (plan.filter) pipeline.push({ $match: viewMatch(plan.filter, pathOf) });
738
+ if (plan.filter) pipeline.push({ $match: viewMatch(plan.filter, pathOf, literalOf) });
719
739
  /** A column's source field as an aggregation operand. */
720
740
  const colSourceField = (col) => `$${prefixes.get(col.sourceTable) ?? ""}${col.sourceColumn}`;
721
741
  const colValue = (col) => col.nullable ? require_mongo_accumulator.orNull(colSourceField(col)) : colSourceField(col);
742
+ const numberPaths = /* @__PURE__ */ new Set();
743
+ for (const fd of view.fieldDescriptors) if (fd.designType === "number") numberPaths.add(fd.path);
744
+ const projected = (col, value) => col.exact && numberPaths.has(col.viewPath) ? require_mongo_accumulator.asDoubleOrNull(value) : value;
722
745
  const byPath = new Map(columns.map((c) => [c.viewPath, c]));
723
746
  const rendered = /* @__PURE__ */ new Map();
724
747
  const computedExpr = (col, leaf) => {
@@ -735,29 +758,31 @@ function buildViewPipeline(view, variant) {
735
758
  if (columns.some((c) => c.aggFn)) {
736
759
  const group = { _id: {} };
737
760
  const project = { _id: 0 };
738
- const distinctSizes = {};
761
+ const settled = {};
739
762
  const computed = {};
740
763
  for (const col of columns) if (col.expr !== void 0) {
741
764
  computed[col.viewColumn] = computedExpr(col, (c) => c.aggFn ? `$${c.viewColumn}` : `$_id.${c.viewColumn}`);
742
765
  project[col.viewColumn] = `$${col.viewColumn}`;
743
766
  } else if (col.aggFn) {
744
- const predicate = col.aggFilter ? require_mongo_accumulator.queryNodeToExpr(col.aggFilter, (ref) => `$${pathOf(ref)}`) : void 0;
767
+ const predicate = col.aggFilter ? require_mongo_accumulator.queryNodeToExpr(col.aggFilter, (ref) => `$${pathOf(ref)}`, literalOf) : void 0;
745
768
  const source = col.aggField === "*" ? "*" : colSourceField(col);
746
- group[col.viewColumn] = require_mongo_accumulator.buildAccumulator(col.aggFn, col.decimal ? require_mongo_accumulator.asDecimal(source) : source, predicate, col.viewColumn);
747
- project[col.viewColumn] = col.decimal ? { $toString: `$${col.viewColumn}` } : `$${col.viewColumn}`;
748
- if (col.aggFn === "countDistinct") distinctSizes[col.viewColumn] = require_mongo_accumulator.distinctCountExpr(`$${col.viewColumn}`);
769
+ const operand = (col.aggFn === "sum" || col.aggFn === "avg") && col.exact !== void 0 ? require_mongo_accumulator.asDecimal(source) : source;
770
+ group[col.viewColumn] = require_mongo_accumulator.buildAccumulator(col.aggFn, operand, predicate, col.viewColumn);
771
+ project[col.viewColumn] = projected(col, `$${col.viewColumn}`);
772
+ if (col.aggFn === "countDistinct") settled[col.viewColumn] = require_mongo_accumulator.distinctCountExpr(`$${col.viewColumn}`);
773
+ else if (col.aggFn === "sum" && !predicate) settled[col.viewColumn] = require_mongo_accumulator.nullWhenEmpty(group, col.viewColumn, operand);
749
774
  } else {
750
775
  group._id[col.viewColumn] = colValue(col);
751
- project[col.viewColumn] = `$_id.${col.viewColumn}`;
776
+ project[col.viewColumn] = projected(col, `$_id.${col.viewColumn}`);
752
777
  }
753
778
  pipeline.push({ $group: group });
754
- if (Object.keys(distinctSizes).length > 0) pipeline.push({ $addFields: distinctSizes });
779
+ if (Object.keys(settled).length > 0) pipeline.push({ $addFields: settled });
755
780
  if (Object.keys(computed).length > 0) pipeline.push({ $addFields: computed });
756
781
  if (plan.having) pipeline.push({ $match: havingMatch(plan.having, byPath) });
757
782
  pipeline.push({ $project: project });
758
783
  } else {
759
784
  const project = { _id: 0 };
760
- for (const col of columns) project[col.viewColumn] = col.expr === void 0 ? colValue(col) : computedExpr(col, colValue);
785
+ for (const col of columns) project[col.viewColumn] = col.expr === void 0 ? projected(col, colValue(col)) : computedExpr(col, colValue);
761
786
  pipeline.push({ $project: project });
762
787
  }
763
788
  return pipeline;
@@ -775,7 +800,7 @@ function buildViewPipeline(view, variant) {
775
800
  * can't before MongoDB 5.0. Everything else uses the pipeline form (`let` +
776
801
  * `$match: { $expr }`, SQL null semantics).
777
802
  */
778
- function buildLookup(view, join, outer) {
803
+ function buildLookup(view, join, outer, literalOf) {
779
804
  const scope = join.scope;
780
805
  const as = joinedAs(scope);
781
806
  const simple = join.first ? void 0 : simpleJoinFields(view, join, outer);
@@ -800,7 +825,7 @@ function buildLookup(view, join, outer) {
800
825
  }
801
826
  return `$$${varName}`;
802
827
  };
803
- const pipeline = [{ $match: { $expr: require_mongo_accumulator.queryNodeToExpr(join.condition, pathOf) } }];
828
+ const pipeline = [{ $match: { $expr: require_mongo_accumulator.queryNodeToExpr(join.condition, pathOf, literalOf) } }];
804
829
  if (join.first) {
805
830
  const sort = {};
806
831
  for (const { ref, desc } of join.first.order) sort[view.resolveRefSource(ref).source.column] = desc ? -1 : 1;
@@ -850,26 +875,26 @@ function simpleJoinFields(view, join, outer) {
850
875
  * over pipeline paths: the shared query translation (`translateQueryTree` →
851
876
  * `buildMongoFilter`), so operators mean what they mean in queries (`exists`
852
877
  * = holds a value, `matches` takes `/re/flags`); a field-to-field comparison
853
- * becomes `$expr`. A literal compared with one of the `decimals` paths (a
854
- * `Decimal128` there) is a `Decimal128` ({@link decimalComparands}).
878
+ * becomes `$expr`. `literalOf` gives a literal compared with a `Decimal128` /
879
+ * `Long` its `Decimal128` form.
855
880
  */
856
- function viewMatch(node, pathOf, decimals = /* @__PURE__ */ new Set()) {
857
- return require_mongo_accumulator.buildMongoFilter(require_mongo_accumulator.decimalComparands((0, _atscript_db.translateQueryTree)(node, pathOf), decimals), { fieldOperands: true });
881
+ function viewMatch(node, pathOf, literalOf) {
882
+ return require_mongo_accumulator.buildMongoFilter((0, _atscript_db.translateQueryTree)(node, pathOf, literalOf), { fieldOperands: true });
858
883
  }
859
884
  /**
860
885
  * `@db.view.having` as a `$match` after `$group`: refs name view fields —
861
886
  * aggregates are top-level, dimensions under `_id`. A literal compared with
862
- * a decimal aggregate (a `Decimal128` there) is a `Decimal128` (since
863
- * 0.1.207: `high >= 19.99` compared the double just below 19.99).
887
+ * a column over a decimal or long source (a `Decimal128` / `Long` there) is
888
+ * a `Decimal128` (since 0.1.207: `high >= 19.99` compared the double just
889
+ * below 19.99).
864
890
  */
865
891
  function havingMatch(node, colMap) {
866
- const decimals = /* @__PURE__ */ new Set();
867
- for (const col of colMap.values()) if (col.decimal) decimals.add(col.viewColumn);
892
+ const colOf = (ref) => ref.type ? void 0 : colMap.get(ref.field);
868
893
  return viewMatch(node, (ref) => {
869
- const col = ref.type ? void 0 : colMap.get(ref.field);
894
+ const col = colOf(ref);
870
895
  if (!col) return ref.field;
871
896
  return col.aggFn || col.expr !== void 0 ? col.viewColumn : `_id.${col.viewColumn}`;
872
- }, decimals);
897
+ }, (ref, value) => colOf(ref)?.exact ? require_mongo_accumulator.exactLiteral(value, ref.field) : value);
873
898
  }
874
899
  //#endregion
875
900
  //#region src/lib/mongo-view-read.ts
@@ -1736,13 +1761,18 @@ const VECTOR_FILTER_OPS = new Set([
1736
1761
  "$in",
1737
1762
  "$nin"
1738
1763
  ]);
1739
- /** A value `$vectorSearch.filter` compares like `$match` (no `null`, arrays, regexes). */
1764
+ /**
1765
+ * A value `$vectorSearch.filter` compares like `$match` (no `null`, arrays,
1766
+ * regexes): a `long`'s Int64 included (since 0.1.209); a `decimal`'s
1767
+ * `Decimal128` is no type the vector index filters on — such a condition
1768
+ * runs after the search.
1769
+ */
1740
1770
  function isVectorFilterValue(value) {
1741
1771
  switch (typeof value) {
1742
1772
  case "string":
1743
1773
  case "boolean": return true;
1744
1774
  case "number": return Number.isFinite(value);
1745
- case "object": return value instanceof Date && !Number.isNaN(value.getTime()) || value instanceof mongodb.ObjectId;
1775
+ case "object": return value instanceof Date && !Number.isNaN(value.getTime()) || value instanceof mongodb.ObjectId || value?._bsontype === "Long";
1746
1776
  default: return false;
1747
1777
  }
1748
1778
  }
@@ -2068,7 +2098,7 @@ async function syncColumnsImpl(host, diff) {
2068
2098
  }
2069
2099
  if (renamed.length > 0) await host.collection.updateMany({}, { $rename: renameSpec }, host._getSessionOpts());
2070
2100
  for (const field of diff.added) {
2071
- const value = resolveSyncDefault(field);
2101
+ const value = resolveSyncDefault(host, field);
2072
2102
  if (value !== void 0) await defaultBackfill(host, field.path, value);
2073
2103
  added.push(field.physicalName);
2074
2104
  }
@@ -2160,9 +2190,13 @@ function pathCrossesArray(host, logicalPath) {
2160
2190
  return false;
2161
2191
  }
2162
2192
  /** Resolves a field's default value for bulk $set during column sync. */
2163
- function resolveSyncDefault(field) {
2193
+ function resolveSyncDefault(host, field) {
2164
2194
  if (!field.defaultValue) return;
2165
- if (field.defaultValue.kind === "value") return (0, _atscript_db.parseDefaultLiteral)(field.designType, field.defaultValue.value);
2195
+ if (field.defaultValue.kind === "value") {
2196
+ const value = (0, _atscript_db.parseDefaultLiteral)(field.designType, field.defaultValue.value);
2197
+ const toStorage = host._table.getMetadata().toStorageFormatters?.get(field.physicalName);
2198
+ return toStorage ? toStorage(value) : value;
2199
+ }
2166
2200
  }
2167
2201
  /**
2168
2202
  * Whether an index's fields include one of `paths` or a path under one —
@@ -2424,8 +2458,9 @@ function bsonPresentTypes(designType) {
2424
2458
  switch (designType) {
2425
2459
  case "string": return "string";
2426
2460
  case "objectId": return ["objectId", "string"];
2427
- case "number": return "number";
2428
- case "decimal": return "string";
2461
+ case "number":
2462
+ case "decimal":
2463
+ case "long": return "number";
2429
2464
  case "boolean": return "bool";
2430
2465
  default: return [
2431
2466
  "double",
@@ -2601,13 +2636,6 @@ function objectIdFromStorage(value) {
2601
2636
  * predicates (see {@link MongoAdapter.supportsRelationFilters}).
2602
2637
  */
2603
2638
  const REL_WRITE_BATCH = 1e3;
2604
- /** The view aggregates a decimal is projected as text by (`buildViewPipeline`). */
2605
- const DECIMAL_VIEW_AGGS = [
2606
- "db.agg.sum",
2607
- "db.agg.avg",
2608
- "db.agg.min",
2609
- "db.agg.max"
2610
- ];
2611
2639
  var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2612
2640
  db;
2613
2641
  client;
@@ -2639,6 +2667,12 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2639
2667
  _hasExplicitId = false;
2640
2668
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
2641
2669
  _pendingUniqueFields = [];
2670
+ /**
2671
+ * Paths holding a JSON value — an array, a `@db.json` field — recorded
2672
+ * during onFieldScanned: a leaf below one is part of that value, stored as
2673
+ * written, never formatted ({@link formatValue}).
2674
+ */
2675
+ _jsonValuePaths = /* @__PURE__ */ new Set();
2642
2676
  /** {@link _patcherMaps}' memo. */
2643
2677
  _patcherMapsMemo;
2644
2678
  constructor(db, client, options = {}) {
@@ -2843,13 +2877,13 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2843
2877
  }
2844
2878
  /**
2845
2879
  * See BaseDbAdapter.viewRenderRevision. 2 = 0.1.137 (null-guarded field filters, nested document paths);
2846
- * 3 = 0.1.207, for a view with a `sum` / `avg` / `min` / `max` column of a decimal only (aggregated as a
2847
- * `Decimal128`, projected as its text) — every other view keeps 2, so only those are recreated.
2880
+ * 3 = 0.1.207 (decimal aggregate views only); 4 = 0.1.209, every view: decimals and longs stay
2881
+ * `Decimal128` / `Long` in the view, an unconditional `sum` over no value is null, a `number` column over
2882
+ * a decimal or long source is a double, predicate literals compared with one are `Decimal128`s.
2848
2883
  * BUMP whenever `buildViewPipeline` output changes for an unchanged view definition.
2849
2884
  */
2850
2885
  viewRenderRevision() {
2851
- const view = this._table;
2852
- return view?.isView && !view.isExternal && view.getViewColumnMappings().some((c) => c.decimal) ? "3" : "2";
2886
+ return "4";
2853
2887
  }
2854
2888
  getValidatorPlugins() {
2855
2889
  return [validateMongoIdPlugin];
@@ -2878,18 +2912,20 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2878
2912
  * formatters, so id envelopes (`@DbActionID` row loading), FK filters
2879
2913
  * (`{ leadId: '<hex>' }`), and inserted documents match natively stored
2880
2914
  * ObjectIds — and reads return the hex strings the declared type promises.
2881
- * Top-level fields only: nested values skip the write/read formatter passes,
2882
- * so a nested formatter would coerce filters against un-coerced storage.
2915
+ * Top-level fields only: a nested id has always been stored as its hex text.
2916
+ *
2917
+ * Stores a `decimal` as a `Decimal128` and a `long` as an Int64 (since
2918
+ * 0.1.209; `mongo-exact.ts`), at any depth of plain nested objects — reads
2919
+ * need no decoding (the core turns either into its text).
2883
2920
  *
2884
- * A view's `sum` / `avg` / `min` / `max` of a decimal is projected as its
2885
- * `Decimal128`'s text, which may be exponent notation (`"5E-8"`): it reads
2886
- * as a decimal string (`toDecimalString`, since 0.1.207).
2921
+ * Never a leaf inside a JSON value (an array, a `@db.json` field) or an
2922
+ * encrypted one: that value is stored as written, so a filter on the leaf
2923
+ * compares what is stored.
2887
2924
  */
2888
2925
  formatValue(field) {
2889
- if (field.designType === "decimal" && DECIMAL_VIEW_AGGS.some((k) => field.type.metadata.has(k))) return {
2890
- toStorage: (value) => value,
2891
- fromStorage: _atscript_db.toDecimalString
2892
- };
2926
+ if (field.encrypted || (0, _atscript_db.jsonValueAncestor)(field.path, this._jsonValuePaths) !== void 0) return;
2927
+ const kind = (0, _atscript_db.exactKindOf)(field.designType);
2928
+ if (kind) return require_mongo_accumulator.exactToStorage(kind, field.path);
2893
2929
  if (field.isGeoPoint) return {
2894
2930
  toStorage: (value) => Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number" ? {
2895
2931
  type: "Point",
@@ -2905,6 +2941,15 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2905
2941
  fromStorage: objectIdFromStorage
2906
2942
  };
2907
2943
  }
2944
+ /**
2945
+ * A `$having` comparand of an exact-kind alias (since 0.1.209): a
2946
+ * `Decimal128` for a decimal and a long alike — the server compares it with
2947
+ * the aggregate's `Decimal128` (a `sum` / `avg`) or the stored `Decimal128`
2948
+ * / `Long` (a `min` / `max` / `first` / `last`) by value.
2949
+ */
2950
+ exactComparand(_kind, text) {
2951
+ return require_mongo_accumulator.exactLiteral(text, "$having");
2952
+ }
2908
2953
  getAdapterTableName(_type) {}
2909
2954
  supportsNativeRelations() {
2910
2955
  return true;
@@ -3080,7 +3125,14 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
3080
3125
  });
3081
3126
  }
3082
3127
  onFieldScanned(field, _type, metadata) {
3083
- if (field === "_id") this._hasExplicitId = true;
3128
+ const type = _type;
3129
+ if (field === "_id") {
3130
+ this._hasExplicitId = true;
3131
+ const kind = (0, _atscript_db.exactKindOf)((0, _atscript_db.resolveDesignType)(type));
3132
+ if (kind) throw new Error(`[db.mongo] _id can't be a ${kind} in collection "${this._table.tableName}" — _id is a string, number or mongo.objectId; declare the ${kind} key as another @meta.id field`);
3133
+ }
3134
+ const designType = (0, _atscript_db.resolveDesignType)(type);
3135
+ if (designType === "array" || designType === "json" || metadata.has("db.json")) this._jsonValuePaths.add(field);
3084
3136
  if (field !== "_id" && !field.includes(".") && metadata.has("meta.id")) this._pendingUniqueFields.push(field);
3085
3137
  for (const index of metadata.get("db.mongo.search.text") || []) this._pendingSearchFields.push({
3086
3138
  indexName: index.indexName,
@@ -3471,7 +3523,7 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
3471
3523
  const fields = this._fieldsNeedingIncrement(data);
3472
3524
  if (fields.length > 0) {
3473
3525
  const nextValues = await this._allocateIncrementValues(fields, 1);
3474
- for (const physical of fields) data[physical] = nextValues.get(physical) ?? 1;
3526
+ for (const physical of fields) data[physical] = this._storageForm(physical, nextValues.get(physical) ?? 1);
3475
3527
  }
3476
3528
  }
3477
3529
  this._log("insertOne", data);
@@ -3537,7 +3589,8 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
3537
3589
  */
3538
3590
  async _findStoredKeyConflicts(data) {
3539
3591
  const keySets = [["_id"], ...this._table.uniqueKeySets.filter((f) => !(f.length === 1 && f[0] === "_id"))];
3540
- const rowTuples = data.map((row) => keySets.map((fields) => (0, _atscript_db.uniqueKeyTuple)(row, fields)));
3592
+ const exact = this._table.getMetadata().exactFields;
3593
+ const rowTuples = data.map((row) => keySets.map((fields) => (0, _atscript_db.uniqueKeyTuple)(row, fields, exact)));
3541
3594
  const projection = Object.fromEntries(keySets.flat().map((f) => [f, 1]));
3542
3595
  const stored = keySets.map(() => /* @__PURE__ */ new Set());
3543
3596
  const CHUNK = 1e3;
@@ -3555,7 +3608,7 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
3555
3608
  ...this._getSessionOpts()
3556
3609
  }).toArray();
3557
3610
  for (const doc of found) keySets.forEach((fields, k) => {
3558
- const tuple = (0, _atscript_db.uniqueKeyTuple)(doc, fields);
3611
+ const tuple = (0, _atscript_db.uniqueKeyTuple)(doc, fields, exact);
3559
3612
  if (tuple !== void 0) stored[k].add(tuple);
3560
3613
  });
3561
3614
  }
@@ -3799,7 +3852,20 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
3799
3852
  }
3800
3853
  return result;
3801
3854
  }
3802
- /** Reads current max value for a single field via $group aggregation. */
3855
+ /**
3856
+ * An allocated `@db.default.increment` value in its storage form — the
3857
+ * column's write formatter applied (a `long` field's is an Int64, since
3858
+ * 0.1.209). The insert's own values are formatted before they reach here.
3859
+ */
3860
+ _storageForm(physical, value) {
3861
+ const fmt = this._table.getMetadata().toStorageFormatters?.get(physical);
3862
+ return fmt ? fmt(value) : value;
3863
+ }
3864
+ /**
3865
+ * Reads current max value for a single field via $group aggregation. A
3866
+ * `long` field's maximum beyond 2^53 (a `Long` — smaller ones are read as
3867
+ * numbers) is refused: the counter allocates JS numbers.
3868
+ */
3803
3869
  async _getCurrentFieldMax(field) {
3804
3870
  const alias = `max__${field.replace(/\./g, "__")}`;
3805
3871
  const agg = await this.collection.aggregate([{ $group: {
@@ -3809,6 +3875,10 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
3809
3875
  if (agg.length > 0) {
3810
3876
  const val = agg[0][alias];
3811
3877
  if (typeof val === "number") return val;
3878
+ if (require_mongo_accumulator.isBsonNumber(val)) throw new _atscript_db.DbError("NOT_SUPPORTED", [{
3879
+ path: field,
3880
+ message: `@db.default.increment on "${field}" cannot continue past 2^53 - 1 (the stored maximum is ${val.toString()})`
3881
+ }]);
3812
3882
  }
3813
3883
  return 0;
3814
3884
  }
@@ -3827,7 +3897,7 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
3827
3897
  }
3828
3898
  for (const item of data) for (const physical of allFields) if (item[physical] === void 0 || item[physical] === null) {
3829
3899
  const next = fieldCounters.get(physical) ?? 1;
3830
- item[physical] = next;
3900
+ item[physical] = this._storageForm(physical, next);
3831
3901
  fieldCounters.set(physical, next + 1);
3832
3902
  }
3833
3903
  }
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as buildMongoFilter, c as mongoFilterStages, i as TMongoFilterPlan, l as planStages, n as TMongoFieldCollation, o as buildMongoQuery, r as TMongoFilterOptions, s as collationOfAdapter, t as REL_FILTER_TEMP_PREFIX } from "./mongo-filter-CGd9ryOD.cjs";
2
- import { BaseDbAdapter, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbCollation, TDbDeleteResult, TDbFieldMeta, TDbForeignKey, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbRelation, TDbUpdateOptions, TDbUpdateResult, TExistingTableOption, TFieldOps, TIndexChange, TMetadataOverrides, TPrimaryKeyChange, TSearchIndexInfo, TSyncColumnResult, TSyncIndexesOptions, TTableResolver, TTransactionOptions, TViewCapability, TableMetadata, WithRelation, getKeyProps, toDecimalString } from "@atscript/db";
2
+ import { BaseDbAdapter, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbCollation, TDbDeleteResult, TDbFieldMeta, TDbForeignKey, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbRelation, TDbUpdateOptions, TDbUpdateResult, TExactKind, TExistingTableOption, TFieldOps, TIndexChange, TMetadataOverrides, TPrimaryKeyChange, TSearchIndexInfo, TSyncColumnResult, TSyncIndexesOptions, TTableResolver, TTransactionOptions, TViewCapability, TableMetadata, WithRelation, getKeyProps } from "@atscript/db";
3
3
  import { AggregateOptions, AggregationCursor, ClientSession, Collection, Db, Document, Filter, MongoClient, ObjectId, UpdateFilter, UpdateOptions } from "mongodb";
4
4
  import { TAtscriptAnnotatedType, TMetadataMap, TValidatorOptions, TValidatorPlugin, Validator } from "@atscript/typescript/utils";
5
5
  import { AggregateFn, BucketUnit } from "@uniqu/core";
@@ -348,6 +348,12 @@ declare class MongoAdapter extends BaseDbAdapter {
348
348
  protected _hasExplicitId: boolean;
349
349
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
350
350
  private _pendingUniqueFields;
351
+ /**
352
+ * Paths holding a JSON value — an array, a `@db.json` field — recorded
353
+ * during onFieldScanned: a leaf below one is part of that value, stored as
354
+ * written, never formatted ({@link formatValue}).
355
+ */
356
+ private _jsonValuePaths;
351
357
  /** {@link _patcherMaps}' memo. */
352
358
  private _patcherMapsMemo?;
353
359
  constructor(db: Db, client?: MongoClient | undefined, options?: TMongoAdapterOptions);
@@ -434,8 +440,9 @@ declare class MongoAdapter extends BaseDbAdapter {
434
440
  viewCapabilities(): ReadonlySet<TViewCapability>;
435
441
  /**
436
442
  * See BaseDbAdapter.viewRenderRevision. 2 = 0.1.137 (null-guarded field filters, nested document paths);
437
- * 3 = 0.1.207, for a view with a `sum` / `avg` / `min` / `max` column of a decimal only (aggregated as a
438
- * `Decimal128`, projected as its text) — every other view keeps 2, so only those are recreated.
443
+ * 3 = 0.1.207 (decimal aggregate views only); 4 = 0.1.209, every view: decimals and longs stay
444
+ * `Decimal128` / `Long` in the view, an unconditional `sum` over no value is null, a `number` column over
445
+ * a decimal or long source is a double, predicate literals compared with one are `Decimal128`s.
439
446
  * BUMP whenever `buildViewPipeline` output changes for an unchanged view definition.
440
447
  */
441
448
  viewRenderRevision(): string;
@@ -462,17 +469,27 @@ declare class MongoAdapter extends BaseDbAdapter {
462
469
  * formatters, so id envelopes (`@DbActionID` row loading), FK filters
463
470
  * (`{ leadId: '<hex>' }`), and inserted documents match natively stored
464
471
  * ObjectIds — and reads return the hex strings the declared type promises.
465
- * Top-level fields only: nested values skip the write/read formatter passes,
466
- * so a nested formatter would coerce filters against un-coerced storage.
472
+ * Top-level fields only: a nested id has always been stored as its hex text.
473
+ *
474
+ * Stores a `decimal` as a `Decimal128` and a `long` as an Int64 (since
475
+ * 0.1.209; `mongo-exact.ts`), at any depth of plain nested objects — reads
476
+ * need no decoding (the core turns either into its text).
467
477
  *
468
- * A view's `sum` / `avg` / `min` / `max` of a decimal is projected as its
469
- * `Decimal128`'s text, which may be exponent notation (`"5E-8"`): it reads
470
- * as a decimal string (`toDecimalString`, since 0.1.207).
478
+ * Never a leaf inside a JSON value (an array, a `@db.json` field) or an
479
+ * encrypted one: that value is stored as written, so a filter on the leaf
480
+ * compares what is stored.
471
481
  */
472
- formatValue(field: TDbFieldMeta): {
482
+ formatValue(field: TDbFieldMeta): ((value: unknown) => unknown) | {
473
483
  toStorage: (value: unknown) => unknown;
474
- fromStorage: typeof toDecimalString;
484
+ fromStorage: (value: unknown) => unknown;
475
485
  } | undefined;
486
+ /**
487
+ * A `$having` comparand of an exact-kind alias (since 0.1.209): a
488
+ * `Decimal128` for a decimal and a long alike — the server compares it with
489
+ * the aggregate's `Decimal128` (a `sum` / `avg`) or the stored `Decimal128`
490
+ * / `Long` (a `min` / `max` / `first` / `last`) by value.
491
+ */
492
+ exactComparand(_kind: TExactKind, text: string): unknown;
476
493
  getAdapterTableName(_type: unknown): string | undefined;
477
494
  supportsNativeRelations(): boolean;
478
495
  /**
@@ -728,7 +745,17 @@ declare class MongoAdapter extends BaseDbAdapter {
728
745
  * using a counter collection. Returns a map of field → first allocated value.
729
746
  */
730
747
  private _allocateIncrementValues;
731
- /** Reads current max value for a single field via $group aggregation. */
748
+ /**
749
+ * An allocated `@db.default.increment` value in its storage form — the
750
+ * column's write formatter applied (a `long` field's is an Int64, since
751
+ * 0.1.209). The insert's own values are formatted before they reach here.
752
+ */
753
+ private _storageForm;
754
+ /**
755
+ * Reads current max value for a single field via $group aggregation. A
756
+ * `long` field's maximum beyond 2^53 (a `Long` — smaller ones are read as
757
+ * numbers) is refused: the counter allocates JS numbers.
758
+ */
732
759
  private _getCurrentFieldMax;
733
760
  /** Allocates increment values for a batch of items, assigning in order. */
734
761
  private _assignBatchIncrements;
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as buildMongoFilter, c as mongoFilterStages, i as TMongoFilterPlan, l as planStages, n as TMongoFieldCollation, o as buildMongoQuery, r as TMongoFilterOptions, s as collationOfAdapter, t as REL_FILTER_TEMP_PREFIX } from "./mongo-filter-CGd9ryOD.mjs";
2
- import { BaseDbAdapter, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbCollation, TDbDeleteResult, TDbFieldMeta, TDbForeignKey, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbRelation, TDbUpdateOptions, TDbUpdateResult, TExistingTableOption, TFieldOps, TIndexChange, TMetadataOverrides, TPrimaryKeyChange, TSearchIndexInfo, TSyncColumnResult, TSyncIndexesOptions, TTableResolver, TTransactionOptions, TViewCapability, TableMetadata, WithRelation, getKeyProps, toDecimalString } from "@atscript/db";
2
+ import { BaseDbAdapter, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbCollation, TDbDeleteResult, TDbFieldMeta, TDbForeignKey, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbRelation, TDbUpdateOptions, TDbUpdateResult, TExactKind, TExistingTableOption, TFieldOps, TIndexChange, TMetadataOverrides, TPrimaryKeyChange, TSearchIndexInfo, TSyncColumnResult, TSyncIndexesOptions, TTableResolver, TTransactionOptions, TViewCapability, TableMetadata, WithRelation, getKeyProps } from "@atscript/db";
3
3
  import { AggregateOptions, AggregationCursor, ClientSession, Collection, Db, Document, Filter, MongoClient, ObjectId, UpdateFilter, UpdateOptions } from "mongodb";
4
4
  import { AggregateFn, BucketUnit } from "@uniqu/core";
5
5
  import { TAtscriptAnnotatedType, TMetadataMap, TValidatorOptions, TValidatorPlugin, Validator } from "@atscript/typescript/utils";
@@ -348,6 +348,12 @@ declare class MongoAdapter extends BaseDbAdapter {
348
348
  protected _hasExplicitId: boolean;
349
349
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
350
350
  private _pendingUniqueFields;
351
+ /**
352
+ * Paths holding a JSON value — an array, a `@db.json` field — recorded
353
+ * during onFieldScanned: a leaf below one is part of that value, stored as
354
+ * written, never formatted ({@link formatValue}).
355
+ */
356
+ private _jsonValuePaths;
351
357
  /** {@link _patcherMaps}' memo. */
352
358
  private _patcherMapsMemo?;
353
359
  constructor(db: Db, client?: MongoClient | undefined, options?: TMongoAdapterOptions);
@@ -434,8 +440,9 @@ declare class MongoAdapter extends BaseDbAdapter {
434
440
  viewCapabilities(): ReadonlySet<TViewCapability>;
435
441
  /**
436
442
  * See BaseDbAdapter.viewRenderRevision. 2 = 0.1.137 (null-guarded field filters, nested document paths);
437
- * 3 = 0.1.207, for a view with a `sum` / `avg` / `min` / `max` column of a decimal only (aggregated as a
438
- * `Decimal128`, projected as its text) — every other view keeps 2, so only those are recreated.
443
+ * 3 = 0.1.207 (decimal aggregate views only); 4 = 0.1.209, every view: decimals and longs stay
444
+ * `Decimal128` / `Long` in the view, an unconditional `sum` over no value is null, a `number` column over
445
+ * a decimal or long source is a double, predicate literals compared with one are `Decimal128`s.
439
446
  * BUMP whenever `buildViewPipeline` output changes for an unchanged view definition.
440
447
  */
441
448
  viewRenderRevision(): string;
@@ -462,17 +469,27 @@ declare class MongoAdapter extends BaseDbAdapter {
462
469
  * formatters, so id envelopes (`@DbActionID` row loading), FK filters
463
470
  * (`{ leadId: '<hex>' }`), and inserted documents match natively stored
464
471
  * ObjectIds — and reads return the hex strings the declared type promises.
465
- * Top-level fields only: nested values skip the write/read formatter passes,
466
- * so a nested formatter would coerce filters against un-coerced storage.
472
+ * Top-level fields only: a nested id has always been stored as its hex text.
473
+ *
474
+ * Stores a `decimal` as a `Decimal128` and a `long` as an Int64 (since
475
+ * 0.1.209; `mongo-exact.ts`), at any depth of plain nested objects — reads
476
+ * need no decoding (the core turns either into its text).
467
477
  *
468
- * A view's `sum` / `avg` / `min` / `max` of a decimal is projected as its
469
- * `Decimal128`'s text, which may be exponent notation (`"5E-8"`): it reads
470
- * as a decimal string (`toDecimalString`, since 0.1.207).
478
+ * Never a leaf inside a JSON value (an array, a `@db.json` field) or an
479
+ * encrypted one: that value is stored as written, so a filter on the leaf
480
+ * compares what is stored.
471
481
  */
472
- formatValue(field: TDbFieldMeta): {
482
+ formatValue(field: TDbFieldMeta): ((value: unknown) => unknown) | {
473
483
  toStorage: (value: unknown) => unknown;
474
- fromStorage: typeof toDecimalString;
484
+ fromStorage: (value: unknown) => unknown;
475
485
  } | undefined;
486
+ /**
487
+ * A `$having` comparand of an exact-kind alias (since 0.1.209): a
488
+ * `Decimal128` for a decimal and a long alike — the server compares it with
489
+ * the aggregate's `Decimal128` (a `sum` / `avg`) or the stored `Decimal128`
490
+ * / `Long` (a `min` / `max` / `first` / `last`) by value.
491
+ */
492
+ exactComparand(_kind: TExactKind, text: string): unknown;
476
493
  getAdapterTableName(_type: unknown): string | undefined;
477
494
  supportsNativeRelations(): boolean;
478
495
  /**
@@ -728,7 +745,17 @@ declare class MongoAdapter extends BaseDbAdapter {
728
745
  * using a counter collection. Returns a map of field → first allocated value.
729
746
  */
730
747
  private _allocateIncrementValues;
731
- /** Reads current max value for a single field via $group aggregation. */
748
+ /**
749
+ * An allocated `@db.default.increment` value in its storage form — the
750
+ * column's write formatter applied (a `long` field's is an Int64, since
751
+ * 0.1.209). The insert's own values are formatted before they reach here.
752
+ */
753
+ private _storageForm;
754
+ /**
755
+ * Reads current max value for a single field via $group aggregation. A
756
+ * `long` field's maximum beyond 2^53 (a `Long` — smaller ones are read as
757
+ * numbers) is refused: the counter allocates JS numbers.
758
+ */
732
759
  private _getCurrentFieldMax;
733
760
  /** Allocates increment values for a batch of items, assigning in order. */
734
761
  private _assignBatchIncrements;