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