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