@atscript/db-mongo 0.1.173 → 0.1.175

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_mongo_accumulator = require("./mongo-accumulator-BOwAFmrt.cjs");
2
+ const require_mongo_accumulator = require("./mongo-accumulator-BBRS2_8v.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");
package/dist/agg.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { d as rowOrderStages, f as sortStages, g as whereToExpr, i as buildMongoFilter, m as orNull, n as distinctCountExpr, p as exprToMongo, s as mongoFilterStages, t as buildAccumulator } from "./mongo-accumulator-D4drEz0-.mjs";
1
+ import { d as rowOrderStages, f as sortStages, g as whereToExpr, i as buildMongoFilter, m as orNull, n as distinctCountExpr, p as exprToMongo, s as mongoFilterStages, t as buildAccumulator } from "./mongo-accumulator-CFVRBDiw.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";
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-BOwAFmrt.cjs");
2
+ const require_mongo_accumulator = require("./mongo-accumulator-BBRS2_8v.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");
@@ -50,19 +50,87 @@ async function wrapInvalidQuery(fn) {
50
50
  try {
51
51
  return await fn();
52
52
  } catch (error) {
53
- if (error instanceof mongodb.MongoServerError) {
54
- if (error.code === 31249 || error.code === 31254) throw new _atscript_db.DbError("INVALID_QUERY", [{
55
- path: "$select",
56
- message: error.message
57
- }]);
58
- if (error.code === UNKNOWN_TIME_ZONE) {
59
- const zone = /time zone identifier:\s*"([^"]*)"/.exec(error.message)?.[1];
60
- throw (0, _atscript_db.bucketTimeZoneUnavailable)(zone ? `MongoDB does not recognize time zone "${zone}" — its time zone database may be outdated` : `MongoDB does not recognize a bucket time zone: ${error.message}`);
61
- }
53
+ const code = serverErrorCode(error);
54
+ if (code === 31249 || code === 31254) throw new _atscript_db.DbError("INVALID_QUERY", [{
55
+ path: "$select",
56
+ message: error.message
57
+ }]);
58
+ if (code === UNKNOWN_TIME_ZONE) {
59
+ const message = error.message;
60
+ const zone = /time zone identifier:\s*"([^"]*)"/.exec(message)?.[1];
61
+ throw (0, _atscript_db.bucketTimeZoneUnavailable)(zone ? `MongoDB does not recognize time zone "${zone}" — its time zone database may be outdated` : `MongoDB does not recognize a bucket time zone: ${message}`);
62
62
  }
63
63
  throw error;
64
64
  }
65
65
  }
66
+ /** The numeric server code of a driver error, `undefined` for anything else. */
67
+ function serverErrorCode(error) {
68
+ if (!(error instanceof Error)) return void 0;
69
+ const code = error.code;
70
+ return typeof code === "number" ? code : void 0;
71
+ }
72
+ /** `WriteConflict`: a write met a concurrent transaction's uncommitted change. */
73
+ const WRITE_CONFLICT = 112;
74
+ /**
75
+ * The retryable `SERIALIZATION_FAILURE` of a driver error that ended a
76
+ * transaction without committing it — one labelled `TransientTransactionError`
77
+ * or `UnknownTransactionCommitResult` (`session.withTransaction` retries
78
+ * those itself for 120 s, then rethrows), or a `WriteConflict` — else `error`
79
+ * as is. The raw driver error is kept as `cause`.
80
+ */
81
+ function mapTransientTransactionError(error) {
82
+ if (!(error instanceof Error)) return error;
83
+ const labels = error.errorLabels;
84
+ if (!(Array.isArray(labels) && (labels.includes("TransientTransactionError") || labels.includes("UnknownTransactionCommitResult"))) && serverErrorCode(error) !== WRITE_CONFLICT) return error;
85
+ return new _atscript_db.DbError("SERIALIZATION_FAILURE", [{
86
+ path: "",
87
+ message: error.message
88
+ }], void 0, { cause: error });
89
+ }
90
+ /** `DuplicateKey` (E11000) and its legacy update form `DuplicateKeyValue` (E11001). */
91
+ function isDuplicateKeyCode(code) {
92
+ return code === 11e3 || code === 11001;
93
+ }
94
+ /** A bulk error's per-statement write errors (`MongoBulkWriteError.writeErrors`) — `[]` for other errors. */
95
+ function bulkWriteErrors(error) {
96
+ if (!(error instanceof Error)) return [];
97
+ return [error.writeErrors].flat().filter((w) => !!w);
98
+ }
99
+ /**
100
+ * Whether a driver error carries a write-concern failure (`MongoWriteConcernError`,
101
+ * or a bulk error whose result holds one): the write's durability is unknown, so it
102
+ * is never read as a duplicate key, whatever its write errors say.
103
+ */
104
+ function hasWriteConcernError(error) {
105
+ const e = error;
106
+ return Boolean(e.writeConcernError || e.result?.getWriteConcernError?.() || e.result?.writeConcernErrors?.length);
107
+ }
108
+ /**
109
+ * The duplicate-key violation a write failed with, or `undefined` when the error
110
+ * is anything else — for every shape the driver reports one in:
111
+ * - a `MongoServerError` (single-document writes: `code` 11000, `keyPattern`);
112
+ * - a `MongoBulkWriteError` (`insertMany` / `bulkWrite` — the table layer sends
113
+ * every insert through `insertMany`): 11000 on top and in `writeErrors`, or in
114
+ * `writeErrors` only — a bulk error counts only when EVERY write error is a
115
+ * duplicate key (another failure in the batch is not a conflict);
116
+ * - a bare `WriteError` (`code` getter, `errmsg`).
117
+ *
118
+ * A write-concern failure is never a duplicate key (see {@link hasWriteConcernError}).
119
+ */
120
+ function duplicateKeyViolation(error) {
121
+ if (error === null || typeof error !== "object" || hasWriteConcernError(error)) return void 0;
122
+ const e = error;
123
+ const writeErrors = bulkWriteErrors(error);
124
+ if (!(writeErrors.length > 0 ? writeErrors.map((w) => w.code) : [e.code]).every(isDuplicateKeyCode)) return void 0;
125
+ return {
126
+ message: [
127
+ e.message,
128
+ e.errmsg,
129
+ writeErrors[0]?.errmsg
130
+ ].find((m) => typeof m === "string" && m !== "") ?? "E11000 duplicate key error",
131
+ keyPattern: e.keyPattern
132
+ };
133
+ }
66
134
  //#endregion
