@atscript/db-mongo 0.1.206 → 0.1.207
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/agg.cjs +51 -11
- package/dist/agg.mjs +51 -11
- package/dist/index.cjs +39 -13
- package/dist/index.d.cts +9 -3
- package/dist/index.d.mts +9 -3
- package/dist/index.mjs +40 -14
- package/dist/{mongo-accumulator-E7JzXDXL.cjs → mongo-accumulator-DLHfj5bv.cjs} +69 -0
- package/dist/{mongo-accumulator-BSFQ_Ccy.mjs → mongo-accumulator-DyBCoPSm.mjs} +60 -3
- package/package.json +9 -9
package/dist/agg.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_mongo_accumulator = require("./mongo-accumulator-
|
|
2
|
+
const require_mongo_accumulator = require("./mongo-accumulator-DLHfj5bv.cjs");
|
|
3
3
|
let _atscript_db = require("@atscript/db");
|
|
4
4
|
let _uniqu_core = require("@uniqu/core");
|
|
5
5
|
let _atscript_db_agg = require("@atscript/db/agg");
|
|
@@ -11,17 +11,22 @@ let _atscript_db_agg = require("@atscript/db/agg");
|
|
|
11
11
|
* Constructs MongoDB aggregation pipelines from translated DbQuery objects
|
|
12
12
|
* containing $groupBy, $select (with AggregateExpr), $having, $sort, etc.
|
|
13
13
|
*/
|
|
14
|
-
/**
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
/**
|
|
15
|
+
* The condition of a conditional aggregate as an aggregation expression, or
|
|
16
|
+
* `undefined`; `decimals` are the row columns holding `Decimal128`s (the
|
|
17
|
+
* inner level's, at the outer level of a two-level aggregate —
|
|
18
|
+
* {@link decimalAliases}).
|
|
19
|
+
*/
|
|
20
|
+
function conditionOf(where, decimals) {
|
|
21
|
+
return where === void 0 ? void 0 : require_mongo_accumulator.whereToExpr(require_mongo_accumulator.decimalComparands(where, decimals));
|
|
17
22
|
}
|
|
18
23
|
/**
|
|
19
24
|
* Maps an AggregateExpr to its MongoDB `$group` accumulator (see
|
|
20
25
|
* `buildAccumulator`), restricted to the rows `where` matches. A field list
|
|
21
26
|
* (since 0.1.168) is `countDistinct`'s only.
|
|
22
27
|
*/
|
|
23
|
-
function toAccumulator(expr, where) {
|
|
24
|
-
if (typeof expr.$field === "string") return require_mongo_accumulator.buildAccumulator(expr.$fn, expr
|
|
28
|
+
function toAccumulator(expr, where, select) {
|
|
29
|
+
if (typeof expr.$field === "string") return require_mongo_accumulator.buildAccumulator(expr.$fn, sourceOperand(expr, select), where);
|
|
25
30
|
(0, _atscript_db_agg.assertAggregateFn)(expr.$fn);
|
|
26
31
|
if (expr.$fn !== "countDistinct") throw new _atscript_db.DbError("INVALID_QUERY", [{
|
|
27
32
|
path: "$select",
|
|
@@ -32,6 +37,40 @@ function toAccumulator(expr, where) {
|
|
|
32
37
|
}
|
|
33
38
|
/** An operand of query-time arithmetic: the field as a double (IEEE, like the SQL adapters). */
|
|
34
39
|
const asDouble = (path) => ({ $toDouble: `$${path}` });
|
|
40
|
+
/**
|
|
41
|
+
* The operand a single-field aggregate reads: `"*"` for `count(*)`, the field
|
|
42
|
+
* path — or, for a `sum` / `avg` / `min` / `max` of a decimal, which is stored
|
|
43
|
+
* as its text, the text read as a `Decimal128` ({@link asDecimal}, since
|
|
44
|
+
* 0.1.207): exact, and ordered by value. The core reads it back as a decimal
|
|
45
|
+
* string.
|
|
46
|
+
*/
|
|
47
|
+
function sourceOperand(expr, select) {
|
|
48
|
+
const field = expr.$field;
|
|
49
|
+
if (field === "*") return "*";
|
|
50
|
+
return readsDecimal(expr, select) ? require_mongo_accumulator.asDecimal(`$${field}`) : `$${field}`;
|
|
51
|
+
}
|
|
52
|
+
/** Whether `expr` is a `sum` / `avg` / `min` / `max` of a decimal — a `Decimal128` ({@link sourceOperand}). */
|
|
53
|
+
function readsDecimal(expr, select) {
|
|
54
|
+
return typeof expr.$field === "string" && expr.$fn !== "count" && expr.$fn !== "countDistinct" && select?.sources.get(expr.$field)?.designType === "decimal";
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The columns of a level's rows that hold `Decimal128`s (since 0.1.207): its
|
|
58
|
+
* `sum` / `avg` / `min` / `max` of a decimal ({@link readsDecimal}) and, at
|
|
59
|
+
* the outer level of a two-level aggregate, a group key or `first` / `last`
|
|
60
|
+
* of an inner one — a `$having` comparand of one is compared as a
|
|
61
|
+
* `Decimal128` ({@link decimalComparands}).
|
|
62
|
+
*/
|
|
63
|
+
function decimalAliases(controls) {
|
|
64
|
+
const select = controls.$select;
|
|
65
|
+
const out = /* @__PURE__ */ new Set();
|
|
66
|
+
for (const expr of select?.aggregates ?? []) if (readsDecimal(expr, select)) out.add((0, _atscript_db_agg.resolveAlias)(expr));
|
|
67
|
+
const inner = controls.$from ? decimalAliases(controls.$from) : void 0;
|
|
68
|
+
if (inner?.size) {
|
|
69
|
+
for (const key of controls.$groupBy ?? []) if (inner.has(key)) out.add(key);
|
|
70
|
+
for (const fl of select?.firstLast ?? []) if (inner.has(fl.column)) out.add(fl.alias);
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
35
74
|
/** Prefix of the hidden `$group` field counting a sum's non-null values. */
|
|
36
75
|
const NON_NULL_PREFIX = "__as_n_";
|
|
37
76
|
const DAY_MS = 864e5;
|
|
@@ -189,15 +228,16 @@ function buildGroupedStages(controls, pipeline, accumulators) {
|
|
|
189
228
|
`$${alias}`
|
|
190
229
|
] };
|
|
191
230
|
};
|
|
231
|
+
const rowDecimals = controls.$from ? decimalAliases(controls.$from) : /* @__PURE__ */ new Set();
|
|
192
232
|
for (const expr of controls.$select?.aggregates ?? []) {
|
|
193
233
|
const alias = (0, _atscript_db_agg.resolveAlias)(expr);
|
|
194
|
-
const where = conditionOf(expr.$where);
|
|
195
|
-
groupStage[alias] = toAccumulator(expr, where);
|
|
196
|
-
project[alias] = expr.$fn === "countDistinct" ? require_mongo_accumulator.distinctCountExpr(`$${alias}`) : expr.$fn === "sum" ? nullWhenEmpty(alias,
|
|
234
|
+
const where = conditionOf(expr.$where, rowDecimals);
|
|
235
|
+
groupStage[alias] = toAccumulator(expr, where, controls.$select);
|
|
236
|
+
project[alias] = expr.$fn === "countDistinct" ? require_mongo_accumulator.distinctCountExpr(`$${alias}`) : expr.$fn === "sum" ? nullWhenEmpty(alias, sourceOperand(expr, controls.$select), where) : 1;
|
|
197
237
|
}
|
|
198
238
|
for (const e of controls.$select?.exprAggregates ?? []) {
|
|
199
239
|
const value = require_mongo_accumulator.exprToMongo(e.expr, asDouble);
|
|
200
|
-
const where = conditionOf(e.where);
|
|
240
|
+
const where = conditionOf(e.where, rowDecimals);
|
|
201
241
|
groupStage[e.alias] = require_mongo_accumulator.buildAccumulator(e.fn, value, where);
|
|
202
242
|
project[e.alias] = e.fn === "sum" ? nullWhenEmpty(e.alias, value, where) : 1;
|
|
203
243
|
}
|
|
@@ -208,7 +248,7 @@ function buildGroupedStages(controls, pipeline, accumulators) {
|
|
|
208
248
|
pipeline.push({ $group: groupStage });
|
|
209
249
|
pipeline.push({ $project: project });
|
|
210
250
|
for (const e of controls.$select?.exprs ?? []) pipeline.push({ $addFields: { [e.alias]: require_mongo_accumulator.exprToMongo(e.expr, asDouble) } });
|
|
211
|
-
if (controls.$having) pipeline.push({ $match: require_mongo_accumulator.buildMongoFilter(controls.$having) });
|
|
251
|
+
if (controls.$having) pipeline.push({ $match: require_mongo_accumulator.buildMongoFilter(require_mongo_accumulator.decimalComparands(controls.$having, decimalAliases(controls))) });
|
|
212
252
|
return pipeline;
|
|
213
253
|
}
|
|
214
254
|
/**
|
package/dist/agg.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { g as orNull, h as exprToMongo, i as distinctCountExpr, l as mongoFilterStages, m as sortStages, n as buildAccumulator, o as buildMongoFilter, p as rowOrderStages, r as decimalComparands, t as asDecimal, v as whereToExpr } from "./mongo-accumulator-DyBCoPSm.mjs";
|
|
2
2
|
import { DbError, aggregateColumns, evaluateExpr } from "@atscript/db";
|
|
3
3
|
import { BUCKET_MAX_INSTANT, BUCKET_MIN_INSTANT } from "@uniqu/core";
|
|
4
4
|
import { assertAggregateFn, resolveAlias } from "@atscript/db/agg";
|
|
@@ -10,17 +10,22 @@ import { assertAggregateFn, resolveAlias } from "@atscript/db/agg";
|
|
|
10
10
|
* Constructs MongoDB aggregation pipelines from translated DbQuery objects
|
|
11
11
|
* containing $groupBy, $select (with AggregateExpr), $having, $sort, etc.
|
|
12
12
|
*/
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
/**
|
|
14
|
+
* The condition of a conditional aggregate as an aggregation expression, or
|
|
15
|
+
* `undefined`; `decimals` are the row columns holding `Decimal128`s (the
|
|
16
|
+
* inner level's, at the outer level of a two-level aggregate —
|
|
17
|
+
* {@link decimalAliases}).
|
|
18
|
+
*/
|
|
19
|
+
function conditionOf(where, decimals) {
|
|
20
|
+
return where === void 0 ? void 0 : whereToExpr(decimalComparands(where, decimals));
|
|
16
21
|
}
|
|
17
22
|
/**
|
|
18
23
|
* Maps an AggregateExpr to its MongoDB `$group` accumulator (see
|
|
19
24
|
* `buildAccumulator`), restricted to the rows `where` matches. A field list
|
|
20
25
|
* (since 0.1.168) is `countDistinct`'s only.
|
|
21
26
|
*/
|
|
22
|
-
function toAccumulator(expr, where) {
|
|
23
|
-
if (typeof expr.$field === "string") return buildAccumulator(expr.$fn, expr
|
|
27
|
+
function toAccumulator(expr, where, select) {
|
|
28
|
+
if (typeof expr.$field === "string") return buildAccumulator(expr.$fn, sourceOperand(expr, select), where);
|
|
24
29
|
assertAggregateFn(expr.$fn);
|
|
25
30
|
if (expr.$fn !== "countDistinct") throw new DbError("INVALID_QUERY", [{
|
|
26
31
|
path: "$select",
|
|
@@ -31,6 +36,40 @@ function toAccumulator(expr, where) {
|
|
|
31
36
|
}
|
|
32
37
|
/** An operand of query-time arithmetic: the field as a double (IEEE, like the SQL adapters). */
|
|
33
38
|
const asDouble = (path) => ({ $toDouble: `$${path}` });
|
|
39
|
+
/**
|
|
40
|
+
* The operand a single-field aggregate reads: `"*"` for `count(*)`, the field
|
|
41
|
+
* path — or, for a `sum` / `avg` / `min` / `max` of a decimal, which is stored
|
|
42
|
+
* as its text, the text read as a `Decimal128` ({@link asDecimal}, since
|
|
43
|
+
* 0.1.207): exact, and ordered by value. The core reads it back as a decimal
|
|
44
|
+
* string.
|
|
45
|
+
*/
|
|
46
|
+
function sourceOperand(expr, select) {
|
|
47
|
+
const field = expr.$field;
|
|
48
|
+
if (field === "*") return "*";
|
|
49
|
+
return readsDecimal(expr, select) ? asDecimal(`$${field}`) : `$${field}`;
|
|
50
|
+
}
|
|
51
|
+
/** Whether `expr` is a `sum` / `avg` / `min` / `max` of a decimal — a `Decimal128` ({@link sourceOperand}). */
|
|
52
|
+
function readsDecimal(expr, select) {
|
|
53
|
+
return typeof expr.$field === "string" && expr.$fn !== "count" && expr.$fn !== "countDistinct" && select?.sources.get(expr.$field)?.designType === "decimal";
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The columns of a level's rows that hold `Decimal128`s (since 0.1.207): its
|
|
57
|
+
* `sum` / `avg` / `min` / `max` of a decimal ({@link readsDecimal}) and, at
|
|
58
|
+
* the outer level of a two-level aggregate, a group key or `first` / `last`
|
|
59
|
+
* of an inner one — a `$having` comparand of one is compared as a
|
|
60
|
+
* `Decimal128` ({@link decimalComparands}).
|
|
61
|
+
*/
|
|
62
|
+
function decimalAliases(controls) {
|
|
63
|
+
const select = controls.$select;
|
|
64
|
+
const out = /* @__PURE__ */ new Set();
|
|
65
|
+
for (const expr of select?.aggregates ?? []) if (readsDecimal(expr, select)) out.add(resolveAlias(expr));
|
|
66
|
+
const inner = controls.$from ? decimalAliases(controls.$from) : void 0;
|
|
67
|
+
if (inner?.size) {
|
|
68
|
+
for (const key of controls.$groupBy ?? []) if (inner.has(key)) out.add(key);
|
|
69
|
+
for (const fl of select?.firstLast ?? []) if (inner.has(fl.column)) out.add(fl.alias);
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
34
73
|
/** Prefix of the hidden `$group` field counting a sum's non-null values. */
|
|
35
74
|
const NON_NULL_PREFIX = "__as_n_";
|
|
36
75
|
const DAY_MS = 864e5;
|
|
@@ -188,15 +227,16 @@ function buildGroupedStages(controls, pipeline, accumulators) {
|
|
|
188
227
|
`$${alias}`
|
|
189
228
|
] };
|
|
190
229
|
};
|
|
230
|
+
const rowDecimals = controls.$from ? decimalAliases(controls.$from) : /* @__PURE__ */ new Set();
|
|
191
231
|
for (const expr of controls.$select?.aggregates ?? []) {
|
|
192
232
|
const alias = resolveAlias(expr);
|
|
193
|
-
const where = conditionOf(expr.$where);
|
|
194
|
-
groupStage[alias] = toAccumulator(expr, where);
|
|
195
|
-
project[alias] = expr.$fn === "countDistinct" ? distinctCountExpr(`$${alias}`) : expr.$fn === "sum" ? nullWhenEmpty(alias,
|
|
233
|
+
const where = conditionOf(expr.$where, rowDecimals);
|
|
234
|
+
groupStage[alias] = toAccumulator(expr, where, controls.$select);
|
|
235
|
+
project[alias] = expr.$fn === "countDistinct" ? distinctCountExpr(`$${alias}`) : expr.$fn === "sum" ? nullWhenEmpty(alias, sourceOperand(expr, controls.$select), where) : 1;
|
|
196
236
|
}
|
|
197
237
|
for (const e of controls.$select?.exprAggregates ?? []) {
|
|
198
238
|
const value = exprToMongo(e.expr, asDouble);
|
|
199
|
-
const where = conditionOf(e.where);
|
|
239
|
+
const where = conditionOf(e.where, rowDecimals);
|
|
200
240
|
groupStage[e.alias] = buildAccumulator(e.fn, value, where);
|
|
201
241
|
project[e.alias] = e.fn === "sum" ? nullWhenEmpty(e.alias, value, where) : 1;
|
|
202
242
|
}
|
|
@@ -207,7 +247,7 @@ function buildGroupedStages(controls, pipeline, accumulators) {
|
|
|
207
247
|
pipeline.push({ $group: groupStage });
|
|
208
248
|
pipeline.push({ $project: project });
|
|
209
249
|
for (const e of controls.$select?.exprs ?? []) pipeline.push({ $addFields: { [e.alias]: exprToMongo(e.expr, asDouble) } });
|
|
210
|
-
if (controls.$having) pipeline.push({ $match: buildMongoFilter(controls.$having) });
|
|
250
|
+
if (controls.$having) pipeline.push({ $match: buildMongoFilter(decimalComparands(controls.$having, decimalAliases(controls))) });
|
|
211
251
|
return pipeline;
|
|
212
252
|
}
|
|
213
253
|
/**
|
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-
|
|
2
|
+
const require_mongo_accumulator = require("./mongo-accumulator-DLHfj5bv.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");
|
|
@@ -681,7 +681,9 @@ function joinedAs(table) {
|
|
|
681
681
|
* 3. aggregates → `$group` (+ `$addFields` turning `countDistinct` sets into
|
|
682
682
|
* their sizes, + `@db.view.having` → `$match`) + `$project`, otherwise a
|
|
683
683
|
* flat `$project`. A conditional aggregate's predicate reads the same
|
|
684
|
-
* pipeline paths (SQL null semantics — `queryNodeToExpr`).
|
|
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).
|
|
685
687
|
*
|
|
686
688
|
* All field paths are PHYSICAL document paths (`@db.column` renames), joined
|
|
687
689
|
* tables live under `__joined_<scope>` — the physical collection, or the
|
|
@@ -740,8 +742,9 @@ function buildViewPipeline(view, variant) {
|
|
|
740
742
|
project[col.viewColumn] = `$${col.viewColumn}`;
|
|
741
743
|
} else if (col.aggFn) {
|
|
742
744
|
const predicate = col.aggFilter ? require_mongo_accumulator.queryNodeToExpr(col.aggFilter, (ref) => `$${pathOf(ref)}`) : void 0;
|
|
743
|
-
|
|
744
|
-
|
|
745
|
+
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}`;
|
|
745
748
|
if (col.aggFn === "countDistinct") distinctSizes[col.viewColumn] = require_mongo_accumulator.distinctCountExpr(`$${col.viewColumn}`);
|
|
746
749
|
} else {
|
|
747
750
|
group._id[col.viewColumn] = colValue(col);
|
|
@@ -847,21 +850,26 @@ function simpleJoinFields(view, join, outer) {
|
|
|
847
850
|
* over pipeline paths: the shared query translation (`translateQueryTree` →
|
|
848
851
|
* `buildMongoFilter`), so operators mean what they mean in queries (`exists`
|
|
849
852
|
* = holds a value, `matches` takes `/re/flags`); a field-to-field comparison
|
|
850
|
-
* becomes `$expr`.
|
|
853
|
+
* becomes `$expr`. A literal compared with one of the `decimals` paths (a
|
|
854
|
+
* `Decimal128` there) is a `Decimal128` ({@link decimalComparands}).
|
|
851
855
|
*/
|
|
852
|
-
function viewMatch(node, pathOf) {
|
|
853
|
-
return require_mongo_accumulator.buildMongoFilter((0, _atscript_db.translateQueryTree)(node, pathOf), { fieldOperands: true });
|
|
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 });
|
|
854
858
|
}
|
|
855
859
|
/**
|
|
856
860
|
* `@db.view.having` as a `$match` after `$group`: refs name view fields —
|
|
857
|
-
* aggregates are top-level, dimensions under `_id`.
|
|
861
|
+
* 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).
|
|
858
864
|
*/
|
|
859
865
|
function havingMatch(node, colMap) {
|
|
866
|
+
const decimals = /* @__PURE__ */ new Set();
|
|
867
|
+
for (const col of colMap.values()) if (col.decimal) decimals.add(col.viewColumn);
|
|
860
868
|
return viewMatch(node, (ref) => {
|
|
861
869
|
const col = ref.type ? void 0 : colMap.get(ref.field);
|
|
862
870
|
if (!col) return ref.field;
|
|
863
871
|
return col.aggFn || col.expr !== void 0 ? col.viewColumn : `_id.${col.viewColumn}`;
|
|
864
|
-
});
|
|
872
|
+
}, decimals);
|
|
865
873
|
}
|
|
866
874
|
//#endregion
|
|
867
875
|
//#region src/lib/mongo-view-read.ts
|
|
@@ -2416,8 +2424,8 @@ function bsonPresentTypes(designType) {
|
|
|
2416
2424
|
switch (designType) {
|
|
2417
2425
|
case "string": return "string";
|
|
2418
2426
|
case "objectId": return ["objectId", "string"];
|
|
2419
|
-
case "number":
|
|
2420
|
-
case "decimal": return "
|
|
2427
|
+
case "number": return "number";
|
|
2428
|
+
case "decimal": return "string";
|
|
2421
2429
|
case "boolean": return "bool";
|
|
2422
2430
|
default: return [
|
|
2423
2431
|
"double",
|
|
@@ -2593,6 +2601,13 @@ function objectIdFromStorage(value) {
|
|
|
2593
2601
|
* predicates (see {@link MongoAdapter.supportsRelationFilters}).
|
|
2594
2602
|
*/
|
|
2595
2603
|
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
|
+
];
|
|
2596
2611
|
var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
|
|
2597
2612
|
db;
|
|
2598
2613
|
client;
|
|
@@ -2827,11 +2842,14 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2827
2842
|
return _atscript_db.ALL_VIEW_CAPABILITIES;
|
|
2828
2843
|
}
|
|
2829
2844
|
/**
|
|
2830
|
-
* See BaseDbAdapter.viewRenderRevision. 2 = 0.1.137 (null-guarded field filters, nested document paths)
|
|
2845
|
+
* 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.
|
|
2831
2848
|
* BUMP whenever `buildViewPipeline` output changes for an unchanged view definition.
|
|
2832
2849
|
*/
|
|
2833
2850
|
viewRenderRevision() {
|
|
2834
|
-
|
|
2851
|
+
const view = this._table;
|
|
2852
|
+
return view?.isView && !view.isExternal && view.getViewColumnMappings().some((c) => c.decimal) ? "3" : "2";
|
|
2835
2853
|
}
|
|
2836
2854
|
getValidatorPlugins() {
|
|
2837
2855
|
return [validateMongoIdPlugin];
|
|
@@ -2862,8 +2880,16 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2862
2880
|
* ObjectIds — and reads return the hex strings the declared type promises.
|
|
2863
2881
|
* Top-level fields only: nested values skip the write/read formatter passes,
|
|
2864
2882
|
* so a nested formatter would coerce filters against un-coerced storage.
|
|
2883
|
+
*
|
|
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).
|
|
2865
2887
|
*/
|
|
2866
2888
|
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
|
+
};
|
|
2867
2893
|
if (field.isGeoPoint) return {
|
|
2868
2894
|
toStorage: (value) => Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number" ? {
|
|
2869
2895
|
type: "Point",
|
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 } from "@atscript/db";
|
|
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";
|
|
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";
|
|
@@ -433,7 +433,9 @@ declare class MongoAdapter extends BaseDbAdapter {
|
|
|
433
433
|
/** Computed view columns and first-row joins. */
|
|
434
434
|
viewCapabilities(): ReadonlySet<TViewCapability>;
|
|
435
435
|
/**
|
|
436
|
-
* See BaseDbAdapter.viewRenderRevision. 2 = 0.1.137 (null-guarded field filters, nested document paths)
|
|
436
|
+
* 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.
|
|
437
439
|
* BUMP whenever `buildViewPipeline` output changes for an unchanged view definition.
|
|
438
440
|
*/
|
|
439
441
|
viewRenderRevision(): string;
|
|
@@ -462,10 +464,14 @@ declare class MongoAdapter extends BaseDbAdapter {
|
|
|
462
464
|
* ObjectIds — and reads return the hex strings the declared type promises.
|
|
463
465
|
* Top-level fields only: nested values skip the write/read formatter passes,
|
|
464
466
|
* so a nested formatter would coerce filters against un-coerced storage.
|
|
467
|
+
*
|
|
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).
|
|
465
471
|
*/
|
|
466
472
|
formatValue(field: TDbFieldMeta): {
|
|
467
473
|
toStorage: (value: unknown) => unknown;
|
|
468
|
-
fromStorage:
|
|
474
|
+
fromStorage: typeof toDecimalString;
|
|
469
475
|
} | undefined;
|
|
470
476
|
getAdapterTableName(_type: unknown): string | undefined;
|
|
471
477
|
supportsNativeRelations(): boolean;
|
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 } from "@atscript/db";
|
|
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";
|
|
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";
|
|
@@ -433,7 +433,9 @@ declare class MongoAdapter extends BaseDbAdapter {
|
|
|
433
433
|
/** Computed view columns and first-row joins. */
|
|
434
434
|
viewCapabilities(): ReadonlySet<TViewCapability>;
|
|
435
435
|
/**
|
|
436
|
-
* See BaseDbAdapter.viewRenderRevision. 2 = 0.1.137 (null-guarded field filters, nested document paths)
|
|
436
|
+
* 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.
|
|
437
439
|
* BUMP whenever `buildViewPipeline` output changes for an unchanged view definition.
|
|
438
440
|
*/
|
|
439
441
|
viewRenderRevision(): string;
|
|
@@ -462,10 +464,14 @@ declare class MongoAdapter extends BaseDbAdapter {
|
|
|
462
464
|
* ObjectIds — and reads return the hex strings the declared type promises.
|
|
463
465
|
* Top-level fields only: nested values skip the write/read formatter passes,
|
|
464
466
|
* so a nested formatter would coerce filters against un-coerced storage.
|
|
467
|
+
*
|
|
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).
|
|
465
471
|
*/
|
|
466
472
|
formatValue(field: TDbFieldMeta): {
|
|
467
473
|
toStorage: (value: unknown) => unknown;
|
|
468
|
-
fromStorage:
|
|
474
|
+
fromStorage: typeof toDecimalString;
|
|
469
475
|
} | undefined;
|
|
470
476
|
getAdapterTableName(_type: unknown): string | undefined;
|
|
471
477
|
supportsNativeRelations(): boolean;
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as
|
|
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";
|
|
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, 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, geoIndexNotFoundMessage, getDbFieldOp, getKeyProps, getPath, isAtscriptDbView, isFieldRef, isPlainObject, isViewType, parseDefaultLiteral, queryReadColumns, relationStaticFilter, resolveDesignType, searchIndexNotFoundMessage, searchTermInteger, storedObjectType, tableNameOf, toDecimalString, 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
|
|
@@ -680,7 +680,9 @@ function joinedAs(table) {
|
|
|
680
680
|
* 3. aggregates → `$group` (+ `$addFields` turning `countDistinct` sets into
|
|
681
681
|
* their sizes, + `@db.view.having` → `$match`) + `$project`, otherwise a
|
|
682
682
|
* flat `$project`. A conditional aggregate's predicate reads the same
|
|
683
|
-
* pipeline paths (SQL null semantics — `queryNodeToExpr`).
|
|
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).
|
|
684
686
|
*
|
|
685
687
|
* All field paths are PHYSICAL document paths (`@db.column` renames), joined
|
|
686
688
|
* tables live under `__joined_<scope>` — the physical collection, or the
|
|
@@ -739,8 +741,9 @@ function buildViewPipeline(view, variant) {
|
|
|
739
741
|
project[col.viewColumn] = `$${col.viewColumn}`;
|
|
740
742
|
} else if (col.aggFn) {
|
|
741
743
|
const predicate = col.aggFilter ? queryNodeToExpr(col.aggFilter, (ref) => `$${pathOf(ref)}`) : void 0;
|
|
742
|
-
|
|
743
|
-
|
|
744
|
+
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}`;
|
|
744
747
|
if (col.aggFn === "countDistinct") distinctSizes[col.viewColumn] = distinctCountExpr(`$${col.viewColumn}`);
|
|
745
748
|
} else {
|
|
746
749
|
group._id[col.viewColumn] = colValue(col);
|
|
@@ -846,21 +849,26 @@ function simpleJoinFields(view, join, outer) {
|
|
|
846
849
|
* over pipeline paths: the shared query translation (`translateQueryTree` →
|
|
847
850
|
* `buildMongoFilter`), so operators mean what they mean in queries (`exists`
|
|
848
851
|
* = holds a value, `matches` takes `/re/flags`); a field-to-field comparison
|
|
849
|
-
* becomes `$expr`.
|
|
852
|
+
* becomes `$expr`. A literal compared with one of the `decimals` paths (a
|
|
853
|
+
* `Decimal128` there) is a `Decimal128` ({@link decimalComparands}).
|
|
850
854
|
*/
|
|
851
|
-
function viewMatch(node, pathOf) {
|
|
852
|
-
return buildMongoFilter(translateQueryTree(node, pathOf), { fieldOperands: true });
|
|
855
|
+
function viewMatch(node, pathOf, decimals = /* @__PURE__ */ new Set()) {
|
|
856
|
+
return buildMongoFilter(decimalComparands(translateQueryTree(node, pathOf), decimals), { fieldOperands: true });
|
|
853
857
|
}
|
|
854
858
|
/**
|
|
855
859
|
* `@db.view.having` as a `$match` after `$group`: refs name view fields —
|
|
856
|
-
* aggregates are top-level, dimensions under `_id`.
|
|
860
|
+
* 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).
|
|
857
863
|
*/
|
|
858
864
|
function havingMatch(node, colMap) {
|
|
865
|
+
const decimals = /* @__PURE__ */ new Set();
|
|
866
|
+
for (const col of colMap.values()) if (col.decimal) decimals.add(col.viewColumn);
|
|
859
867
|
return viewMatch(node, (ref) => {
|
|
860
868
|
const col = ref.type ? void 0 : colMap.get(ref.field);
|
|
861
869
|
if (!col) return ref.field;
|
|
862
870
|
return col.aggFn || col.expr !== void 0 ? col.viewColumn : `_id.${col.viewColumn}`;
|
|
863
|
-
});
|
|
871
|
+
}, decimals);
|
|
864
872
|
}
|
|
865
873
|
//#endregion
|
|
866
874
|
//#region src/lib/mongo-view-read.ts
|
|
@@ -2415,8 +2423,8 @@ function bsonPresentTypes(designType) {
|
|
|
2415
2423
|
switch (designType) {
|
|
2416
2424
|
case "string": return "string";
|
|
2417
2425
|
case "objectId": return ["objectId", "string"];
|
|
2418
|
-
case "number":
|
|
2419
|
-
case "decimal": return "
|
|
2426
|
+
case "number": return "number";
|
|
2427
|
+
case "decimal": return "string";
|
|
2420
2428
|
case "boolean": return "bool";
|
|
2421
2429
|
default: return [
|
|
2422
2430
|
"double",
|
|
@@ -2592,6 +2600,13 @@ function objectIdFromStorage(value) {
|
|
|
2592
2600
|
* predicates (see {@link MongoAdapter.supportsRelationFilters}).
|
|
2593
2601
|
*/
|
|
2594
2602
|
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
|
+
];
|
|
2595
2610
|
var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
|
|
2596
2611
|
db;
|
|
2597
2612
|
client;
|
|
@@ -2826,11 +2841,14 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
|
|
|
2826
2841
|
return ALL_VIEW_CAPABILITIES;
|
|
2827
2842
|
}
|
|
2828
2843
|
/**
|
|
2829
|
-
* See BaseDbAdapter.viewRenderRevision. 2 = 0.1.137 (null-guarded field filters, nested document paths)
|
|
2844
|
+
* 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.
|
|
2830
2847
|
* BUMP whenever `buildViewPipeline` output changes for an unchanged view definition.
|
|
2831
2848
|
*/
|
|
2832
2849
|
viewRenderRevision() {
|
|
2833
|
-
|
|
2850
|
+
const view = this._table;
|
|
2851
|
+
return view?.isView && !view.isExternal && view.getViewColumnMappings().some((c) => c.decimal) ? "3" : "2";
|
|
2834
2852
|
}
|
|
2835
2853
|
getValidatorPlugins() {
|
|
2836
2854
|
return [validateMongoIdPlugin];
|
|
@@ -2861,8 +2879,16 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
|
|
|
2861
2879
|
* ObjectIds — and reads return the hex strings the declared type promises.
|
|
2862
2880
|
* Top-level fields only: nested values skip the write/read formatter passes,
|
|
2863
2881
|
* so a nested formatter would coerce filters against un-coerced storage.
|
|
2882
|
+
*
|
|
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).
|
|
2864
2886
|
*/
|
|
2865
2887
|
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
|
+
};
|
|
2866
2892
|
if (field.isGeoPoint) return {
|
|
2867
2893
|
toStorage: (value) => Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number" ? {
|
|
2868
2894
|
type: "Point",
|
|
@@ -778,6 +778,63 @@ function buildAccumulator(fn, src, where, path) {
|
|
|
778
778
|
return fn === "countDistinct" ? { $addToSet: { $ifNull: [value, "$$REMOVE"] } } : { [`$${fn}`]: value };
|
|
779
779
|
}
|
|
780
780
|
/**
|
|
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.
|
|
786
|
+
*/
|
|
787
|
+
function asDecimal(src) {
|
|
788
|
+
return { $convert: {
|
|
789
|
+
input: src,
|
|
790
|
+
to: "decimal",
|
|
791
|
+
onError: null,
|
|
792
|
+
onNull: null
|
|
793
|
+
} };
|
|
794
|
+
}
|
|
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
|
+
}
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
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 ((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;
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
781
838
|
* The size of a `countDistinct` set (`"$alias"`) — the value the accumulator
|
|
782
839
|
* stands for, projected right after `$group` so later stages (`$having`,
|
|
783
840
|
* `$sort`) see a number.
|
|
@@ -792,6 +849,12 @@ Object.defineProperty(exports, "REL_FILTER_TEMP_PREFIX", {
|
|
|
792
849
|
return REL_FILTER_TEMP_PREFIX;
|
|
793
850
|
}
|
|
794
851
|
});
|
|
852
|
+
Object.defineProperty(exports, "asDecimal", {
|
|
853
|
+
enumerable: true,
|
|
854
|
+
get: function() {
|
|
855
|
+
return asDecimal;
|
|
856
|
+
}
|
|
857
|
+
});
|
|
795
858
|
Object.defineProperty(exports, "buildAccumulator", {
|
|
796
859
|
enumerable: true,
|
|
797
860
|
get: function() {
|
|
@@ -822,6 +885,12 @@ Object.defineProperty(exports, "correlate", {
|
|
|
822
885
|
return correlate;
|
|
823
886
|
}
|
|
824
887
|
});
|
|
888
|
+
Object.defineProperty(exports, "decimalComparands", {
|
|
889
|
+
enumerable: true,
|
|
890
|
+
get: function() {
|
|
891
|
+
return decimalComparands;
|
|
892
|
+
}
|
|
893
|
+
});
|
|
825
894
|
Object.defineProperty(exports, "distinctCountExpr", {
|
|
826
895
|
enumerable: true,
|
|
827
896
|
get: function() {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { DbError, INTEGER_REGEX_OP, andFilters, assertExprArity, containsRelationFilter, isFieldRef, isResolvedRelationFilter, walkFilter } from "@atscript/db";
|
|
2
|
-
import { BSONRegExp } from "mongodb";
|
|
1
|
+
import { DbError, INTEGER_REGEX_OP, andFilters, assertExprArity, containsRelationFilter, isFieldRef, isPrimitive, isResolvedRelationFilter, walkFilter } from "@atscript/db";
|
|
2
|
+
import { BSONRegExp, Decimal128 } from "mongodb";
|
|
3
3
|
import { isNullsPlacement } from "@uniqu/core";
|
|
4
4
|
import { assertAggregateFn } from "@atscript/db/agg";
|
|
5
5
|
//#region src/lib/mongo-view-expr.ts
|
|
@@ -778,6 +778,63 @@ function buildAccumulator(fn, src, where, path) {
|
|
|
778
778
|
return fn === "countDistinct" ? { $addToSet: { $ifNull: [value, "$$REMOVE"] } } : { [`$${fn}`]: value };
|
|
779
779
|
}
|
|
780
780
|
/**
|
|
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.
|
|
786
|
+
*/
|
|
787
|
+
function asDecimal(src) {
|
|
788
|
+
return { $convert: {
|
|
789
|
+
input: src,
|
|
790
|
+
to: "decimal",
|
|
791
|
+
onError: null,
|
|
792
|
+
onNull: null
|
|
793
|
+
} };
|
|
794
|
+
}
|
|
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
|
+
}
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
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;
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
781
838
|
* The size of a `countDistinct` set (`"$alias"`) — the value the accumulator
|
|
782
839
|
* stands for, projected right after `$group` so later stages (`$having`,
|
|
783
840
|
* `$sort`) see a number.
|
|
@@ -786,4 +843,4 @@ function distinctCountExpr(set) {
|
|
|
786
843
|
return { $size: set };
|
|
787
844
|
}
|
|
788
845
|
//#endregion
|
|
789
|
-
export {
|
|
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 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atscript/db-mongo",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.207",
|
|
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.
|
|
50
|
-
"@atscript/typescript": "^0.2.
|
|
51
|
-
"@uniqu/core": "^0.2.
|
|
49
|
+
"@atscript/core": "^0.2.30",
|
|
50
|
+
"@atscript/typescript": "^0.2.30",
|
|
51
|
+
"@uniqu/core": "^0.2.3",
|
|
52
52
|
"mongodb": "^6.17.0",
|
|
53
53
|
"mongodb-memory-server-core": "^10.0.0",
|
|
54
|
-
"unplugin-atscript": "^0.2.
|
|
54
|
+
"unplugin-atscript": "^0.2.30"
|
|
55
55
|
},
|
|
56
56
|
"peerDependencies": {
|
|
57
|
-
"@atscript/core": "^0.2.
|
|
58
|
-
"@atscript/typescript": "^0.2.
|
|
59
|
-
"@uniqu/core": "^0.2.
|
|
57
|
+
"@atscript/core": "^0.2.30",
|
|
58
|
+
"@atscript/typescript": "^0.2.30",
|
|
59
|
+
"@uniqu/core": "^0.2.3",
|
|
60
60
|
"mongodb": "^6.17.0",
|
|
61
|
-
"@atscript/db": "^0.1.
|
|
61
|
+
"@atscript/db": "^0.1.207"
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
64
|
"build": "vp pack",
|