@mastra/dsql 1.5.4 → 1.5.5-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -7,7 +7,7 @@ let _mastra_core_base = require("@mastra/core/base");
7
7
  let _mastra_core_utils = require("@mastra/core/utils");
8
8
  let _mastra_core_agent = require("@mastra/core/agent");
9
9
  let _mastra_core_evals = require("@mastra/core/evals");
10
- //#region src/shared/config.ts
10
+ // src/shared/config.ts
11
11
  /**
12
12
  * Default connection pool settings optimized for Aurora DSQL.
13
13
  *
@@ -71,8 +71,7 @@ const getEffectiveRegion = (config) => {
71
71
  if (extractedRegion) return extractedRegion;
72
72
  throw new Error("DSQLStore: region could not be determined. Provide region in config or use a standard DSQL endpoint.");
73
73
  };
74
- //#endregion
75
- //#region src/storage/client.ts
74
+ // src/storage/client.ts
76
75
  /**
77
76
  * Truncate a query string for error messages.
78
77
  */
@@ -440,8 +439,7 @@ async function withRetry(fn, options = {}) {
440
439
  }
441
440
  throw lastError;
442
441
  }
443
- //#endregion
444
- //#region src/shared/batch.ts
442
+ // src/shared/batch.ts
445
443
  /**
446
444
  * Batch utilities for Aurora DSQL.
447
445
  *
@@ -490,8 +488,7 @@ function splitIntoBatches(records, options = {}) {
490
488
  batchCount: batches.length
491
489
  };
492
490
  }
493
- //#endregion
494
- //#region src/storage/db/index.ts
491
+ // src/storage/db/index.ts
495
492
  /**
496
493
  * Resolves DsqlDomainConfi to a database client and schema.
497
494
  * Handles creating a new pool if config is provided.
@@ -1231,8 +1228,7 @@ var DsqlDB = class extends _mastra_core_base.MastraBase {
1231
1228
  return this.clearTable({ tableName });
1232
1229
  }
1233
1230
  };
1234
- //#endregion
1235
- //#region src/storage/domains/utils.ts
1231
+ // src/storage/domains/utils.ts
1236
1232
  function getSchemaName(schema) {
1237
1233
  return schema ? `"${(0, _mastra_core_utils.parseSqlIdentifier)(schema, "schema name")}"` : void 0;
1238
1234
  }
@@ -1261,8 +1257,7 @@ function transformFromSqlRow({ tableName, sqlRow }) {
1261
1257
  });
1262
1258
  return result;
1263
1259
  }
1264
- //#endregion
1265
- //#region src/storage/domains/agents/index.ts
1260
+ // src/storage/domains/agents/index.ts
1266
1261
  var AgentsDSQL = class AgentsDSQL extends _mastra_core_storage.AgentsStorage {
1267
1262
  #db;
1268
1263
  #schema;
@@ -1826,8 +1821,7 @@ var AgentsDSQL = class AgentsDSQL extends _mastra_core_storage.AgentsStorage {
1826
1821
  };
1827
1822
  }
1828
1823
  };
1829
- //#endregion
1830
- //#region src/storage/db/run-fencing.ts
1824
+ // src/storage/db/run-fencing.ts
1831
1825
  /**
1832
1826
  * Epoch milliseconds on the database clock. Aurora DSQL never waits on a row
1833
1827
  * lock, so the transaction's start time is the time its statements run, and
@@ -1870,8 +1864,7 @@ function withRunFence(client, claimsTable, fence, operation, write) {
1870
1864
  return write(t);
1871
1865
  });
1872
1866
  }
1873
- //#endregion
1874
- //#region src/storage/domains/memory/index.ts
1867
+ // src/storage/domains/memory/index.ts
1875
1868
  /**
1876
1869
  * Generate SQL placeholder string for IN clauses.
1877
1870
  * @param count - Number of placeholders to generate
@@ -2534,11 +2527,13 @@ var MemoryDSQL = class MemoryDSQL extends _mastra_core_storage.MemoryStorage {
2534
2527
  queryParams.push(resourceId);
2535
2528
  }
2536
2529
  if (filter?.dateRange?.start) {
2537
- conditions.push(`"createdAtZ" >= $${paramIndex++}::timestamptz`);
2530
+ const operator = filter.dateRange.startExclusive ? ">" : ">=";
2531
+ conditions.push(`"createdAtZ" ${operator} $${paramIndex++}::timestamptz`);
2538
2532
  queryParams.push(filter.dateRange.start);
2539
2533
  }
2540
2534
  if (filter?.dateRange?.end) {
2541
- conditions.push(`"createdAtZ" <= $${paramIndex++}::timestamptz`);
2535
+ const operator = filter.dateRange.endExclusive ? "<" : "<=";
2536
+ conditions.push(`"createdAtZ" ${operator} $${paramIndex++}::timestamptz`);
2542
2537
  queryParams.push(filter.dateRange.end);
2543
2538
  }
2544
2539
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
@@ -2947,8 +2942,7 @@ var MemoryDSQL = class MemoryDSQL extends _mastra_core_storage.MemoryStorage {
2947
2942
  return result;
2948
2943
  }
2949
2944
  };
2950
- //#endregion
2951
- //#region src/storage/domains/observability/index.ts
2945
+ // src/storage/domains/observability/index.ts
2952
2946
  var ObservabilityDSQL = class ObservabilityDSQL extends _mastra_core_storage.ObservabilityStorage {
2953
2947
  static retentionTables = { spans: {
2954
2948
  table: _mastra_core_storage.TABLE_SPANS,
@@ -3504,8 +3498,7 @@ var ObservabilityDSQL = class ObservabilityDSQL extends _mastra_core_storage.Obs
3504
3498
  }
3505
3499
  }
3506
3500
  };
3507
- //#endregion
3508
- //#region src/storage/domains/scores/index.ts
3501
+ // src/storage/domains/scores/index.ts
3509
3502
  /**
3510
3503
  * DSQL-specific score row transformation.
3511
3504
  * Uses Z-suffix timestamps (createdAtZ, updatedAtZ) when available.
@@ -3882,8 +3875,7 @@ var ScoresDSQL = class ScoresDSQL extends _mastra_core_storage.ScoresStorage {
3882
3875
  }
3883
3876
  }
3884
3877
  };
3885
- //#endregion
3886
- //#region src/storage/domains/workflows/index.ts
3878
+ // src/storage/domains/workflows/index.ts
3887
3879
  const RUN_OWNER_COLUMNS = `generation, "ownerId", "leaseExpiresAt", ${DB_NOW_MS} AS "nowMs"`;
3888
3880
  function toRunOwnershipRecord(runId, row) {
3889
3881
  const leaseExpiresAt = row.leaseExpiresAt === null ? null : Number(row.leaseExpiresAt);
@@ -3943,6 +3935,9 @@ var WorkflowsDSQL = class WorkflowsDSQL extends _mastra_core_storage.WorkflowsSt
3943
3935
  supportsConcurrentUpdates() {
3944
3936
  return true;
3945
3937
  }
3938
+ supportsGuardedSnapshotWrites() {
3939
+ return true;
3940
+ }
3946
3941
  /**
3947
3942
  * Returns default index definitions for the workflows domain tables.
3948
3943
  * Currently no default indexes are defined for workflows.
@@ -4237,26 +4232,29 @@ var WorkflowsDSQL = class WorkflowsDSQL extends _mastra_core_storage.WorkflowsSt
4237
4232
  }, error);
4238
4233
  }
4239
4234
  }
4240
- async persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot, createdAt, updatedAt, fence }) {
4235
+ async persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot, createdAt, updatedAt, fence, expectedStatus }) {
4241
4236
  try {
4242
4237
  const now = /* @__PURE__ */ new Date();