67
135
  //#region src/lib/collection-patcher.ts
68
136
  /**
@@ -481,7 +549,7 @@ function buildViewPipeline(view, variant) {
481
549
  out = require_mongo_accumulator.exprToMongo(col.expr, (path) => {
482
550
  const c = byPath.get(path);
483
551
  return c.expr === void 0 ? { $toDouble: leaf(c) } : computedExpr(c, leaf);
484
- });
552
+ }, col.viewPath);
485
553
  rendered.set(col.viewPath, out);
486
554
  }
487
555
  return out;
@@ -717,7 +785,7 @@ async function loadRelationsImpl(host, rows, withRelations, relations, foreignKe
717
785
  for (const withRel of withRelations) {
718
786
  if (withRel.name.includes(".")) continue;
719
787
  const relation = relations.get(withRel.name);
720
- if (!relation) throw new Error(`Unknown relation "${withRel.name}" in $with. Available relations: ${[...relations.keys()].join(", ") || "(none)"}`);
788
+ if (!relation) throw (0, _atscript_db.unknownWithRelation)(withRel.name);
721
789
  const lookup = buildRelationLookup(source, withRel, relation, foreignKeys, tableResolver);
722
790
  if (lookup) relMeta.push(lookup);
723
791
  }
@@ -1037,6 +1105,8 @@ const RELEVANCE_SORT = { $sort: {
1037
1105
  _score: -1,
1038
1106
  _id: 1
1039
1107
  } };
1108
+ /** The order of an unranked search (`$rank: false`, since 0.1.175): the primary key. */
1109
+ const UNRANKED_SORT = { $sort: { _id: 1 } };
1040
1110
  function getSearchIndexesImpl(host) {
1041
1111
  const result = [];
1042
1112
  const indexes = host.getMongoSearchIndexes();
@@ -1105,12 +1175,24 @@ function buildAggregateSearchStage(host, controls) {
1105
1175
  /** Text search via $search aggregation stage. */
1106
1176
  async function searchImpl(host, text, query, indexName) {
1107
1177
  const plan = requireSearchStage(host, text, indexName, query.controls);
1108
- return runSearchPipeline(host, plan.stage, query, "search", { classicText: plan.classicText });
1178
+ return runSearchPipeline(host, plan.stage, query, "search", textRunOptions(plan, query));
1109
1179
  }
1110
1180
  /** Text search with faceted count. */
1111
1181
  async function searchWithCountImpl(host, text, query, indexName) {
1112
1182
  const plan = requireSearchStage(host, text, indexName, query.controls);
1113
- return runSearchWithCountPipeline(host, plan.stage, query, "searchWithCount", { classicText: plan.classicText });
1183
+ return runSearchWithCountPipeline(host, plan.stage, query, "searchWithCount", textRunOptions(plan, query));
1184
+ }
1185
+ /**
1186
+ * The runner options of a text search: relevance from `textScore` for a
1187
+ * classic `$text` match — none under `$rank: false` (since 0.1.175), which
1188
+ * orders by `_id` instead (an Atlas `$search` included).
1189
+ */
1190
+ function textRunOptions(plan, query) {
1191
+ if (query.controls?.$rank === false) return { defaultSort: UNRANKED_SORT };
1192
+ return plan.classicText ? {
1193
+ classicText: true,
1194
+ defaultSort: RELEVANCE_SORT
1195
+ } : {};
1114
1196
  }
1115
1197
  /** Vector search via $vectorSearch aggregation stage. */
1116
1198
  async function vectorSearchImpl(host, vector, query, indexName) {
@@ -1519,7 +1601,7 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
1519
1601
  };
1520
1602
  }
1521
1603
  /** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
1522
- async function runSearchPipeline(host, stage, query, label, { threshold, classicText = false, filterStages } = {}) {
1604
+ async function runSearchPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1523
1605
  const controls = query.controls || {};
1524
1606
  const pipeline = [stage];
1525
1607
  if (threshold !== void 0) {
@@ -1529,7 +1611,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1529
1611
  pipeline.push(...filterStages ?? require_mongo_accumulator.mongoFilterStages(query.filter, filterOptionsOf(host)));
1530
1612
  const { stages: sorted, cleanup } = require_mongo_accumulator.sortStages(controls);
1531
1613
  if (sorted.length > 0) pipeline.push(...sorted);
1532
- else if (classicText) pipeline.push(RELEVANCE_SORT);
1614
+ else if (defaultSort) pipeline.push(defaultSort);
1533
1615
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
1534
1616
  if (controls.$limit) pipeline.push({ $limit: controls.$limit });
1535
1617
  else pipeline.push({ $limit: 1e3 });
@@ -1551,7 +1633,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1551
1633
  * `count: total` — the same counts `$$SEARCH_META` reports), concurrently
1552
1634
  * outside a transaction.
1553
1635
  */
1554
- async function runSearchWithCountPipeline(host, stage, query, label, { threshold, classicText = false, filterStages } = {}) {
1636
+ async function runSearchWithCountPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1555
1637
  const controls = query.controls || {};
1556
1638
  const preStages = [];
1557
1639
  if (threshold !== void 0) {
@@ -1559,7 +1641,7 @@ async function runSearchWithCountPipeline(host, stage, query, label, { threshold
1559
1641
  preStages.push({ $match: { _score: { $gte: threshold } } });
1560
1642
  } else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1561
1643
  const { stages: dataStages, cleanup } = require_mongo_accumulator.sortStages(controls);
1562
- if (dataStages.length === 0 && classicText) dataStages.push(RELEVANCE_SORT);
1644
+ if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
1563
1645
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1564
1646
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1565
1647
  if (cleanup) dataStages.push(cleanup);
@@ -2279,7 +2361,7 @@ async function probe(client) {
2279
2361
  try {
2280
2362
  reply = await admin.command({ hello: 1 });
2281
2363
  } catch (error) {
2282
- if (!(error instanceof mongodb.MongoServerError) || error.code !== 59) throw error;
2364
+ if (serverErrorCode(error) !== 59) throw error;
2283
2365
  reply = await admin.command({ isMaster: 1 });
2284
2366
  }
2285
2367
  return reply.setName != null || reply.isreplicaset === true || reply.msg === "isdbgrid";
@@ -2309,11 +2391,6 @@ function objectIdFromStorage(value) {
2309
2391
  * predicates (see {@link MongoAdapter.supportsRelationFilters}).
2310
2392
  */
2311
2393
  const REL_WRITE_BATCH = 1e3;
2312
- /** Whether a bulk-write error carries a write-concern failure besides (or instead of) write errors. */
2313
- function hasWriteConcernError(error) {
2314
- const e = error;
2315
- return Boolean(e.writeConcernError || e.result?.getWriteConcernError?.() || e.result?.writeConcernErrors?.length);
2316
- }
2317
2394
  var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2318
2395
  db;
2319
2396
  client;
@@ -2401,6 +2478,8 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2401
2478
  result = await this._runInTransactionContext(session, fn);
2402
2479
  });
2403
2480
  return result;
2481
+ } catch (error) {
2482
+ throw mapTransientTransactionError(error);
2404
2483
  } finally {
2405
2484
  try {
2406
2485
  await session.endSession();
@@ -3087,12 +3166,16 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
3087
3166
  return this._mapConstraintError(error);
3088
3167
  }
3089
3168
  }
3090
- /** Rethrows a duplicate-key (11000) server error as `CONFLICT`, anything else as is. */
3169
+ /**
3170
+ * Rethrows a duplicate-key error as `CONFLICT` — whatever driver error class
3171
+ * carries it (see {@link duplicateKeyViolation}) — anything else as is.
3172
+ */
3091
3173
  _mapConstraintError(error) {
3092
- if (error instanceof mongodb.MongoServerError && error.code === 11e3) throw (0, _atscript_db.constraintViolation)("CONFLICT", {
3093
- columns: error.keyPattern ? Object.keys(error.keyPattern) : void 0,
3094
- name: error.message.match(/index: (\S+) dup key/)?.[1]
3095
- }, error.message);
3174
+ const duplicate = duplicateKeyViolation(error);
3175
+ if (duplicate) throw (0, _atscript_db.constraintViolation)("CONFLICT", {
3176
+ columns: duplicate.keyPattern ? Object.keys(duplicate.keyPattern) : void 0,
3177
+ name: duplicate.message.match(/index: (\S+) dup key/)?.[1]
3178
+ }, duplicate.message);
3096
3179
  throw error;
3097
3180
  }
3098
3181
  /** An update-shaped write under {@link _wrapDuplicateKeyError}, reduced to `TDbUpdateResult`. */
@@ -3163,13 +3246,9 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
3163
3246
  ...this._getSessionOpts()
3164
3247
  });
3165
3248
  } catch (error) {
3166
- if (!(error instanceof mongodb.MongoBulkWriteError)) this._mapConstraintError(error);
3167
- const writeErrors = [error.writeErrors].flat().filter(Boolean);
3168
- if (writeErrors.length === 0 || hasWriteConcernError(error)) throw error;
3169
- for (const writeError of writeErrors) {
3170
- if (writeError.code !== 11e3) throw error;
3171
- skipped.add(writeError.index);
3172
- }
3249
+ const writeErrors = bulkWriteErrors(error);
3250
+ if (writeErrors.length === 0 || !duplicateKeyViolation(error)) this._mapConstraintError(error);
3251
+ for (const writeError of writeErrors) skipped.add(writeError.index);
3173
3252
  }
