@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.
@@ -2,6 +2,80 @@ let _atscript_db = require("@atscript/db");
2
2
  let mongodb = require("mongodb");
3
3
  let _uniqu_core = require("@uniqu/core");
4
4
  let _atscript_db_agg = require("@atscript/db/agg");
5
+ //#region src/lib/mongo-exact.ts
6
+ /**
7
+ * MongoDB storage of the exact kinds (since 0.1.209): a `decimal` is a
8
+ * `Decimal128`, a `long` an Int64 (`Long`) — so the server compares, sorts,
9
+ * groups, indexes and aggregates them by value. Reads need no decoding of
10
+ * their own: the core turns either object into its text
11
+ * (`Decimal128.toString()`, an exponent written out).
12
+ */
13
+ /** A decimal as `decimal` validates it — stored as written, so its scale survives (`"12.50"`). */
14
+ const DECIMAL_TEXT_RE = /^[+-]?\d+(\.\d+)?$/;
15
+ /** Whether `value` is a BSON number object — a `Decimal128` or a `Long` (a stored decimal / long). */
16
+ function isBsonNumber(value) {
17
+ if (value === null || typeof value !== "object") return false;
18
+ const type = value._bsontype;
19
+ return type === "Decimal128" || type === "Long";
20
+ }
21
+ function refuse(path, message) {
22
+ throw new _atscript_db.DbError("INVALID_QUERY", [{
23
+ path,
24
+ message
25
+ }]);
26
+ }
27
+ /**
28
+ * `text` as a `Decimal128`: decimal text as written (its scale kept), a
29
+ * lenient numeric form a filter may carry (`" 5 "`, `".5"`, `"1e3"`) by its
30
+ * value. `INVALID_QUERY` (400) for text that is no number, and for a value
31
+ * `Decimal128` cannot hold exactly — more than 34 significant digits, or an
32
+ * exponent beyond its range — instead of the driver's rounding error.
33
+ */
34
+ function toDecimal128(text, path) {
35
+ const exact = DECIMAL_TEXT_RE.test(text) ? text : (0, _atscript_db.exactKey)(text);
36
+ if (exact === void 0) refuse(path, `Expected a decimal, got ${JSON.stringify(text)}`);
37
+ try {
38
+ return mongodb.Decimal128.fromString(exact);
39
+ } catch {
40
+ const digits = exact.replace(/^[+-]/, "").replace(".", "").replace(/^0+/, "").length;
41
+ return refuse(path, `${JSON.stringify(text)} ${digits > 34 ? "has more than 34 significant digits" : "is beyond the exponent range of a Decimal128"} — MongoDB stores a decimal as a Decimal128`);
42
+ }
43
+ }
44
+ /**
45
+ * `value` as an Int64: a long's text, a safe-integer number or a bigint
46
+ * (`canonicalLong` — never `Long.fromString`, which wraps 2^63 to -2^63 and
47
+ * reads `"1.5"` as 1). `INVALID_QUERY` (400) for one outside the signed
48
+ * 64-bit range.
49
+ */
50
+ function toLong(value, path) {
51
+ const text = (0, _atscript_db.canonicalLong)(value);
52
+ if (text === void 0) refuse(path, `Expected a 64-bit integer, got ${JSON.stringify(String(value))}`);
53
+ return mongodb.Long.fromBigInt(BigInt(text));
54
+ }
55
+ /**
56
+ * The write / filter formatter (`toStorage`) of a scalar `decimal` or `long`
57
+ * field at `path`: text (the core has already written a number out as text,
58
+ * and canonicalized a long) becomes a `Decimal128` / `Long`; any other value
59
+ * — `null`, an operator payload such as `$exists: true`, an already-encoded
60
+ * object — passes through.
61
+ */
62
+ function exactToStorage(kind, path) {
63
+ return kind === "decimal" ? (value) => typeof value === "string" ? toDecimal128(value, path) : value : (value) => typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? toLong(value, path) : value;
64
+ }
65
+ /**
66
+ * A literal compared with an exact-kind value (a `$having` comparand, a view
67
+ * predicate's literal): a number, a bigint or numeric text as a `Decimal128`
68
+ * — MongoDB compares it with a stored `Decimal128` or `Long` (or an
69
+ * aggregate's `Decimal128`) by value, exactly; a double would not equal the
70
+ * decimal `19.99`. Any other value passes through.
71
+ */
72
+ function exactLiteral(value, path) {
73
+ if (Array.isArray(value)) return value.map((item) => exactLiteral(item, path));
74
+ if (typeof value === "number") return Number.isFinite(value) ? toDecimal128(String(value), path) : value;
75
+ if (typeof value === "bigint" || typeof value === "string") return toDecimal128(String(value), path);
76
+ return value;
77
+ }
78
+ //#endregion
5
79
  //#region src/lib/mongo-view-expr.ts