4243
4238
  const createdAtValue = createdAt ? createdAt : now;
4244
4239
  const updatedAtValue = updatedAt ? updatedAt : now;
4245
4240
  const resolvedFence = (0, _mastra_core_storage.resolveRunFence)(this, fence, runId);
4246
- await withRetry(() => withRunFence(this.#db.client, this.#runOwnersTable(), resolvedFence, "persistWorkflowSnapshot", (q) => q.none(`INSERT INTO ${getTableName({
4241
+ const guard = expectedStatus === void 0 ? "" : ` WHERE t.snapshot::jsonb ->> 'status' = ANY($7::text[])`;
4242
+ return await withRetry(() => withRunFence(this.#db.client, this.#runOwnersTable(), resolvedFence, "persistWorkflowSnapshot", (q) => q.oneOrNone(`INSERT INTO ${getTableName({
4247
4243
  indexName: _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT,
4248
4244
  schemaName: getSchemaName(this.#schema)
4249
- })} (workflow_name, run_id, "resourceId", snapshot, "createdAt", "updatedAt")
4245
+ })} AS t (workflow_name, run_id, "resourceId", snapshot, "createdAt", "updatedAt")
4250
4246
  VALUES ($1, $2, $3, $4, $5, $6)
4251
4247
  ON CONFLICT (workflow_name, run_id) DO UPDATE