3174
3253
  return data.map((item, i) => skipped.has(i) ? null : { insertedId: idOf(item) });
3175
3254
  }
package/dist/index.d.cts CHANGED
@@ -576,7 +576,10 @@ declare class MongoAdapter extends BaseDbAdapter {
576
576
  * so a unique-index violation is a `CONFLICT` whichever statement hit it.
577
577
  */
578
578
  private _wrapDuplicateKeyError;
579
- /** Rethrows a duplicate-key (11000) server error as `CONFLICT`, anything else as is. */
579
+ /**
580
+ * Rethrows a duplicate-key error as `CONFLICT` — whatever driver error class
581
+ * carries it (see {@link duplicateKeyViolation}) — anything else as is.
582
+ */
580
583
  private _mapConstraintError;
581
584
  /** An update-shaped write under {@link _wrapDuplicateKeyError}, reduced to `TDbUpdateResult`. */
582
585
  private _wrapUpdate;
package/dist/index.d.mts CHANGED
@@ -576,7 +576,10 @@ declare class MongoAdapter extends BaseDbAdapter {
576
576
  * so a unique-index violation is a `CONFLICT` whichever statement hit it.
577
577
  */
578
578
  private _wrapDuplicateKeyError;
579
- /** Rethrows a duplicate-key (11000) server error as `CONFLICT`, anything else as is. */
579
+ /**
580
+ * Rethrows a duplicate-key error as `CONFLICT` — whatever driver error class
581
+ * carries it (see {@link duplicateKeyViolation}) — anything else as is.
582
+ */
580
583
  private _mapConstraintError;
581
584
  /** An update-shaped write under {@link _wrapDuplicateKeyError}, reduced to `TDbUpdateResult`. */
582
585
  private _wrapUpdate;
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { a as buildMongoQuery, c as planStages, f as sortStages, h as queryNodeToExpr, i as buildMongoFilter, l as correlate, m as orNull, n as distinctCountExpr, o as collationOfAdapter, p as exprToMongo, r as REL_FILTER_TEMP_PREFIX, s as mongoFilterStages, t as buildAccumulator, u as hasNullsPlacement } from "./mongo-accumulator-D4drEz0-.mjs";
1
+ import { a as buildMongoQuery, c as planStages, f as sortStages, h as queryNodeToExpr, i as buildMongoFilter, l as correlate, m as orNull, n as distinctCountExpr, o as collationOfAdapter, p as exprToMongo, r as REL_FILTER_TEMP_PREFIX, s as mongoFilterStages, t as buildAccumulator, u as hasNullsPlacement } from "./mongo-accumulator-CFVRBDiw.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, tableNameOf, translateQueryTree, uniqueKeyTuple, vectorIndexNotFoundMessage } from "@atscript/db";
4
- import { MongoBulkWriteError, MongoClient, MongoServerError, ObjectId } from "mongodb";
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, tableNameOf, translateQueryTree, uniqueKeyTuple, unknownWithRelation, vectorIndexNotFoundMessage } from "@atscript/db";
4
+ import { MongoClient, ObjectId } from "mongodb";
5
5
  import { resolveAggregateSearch } from "@atscript/db/agg";
6
6
  //#region src/lib/path-utils.ts
7
7
  function joinPath(prefix, segment) {
@@ -49,19 +49,87 @@ async function wrapInvalidQuery(fn) {
49
49
  try {
50
50
  return await fn();
51
51
  } catch (error) {
52
- if (error instanceof MongoServerError) {
53
- if (error.code === 31249 || error.code === 31254) throw new DbError("INVALID_QUERY", [{
54
- path: "$select",
55
- message: error.message
56
- }]);
57
- if (error.code === UNKNOWN_TIME_ZONE) {
58
- const zone = /time zone identifier:\s*"([^"]*)"/.exec(error.message)?.[1];
59
- throw bucketTimeZoneUnavailable(zone ? `MongoDB does not recognize time zone "${zone}" — its time zone database may be outdated` : `MongoDB does not recognize a bucket time zone: ${error.message}`);
60
- }
52
+ const code = serverErrorCode(error);
53
+ if (code === 31249 || code === 31254) throw new DbError("INVALID_QUERY", [{
54
+ path: "$select",
55
+ message: error.message
56
+ }]);
57
+ if (code === UNKNOWN_TIME_ZONE) {
58
+ const message = error.message;
59
+ const zone = /time zone identifier:\s*"([^"]*)"/.exec(message)?.[1];
60
+ throw bucketTimeZoneUnavailable(zone ? `MongoDB does not recognize time zone "${zone}" — its time zone database may be outdated` : `MongoDB does not recognize a bucket time zone: ${message}`);
61
61
  }
62
62
  throw error;
63
63
  }