6
80
  /**
7
81
  * `x IS NOT NULL` in SQL terms — true when `x` is neither null nor missing.
@@ -66,21 +140,25 @@ function fieldCompareExpr(op, x, y) {
66
140
  * - `and` / `or` / `not` map directly — so `not (x > 1)` is TRUE for a null
67
141
  * `x` here while SQL yields UNKNOWN (documented divergence);
68
142
  * - `matches` is rejected (`$regexMatch` needs MongoDB 4.2).
143
+ *
144
+ * `literalOf` (since 0.1.209) gives a literal compared with `ref` its
145
+ * storage form — a `Decimal128` against a decimal or long source.
69
146
  * @since 0.1.136
70
147
  */
71
- function queryNodeToExpr(node, pathOf) {
72
- if ("$and" in node) return { $and: node.$and.map((n) => queryNodeToExpr(n, pathOf)) };
73
- if ("$or" in node) return { $or: node.$or.map((n) => queryNodeToExpr(n, pathOf)) };
74
- if ("$not" in node) return { $not: [queryNodeToExpr(node.$not, pathOf)] };
148
+ function queryNodeToExpr(node, pathOf, literalOf) {
149
+ if ("$and" in node) return { $and: node.$and.map((n) => queryNodeToExpr(n, pathOf, literalOf)) };
150
+ if ("$or" in node) return { $or: node.$or.map((n) => queryNodeToExpr(n, pathOf, literalOf)) };
151
+ if ("$not" in node) return { $not: [queryNodeToExpr(node.$not, pathOf, literalOf)] };
75
152
  const comp = node;
76
153
  const x = pathOf(comp.left);
154
+ const stored = (value) => literal(literalOf ? literalOf(comp.left, value) : value);
77
155
  switch (comp.op) {
78
156
  case "$exists": return comp.right === false ? isNullExpr(x) : notNullExpr(x);
79
- case "$in": return { $in: [x, (Array.isArray(comp.right) ? comp.right : [comp.right]).map((v) => literal(v))] };
157
+ case "$in": return { $in: [x, (Array.isArray(comp.right) ? comp.right : [comp.right]).map((v) => stored(v))] };
80
158
  case "$nin": {
81
159
  const values = Array.isArray(comp.right) ? comp.right : [comp.right];
82
160
  if (values.length === 0) return { $literal: true };
83
- return guarded([x], { $not: [{ $in: [x, values.map((v) => literal(v))] }] });
161
+ return guarded([x], { $not: [{ $in: [x, values.map((v) => stored(v))] }] });
84
162
  }
85
163
  case "$regex": throw new Error("matches is not supported in view predicates");
86
164
  default:
@@ -93,7 +171,7 @@ function queryNodeToExpr(node, pathOf) {
93
171
  if (op === "$ne") return notNullExpr(x);
94
172
  return { $literal: false };
95
173
  }
96
- const value = literal(comp.right);
174
+ const value = stored(comp.right);
97
175
  if (op === "$eq") return { $eq: [x, value] };
98
176
  return guarded([x], { [op]: [x, value] });
99
177
  }
@@ -227,9 +305,13 @@ function eqCond(x, value) {
227
305
  { $eq: [x, v] }
228
306
  ] };
229
307
  }
230
- /** The comparison-class test of a range operand: only values of the operand's BSON class compare. */
308
+ /**
309
+ * The comparison-class test of a range operand: only values of the operand's
310
+ * BSON class compare — a number (a `Decimal128` / `Long` comparand of a
311
+ * decimal or long included) with any numeric BSON type.
312
+ */
231
313
  function sameClass(v, value) {
232
- if (typeof value === "number" || typeof value === "bigint") return { $isNumber: v };
314
+ if (typeof value === "number" || typeof value === "bigint" || isBsonNumber(value)) return { $isNumber: v };
233
315
  return { $eq: [{ $type: v }, { $type: valueOf(value) }] };
234
316
  }
