@mastra/mssql 1.11.1 → 1.11.2-alpha.0

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
@@ -4631,6 +4631,28 @@ var WorkflowDefinitionsMSSQL = class WorkflowDefinitionsMSSQL extends WorkflowDe
4631
4631
  };
4632
4632
  // src/storage/domains/workflows/index.ts
4633
4633
  const RUN_OWNER_COLUMNS = `[generation], [ownerId], [leaseExpiresAt], ${DB_NOW_MS} AS [nowMs]`;
4634
+ /** Run ids per query in `getRunOwnerships`, well under SQL Server's 2,100 parameters per request. */
4635
+ const RUN_OWNERSHIP_BATCH_SIZE = 500;
4636
+ /**
4637
+ * The summary snapshot `listWorkflowRuns({ summary: true })` returns: `status` and `timestamp`
4638
+ * when set, and `parentWorkflow` with only its `workflowId` and `runId` when both are non-empty.
4639
+ * Only these paths are read, so `context` is never sent. OPENJSON parses each snapshot once, and
4640
+ * FOR JSON PATH leaves out NULL values. A snapshot that isn't valid JSON lists as `{}`, since
4641
+ * OPENJSON would fail the whole listing on it. OPENJSON returns one row per element of a JSON
4642
+ * array, so `TOP (1)` keeps the summary to one object.
4643
+ */
4644
+ const SUMMARY_SNAPSHOT_SQL = `COALESCE(CASE WHEN ISJSON([snapshot]) = 1 THEN (
4645
+ SELECT TOP (1) s.[status],
4646
+ TRY_CAST(s.[timestamp] AS BIGINT) AS [timestamp],
4647
+ CASE WHEN s.[workflowId] <> '' AND s.[runId] <> '' THEN s.[workflowId] END AS [parentWorkflow.workflowId],
4648
+ CASE WHEN s.[workflowId] <> '' AND s.[runId] <> '' THEN s.[runId] END AS [parentWorkflow.runId]
4649
+ FROM OPENJSON([snapshot]) WITH (
4650
+ [status] NVARCHAR(MAX) '$.status',
4651
+ [timestamp] NVARCHAR(64) '$.timestamp',
4652
+ [workflowId] NVARCHAR(MAX) '$.parentWorkflow.workflowId',
4653
+ [runId] NVARCHAR(MAX) '$.parentWorkflow.runId'
4654
+ ) AS s
4655
+ FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) END, '{}')`;
4634
4656
  function toRunOwnershipRecord(runId, row) {
4635
4657
  const leaseExpiresAt = row.leaseExpiresAt === null ? null : Number(row.leaseExpiresAt);
4636
4658
  return {
@@ -4648,6 +4670,8 @@ var WorkflowsMSSQL = class WorkflowsMSSQL extends WorkflowsStorage {
4648
4670
  needsConnect;
4649
4671
  skipDefaultIndexes;
4650
4672
  indexes;
4673
+ /** Set once the snapshot table is seen with a `resourceId` column, which is never dropped. */
4674
+ #hasResourceIdColumn = false;
4651
4675
  /** Tables managed by this domain */
4652
4676
  static MANAGED_TABLES = [TABLE_WORKFLOW_SNAPSHOT];
4653
4677
  /**
@@ -4836,6 +4860,38 @@ var WorkflowsMSSQL = class WorkflowsMSSQL extends WorkflowsStorage {
4836
4860
  throw this.#ownershipError("GET_RUN_OWNERSHIP", runId, error);
4837
4861
  }
4838
4862
  }
4863
+ /** Reads the records with one query per {@link RUN_OWNERSHIP_BATCH_SIZE} runs. */
4864
+ async getRunOwnerships({ runIds }) {
4865
+ const records = /* @__PURE__ */ new Map();
4866
+ const ids = [...new Set(runIds)];
4867
+ try {
4868
+ for (let start = 0; start < ids.length; start += RUN_OWNERSHIP_BATCH_SIZE) {
4869
+ const chunk = ids.slice(start, start + RUN_OWNERSHIP_BATCH_SIZE);
4870
+ const request = this.pool.request();
4871
+ chunk.forEach((runId, i) => request.input(`runId${i}`, runId));
4872
+ const rows = (await request.query(`SELECT j.[reqId], ${RUN_OWNER_COLUMNS}
4873
+ FROM (VALUES ${chunk.map((_, i) => `(@runId${i})`).join(", ")}) AS j ([reqId])
4874
+ JOIN ${this.#runOwnersTable} o ON o.[runId] = j.[reqId]`)).recordset;
4875
+ for (const row of rows) {
4876
+ const runId = String(row.reqId);
4877
+ records.set(runId, toRunOwnershipRecord(runId, row));
4878
+ }
4879
+ }
4880
+ return records;
4881
+ } catch (error) {
4882
+ throw new MastraError({
4883
+ id: createStorageErrorId("MSSQL", "GET_RUN_OWNERSHIPS", "FAILED"),
4884
+ domain: ErrorDomain.STORAGE,
4885
+ category: ErrorCategory.THIRD_PARTY,
4886
+ details: { runCount: ids.length }
4887
+ }, error);
4888
+ }
4889
+ }
4890
+ /** Whether the snapshot table has `resourceId`, which tables created before it existed lack. */
4891
+ async #resourceIdColumnExists() {
4892
+ if (!this.#hasResourceIdColumn) this.#hasResourceIdColumn = await this.db.hasColumn(TABLE_WORKFLOW_SNAPSHOT, "resourceId");
4893
+ return this.#hasResourceIdColumn;
4894
+ }
4839
4895
  parseWorkflowRun(row) {
4840
4896
  let parsedSnapshot = row.snapshot;
4841
4897
  if (typeof parsedSnapshot === "string") try {
@@ -5127,7 +5183,11 @@ var WorkflowsMSSQL = class WorkflowsMSSQL extends WorkflowsStorage {
5127
5183
  }, error);
5128
5184
  }
5129
5185
  }
5130
- async listWorkflowRuns({ workflowName, fromDate, toDate, page, perPage, resourceId, status } = {}) {
5186
+ /**
5187
+ * Lists runs newest first, with optional filters and pagination. With `summary`, each run's
5188
+ * snapshot holds only `status`, `timestamp` and `parentWorkflow`.
5189
+ */
5190
+ async listWorkflowRuns({ workflowName, fromDate, toDate, page, perPage, resourceId, status, summary } = {}) {
5131
5191
  try {
5132
5192
  const conditions = [];
5133
5193
  const paramMap = {};
@@ -5140,7 +5200,7 @@ var WorkflowsMSSQL = class WorkflowsMSSQL extends WorkflowsStorage {
5140
5200
  paramMap["status"] = status;
5141
5201
  }
5142
5202
  if (resourceId) {
5143
- if (await this.db.hasColumn(TABLE_WORKFLOW_SNAPSHOT, "resourceId")) {
5203
+ if (await this.#resourceIdColumnExists()) {
5144
5204
  conditions.push(`[resourceId] = @resourceId`);
5145
5205
  paramMap["resourceId"] = resourceId;
5146
5206
  } else this.logger?.warn?.(`[${TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
@@ -5170,7 +5230,9 @@ var WorkflowsMSSQL = class WorkflowsMSSQL extends WorkflowsStorage {
5170
5230
  const countResult = await request.query(countQuery);
5171
5231
  total = Number(countResult.recordset[0]?.count || 0);
5172
5232
  }
5173
- let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
5233
+ let columns = "*";
5234
+ if (summary) columns = `[workflow_name], [run_id], ${await this.#resourceIdColumnExists() ? "[resourceId], " : ""}${SUMMARY_SNAPSHOT_SQL} AS [snapshot], [createdAt], [updatedAt]`;
5235
+ let query = `SELECT ${columns} FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
5174
5236
  if (usePagination) {
5175
5237
  const normalizedPerPage = normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
5176
5238
  const offset = page * normalizedPerPage;