64
64
  }
65
+ /** The numeric server code of a driver error, `undefined` for anything else. */
66
+ function serverErrorCode(error) {
67
+ if (!(error instanceof Error)) return void 0;
68
+ const code = error.code;
69
+ return typeof code === "number" ? code : void 0;
70
+ }
71
+ /** `WriteConflict`: a write met a concurrent transaction's uncommitted change. */
72
+ const WRITE_CONFLICT = 112;
73
+ /**
74
+ * The retryable `SERIALIZATION_FAILURE` of a driver error that ended a
75
+ * transaction without committing it — one labelled `TransientTransactionError`
76
+ * or `UnknownTransactionCommitResult` (`session.withTransaction` retries
77
+ * those itself for 120 s, then rethrows), or a `WriteConflict` — else `error`
78
+ * as is. The raw driver error is kept as `cause`.
79
+ */
80
+ function mapTransientTransactionError(error) {
81
+ if (!(error instanceof Error)) return error;
82
+ const labels = error.errorLabels;
83
+ if (!(Array.isArray(labels) && (labels.includes("TransientTransactionError") || labels.includes("UnknownTransactionCommitResult"))) && serverErrorCode(error) !== WRITE_CONFLICT) return error;
84
+ return new DbError("SERIALIZATION_FAILURE", [{
85
+ path: "",
86
+ message: error.message
87
+ }], void 0, { cause: error });
88
+ }
89
+ /** `DuplicateKey` (E11000) and its legacy update form `DuplicateKeyValue` (E11001). */
90
+ function isDuplicateKeyCode(code) {
91
+ return code === 11e3 || code === 11001;
92
+ }
93
+ /** A bulk error's per-statement write errors (`MongoBulkWriteError.writeErrors`) — `[]` for other errors. */
94
+ function bulkWriteErrors(error) {
95
+ if (!(error instanceof Error)) return [];
96
+ return [error.writeErrors].flat().filter((w) => !!w);
97
+ }
98
+ /**
99
+ * Whether a driver error carries a write-concern failure (`MongoWriteConcernError`,
100
+ * or a bulk error whose result holds one): the write's durability is unknown, so it
101
+ * is never read as a duplicate key, whatever its write errors say.
102
+ */
103
+ function hasWriteConcernError(error) {
104
+ const e = error;
105
+ return Boolean(e.writeConcernError || e.result?.getWriteConcernError?.() || e.result?.writeConcernErrors?.length);
106
+ }
107
+ /**
108
+ * The duplicate-key violation a write failed with, or `undefined` when the error
109
+ * is anything else — for every shape the driver reports one in:
110
+ * - a `MongoServerError` (single-document writes: `code` 11000, `keyPattern`);
111
+ * - a `MongoBulkWriteError` (`insertMany` / `bulkWrite` — the table layer sends
112
+ * every insert through `insertMany`): 11000 on top and in `writeErrors`, or in
113
+ * `writeErrors` only — a bulk error counts only when EVERY write error is a
114
+ * duplicate key (another failure in the batch is not a conflict);
115
+ * - a bare `WriteError` (`code` getter, `errmsg`).
116
+ *
117
+ * A write-concern failure is never a duplicate key (see {@link hasWriteConcernError}).
118
+ */
119
+ function duplicateKeyViolation(error) {
120
+ if (error === null || typeof error !== "object" || hasWriteConcernError(error)) return void 0;
121
+ const e = error;
122
+ const writeErrors = bulkWriteErrors(error);
123
+ if (!(writeErrors.length > 0 ? writeErrors.map((w) => w.code) : [e.code]).every(isDuplicateKeyCode)) return void 0;
124
+ return {
125
+ message: [
126
+ e.message,
127
+ e.errmsg,
128
+ writeErrors[0]?.errmsg
129
+ ].find((m) => typeof m === "string" && m !== "") ?? "E11000 duplicate key error",
130
+ keyPattern: e.keyPattern
131
+ };
132
+ }
65
133
  //#endregion