235
317
  /**
@@ -778,11 +860,12 @@ function buildAccumulator(fn, src, where, path) {
778
860
  return fn === "countDistinct" ? { $addToSet: { $ifNull: [value, "$$REMOVE"] } } : { [`$${fn}`]: value };
779
861
  }
780
862
  /**
781
- * A decimal stored as its text, read as a `Decimal128` — exact, ordered by
782
- * value — for a `sum` / `avg` / `min` / `max` of it (since 0.1.207: `$sum` /
783
- * `$avg` skip text, `$min` / `$max` compare it as text). A value that is no
784
- * decimal text (`""`) reads as null, like a missing one, instead of failing
785
- * the pipeline.
863
+ * The operand of a `sum` / `avg` of a `decimal` or `long` field, read as a
864
+ * `Decimal128` (since 0.1.207; longs since 0.1.209): exact, where `$sum`
865
+ * over Int64 values overflows to a double and `$avg` of them is a double. A
866
+ * stored `Decimal128` is unchanged, a decimal stored as text by an earlier
867
+ * version is read by its value; a value that is no number (`""`) reads as
868
+ * null, like a missing one, instead of failing the pipeline.
786
869
  */
787
870
  function asDecimal(src) {
788
871
  return { $convert: {
@@ -792,47 +875,34 @@ function asDecimal(src) {
792
875
  onNull: null
793
876
  } };
794
877
  }
795
- /** Operators whose operand is compared with the column's values. */
796
- const COMPARE_OPS = new Set([
797
- "$eq",
798
- "$ne",
799
- "$gt",
800
- "$gte",
801
- "$lt",
802
- "$lte",
803
- "$in",
804
- "$nin"
805
- ]);
806
- /** A number or numeric text as a `Decimal128` (an array element-wise); any other value as it is. */
807
- function toDecimal128(value) {
808
- if (Array.isArray(value)) return value.map(toDecimal128);
809
- if (typeof value === "number" ? !Number.isFinite(value) : typeof value !== "string") return value;
810
- try {
811
- return mongodb.Decimal128.fromString(String(value).trim());
812
- } catch {
813
- return value;
814
- }
878
+ /**
879
+ * `src` as a double — a `Decimal128` / `Long` (a `number` view column over a
880
+ * decimal / long source, since 0.1.209); null when it is no number.
881
+ */
882
+ function asDoubleOrNull(src) {
883
+ return { $convert: {
884
+ input: src,
885
+ to: "double",
886
+ onError: null,
887
+ onNull: null
888
+ } };
815
889
  }
890
+ /** Prefix of the hidden `$group` field counting a sum's non-null values. */
891
+ const NON_NULL_PREFIX = "__as_n_";
816
892
  /**
817
- * `filter` (a `$having` or a `$where` over aggregate rows) with the
818
- * comparands of the `columns` holding `Decimal128`s ({@link asDecimal}'s
819
- * results) as `Decimal128`s (since 0.1.207): MongoDB compares a
820
- * `Decimal128` with a double exactly, so `19.99` — the double just below —
821
- * would never equal the decimal 19.99.
893
+ * `$sum` of no (non-null) value is 0 in MongoDB, NULL in SQL and the memory
894
+ * adapter: adds a hidden count of `operand`'s values (of the rows `where`
895
+ * matches) to `group` and returns the sum `alias` read as null over none —
896
+ * for a stage after `$group`.
822
897
  */
823
- function decimalComparands(filter, columns) {
824
- if (columns.size === 0 || !filter || typeof filter !== "object") return filter;
825
- const out = {};
826
- for (const [key, value] of Object.entries(filter)) if (key === "$and" || key === "$or") out[key] = value.map((f) => decimalComparands(f, columns));
827
- else if (key === "$not") out[key] = decimalComparands(value, columns);
828
- else if (!columns.has(key)) out[key] = value;
829
- else if ((0, _atscript_db.isPrimitive)(value) || Array.isArray(value)) out[key] = toDecimal128(value);
830
- else {
831
- const ops = {};
832
- for (const [op, operand] of Object.entries(value)) ops[op] = COMPARE_OPS.has(op) ? toDecimal128(operand) : operand;
833
- out[key] = ops;
834
- }
835
- return out;
898
+ function nullWhenEmpty(group, alias, operand, where) {
899
+ const count = `${NON_NULL_PREFIX}${alias}`;
900
+ group[count] = buildAccumulator("count", operand, where);
901
+ return { $cond: [
902
+ { $eq: [`$${count}`, 0] },
903
+ null,
904
+ `$${alias}`
905
+ ] };
836
906
  }
837
907
  /**
838
908
  * The size of a `countDistinct` set (`"$alias"`) — the value the accumulator
@@ -855,6 +925,12 @@ Object.defineProperty(exports, "asDecimal", {
855
925
  return asDecimal;
856
926
  }
857
927
  });
928
+ Object.defineProperty(exports, "asDoubleOrNull", {
929
+ enumerable: true,
930
+ get: function() {
931
+ return asDoubleOrNull;
932
+ }
933
+ });
858
934
  Object.defineProperty(exports, "buildAccumulator", {
859
935
  enumerable: true,
860
936
  get: function() {
@@ -885,16 +961,22 @@ Object.defineProperty(exports, "correlate", {
885
961
  return correlate;
886
962
  }
887
963
  });
888
- Object.defineProperty(exports, "decimalComparands", {
964
+ Object.defineProperty(exports, "distinctCountExpr", {
889
965
  enumerable: true,
890
966
  get: function() {
891
- return decimalComparands;
967
+ return distinctCountExpr;
892
968
  }
893
969
  });
894
- Object.defineProperty(exports, "distinctCountExpr", {
970
+ Object.defineProperty(exports, "exactLiteral", {
895
971
  enumerable: true,
896
972
  get: function() {
897
- return distinctCountExpr;
973
+ return exactLiteral;
974
+ }
975
+ });
976
+ Object.defineProperty(exports, "exactToStorage", {
977
+ enumerable: true,
978
+ get: function() {
979
+ return exactToStorage;
898
980
  }
899
981
  });
900
982
  Object.defineProperty(exports, "exprToMongo", {
@@ -909,12 +991,24 @@ Object.defineProperty(exports, "hasNullsPlacement", {
909
991
  return hasNullsPlacement;
910
992
  }
911
993
  });
994
+ Object.defineProperty(exports, "isBsonNumber", {
995
+ enumerable: true,
996
+ get: function() {
997
+ return isBsonNumber;
998
+ }
999
+ });
912
1000
  Object.defineProperty(exports, "mongoFilterStages", {
913
1001
  enumerable: true,
914
1002
  get: function() {
915
1003
  return mongoFilterStages;
916
1004
  }
917
1005
  });
1006
+ Object.defineProperty(exports, "nullWhenEmpty", {
1007
+ enumerable: true,
1008
+ get: function() {
1009
+ return nullWhenEmpty;
1010
+ }
1011
+ });
918
1012
  Object.defineProperty(exports, "orNull", {
919
1013
  enumerable: true,
920
1014
  get: function() {
@@ -1,7 +1,81 @@
1
- import { DbError, INTEGER_REGEX_OP, andFilters, assertExprArity, containsRelationFilter, isFieldRef, isPrimitive, isResolvedRelationFilter, walkFilter } from "@atscript/db";
2
- import { BSONRegExp, Decimal128 } from "mongodb";
1
+ import { DbError, INTEGER_REGEX_OP, andFilters, assertExprArity, canonicalLong, containsRelationFilter, exactKey, isFieldRef, isResolvedRelationFilter, walkFilter } from "@atscript/db";
2
+ import { BSONRegExp, Decimal128, Long } from "mongodb";
3
3
  import { isNullsPlacement } from "@uniqu/core";
4
4
  import { assertAggregateFn } from "@atscript/db/agg";
5
+ //#region src/lib/mongo-exact.ts
6
+ /**
7
+ * MongoDB storage of the exact kinds (since 0.1.209): a `decimal` is a
8
+ * `Decimal128`, a `long` an Int64 (`Long`) — so the server compares, sorts,
9
+ * groups, indexes and aggregates them by value. Reads need no decoding of
10
+ * their own: the core turns either object into its text
11
+ * (`Decimal128.toString()`, an exponent written out).
12
+ */
13
+ /** A decimal as `decimal` validates it — stored as written, so its scale survives (`"12.50"`). */
14
+ const DECIMAL_TEXT_RE = /^[+-]?\d+(\.\d+)?$/;
15
+ /** Whether `value` is a BSON number object — a `Decimal128` or a `Long` (a stored decimal / long). */
16
+ function isBsonNumber(value) {
17
+ if (value === null || typeof value !== "object") return false;
18
+ const type = value._bsontype;
19
+ return type === "Decimal128" || type === "Long";
20
+ }
21
+ function refuse(path, message) {
22
+ throw new DbError("INVALID_QUERY", [{
23
+ path,
24
+ message
25
+ }]);
26
+ }
27
+ /**
28
+ * `text` as a `Decimal128`: decimal text as written (its scale kept), a
29
+ * lenient numeric form a filter may carry (`" 5 "`, `".5"`, `"1e3"`) by its
30
+ * value. `INVALID_QUERY` (400) for text that is no number, and for a value
31
+ * `Decimal128` cannot hold exactly — more than 34 significant digits, or an
32
+ * exponent beyond its range — instead of the driver's rounding error.
33
+ */
34
+ function toDecimal128(text, path) {
35
+ const exact = DECIMAL_TEXT_RE.test(text) ? text : exactKey(text);
36
+ if (exact === void 0) refuse(path, `Expected a decimal, got ${JSON.stringify(text)}`);
37
+ try {
38
+ return Decimal128.fromString(exact);
39
+ } catch {
40
+ const digits = exact.replace(/^[+-]/, "").replace(".", "").replace(/^0+/, "").length;
41
+ return refuse(path, `${JSON.stringify(text)} ${digits > 34 ? "has more than 34 significant digits" : "is beyond the exponent range of a Decimal128"} — MongoDB stores a decimal as a Decimal128`);
42
+ }
43
+ }
44
+ /**
45
+ * `value` as an Int64: a long's text, a safe-integer number or a bigint
46
+ * (`canonicalLong` — never `Long.fromString`, which wraps 2^63 to -2^63 and
47
+ * reads `"1.5"` as 1). `INVALID_QUERY` (400) for one outside the signed
48
+ * 64-bit range.
49
+ */
50
+ function toLong(value, path) {
51
+ const text = canonicalLong(value);
52
+ if (text === void 0) refuse(path, `Expected a 64-bit integer, got ${JSON.stringify(String(value))}`);
53
+ return Long.fromBigInt(BigInt(text));
54
+ }
55
+ /**
56
+ * The write / filter formatter (`toStorage`) of a scalar `decimal` or `long`
57
+ * field at `path`: text (the core has already written a number out as text,
58
+ * and canonicalized a long) becomes a `Decimal128` / `Long`; any other value
59
+ * — `null`, an operator payload such as `$exists: true`, an already-encoded
60
+ * object — passes through.
61
+ */
62
+ function exactToStorage(kind, path) {
63
+ return kind === "decimal" ? (value) => typeof value === "string" ? toDecimal128(value, path) : value : (value) => typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? toLong(value, path) : value;
64
+ }
65
+ /**
66
+ * A literal compared with an exact-kind value (a `$having` comparand, a view
67
+ * predicate's literal): a number, a bigint or numeric text as a `Decimal128`
68
+ * — MongoDB compares it with a stored `Decimal128` or `Long` (or an
69
+ * aggregate's `Decimal128`) by value, exactly; a double would not equal the
70
+ * decimal `19.99`. Any other value passes through.
71
+ */
72
+ function exactLiteral(value, path) {
73
+ if (Array.isArray(value)) return value.map((item) => exactLiteral(item, path));
74
+ if (typeof value === "number") return Number.isFinite(value) ? toDecimal128(String(value), path) : value;
75
+ if (typeof value === "bigint" || typeof value === "string") return toDecimal128(String(value), path);
76
+ return value;
77
+ }
78
+ //#endregion
5
79
  //#region src/lib/mongo-view-expr.ts
6
80
  /**
7
81
  * `x IS NOT NULL` in SQL terms — true when `x` is neither null nor missing.
@@ -66,21 +140,25 @@ function fieldCompareExpr(op, x, y) {
66
140
  * - `and` / `or` / `not` map directly — so `not (x > 1)` is TRUE for a null
67
141
  * `x` here while SQL yields UNKNOWN (documented divergence);
68
142
  * - `matches` is rejected (`$regexMatch` needs MongoDB 4.2).
143
+ *
144
+ * `literalOf` (since 0.1.209) gives a literal compared with `ref` its
145
+ * storage form — a `Decimal128` against a decimal or long source.
69
146
  * @since 0.1.136
70
147
  */
71
- function queryNodeToExpr(node, pathOf) {
72
- if ("$and" in node) return { $and: node.$and.map((n) => queryNodeToExpr(n, pathOf)) };
73
- if ("$or" in node) return { $or: node.$or.map((n) => queryNodeToExpr(n, pathOf)) };
74
- if ("$not" in node) return { $not: [queryNodeToExpr(node.$not, pathOf)] };
148
+ function queryNodeToExpr(node, pathOf, literalOf) {
149
+ if ("$and" in node) return { $and: node.$and.map((n) => queryNodeToExpr(n, pathOf, literalOf)) };
150
+ if ("$or" in node) return { $or: node.$or.map((n) => queryNodeToExpr(n, pathOf, literalOf)) };
151
+ if ("$not" in node) return { $not: [queryNodeToExpr(node.$not, pathOf, literalOf)] };
75
152
  const comp = node;
76
153
  const x = pathOf(comp.left);
154
+ const stored = (value) => literal(literalOf ? literalOf(comp.left, value) : value);
77
155
  switch (comp.op) {
78
156
  case "$exists": return comp.right === false ? isNullExpr(x) : notNullExpr(x);
79
- case "$in": return { $in: [x, (Array.isArray(comp.right) ? comp.right : [comp.right]).map((v) => literal(v))] };
157
+ case "$in": return { $in: [x, (Array.isArray(comp.right) ? comp.right : [comp.right]).map((v) => stored(v))] };
80
158
  case "$nin": {
81
159
  const values = Array.isArray(comp.right) ? comp.right : [comp.right];
82
160
  if (values.length === 0) return { $literal: true };
83
- return guarded([x], { $not: [{ $in: [x, values.map((v) => literal(v))] }] });
161
+ return guarded([x], { $not: [{ $in: [x, values.map((v) => stored(v))] }] });
84
162
  }
85
163
  case "$regex": throw new Error("matches is not supported in view predicates");
86
164
  default:
@@ -93,7 +171,7 @@ function queryNodeToExpr(node, pathOf) {
93
171
  if (op === "$ne") return notNullExpr(x);
94
172
  return { $literal: false };
95
173
  }
96
- const value = literal(comp.right);
174
+ const value = stored(comp.right);
97
175
  if (op === "$eq") return { $eq: [x, value] };
98
176
  return guarded([x], { [op]: [x, value] });
99
177
  }
@@ -227,9 +305,13 @@ function eqCond(x, value) {
227
305
  { $eq: [x, v] }
228
306
  ] };
229
307
  }
230
- /** The comparison-class test of a range operand: only values of the operand's BSON class compare. */
308
+ /**
309
+ * The comparison-class test of a range operand: only values of the operand's
310
+ * BSON class compare — a number (a `Decimal128` / `Long` comparand of a
311
+ * decimal or long included) with any numeric BSON type.
312
+ */
231
313
  function sameClass(v, value) {
232
- if (typeof value === "number" || typeof value === "bigint") return { $isNumber: v };
314
+ if (typeof value === "number" || typeof value === "bigint" || isBsonNumber(value)) return { $isNumber: v };
233
315
  return { $eq: [{ $type: v }, { $type: valueOf(value) }] };
234
316
  }
235
317
  /**
@@ -778,11 +860,12 @@ function buildAccumulator(fn, src, where, path) {
778
860
  return fn === "countDistinct" ? { $addToSet: { $ifNull: [value, "$$REMOVE"] } } : { [`$${fn}`]: value };
779
861
  }
780
862
  /**
781
- * A decimal stored as its text, read as a `Decimal128` — exact, ordered by
782
- * value — for a `sum` / `avg` / `min` / `max` of it (since 0.1.207: `$sum` /
783
- * `$avg` skip text, `$min` / `$max` compare it as text). A value that is no
784
- * decimal text (`""`) reads as null, like a missing one, instead of failing
785
- * the pipeline.
863
+ * The operand of a `sum` / `avg` of a `decimal` or `long` field, read as a
864
+ * `Decimal128` (since 0.1.207; longs since 0.1.209): exact, where `$sum`
865
+ * over Int64 values overflows to a double and `$avg` of them is a double. A
866
+ * stored `Decimal128` is unchanged, a decimal stored as text by an earlier
867
+ * version is read by its value; a value that is no number (`""`) reads as
868
+ * null, like a missing one, instead of failing the pipeline.
786
869
  */
787
870
  function asDecimal(src) {
788
871
  return { $convert: {
@@ -792,47 +875,34 @@ function asDecimal(src) {
792
875
  onNull: null
793
876
  } };
794
877
  }
795
- /** Operators whose operand is compared with the column's values. */
796
- const COMPARE_OPS = new Set([
797
- "$eq",
798
- "$ne",
799
- "$gt",
800
- "$gte",
801
- "$lt",
802
- "$lte",
803
- "$in",
804
- "$nin"
805
- ]);
806
- /** A number or numeric text as a `Decimal128` (an array element-wise); any other value as it is. */
807
- function toDecimal128(value) {
808
- if (Array.isArray(value)) return value.map(toDecimal128);
809
- if (typeof value === "number" ? !Number.isFinite(value) : typeof value !== "string") return value;
810
- try {
811
- return Decimal128.fromString(String(value).trim());
812
- } catch {
813
- return value;
814
- }
878
+ /**
879
+ * `src` as a double — a `Decimal128` / `Long` (a `number` view column over a
880
+ * decimal / long source, since 0.1.209); null when it is no number.
881
+ */
882
+ function asDoubleOrNull(src) {
883
+ return { $convert: {
884
+ input: src,
885
+ to: "double",
886
+ onError: null,
887
+ onNull: null
888
+ } };
815
889
  }
890
+ /** Prefix of the hidden `$group` field counting a sum's non-null values. */
891
+ const NON_NULL_PREFIX = "__as_n_";
816
892
  /**
817
- * `filter` (a `$having` or a `$where` over aggregate rows) with the
818
- * comparands of the `columns` holding `Decimal128`s ({@link asDecimal}'s
819
- * results) as `Decimal128`s (since 0.1.207): MongoDB compares a
820
- * `Decimal128` with a double exactly, so `19.99` — the double just below —
821
- * would never equal the decimal 19.99.
822
- */
823
- function decimalComparands(filter, columns) {
824
- if (columns.size === 0 || !filter || typeof filter !== "object") return filter;
825
- const out = {};
826
- for (const [key, value] of Object.entries(filter)) if (key === "$and" || key === "$or") out[key] = value.map((f) => decimalComparands(f, columns));
827
- else if (key === "$not") out[key] = decimalComparands(value, columns);
828
- else if (!columns.has(key)) out[key] = value;
829
- else if (isPrimitive(value) || Array.isArray(value)) out[key] = toDecimal128(value);
830
- else {
831
- const ops = {};
832
- for (const [op, operand] of Object.entries(value)) ops[op] = COMPARE_OPS.has(op) ? toDecimal128(operand) : operand;
833
- out[key] = ops;
834
- }
835
- return out;
893
+ * `$sum` of no (non-null) value is 0 in MongoDB, NULL in SQL and the memory
894
+ * adapter: adds a hidden count of `operand`'s values (of the rows `where`
895
+ * matches) to `group` and returns the sum `alias` read as null over none —
896
+ * for a stage after `$group`.
897
+ */
898
+ function nullWhenEmpty(group, alias, operand, where) {
899
+ const count = `${NON_NULL_PREFIX}${alias}`;
900
+ group[count] = buildAccumulator("count", operand, where);
901
+ return { $cond: [
902
+ { $eq: [`$${count}`, 0] },
903
+ null,
904
+ `$${alias}`
905
+ ] };
836
906
  }
837
907
  /**
838
908
  * The size of a `countDistinct` set (`"$alias"`) — the value the accumulator
@@ -843,4 +913,4 @@ function distinctCountExpr(set) {
843
913
  return { $size: set };
844
914
  }
845
915
  //#endregion
846
- export { queryNodeToExpr as _, REL_FILTER_TEMP_PREFIX as a, collationOfAdapter as c, correlate as d, hasNullsPlacement as f, orNull as g, exprToMongo as h, distinctCountExpr as i, mongoFilterStages as l, sortStages as m, buildAccumulator as n, buildMongoFilter as o, rowOrderStages as p, decimalComparands as r, buildMongoQuery as s, asDecimal as t, planStages as u, whereToExpr as v };
916
+ export { isBsonNumber as S, orNull as _, nullWhenEmpty as a, exactLiteral as b, buildMongoQuery as c, planStages as d, correlate as f, exprToMongo as g, sortStages as h, distinctCountExpr as i, collationOfAdapter as l, rowOrderStages as m, asDoubleOrNull as n, REL_FILTER_TEMP_PREFIX as o, hasNullsPlacement as p, buildAccumulator as r, buildMongoFilter as s, asDecimal as t, mongoFilterStages as u, queryNodeToExpr as v, exactToStorage as x, whereToExpr as y };
package/dist/plugin.cjs CHANGED
@@ -169,12 +169,17 @@ const annotations = {
169
169
  const definition = _id.getDefinition();
170
170
  if (!definition) return errors;
171
171
  let wrongType = false;
172
+ let exactKind;
172
173
  if ((0, _atscript_core.isRef)(definition)) {
173
174
  const def = doc.unwindType(definition.id, definition.chain)?.def;
174
- if ((0, _atscript_core.isPrimitive)(def) && !["string", "number"].includes(def.config.type)) wrongType = true;
175
+ if ((0, _atscript_core.isPrimitive)(def) && !["string", "number"].includes(def.config.type)) {
176
+ wrongType = true;
177
+ const type = def.config.type;
178
+ if (type === "long" || type === "decimal") exactKind = type;
179
+ }
175
180
  } else wrongType = true;
176
181
  if (wrongType) errors.push({
177
- message: `[db.mongo] _id must be of type string, number or mongo.objectId`,
182
+ message: `[db.mongo] _id must be of type string, number or mongo.objectId` + (exactKind ? ` — a ${exactKind} key is another @meta.id field next to _id` : ""),
178
183
  severity: 1,
179
184
  range: _id.token("identifier").range
180
185
  });
package/dist/plugin.mjs CHANGED
@@ -165,12 +165,17 @@ const annotations = {
165
165
  const definition = _id.getDefinition();
166
166
  if (!definition) return errors;
167
167
  let wrongType = false;
168
+ let exactKind;
168
169
  if (isRef(definition)) {
169
170
  const def = doc.unwindType(definition.id, definition.chain)?.def;
170
- if (isPrimitive(def) && !["string", "number"].includes(def.config.type)) wrongType = true;
171
+ if (isPrimitive(def) && !["string", "number"].includes(def.config.type)) {
172
+ wrongType = true;
173
+ const type = def.config.type;
174
+ if (type === "long" || type === "decimal") exactKind = type;
175
+ }
171
176
  } else wrongType = true;
172
177
  if (wrongType) errors.push({
173
- message: `[db.mongo] _id must be of type string, number or mongo.objectId`,
178
+ message: `[db.mongo] _id must be of type string, number or mongo.objectId` + (exactKind ? ` — a ${exactKind} key is another @meta.id field next to _id` : ""),
174
179
  severity: 1,
175
180
  range: _id.token("identifier").range
176
181
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-mongo",
3
- "version": "0.1.207",
3
+ "version": "0.1.209",
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.30",
50
- "@atscript/typescript": "^0.2.30",
51
- "@uniqu/core": "^0.2.3",
49
+ "@atscript/core": "^0.2.31",
50
+ "@atscript/typescript": "^0.2.31",
51
+ "@uniqu/core": "^0.3.0",
52
52
  "mongodb": "^6.17.0",
53
53
  "mongodb-memory-server-core": "^10.0.0",
54
- "unplugin-atscript": "^0.2.30"
54
+ "unplugin-atscript": "^0.2.31"
55
55
  },
56
56
  "peerDependencies": {
57
- "@atscript/core": "^0.2.30",
58
- "@atscript/typescript": "^0.2.30",
59
- "@uniqu/core": "^0.2.3",
57
+ "@atscript/core": "^0.2.31",
58
+ "@atscript/typescript": "^0.2.31",
59
+ "@uniqu/core": "^0.3.0",
60
60
  "mongodb": "^6.17.0",
61
- "@atscript/db": "^0.1.207"
61
+ "@atscript/db": "^0.1.209"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "vp pack",