4252
- SET "resourceId" = $3, snapshot = $4, "updatedAt" = $6`, [
4248
+ SET "resourceId" = $3, snapshot = $4, "updatedAt" = $6${guard}
4249
+ RETURNING 1 AS written`, [
4253
4250
  workflowName,
4254
4251
  runId,
4255
4252
  resourceId,
4256
4253
  JSON.stringify(snapshot),
4257
4254
  createdAtValue.toISOString(),
4258
- updatedAtValue.toISOString()
4259
- ])));
4255
+ updatedAtValue.toISOString(),
4256
+ ...expectedStatus === void 0 ? [] : [Array.isArray(expectedStatus) ? expectedStatus : [expectedStatus]]
4257
+ ]))) !== null;
4260
4258
  } catch (error) {
4261
4259
  if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
4262
4260
  throw new _mastra_core_error.MastraError({
@@ -4266,6 +4264,24 @@ var WorkflowsDSQL = class WorkflowsDSQL extends _mastra_core_storage.WorkflowsSt
4266
4264
  }, error);
4267
4265
  }
4268
4266
  }
4267
+ async loadWorkflowRunStatus({ workflowName, runId }) {
4268
+ try {
4269
+ return (await this.#db.client.oneOrNone(`SELECT snapshot::jsonb ->> 'status' AS status FROM ${getTableName({
4270
+ indexName: _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT,
4271
+ schemaName: getSchemaName(this.#schema)
4272
+ })} WHERE "workflow_name" = $1 AND "run_id" = $2 ORDER BY "createdAt" DESC LIMIT 1`, [workflowName, runId]))?.status ?? null;
4273
+ } catch (error) {
4274
+ throw new _mastra_core_error.MastraError({
4275
+ id: (0, _mastra_core_storage.createStorageErrorId)("DSQL", "LOAD_WORKFLOW_RUN_STATUS", "FAILED"),
4276
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
4277
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
4278
+ details: {
4279
+ workflowName,
4280
+ runId
4281
+ }
4282
+ }, error);
4283
+ }
4284
+ }
4269
4285
  async loadWorkflowSnapshot({ workflowName, runId }) {
4270
4286
  try {
4271
4287
  const result = await this.#db.load({
@@ -4419,8 +4435,7 @@ var WorkflowsDSQL = class WorkflowsDSQL extends _mastra_core_storage.WorkflowsSt
4419
4435
  }
4420
4436
  }
4421
4437
  };
4422
- //#endregion
4423
- //#region src/storage/index.ts
4438
+ // src/storage/index.ts
4424
4439
  var DSQLStore = class extends _mastra_core_storage.MastraStorage {
4425
4440
  #pool;
4426
4441
  #db;
@@ -4530,7 +4545,6 @@ var DSQLStore = class extends _mastra_core_storage.MastraStorage {
4530
4545
  this.isInitialized = false;
4531
4546
  }
4532
4547
  };
4533
- //#endregion
4534
4548
  exports.AgentsDSQL = AgentsDSQL;
4535
4549
  exports.DSQLStore = DSQLStore;
4536
4550
  exports.DSQL_POOL_DEFAULTS = DSQL_POOL_DEFAULTS;