66
134
  //#region src/lib/collection-patcher.ts
67
135
  /**
@@ -480,7 +548,7 @@ function buildViewPipeline(view, variant) {
480
548
  out = exprToMongo(col.expr, (path) => {
481
549
  const c = byPath.get(path);
482
550
  return c.expr === void 0 ? { $toDouble: leaf(c) } : computedExpr(c, leaf);
483
- });
551
+ }, col.viewPath);
484
552
  rendered.set(col.viewPath, out);
485
553
  }
486
554
  return out;
@@ -716,7 +784,7 @@ async function loadRelationsImpl(host, rows, withRelations, relations, foreignKe
716
784
  for (const withRel of withRelations) {
717
785
  if (withRel.name.includes(".")) continue;
718
786
  const relation = relations.get(withRel.name);
719
- if (!relation) throw new Error(`Unknown relation "${withRel.name}" in $with. Available relations: ${[...relations.keys()].join(", ") || "(none)"}`);
787
+ if (!relation) throw unknownWithRelation(withRel.name);
720
788
  const lookup = buildRelationLookup(source, withRel, relation, foreignKeys, tableResolver);
721
789
  if (lookup) relMeta.push(lookup);
722
790
  }
@@ -1036,6 +1104,8 @@ const RELEVANCE_SORT = { $sort: {
1036
1104
  _score: -1,
1037
1105
  _id: 1
1038
1106
  } };
1107
+ /** The order of an unranked search (`$rank: false`, since 0.1.175): the primary key. */
1108
+ const UNRANKED_SORT = { $sort: { _id: 1 } };
1039
1109
  function getSearchIndexesImpl(host) {
1040
1110
  const result = [];
1041
1111
  const indexes = host.getMongoSearchIndexes();
@@ -1104,12 +1174,24 @@ function buildAggregateSearchStage(host, controls) {
1104
1174
  /** Text search via $search aggregation stage. */
1105
1175
  async function searchImpl(host, text, query, indexName) {
1106
1176
  const plan = requireSearchStage(host, text, indexName, query.controls);
1107
- return runSearchPipeline(host, plan.stage, query, "search", { classicText: plan.classicText });
1177
+ return runSearchPipeline(host, plan.stage, query, "search", textRunOptions(plan, query));
1108
1178
  }
1109
1179
  /** Text search with faceted count. */
1110
1180
  async function searchWithCountImpl(host, text, query, indexName) {
1111
1181
  const plan = requireSearchStage(host, text, indexName, query.controls);
1112
- return runSearchWithCountPipeline(host, plan.stage, query, "searchWithCount", { classicText: plan.classicText });
1182
+ return runSearchWithCountPipeline(host, plan.stage, query, "searchWithCount", textRunOptions(plan, query));
1183
+ }
1184
+ /**
1185
+ * The runner options of a text search: relevance from `textScore` for a
1186
+ * classic `$text` match — none under `$rank: false` (since 0.1.175), which
1187
+ * orders by `_id` instead (an Atlas `$search` included).
1188
+ */
1189
+ function textRunOptions(plan, query) {
1190
+ if (query.controls?.$rank === false) return { defaultSort: UNRANKED_SORT };
1191
+ return plan.classicText ? {
1192
+ classicText: true,
1193
+ defaultSort: RELEVANCE_SORT
1194
+ } : {};
1113
1195
  }
1114
1196
  /** Vector search via $vectorSearch aggregation stage. */
1115
1197
  async function vectorSearchImpl(host, vector, query, indexName) {
@@ -1518,7 +1600,7 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
1518
1600
  };
1519
1601
  }
1520
1602
  /** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
1521
- async function runSearchPipeline(host, stage, query, label, { threshold, classicText = false, filterStages } = {}) {
1603
+ async function runSearchPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1522
1604
  const controls = query.controls || {};
1523
1605
  const pipeline = [stage];
1524
1606
  if (threshold !== void 0) {
@@ -1528,7 +1610,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1528
1610
  pipeline.push(...filterStages ?? mongoFilterStages(query.filter, filterOptionsOf(host)));
1529
1611
  const { stages: sorted, cleanup } = sortStages(controls);
1530
1612
  if (sorted.length > 0) pipeline.push(...sorted);
1531
- else if (classicText) pipeline.push(RELEVANCE_SORT);
1613
+ else if (defaultSort) pipeline.push(defaultSort);
1532
1614
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
1533
1615
  if (controls.$limit) pipeline.push({ $limit: controls.$limit });
1534
1616
  else pipeline.push({ $limit: 1e3 });
@@ -1550,7 +1632,7 @@ async function runSearchPipeline(host, stage, query, label, { threshold, classic
1550
1632
  * `count: total` — the same counts `$$SEARCH_META` reports), concurrently
1551
1633
  * outside a transaction.
1552
1634
  */
1553
- async function runSearchWithCountPipeline(host, stage, query, label, { threshold, classicText = false, filterStages } = {}) {
1635
+ async function runSearchWithCountPipeline(host, stage, query, label, { threshold, classicText = false, defaultSort, filterStages } = {}) {
1554
1636
  const controls = query.controls || {};
1555
1637
  const preStages = [];
1556
1638
  if (threshold !== void 0) {
@@ -1558,7 +1640,7 @@ async function runSearchWithCountPipeline(host, stage, query, label, { threshold
1558
1640
  preStages.push({ $match: { _score: { $gte: threshold } } });
1559
1641
  } else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1560
1642
  const { stages: dataStages, cleanup } = sortStages(controls);
1561
- if (dataStages.length === 0 && classicText) dataStages.push(RELEVANCE_SORT);
1643
+ if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
1562
1644
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1563
1645
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1564
1646
  if (cleanup) dataStages.push(cleanup);
@@ -2278,7 +2360,7 @@ async function probe(client) {
2278
2360
  try {
2279
2361
  reply = await admin.command({ hello: 1 });
2280
2362
  } catch (error) {
2281
- if (!(error instanceof MongoServerError) || error.code !== 59) throw error;
2363
+ if (serverErrorCode(error) !== 59) throw error;
2282
2364
  reply = await admin.command({ isMaster: 1 });
2283
2365
  }
2284
2366
  return reply.setName != null || reply.isreplicaset === true || reply.msg === "isdbgrid";
@@ -2308,11 +2390,6 @@ function objectIdFromStorage(value) {
2308
2390
  * predicates (see {@link MongoAdapter.supportsRelationFilters}).
2309
2391
  */
2310
2392
  const REL_WRITE_BATCH = 1e3;
2311
- /** Whether a bulk-write error carries a write-concern failure besides (or instead of) write errors. */
2312
- function hasWriteConcernError(error) {
2313
- const e = error;
2314
- return Boolean(e.writeConcernError || e.result?.getWriteConcernError?.() || e.result?.writeConcernErrors?.length);
2315
- }
2316
2393
  var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2317
2394
  db;
2318
2395
  client;
@@ -2400,6 +2477,8 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2400
2477
  result = await this._runInTransactionContext(session, fn);
2401
2478
  });
2402
2479
  return result;
2480
+ } catch (error) {
2481
+ throw mapTransientTransactionError(error);
2403
2482
  } finally {
2404
2483
  try {
2405
2484
  await session.endSession();
@@ -3086,12 +3165,16 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
3086
3165
  return this._mapConstraintError(error);
3087
3166
  }
3088
3167
  }
3089
- /** Rethrows a duplicate-key (11000) server error as `CONFLICT`, anything else as is. */
3168
+ /**
3169
+ * Rethrows a duplicate-key error as `CONFLICT` — whatever driver error class
3170
+ * carries it (see {@link duplicateKeyViolation}) — anything else as is.
3171
+ */
3090
3172
  _mapConstraintError(error) {
3091
- if (error instanceof MongoServerError && error.code === 11e3) throw constraintViolation("CONFLICT", {
3092
- columns: error.keyPattern ? Object.keys(error.keyPattern) : void 0,
3093
- name: error.message.match(/index: (\S+) dup key/)?.[1]
3094
- }, error.message);
3173
+ const duplicate = duplicateKeyViolation(error);
3174
+ if (duplicate) throw constraintViolation("CONFLICT", {
3175
+ columns: duplicate.keyPattern ? Object.keys(duplicate.keyPattern) : void 0,
3176
+ name: duplicate.message.match(/index: (\S+) dup key/)?.[1]
3177
+ }, duplicate.message);
3095
3178
  throw error;
3096
3179
  }
3097
3180
  /** An update-shaped write under {@link _wrapDuplicateKeyError}, reduced to `TDbUpdateResult`. */
@@ -3162,13 +3245,9 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
3162
3245
  ...this._getSessionOpts()
3163
3246
  });
3164
3247
  } catch (error) {
3165
- if (!(error instanceof MongoBulkWriteError)) this._mapConstraintError(error);
3166
- const writeErrors = [error.writeErrors].flat().filter(Boolean);
3167
- if (writeErrors.length === 0 || hasWriteConcernError(error)) throw error;
3168
- for (const writeError of writeErrors) {
3169
- if (writeError.code !== 11e3) throw error;
3170
- skipped.add(writeError.index);
3171
- }
3248
+ const writeErrors = bulkWriteErrors(error);
3249
+ if (writeErrors.length === 0 || !duplicateKeyViolation(error)) this._mapConstraintError(error);
3250
+ for (const writeError of writeErrors) skipped.add(writeError.index);
3172
3251
  }
3173
3252
  return data.map((item, i) => skipped.has(i) ? null : { insertedId: idOf(item) });
3174
3253
  }
@@ -110,10 +110,11 @@ function queryNodeToExpr(node, pathOf) {
110
110
  * arithmetic would stay exact past 2^53 where SQL rounds.
111
111
  * @since 0.1.147
112
112
  */
113
- function exprToMongo(node, operand) {
113
+ function exprToMongo(node, operand, path = "$select") {
114
114
  if (typeof node === "number") return { $toDouble: node };
115
115
  if ("field" in node) return operand(node.field);
116
- const args = node.args.map((arg) => exprToMongo(arg, operand));
116
+ (0, _atscript_db.assertExprArity)(node, path);
117
+ const args = node.args.map((arg) => exprToMongo(arg, operand, path));
117
118
  switch (node.op) {
118
119
  case "+": return { $add: args };
119
120
  case "-": return { $subtract: args };
@@ -1,4 +1,4 @@
1
- import { DbError, INTEGER_REGEX_OP, andFilters, containsRelationFilter, isFieldRef, isResolvedRelationFilter, walkFilter } from "@atscript/db";
1
+ import { DbError, INTEGER_REGEX_OP, andFilters, assertExprArity, containsRelationFilter, isFieldRef, isResolvedRelationFilter, walkFilter } from "@atscript/db";
2
2
  import { BSONRegExp } from "mongodb";
3
3
  import { isNullsPlacement } from "@uniqu/core";
4
4
  import { assertAggregateFn } from "@atscript/db/agg";
@@ -110,10 +110,11 @@ function queryNodeToExpr(node, pathOf) {
110
110
  * arithmetic would stay exact past 2^53 where SQL rounds.
111
111
  * @since 0.1.147
112
112
  */
113
- function exprToMongo(node, operand) {
113
+ function exprToMongo(node, operand, path = "$select") {
114
114
  if (typeof node === "number") return { $toDouble: node };
115
115
  if ("field" in node) return operand(node.field);
116
- const args = node.args.map((arg) => exprToMongo(arg, operand));
116
+ assertExprArity(node, path);
117
+ const args = node.args.map((arg) => exprToMongo(arg, operand, path));
117
118
  switch (node.op) {
118
119
  case "+": return { $add: args };
119
120
  case "-": return { $subtract: args };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-mongo",
3
- "version": "0.1.173",
3
+ "version": "0.1.175",
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.9",
50
- "@atscript/typescript": "^0.2.9",
51
- "@uniqu/core": "^0.2.1",
49
+ "@atscript/core": "^0.2.11",
50
+ "@atscript/typescript": "^0.2.11",
51
+ "@uniqu/core": "^0.2.2",
52
52
  "mongodb": "^6.17.0",
53
53
  "mongodb-memory-server-core": "^10.0.0",
54
- "unplugin-atscript": "^0.2.9"
54
+ "unplugin-atscript": "^0.2.11"
55
55
  },
56
56
  "peerDependencies": {
57
- "@atscript/core": "^0.2.9",
58
- "@atscript/typescript": "^0.2.9",
59
- "@uniqu/core": "^0.2.1",
57
+ "@atscript/core": "^0.2.11",
58
+ "@atscript/typescript": "^0.2.11",
59
+ "@uniqu/core": "^0.2.2",
60
60
  "mongodb": "^6.17.0",
61
- "@atscript/db": "^0.1.173"
61
+ "@atscript/db": "^0.1.175"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "vp pack",