@mastra/mssql 0.0.0-share-agent-metadata-with-cloud-20250718123411 → 0.0.0-sidebar-window-undefined-fix-20251029233656

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +560 -3
  2. package/README.md +315 -36
  3. package/dist/index.cjs +2701 -994
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.ts +3 -4
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +2702 -995
  8. package/dist/index.js.map +1 -0
  9. package/dist/storage/domains/legacy-evals/index.d.ts +20 -0
  10. package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
  11. package/dist/storage/domains/memory/index.d.ts +98 -0
  12. package/dist/storage/domains/memory/index.d.ts.map +1 -0
  13. package/dist/storage/domains/observability/index.d.ts +44 -0
  14. package/dist/storage/domains/observability/index.d.ts.map +1 -0
  15. package/dist/storage/domains/operations/index.d.ts +114 -0
  16. package/dist/storage/domains/operations/index.d.ts.map +1 -0
  17. package/dist/storage/domains/scores/index.d.ts +55 -0
  18. package/dist/storage/domains/scores/index.d.ts.map +1 -0
  19. package/dist/storage/domains/utils.d.ts +25 -0
  20. package/dist/storage/domains/utils.d.ts.map +1 -0
  21. package/dist/storage/domains/workflows/index.d.ts +56 -0
  22. package/dist/storage/domains/workflows/index.d.ts.map +1 -0
  23. package/dist/storage/index.d.ts +280 -0
  24. package/dist/storage/index.d.ts.map +1 -0
  25. package/package.json +26 -12
  26. package/dist/_tsup-dts-rollup.d.cts +0 -213
  27. package/dist/_tsup-dts-rollup.d.ts +0 -213
  28. package/dist/index.d.cts +0 -4
  29. package/docker-compose.yaml +0 -14
  30. package/eslint.config.js +0 -6
  31. package/src/index.ts +0 -2
  32. package/src/storage/index.test.ts +0 -2239
  33. package/src/storage/index.ts +0 -2044
  34. package/tsconfig.json +0 -5
  35. package/vitest.config.ts +0 -12
package/dist/index.js CHANGED
@@ -1,124 +1,125 @@
1
- import { MessageList } from '@mastra/core/agent';
2
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
- import { MastraStorage, TABLE_EVALS, TABLE_TRACES, TABLE_WORKFLOW_SNAPSHOT, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES } from '@mastra/core/storage';
4
- import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
5
- import sql from 'mssql';
2
+ import { MastraStorage, LegacyEvalsStorage, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_TRACES, TABLE_EVALS, TABLE_SCORERS, TABLE_AI_SPANS, ScoresStorage, WorkflowsStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ObservabilityStorage, safelyParseJSON } from '@mastra/core/storage';
3
+ import sql3 from 'mssql';
4
+ import { parseSqlIdentifier } from '@mastra/core/utils';
5
+ import { MessageList } from '@mastra/core/agent';
6
+ import { randomUUID } from 'crypto';
7
+ import { saveScorePayloadSchema } from '@mastra/core/scores';
6
8
 
7
9
  // src/storage/index.ts
8
- var MSSQLStore = class extends MastraStorage {
9
- pool;
10
- schema;
11
- setupSchemaPromise = null;
12
- schemaSetupComplete = void 0;
13
- isConnected = null;
14
- constructor(config) {
15
- super({ name: "MSSQLStore" });
16
- try {
17
- if ("connectionString" in config) {
18
- if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
19
- throw new Error("MSSQLStore: connectionString must be provided and cannot be empty.");
20
- }
21
- } else {
22
- const required = ["server", "database", "user", "password"];
23
- for (const key of required) {
24
- if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
25
- throw new Error(`MSSQLStore: ${key} must be provided and cannot be empty.`);
26
- }
27
- }
28
- }
29
- this.schema = config.schemaName;
30
- this.pool = "connectionString" in config ? new sql.ConnectionPool(config.connectionString) : new sql.ConnectionPool({
31
- server: config.server,
32
- database: config.database,
33
- user: config.user,
34
- password: config.password,
35
- port: config.port,
36
- options: config.options || { encrypt: true, trustServerCertificate: true }
37
- });
38
- } catch (e) {
39
- throw new MastraError(
40
- {
41
- id: "MASTRA_STORAGE_MSSQL_STORE_INITIALIZATION_FAILED",
42
- domain: ErrorDomain.STORAGE,
43
- category: ErrorCategory.USER
44
- },
45
- e
46
- );
47
- }
10
+ function getSchemaName(schema) {
11
+ return schema ? `[${parseSqlIdentifier(schema, "schema name")}]` : void 0;
12
+ }
13
+ function getTableName({ indexName, schemaName }) {
14
+ const parsedIndexName = parseSqlIdentifier(indexName, "index name");
15
+ const quotedIndexName = `[${parsedIndexName}]`;
16
+ const quotedSchemaName = schemaName;
17
+ return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
18
+ }
19
+ function buildDateRangeFilter(dateRange, fieldName) {
20
+ const filters = {};
21
+ if (dateRange?.start) {
22
+ filters[`${fieldName}_gte`] = dateRange.start;
48
23
  }
49
- async init() {
50
- if (this.isConnected === null) {
51
- this.isConnected = this._performInitializationAndStore();
52
- }
53
- try {
54
- await this.isConnected;
55
- await super.init();
56
- } catch (error) {
57
- this.isConnected = null;
58
- throw new MastraError(
59
- {
60
- id: "MASTRA_STORAGE_MSSQL_STORE_INIT_FAILED",
61
- domain: ErrorDomain.STORAGE,
62
- category: ErrorCategory.THIRD_PARTY
63
- },
64
- error
65
- );
66
- }
24
+ if (dateRange?.end) {
25
+ filters[`${fieldName}_lte`] = dateRange.end;
67
26
  }
68
- async _performInitializationAndStore() {
69
- try {
70
- await this.pool.connect();
71
- return true;
72
- } catch (err) {
73
- throw err;
27
+ return filters;
28
+ }
29
+ function prepareWhereClause(filters, _schema) {
30
+ const conditions = [];
31
+ const params = {};
32
+ let paramIndex = 1;
33
+ Object.entries(filters).forEach(([key, value]) => {
34
+ if (value === void 0) return;
35
+ const paramName = `p${paramIndex++}`;
36
+ if (key.endsWith("_gte")) {
37
+ const fieldName = key.slice(0, -4);
38
+ conditions.push(`[${parseSqlIdentifier(fieldName, "field name")}] >= @${paramName}`);
39
+ params[paramName] = value instanceof Date ? value.toISOString() : value;
40
+ } else if (key.endsWith("_lte")) {
41
+ const fieldName = key.slice(0, -4);
42
+ conditions.push(`[${parseSqlIdentifier(fieldName, "field name")}] <= @${paramName}`);
43
+ params[paramName] = value instanceof Date ? value.toISOString() : value;
44
+ } else if (value === null) {
45
+ conditions.push(`[${parseSqlIdentifier(key, "field name")}] IS NULL`);
46
+ } else {
47
+ conditions.push(`[${parseSqlIdentifier(key, "field name")}] = @${paramName}`);
48
+ params[paramName] = value instanceof Date ? value.toISOString() : value;
74
49
  }
75
- }
76
- get supports() {
77
- return {
78
- selectByIncludeResourceScope: true,
79
- resourceWorkingMemory: true
80
- };
81
- }
82
- getTableName(indexName) {
83
- const parsedIndexName = parseSqlIdentifier(indexName, "index name");
84
- const quotedIndexName = `[${parsedIndexName}]`;
85
- const quotedSchemaName = this.getSchemaName();
86
- return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
87
- }
88
- getSchemaName() {
89
- return this.schema ? `[${parseSqlIdentifier(this.schema, "schema name")}]` : void 0;
90
- }
91
- transformEvalRow(row) {
92
- let testInfoValue = null, resultValue = null;
93
- if (row.test_info) {
50
+ });
51
+ return {
52
+ sql: conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "",
53
+ params
54
+ };
55
+ }
56
+ function transformFromSqlRow({
57
+ tableName,
58
+ sqlRow
59
+ }) {
60
+ const schema = TABLE_SCHEMAS[tableName];
61
+ const result = {};
62
+ Object.entries(sqlRow).forEach(([key, value]) => {
63
+ const columnSchema = schema?.[key];
64
+ if (columnSchema?.type === "jsonb" && typeof value === "string") {
94
65
  try {
95
- testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
66
+ result[key] = JSON.parse(value);
96
67
  } catch {
68
+ result[key] = value;
97
69
  }
70
+ } else if (columnSchema?.type === "timestamp" && value && typeof value === "string") {
71
+ result[key] = new Date(value);
72
+ } else if (columnSchema?.type === "timestamp" && value instanceof Date) {
73
+ result[key] = value;
74
+ } else if (columnSchema?.type === "boolean") {
75
+ result[key] = Boolean(value);
76
+ } else {
77
+ result[key] = value;
98
78
  }
99
- if (row.test_info) {
100
- try {
101
- resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
102
- } catch {
103
- }
79
+ });
80
+ return result;
81
+ }
82
+
83
+ // src/storage/domains/legacy-evals/index.ts
84
+ function transformEvalRow(row) {
85
+ let testInfoValue = null, resultValue = null;
86
+ if (row.test_info) {
87
+ try {
88
+ testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
89
+ } catch {
104
90
  }
105
- return {
106
- agentName: row.agent_name,
107
- input: row.input,
108
- output: row.output,
109
- result: resultValue,
110
- metricName: row.metric_name,
111
- instructions: row.instructions,
112
- testInfo: testInfoValue,
113
- globalRunId: row.global_run_id,
114
- runId: row.run_id,
115
- createdAt: row.created_at
116
- };
91
+ }
92
+ if (row.result) {
93
+ try {
94
+ resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
95
+ } catch {
96
+ }
97
+ }
98
+ return {
99
+ agentName: row.agent_name,
100
+ input: row.input,
101
+ output: row.output,
102
+ result: resultValue,
103
+ metricName: row.metric_name,
104
+ instructions: row.instructions,
105
+ testInfo: testInfoValue,
106
+ globalRunId: row.global_run_id,
107
+ runId: row.run_id,
108
+ createdAt: row.created_at
109
+ };
110
+ }
111
+ var LegacyEvalsMSSQL = class extends LegacyEvalsStorage {
112
+ pool;
113
+ schema;
114
+ constructor({ pool, schema }) {
115
+ super();
116
+ this.pool = pool;
117
+ this.schema = schema;
117
118
  }
118
119
  /** @deprecated use getEvals instead */
119
120
  async getEvalsByAgentName(agentName, type) {
120
121
  try {
121
- let query = `SELECT * FROM ${this.getTableName(TABLE_EVALS)} WHERE agent_name = @p1`;
122
+ let query = `SELECT * FROM ${getTableName({ indexName: TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
122
123
  if (type === "test") {
123
124
  query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
124
125
  } else if (type === "live") {
@@ -129,495 +130,164 @@ var MSSQLStore = class extends MastraStorage {
129
130
  request.input("p1", agentName);
130
131
  const result = await request.query(query);
131
132
  const rows = result.recordset;
132
- return typeof this.transformEvalRow === "function" ? rows?.map((row) => this.transformEvalRow(row)) ?? [] : rows ?? [];
133
+ return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
133
134
  } catch (error) {
134
135
  if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
135
136
  return [];
136
137
  }
137
- console.error("Failed to get evals for the specified agent: " + error?.message);
138
+ this.logger?.error?.("Failed to get evals for the specified agent:", error);
138
139
  throw error;
139
140
  }
140
141
  }
141
- async batchInsert({ tableName, records }) {
142
- const transaction = this.pool.transaction();
143
- try {
144
- await transaction.begin();
145
- for (const record of records) {
146
- await this.insert({ tableName, record });
147
- }
148
- await transaction.commit();
149
- } catch (error) {
150
- await transaction.rollback();
151
- throw new MastraError(
152
- {
153
- id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
154
- domain: ErrorDomain.STORAGE,
155
- category: ErrorCategory.THIRD_PARTY,
156
- details: {
157
- tableName,
158
- numberOfRecords: records.length
159
- }
160
- },
161
- error
162
- );
163
- }
164
- }
165
- /** @deprecated use getTracesPaginated instead*/
166
- async getTraces(args) {
167
- if (args.fromDate || args.toDate) {
168
- args.dateRange = {
169
- start: args.fromDate,
170
- end: args.toDate
171
- };
172
- }
173
- const result = await this.getTracesPaginated(args);
174
- return result.traces;
175
- }
176
- async getTracesPaginated(args) {
177
- const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
142
+ async getEvals(options = {}) {
143
+ const { agentName, type, page = 0, perPage = 100, dateRange } = options;
178
144
  const fromDate = dateRange?.start;
179
145
  const toDate = dateRange?.end;
180
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
181
- const currentOffset = page * perPage;
182
- const paramMap = {};
183
- const conditions = [];
184
- let paramIndex = 1;
185
- if (name) {
186
- const paramName = `p${paramIndex++}`;
187
- conditions.push(`[name] LIKE @${paramName}`);
188
- paramMap[paramName] = `${name}%`;
189
- }
190
- if (scope) {
191
- const paramName = `p${paramIndex++}`;
192
- conditions.push(`[scope] = @${paramName}`);
193
- paramMap[paramName] = scope;
194
- }
195
- if (attributes) {
196
- Object.entries(attributes).forEach(([key, value]) => {
197
- const parsedKey = parseFieldKey(key);
198
- const paramName = `p${paramIndex++}`;
199
- conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
200
- paramMap[paramName] = value;
201
- });
146
+ const where = [];
147
+ const params = {};
148
+ if (agentName) {
149
+ where.push("agent_name = @agentName");
150
+ params["agentName"] = agentName;
202
151
  }
203
- if (filters) {
204
- Object.entries(filters).forEach(([key, value]) => {
205
- const parsedKey = parseFieldKey(key);
206
- const paramName = `p${paramIndex++}`;
207
- conditions.push(`[${parsedKey}] = @${paramName}`);
208
- paramMap[paramName] = value;
209
- });
152
+ if (type === "test") {
153
+ where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
154
+ } else if (type === "live") {
155
+ where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
210
156
  }
211
157
  if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
212
- const paramName = `p${paramIndex++}`;
213
- conditions.push(`[createdAt] >= @${paramName}`);
214
- paramMap[paramName] = fromDate.toISOString();
158
+ where.push(`[created_at] >= @fromDate`);
159
+ params[`fromDate`] = fromDate.toISOString();
215
160
  }
216
161
  if (toDate instanceof Date && !isNaN(toDate.getTime())) {
217
- const paramName = `p${paramIndex++}`;
218
- conditions.push(`[createdAt] <= @${paramName}`);
219
- paramMap[paramName] = toDate.toISOString();
162
+ where.push(`[created_at] <= @toDate`);
163
+ params[`toDate`] = toDate.toISOString();
220
164
  }
221
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
222
- const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(TABLE_TRACES)} ${whereClause}`;
223
- let total = 0;
165
+ const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
166
+ const tableName = getTableName({ indexName: TABLE_EVALS, schemaName: getSchemaName(this.schema) });
167
+ const offset = page * perPage;
168
+ const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
169
+ const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
224
170
  try {
225
- const countRequest = this.pool.request();
226
- Object.entries(paramMap).forEach(([key, value]) => {
171
+ const countReq = this.pool.request();
172
+ Object.entries(params).forEach(([key, value]) => {
227
173
  if (value instanceof Date) {
228
- countRequest.input(key, sql.DateTime, value);
174
+ countReq.input(key, sql3.DateTime, value);
229
175
  } else {
230
- countRequest.input(key, value);
176
+ countReq.input(key, value);
231
177
  }
232
178
  });
233
- const countResult = await countRequest.query(countQuery);
234
- total = parseInt(countResult.recordset[0].total, 10);
179
+ const countResult = await countReq.query(countQuery);
180
+ const total = countResult.recordset[0]?.total || 0;
181
+ if (total === 0) {
182
+ return {
183
+ evals: [],
184
+ total: 0,
185
+ page,
186
+ perPage,
187
+ hasMore: false
188
+ };
189
+ }
190
+ const req = this.pool.request();
191
+ Object.entries(params).forEach(([key, value]) => {
192
+ if (value instanceof Date) {
193
+ req.input(key, sql3.DateTime, value);
194
+ } else {
195
+ req.input(key, value);
196
+ }
197
+ });
198
+ req.input("offset", offset);
199
+ req.input("perPage", perPage);
200
+ const result = await req.query(dataQuery);
201
+ const rows = result.recordset;
202
+ return {
203
+ evals: rows?.map((row) => transformEvalRow(row)) ?? [],
204
+ total,
205
+ page,
206
+ perPage,
207
+ hasMore: offset + (rows?.length ?? 0) < total
208
+ };
235
209
  } catch (error) {
236
- throw new MastraError(
210
+ const mastraError = new MastraError(
237
211
  {
238
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
212
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
239
213
  domain: ErrorDomain.STORAGE,
240
214
  category: ErrorCategory.THIRD_PARTY,
241
215
  details: {
242
- name: args.name ?? "",
243
- scope: args.scope ?? ""
216
+ agentName: agentName || "all",
217
+ type: type || "all",
218
+ page,
219
+ perPage
244
220
  }
245
221
  },
246
222
  error
247
223
  );
224
+ this.logger?.error?.(mastraError.toString());
225
+ this.logger?.trackException?.(mastraError);
226
+ throw mastraError;
248
227
  }
249
- if (total === 0) {
250
- return {
251
- traces: [],
252
- total: 0,
253
- page,
254
- perPage,
255
- hasMore: false
256
- };
257
- }
258
- const dataQuery = `SELECT * FROM ${this.getTableName(TABLE_TRACES)} ${whereClause} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
259
- const dataRequest = this.pool.request();
260
- Object.entries(paramMap).forEach(([key, value]) => {
261
- if (value instanceof Date) {
262
- dataRequest.input(key, sql.DateTime, value);
263
- } else {
264
- dataRequest.input(key, value);
228
+ }
229
+ };
230
+ var MemoryMSSQL = class extends MemoryStorage {
231
+ pool;
232
+ schema;
233
+ operations;
234
+ _parseAndFormatMessages(messages, format) {
235
+ const messagesWithParsedContent = messages.map((message) => {
236
+ if (typeof message.content === "string") {
237
+ try {
238
+ return { ...message, content: JSON.parse(message.content) };
239
+ } catch {
240
+ return message;
241
+ }
265
242
  }
243
+ return message;
266
244
  });
267
- dataRequest.input("offset", currentOffset);
268
- dataRequest.input("limit", perPage);
245
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
246
+ const list = new MessageList().add(cleanMessages, "memory");
247
+ return format === "v2" ? list.get.all.v2() : list.get.all.v1();
248
+ }
249
+ constructor({
250
+ pool,
251
+ schema,
252
+ operations
253
+ }) {
254
+ super();
255
+ this.pool = pool;
256
+ this.schema = schema;
257
+ this.operations = operations;
258
+ }
259
+ async getThreadById({ threadId }) {
269
260
  try {
270
- const rowsResult = await dataRequest.query(dataQuery);
271
- const rows = rowsResult.recordset;
272
- const traces = rows.map((row) => ({
273
- id: row.id,
274
- parentSpanId: row.parentSpanId,
275
- traceId: row.traceId,
276
- name: row.name,
277
- scope: row.scope,
278
- kind: row.kind,
279
- status: JSON.parse(row.status),
280
- events: JSON.parse(row.events),
281
- links: JSON.parse(row.links),
282
- attributes: JSON.parse(row.attributes),
283
- startTime: row.startTime,
284
- endTime: row.endTime,
285
- other: row.other,
286
- createdAt: row.createdAt
287
- }));
261
+ const sql6 = `SELECT
262
+ id,
263
+ [resourceId],
264
+ title,
265
+ metadata,
266
+ [createdAt],
267
+ [updatedAt]
268
+ FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })}
269
+ WHERE id = @threadId`;
270
+ const request = this.pool.request();
271
+ request.input("threadId", threadId);
272
+ const resultSet = await request.query(sql6);
273
+ const thread = resultSet.recordset[0] || null;
274
+ if (!thread) {
275
+ return null;
276
+ }
288
277
  return {
289
- traces,
290
- total,
291
- page,
292
- perPage,
293
- hasMore: currentOffset + traces.length < total
278
+ ...thread,
279
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
280
+ createdAt: thread.createdAt,
281
+ updatedAt: thread.updatedAt
294
282
  };
295
283
  } catch (error) {
296
284
  throw new MastraError(
297
285
  {
298
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
286
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
299
287
  domain: ErrorDomain.STORAGE,
300
288
  category: ErrorCategory.THIRD_PARTY,
301
289
  details: {
302
- name: args.name ?? "",
303
- scope: args.scope ?? ""
304
- }
305
- },
306
- error
307
- );
308
- }
309
- }
310
- async setupSchema() {
311
- if (!this.schema || this.schemaSetupComplete) {
312
- return;
313
- }
314
- if (!this.setupSchemaPromise) {
315
- this.setupSchemaPromise = (async () => {
316
- try {
317
- const checkRequest = this.pool.request();
318
- checkRequest.input("schemaName", this.schema);
319
- const checkResult = await checkRequest.query(`
320
- SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
321
- `);
322
- const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
323
- if (!schemaExists) {
324
- try {
325
- await this.pool.request().query(`CREATE SCHEMA [${this.schema}]`);
326
- this.logger?.info?.(`Schema "${this.schema}" created successfully`);
327
- } catch (error) {
328
- this.logger?.error?.(`Failed to create schema "${this.schema}"`, { error });
329
- throw new Error(
330
- `Unable to create schema "${this.schema}". This requires CREATE privilege on the database. Either create the schema manually or grant CREATE privilege to the user.`
331
- );
332
- }
333
- }
334
- this.schemaSetupComplete = true;
335
- this.logger?.debug?.(`Schema "${this.schema}" is ready for use`);
336
- } catch (error) {
337
- this.schemaSetupComplete = void 0;
338
- this.setupSchemaPromise = null;
339
- throw error;
340
- } finally {
341
- this.setupSchemaPromise = null;
342
- }
343
- })();
344
- }
345
- await this.setupSchemaPromise;
346
- }
347
- getSqlType(type, isPrimaryKey = false) {
348
- switch (type) {
349
- case "text":
350
- return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(MAX)";
351
- case "timestamp":
352
- return "DATETIME2(7)";
353
- case "uuid":
354
- return "UNIQUEIDENTIFIER";
355
- case "jsonb":
356
- return "NVARCHAR(MAX)";
357
- case "integer":
358
- return "INT";
359
- case "bigint":
360
- return "BIGINT";
361
- default:
362
- throw new MastraError({
363
- id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
364
- domain: ErrorDomain.STORAGE,
365
- category: ErrorCategory.THIRD_PARTY
366
- });
367
- }
368
- }
369
- async createTable({
370
- tableName,
371
- schema
372
- }) {
373
- try {
374
- const uniqueConstraintColumns = tableName === TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
375
- const columns = Object.entries(schema).map(([name, def]) => {
376
- const parsedName = parseSqlIdentifier(name, "column name");
377
- const constraints = [];
378
- if (def.primaryKey) constraints.push("PRIMARY KEY");
379
- if (!def.nullable) constraints.push("NOT NULL");
380
- const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
381
- return `[${parsedName}] ${this.getSqlType(def.type, isIndexed)} ${constraints.join(" ")}`.trim();
382
- }).join(",\n");
383
- if (this.schema) {
384
- await this.setupSchema();
385
- }
386
- const checkTableRequest = this.pool.request();
387
- checkTableRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
388
- const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
389
- checkTableRequest.input("schema", this.schema || "dbo");
390
- const checkTableResult = await checkTableRequest.query(checkTableSql);
391
- const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
392
- if (!tableExists) {
393
- const createSql = `CREATE TABLE ${this.getTableName(tableName)} (
394
- ${columns}
395
- )`;
396
- await this.pool.request().query(createSql);
397
- }
398
- const columnCheckSql = `
399
- SELECT 1 AS found
400
- FROM INFORMATION_SCHEMA.COLUMNS
401
- WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
402
- `;
403
- const checkColumnRequest = this.pool.request();
404
- checkColumnRequest.input("schema", this.schema || "dbo");
405
- checkColumnRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
406
- const columnResult = await checkColumnRequest.query(columnCheckSql);
407
- const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
408
- if (!columnExists) {
409
- const alterSql = `ALTER TABLE ${this.getTableName(tableName)} ADD seq_id BIGINT IDENTITY(1,1)`;
410
- await this.pool.request().query(alterSql);
411
- }
412
- if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
413
- const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
414
- const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
415
- const checkConstraintRequest = this.pool.request();
416
- checkConstraintRequest.input("constraintName", constraintName);
417
- const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
418
- const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
419
- if (!constraintExists) {
420
- const addConstraintSql = `ALTER TABLE ${this.getTableName(tableName)} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
421
- await this.pool.request().query(addConstraintSql);
422
- }
423
- }
424
- } catch (error) {
425
- throw new MastraError(
426
- {
427
- id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
428
- domain: ErrorDomain.STORAGE,
429
- category: ErrorCategory.THIRD_PARTY,
430
- details: {
431
- tableName
432
- }
433
- },
434
- error
435
- );
436
- }
437
- }
438
- getDefaultValue(type) {
439
- switch (type) {
440
- case "timestamp":
441
- return "DEFAULT SYSDATETIMEOFFSET()";
442
- case "jsonb":
443
- return "DEFAULT N'{}'";
444
- default:
445
- return super.getDefaultValue(type);
446
- }
447
- }
448
- async alterTable({
449
- tableName,
450
- schema,
451
- ifNotExists
452
- }) {
453
- const fullTableName = this.getTableName(tableName);
454
- try {
455
- for (const columnName of ifNotExists) {
456
- if (schema[columnName]) {
457
- const columnCheckRequest = this.pool.request();
458
- columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
459
- columnCheckRequest.input("columnName", columnName);
460
- columnCheckRequest.input("schema", this.schema || "dbo");
461
- const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
462
- const checkResult = await columnCheckRequest.query(checkSql);
463
- const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
464
- if (!columnExists) {
465
- const columnDef = schema[columnName];
466
- const sqlType = this.getSqlType(columnDef.type);
467
- const nullable = columnDef.nullable === false ? "NOT NULL" : "";
468
- const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
469
- const parsedColumnName = parseSqlIdentifier(columnName, "column name");
470
- const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
471
- await this.pool.request().query(alterSql);
472
- this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
473
- }
474
- }
475
- }
476
- } catch (error) {
477
- throw new MastraError(
478
- {
479
- id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
480
- domain: ErrorDomain.STORAGE,
481
- category: ErrorCategory.THIRD_PARTY,
482
- details: {
483
- tableName
484
- }
485
- },
486
- error
487
- );
488
- }
489
- }
490
- async clearTable({ tableName }) {
491
- const fullTableName = this.getTableName(tableName);
492
- try {
493
- const fkQuery = `
494
- SELECT
495
- OBJECT_SCHEMA_NAME(fk.parent_object_id) AS schema_name,
496
- OBJECT_NAME(fk.parent_object_id) AS table_name
497
- FROM sys.foreign_keys fk
498
- WHERE fk.referenced_object_id = OBJECT_ID(@fullTableName)
499
- `;
500
- const fkResult = await this.pool.request().input("fullTableName", fullTableName).query(fkQuery);
501
- const childTables = fkResult.recordset || [];
502
- for (const child of childTables) {
503
- const childTableName = this.schema ? `[${child.schema_name}].[${child.table_name}]` : `[${child.table_name}]`;
504
- await this.clearTable({ tableName: childTableName });
505
- }
506
- await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
507
- } catch (error) {
508
- throw new MastraError(
509
- {
510
- id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
511
- domain: ErrorDomain.STORAGE,
512
- category: ErrorCategory.THIRD_PARTY,
513
- details: {
514
- tableName
515
- }
516
- },
517
- error
518
- );
519
- }
520
- }
521
- async insert({ tableName, record }) {
522
- try {
523
- const columns = Object.keys(record).map((col) => parseSqlIdentifier(col, "column name"));
524
- const values = Object.values(record);
525
- const paramNames = values.map((_, i) => `@param${i}`);
526
- const insertSql = `INSERT INTO ${this.getTableName(tableName)} (${columns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
527
- const request = this.pool.request();
528
- values.forEach((value, i) => {
529
- if (value instanceof Date) {
530
- request.input(`param${i}`, sql.DateTime2, value);
531
- } else if (typeof value === "object" && value !== null) {
532
- request.input(`param${i}`, JSON.stringify(value));
533
- } else {
534
- request.input(`param${i}`, value);
535
- }
536
- });
537
- await request.query(insertSql);
538
- } catch (error) {
539
- throw new MastraError(
540
- {
541
- id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
542
- domain: ErrorDomain.STORAGE,
543
- category: ErrorCategory.THIRD_PARTY,
544
- details: {
545
- tableName
546
- }
547
- },
548
- error
549
- );
550
- }
551
- }
552
- async load({ tableName, keys }) {
553
- try {
554
- const keyEntries = Object.entries(keys).map(([key, value]) => [parseSqlIdentifier(key, "column name"), value]);
555
- const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
556
- const values = keyEntries.map(([_, value]) => value);
557
- const sql2 = `SELECT * FROM ${this.getTableName(tableName)} WHERE ${conditions}`;
558
- const request = this.pool.request();
559
- values.forEach((value, i) => {
560
- request.input(`param${i}`, value);
561
- });
562
- const resultSet = await request.query(sql2);
563
- const result = resultSet.recordset[0] || null;
564
- if (!result) {
565
- return null;
566
- }
567
- if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
568
- const snapshot = result;
569
- if (typeof snapshot.snapshot === "string") {
570
- snapshot.snapshot = JSON.parse(snapshot.snapshot);
571
- }
572
- return snapshot;
573
- }
574
- return result;
575
- } catch (error) {
576
- throw new MastraError(
577
- {
578
- id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
579
- domain: ErrorDomain.STORAGE,
580
- category: ErrorCategory.THIRD_PARTY,
581
- details: {
582
- tableName
583
- }
584
- },
585
- error
586
- );
587
- }
588
- }
589
- async getThreadById({ threadId }) {
590
- try {
591
- const sql2 = `SELECT
592
- id,
593
- [resourceId],
594
- title,
595
- metadata,
596
- [createdAt],
597
- [updatedAt]
598
- FROM ${this.getTableName(TABLE_THREADS)}
599
- WHERE id = @threadId`;
600
- const request = this.pool.request();
601
- request.input("threadId", threadId);
602
- const resultSet = await request.query(sql2);
603
- const thread = resultSet.recordset[0] || null;
604
- if (!thread) {
605
- return null;
606
- }
607
- return {
608
- ...thread,
609
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
610
- createdAt: thread.createdAt,
611
- updatedAt: thread.updatedAt
612
- };
613
- } catch (error) {
614
- throw new MastraError(
615
- {
616
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
617
- domain: ErrorDomain.STORAGE,
618
- category: ErrorCategory.THIRD_PARTY,
619
- details: {
620
- threadId
290
+ threadId
621
291
  }
622
292
  },
623
293
  error
@@ -625,11 +295,11 @@ ${columns}
625
295
  }
626
296
  }
627
297
  async getThreadsByResourceIdPaginated(args) {
628
- const { resourceId, page = 0, perPage: perPageInput } = args;
298
+ const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
629
299
  try {
630
300
  const perPage = perPageInput !== void 0 ? perPageInput : 100;
631
301
  const currentOffset = page * perPage;
632
- const baseQuery = `FROM ${this.getTableName(TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
302
+ const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
633
303
  const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
634
304
  const countRequest = this.pool.request();
635
305
  countRequest.input("resourceId", resourceId);
@@ -644,7 +314,9 @@ ${columns}
644
314
  hasMore: false
645
315
  };
646
316
  }
647
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
317
+ const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
318
+ const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
319
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
648
320
  const dataRequest = this.pool.request();
649
321
  dataRequest.input("resourceId", resourceId);
650
322
  dataRequest.input("perPage", perPage);
@@ -684,7 +356,7 @@ ${columns}
684
356
  }
685
357
  async saveThread({ thread }) {
686
358
  try {
687
- const table = this.getTableName(TABLE_THREADS);
359
+ const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
688
360
  const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
689
361
  USING (SELECT @id AS id) AS source
690
362
  ON (target.id = source.id)
@@ -693,7 +365,6 @@ ${columns}
693
365
  [resourceId] = @resourceId,
694
366
  title = @title,
695
367
  metadata = @metadata,
696
- [createdAt] = @createdAt,
697
368
  [updatedAt] = @updatedAt
698
369
  WHEN NOT MATCHED THEN
699
370
  INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
@@ -702,9 +373,14 @@ ${columns}
702
373
  req.input("id", thread.id);
703
374
  req.input("resourceId", thread.resourceId);
704
375
  req.input("title", thread.title);
705
- req.input("metadata", thread.metadata ? JSON.stringify(thread.metadata) : null);
706
- req.input("createdAt", thread.createdAt);
707
- req.input("updatedAt", thread.updatedAt);
376
+ const metadata = thread.metadata ? JSON.stringify(thread.metadata) : null;
377
+ if (metadata === null) {
378
+ req.input("metadata", sql3.NVarChar, null);
379
+ } else {
380
+ req.input("metadata", metadata);
381
+ }
382
+ req.input("createdAt", sql3.DateTime2, thread.createdAt);
383
+ req.input("updatedAt", sql3.DateTime2, thread.updatedAt);
708
384
  await req.query(mergeSql);
709
385
  return thread;
710
386
  } catch (error) {
@@ -725,10 +401,12 @@ ${columns}
725
401
  * @deprecated use getThreadsByResourceIdPaginated instead
726
402
  */
727
403
  async getThreadsByResourceId(args) {
728
- const { resourceId } = args;
404
+ const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
729
405
  try {
730
- const baseQuery = `FROM ${this.getTableName(TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
731
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC`;
406
+ const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
407
+ const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
408
+ const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
409
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir}`;
732
410
  const request = this.pool.request();
733
411
  request.input("resourceId", resourceId);
734
412
  const resultSet = await request.query(dataQuery);
@@ -770,8 +448,8 @@ ${columns}
770
448
  ...metadata
771
449
  };
772
450
  try {
773
- const table = this.getTableName(TABLE_THREADS);
774
- const sql2 = `UPDATE ${table}
451
+ const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
452
+ const sql6 = `UPDATE ${table}
775
453
  SET title = @title,
776
454
  metadata = @metadata,
777
455
  [updatedAt] = @updatedAt
@@ -781,8 +459,8 @@ ${columns}
781
459
  req.input("id", id);
782
460
  req.input("title", title);
783
461
  req.input("metadata", JSON.stringify(mergedMetadata));
784
- req.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
785
- const result = await req.query(sql2);
462
+ req.input("updatedAt", /* @__PURE__ */ new Date());
463
+ const result = await req.query(sql6);
786
464
  let thread = result.recordset && result.recordset[0];
787
465
  if (thread && "seq_id" in thread) {
788
466
  const { seq_id, ...rest } = thread;
@@ -822,8 +500,8 @@ ${columns}
822
500
  }
823
501
  }
824
502
  async deleteThread({ threadId }) {
825
- const messagesTable = this.getTableName(TABLE_MESSAGES);
826
- const threadsTable = this.getTableName(TABLE_THREADS);
503
+ const messagesTable = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
504
+ const threadsTable = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
827
505
  const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
828
506
  const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
829
507
  const tx = this.pool.transaction();
@@ -855,6 +533,7 @@ ${columns}
855
533
  selectBy,
856
534
  orderByStatement
857
535
  }) {
536
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
858
537
  const include = selectBy?.include;
859
538
  if (!include) return null;
860
539
  const unionQueries = [];
@@ -881,7 +560,7 @@ ${columns}
881
560
  m.seq_id
882
561
  FROM (
883
562
  SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
884
- FROM ${this.getTableName(TABLE_MESSAGES)}
563
+ FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
885
564
  WHERE [thread_id] = ${pThreadId}
886
565
  ) AS m
887
566
  WHERE m.id = ${pId}
@@ -889,7 +568,7 @@ ${columns}
889
568
  SELECT 1
890
569
  FROM (
891
570
  SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
892
- FROM ${this.getTableName(TABLE_MESSAGES)}
571
+ FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
893
572
  WHERE [thread_id] = ${pThreadId}
894
573
  ) AS target
895
574
  WHERE target.id = ${pId}
@@ -926,11 +605,12 @@ ${columns}
926
605
  return dedupedRows;
927
606
  }
928
607
  async getMessages(args) {
929
- const { threadId, format, selectBy } = args;
930
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
608
+ const { threadId, resourceId, format, selectBy } = args;
609
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
931
610
  const orderByStatement = `ORDER BY [seq_id] DESC`;
932
- const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
611
+ const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
933
612
  try {
613
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
934
614
  let rows = [];
935
615
  const include = selectBy?.include || [];
936
616
  if (include?.length) {
@@ -940,7 +620,7 @@ ${columns}
940
620
  }
941
621
  }
942
622
  const excludeIds = rows.map((m) => m.id).filter(Boolean);
943
- let query = `${selectStatement} FROM ${this.getTableName(TABLE_MESSAGES)} WHERE [thread_id] = @threadId`;
623
+ let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
944
624
  const request = this.pool.request();
945
625
  request.input("threadId", threadId);
946
626
  if (excludeIds.length > 0) {
@@ -960,30 +640,7 @@ ${columns}
960
640
  return timeDiff;
961
641
  });
962
642
  rows = rows.map(({ seq_id, ...rest }) => rest);
963
- const fetchedMessages = (rows || []).map((message) => {
964
- if (typeof message.content === "string") {
965
- try {
966
- message.content = JSON.parse(message.content);
967
- } catch {
968
- }
969
- }
970
- if (format === "v1") {
971
- if (Array.isArray(message.content)) ; else if (typeof message.content === "object" && message.content && Array.isArray(message.content.parts)) {
972
- message.content = message.content.parts;
973
- } else {
974
- message.content = [{ type: "text", text: "" }];
975
- }
976
- } else {
977
- if (typeof message.content !== "object" || !message.content || !("parts" in message.content)) {
978
- message.content = { format: 2, parts: [{ type: "text", text: "" }] };
979
- }
980
- }
981
- if (message.type === "v2") delete message.type;
982
- return message;
983
- });
984
- return format === "v2" ? fetchedMessages.map(
985
- (m) => ({ ...m, content: m.content || { format: 2, parts: [{ type: "text", text: "" }] } })
986
- ) : fetchedMessages;
643
+ return this._parseAndFormatMessages(rows, format);
987
644
  } catch (error) {
988
645
  const mastraError = new MastraError(
989
646
  {
@@ -991,40 +648,76 @@ ${columns}
991
648
  domain: ErrorDomain.STORAGE,
992
649
  category: ErrorCategory.THIRD_PARTY,
993
650
  details: {
994
- threadId
651
+ threadId,
652
+ resourceId: resourceId ?? ""
995
653
  }
996
654
  },
997
655
  error
998
656
  );
999
657
  this.logger?.error?.(mastraError.toString());
1000
- this.logger?.trackException(mastraError);
658
+ this.logger?.trackException?.(mastraError);
1001
659
  return [];
1002
660
  }
1003
661
  }
1004
- async getMessagesPaginated(args) {
1005
- const { threadId, selectBy } = args;
1006
- const { page = 0, perPage: perPageInput } = selectBy?.pagination || {};
662
+ async getMessagesById({
663
+ messageIds,
664
+ format
665
+ }) {
666
+ if (messageIds.length === 0) return [];
667
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
1007
668
  const orderByStatement = `ORDER BY [seq_id] DESC`;
1008
- if (selectBy?.include?.length) {
1009
- await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
669
+ try {
670
+ let rows = [];
671
+ let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
672
+ const request = this.pool.request();
673
+ messageIds.forEach((id, i) => request.input(`id${i}`, id));
674
+ query += ` ${orderByStatement}`;
675
+ const result = await request.query(query);
676
+ const remainingRows = result.recordset || [];
677
+ rows.push(...remainingRows);
678
+ rows.sort((a, b) => {
679
+ const timeDiff = a.seq_id - b.seq_id;
680
+ return timeDiff;
681
+ });
682
+ rows = rows.map(({ seq_id, ...rest }) => rest);
683
+ if (format === `v1`) return this._parseAndFormatMessages(rows, format);
684
+ return this._parseAndFormatMessages(rows, `v2`);
685
+ } catch (error) {
686
+ const mastraError = new MastraError(
687
+ {
688
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
689
+ domain: ErrorDomain.STORAGE,
690
+ category: ErrorCategory.THIRD_PARTY,
691
+ details: {
692
+ messageIds: JSON.stringify(messageIds)
693
+ }
694
+ },
695
+ error
696
+ );
697
+ this.logger?.error?.(mastraError.toString());
698
+ this.logger?.trackException?.(mastraError);
699
+ return [];
1010
700
  }
701
+ }
702
+ async getMessagesPaginated(args) {
703
+ const { threadId, resourceId, format, selectBy } = args;
704
+ const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
1011
705
  try {
1012
- const { threadId: threadId2, format, selectBy: selectBy2 } = args;
1013
- const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
706
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1014
707
  const fromDate = dateRange?.start;
1015
708
  const toDate = dateRange?.end;
1016
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
1017
- const orderByStatement2 = `ORDER BY [seq_id] DESC`;
1018
- let messages2 = [];
1019
- if (selectBy2?.include?.length) {
1020
- const includeMessages = await this._getIncludedMessages({ threadId: threadId2, selectBy: selectBy2, orderByStatement: orderByStatement2 });
1021
- if (includeMessages) messages2.push(...includeMessages);
1022
- }
1023
- const perPage = perPageInput2 !== void 0 ? perPageInput2 : this.resolveMessageLimit({ last: selectBy2?.last, defaultLimit: 40 });
1024
- const currentOffset = page2 * perPage;
709
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
710
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
711
+ let messages = [];
712
+ if (selectBy?.include?.length) {
713
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
714
+ if (includeMessages) messages.push(...includeMessages);
715
+ }
716
+ const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
717
+ const currentOffset = page * perPage;
1025
718
  const conditions = ["[thread_id] = @threadId"];
1026
719
  const request = this.pool.request();
1027
- request.input("threadId", threadId2);
720
+ request.input("threadId", threadId);
1028
721
  if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1029
722
  conditions.push("[createdAt] >= @fromDate");
1030
723
  request.input("fromDate", fromDate.toISOString());
@@ -1034,38 +727,38 @@ ${columns}
1034
727
  request.input("toDate", toDate.toISOString());
1035
728
  }
1036
729
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
1037
- const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(TABLE_MESSAGES)} ${whereClause}`;
730
+ const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
1038
731
  const countResult = await request.query(countQuery);
1039
732
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
1040
- if (total === 0 && messages2.length > 0) {
1041
- const parsedIncluded = this._parseAndFormatMessages(messages2, format);
733
+ if (total === 0 && messages.length > 0) {
734
+ const parsedIncluded = this._parseAndFormatMessages(messages, format);
1042
735
  return {
1043
736
  messages: parsedIncluded,
1044
737
  total: parsedIncluded.length,
1045
- page: page2,
738
+ page,
1046
739
  perPage,
1047
740
  hasMore: false
1048
741
  };
1049
742
  }
1050
- const excludeIds = messages2.map((m) => m.id);
743
+ const excludeIds = messages.map((m) => m.id);
1051
744
  if (excludeIds.length > 0) {
1052
745
  const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
1053
746
  conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
1054
747
  excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
1055
748
  }
1056
749
  const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
1057
- const dataQuery = `${selectStatement} FROM ${this.getTableName(TABLE_MESSAGES)} ${finalWhereClause} ${orderByStatement2} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
750
+ const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1058
751
  request.input("offset", currentOffset);
1059
752
  request.input("limit", perPage);
1060
753
  const rowsResult = await request.query(dataQuery);
1061
754
  const rows = rowsResult.recordset || [];
1062
755
  rows.sort((a, b) => a.seq_id - b.seq_id);
1063
- messages2.push(...rows);
1064
- const parsed = this._parseAndFormatMessages(messages2, format);
756
+ messages.push(...rows);
757
+ const parsed = this._parseAndFormatMessages(messages, format);
1065
758
  return {
1066
759
  messages: parsed,
1067
- total: total + excludeIds.length,
1068
- page: page2,
760
+ total,
761
+ page,
1069
762
  perPage,
1070
763
  hasMore: currentOffset + rows.length < total
1071
764
  };
@@ -1077,41 +770,17 @@ ${columns}
1077
770
  category: ErrorCategory.THIRD_PARTY,
1078
771
  details: {
1079
772
  threadId,
773
+ resourceId: resourceId ?? "",
1080
774
  page
1081
775
  }
1082
776
  },
1083
777
  error
1084
778
  );
1085
779
  this.logger?.error?.(mastraError.toString());
1086
- this.logger?.trackException(mastraError);
780
+ this.logger?.trackException?.(mastraError);
1087
781
  return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
1088
782
  }
1089
783
  }
1090
- _parseAndFormatMessages(messages, format) {
1091
- const parsedMessages = messages.map((message) => {
1092
- let parsed = message;
1093
- if (typeof parsed.content === "string") {
1094
- try {
1095
- parsed = { ...parsed, content: JSON.parse(parsed.content) };
1096
- } catch {
1097
- }
1098
- }
1099
- if (format === "v1") {
1100
- if (Array.isArray(parsed.content)) ; else if (parsed.content?.parts) {
1101
- parsed.content = parsed.content.parts;
1102
- } else {
1103
- parsed.content = [{ type: "text", text: "" }];
1104
- }
1105
- } else {
1106
- if (!parsed.content?.parts) {
1107
- parsed = { ...parsed, content: { format: 2, parts: [{ type: "text", text: "" }] } };
1108
- }
1109
- }
1110
- return parsed;
1111
- });
1112
- const list = new MessageList().add(parsedMessages, "memory");
1113
- return format === "v2" ? list.get.all.v2() : list.get.all.v1();
1114
- }
1115
784
  async saveMessages({
1116
785
  messages,
1117
786
  format
@@ -1136,8 +805,8 @@ ${columns}
1136
805
  details: { threadId }
1137
806
  });
1138
807
  }
1139
- const tableMessages = this.getTableName(TABLE_MESSAGES);
1140
- const tableThreads = this.getTableName(TABLE_THREADS);
808
+ const tableMessages = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
809
+ const tableThreads = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
1141
810
  try {
1142
811
  const transaction = this.pool.transaction();
1143
812
  await transaction.begin();
@@ -1160,7 +829,7 @@ ${columns}
1160
829
  "content",
1161
830
  typeof message.content === "string" ? message.content : JSON.stringify(message.content)
1162
831
  );
1163
- request.input("createdAt", message.createdAt.toISOString() || (/* @__PURE__ */ new Date()).toISOString());
832
+ request.input("createdAt", sql3.DateTime2, message.createdAt);
1164
833
  request.input("role", message.role);
1165
834
  request.input("type", message.type || "v2");
1166
835
  request.input("resourceId", message.resourceId);
@@ -1179,7 +848,7 @@ ${columns}
1179
848
  await request.query(mergeSql);
1180
849
  }
1181
850
  const threadReq = transaction.request();
1182
- threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
851
+ threadReq.input("updatedAt", sql3.DateTime2, /* @__PURE__ */ new Date());
1183
852
  threadReq.input("id", threadId);
1184
853
  await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
1185
854
  await transaction.commit();
@@ -1212,216 +881,6 @@ ${columns}
1212
881
  );
1213
882
  }
1214
883
  }
1215
- async persistWorkflowSnapshot({
1216
- workflowName,
1217
- runId,
1218
- snapshot
1219
- }) {
1220
- const table = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1221
- const now = (/* @__PURE__ */ new Date()).toISOString();
1222
- try {
1223
- const request = this.pool.request();
1224
- request.input("workflow_name", workflowName);
1225
- request.input("run_id", runId);
1226
- request.input("snapshot", JSON.stringify(snapshot));
1227
- request.input("createdAt", now);
1228
- request.input("updatedAt", now);
1229
- const mergeSql = `MERGE INTO ${table} AS target
1230
- USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
1231
- ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
1232
- WHEN MATCHED THEN UPDATE SET
1233
- snapshot = @snapshot,
1234
- [updatedAt] = @updatedAt
1235
- WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
1236
- VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
1237
- await request.query(mergeSql);
1238
- } catch (error) {
1239
- throw new MastraError(
1240
- {
1241
- id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1242
- domain: ErrorDomain.STORAGE,
1243
- category: ErrorCategory.THIRD_PARTY,
1244
- details: {
1245
- workflowName,
1246
- runId
1247
- }
1248
- },
1249
- error
1250
- );
1251
- }
1252
- }
1253
- async loadWorkflowSnapshot({
1254
- workflowName,
1255
- runId
1256
- }) {
1257
- try {
1258
- const result = await this.load({
1259
- tableName: TABLE_WORKFLOW_SNAPSHOT,
1260
- keys: {
1261
- workflow_name: workflowName,
1262
- run_id: runId
1263
- }
1264
- });
1265
- if (!result) {
1266
- return null;
1267
- }
1268
- return result.snapshot;
1269
- } catch (error) {
1270
- throw new MastraError(
1271
- {
1272
- id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1273
- domain: ErrorDomain.STORAGE,
1274
- category: ErrorCategory.THIRD_PARTY,
1275
- details: {
1276
- workflowName,
1277
- runId
1278
- }
1279
- },
1280
- error
1281
- );
1282
- }
1283
- }
1284
- async hasColumn(table, column) {
1285
- const schema = this.schema || "dbo";
1286
- const request = this.pool.request();
1287
- request.input("schema", schema);
1288
- request.input("table", table);
1289
- request.input("column", column);
1290
- request.input("columnLower", column.toLowerCase());
1291
- const result = await request.query(
1292
- `SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
1293
- );
1294
- return result.recordset.length > 0;
1295
- }
1296
- parseWorkflowRun(row) {
1297
- let parsedSnapshot = row.snapshot;
1298
- if (typeof parsedSnapshot === "string") {
1299
- try {
1300
- parsedSnapshot = JSON.parse(row.snapshot);
1301
- } catch (e) {
1302
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1303
- }
1304
- }
1305
- return {
1306
- workflowName: row.workflow_name,
1307
- runId: row.run_id,
1308
- snapshot: parsedSnapshot,
1309
- createdAt: row.createdAt,
1310
- updatedAt: row.updatedAt,
1311
- resourceId: row.resourceId
1312
- };
1313
- }
1314
- async getWorkflowRuns({
1315
- workflowName,
1316
- fromDate,
1317
- toDate,
1318
- limit,
1319
- offset,
1320
- resourceId
1321
- } = {}) {
1322
- try {
1323
- const conditions = [];
1324
- const paramMap = {};
1325
- if (workflowName) {
1326
- conditions.push(`[workflow_name] = @workflowName`);
1327
- paramMap["workflowName"] = workflowName;
1328
- }
1329
- if (resourceId) {
1330
- const hasResourceId = await this.hasColumn(TABLE_WORKFLOW_SNAPSHOT, "resourceId");
1331
- if (hasResourceId) {
1332
- conditions.push(`[resourceId] = @resourceId`);
1333
- paramMap["resourceId"] = resourceId;
1334
- } else {
1335
- console.warn(`[${TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
1336
- }
1337
- }
1338
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1339
- conditions.push(`[createdAt] >= @fromDate`);
1340
- paramMap[`fromDate`] = fromDate.toISOString();
1341
- }
1342
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1343
- conditions.push(`[createdAt] <= @toDate`);
1344
- paramMap[`toDate`] = toDate.toISOString();
1345
- }
1346
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1347
- let total = 0;
1348
- const tableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1349
- const request = this.pool.request();
1350
- Object.entries(paramMap).forEach(([key, value]) => {
1351
- if (value instanceof Date) {
1352
- request.input(key, sql.DateTime, value);
1353
- } else {
1354
- request.input(key, value);
1355
- }
1356
- });
1357
- if (limit !== void 0 && offset !== void 0) {
1358
- const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
1359
- const countResult = await request.query(countQuery);
1360
- total = Number(countResult.recordset[0]?.count || 0);
1361
- }
1362
- let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
1363
- if (limit !== void 0 && offset !== void 0) {
1364
- query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1365
- request.input("limit", limit);
1366
- request.input("offset", offset);
1367
- }
1368
- const result = await request.query(query);
1369
- const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
1370
- return { runs, total: total || runs.length };
1371
- } catch (error) {
1372
- throw new MastraError(
1373
- {
1374
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
1375
- domain: ErrorDomain.STORAGE,
1376
- category: ErrorCategory.THIRD_PARTY,
1377
- details: {
1378
- workflowName: workflowName || "all"
1379
- }
1380
- },
1381
- error
1382
- );
1383
- }
1384
- }
1385
- async getWorkflowRunById({
1386
- runId,
1387
- workflowName
1388
- }) {
1389
- try {
1390
- const conditions = [];
1391
- const paramMap = {};
1392
- if (runId) {
1393
- conditions.push(`[run_id] = @runId`);
1394
- paramMap["runId"] = runId;
1395
- }
1396
- if (workflowName) {
1397
- conditions.push(`[workflow_name] = @workflowName`);
1398
- paramMap["workflowName"] = workflowName;
1399
- }
1400
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1401
- const tableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1402
- const query = `SELECT * FROM ${tableName} ${whereClause}`;
1403
- const request = this.pool.request();
1404
- Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
1405
- const result = await request.query(query);
1406
- if (!result.recordset || result.recordset.length === 0) {
1407
- return null;
1408
- }
1409
- return this.parseWorkflowRun(result.recordset[0]);
1410
- } catch (error) {
1411
- throw new MastraError(
1412
- {
1413
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
1414
- domain: ErrorDomain.STORAGE,
1415
- category: ErrorCategory.THIRD_PARTY,
1416
- details: {
1417
- runId,
1418
- workflowName: workflowName || ""
1419
- }
1420
- },
1421
- error
1422
- );
1423
- }
1424
- }
1425
884
  async updateMessages({
1426
885
  messages
1427
886
  }) {
@@ -1430,7 +889,7 @@ ${columns}
1430
889
  }
1431
890
  const messageIds = messages.map((m) => m.id);
1432
891
  const idParams = messageIds.map((_, i) => `@id${i}`).join(", ");
1433
- let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${this.getTableName(TABLE_MESSAGES)}`;
892
+ let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}`;
1434
893
  if (idParams.length > 0) {
1435
894
  selectQuery += ` WHERE id IN (${idParams})`;
1436
895
  } else {
@@ -1487,7 +946,7 @@ ${columns}
1487
946
  }
1488
947
  }
1489
948
  if (setClauses.length > 0) {
1490
- const updateSql = `UPDATE ${this.getTableName(TABLE_MESSAGES)} SET ${setClauses.join(", ")} WHERE id = @id`;
949
+ const updateSql = `UPDATE ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} SET ${setClauses.join(", ")} WHERE id = @id`;
1491
950
  await req.query(updateSql);
1492
951
  }
1493
952
  }
@@ -1496,7 +955,7 @@ ${columns}
1496
955
  const threadReq = transaction.request();
1497
956
  Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
1498
957
  threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
1499
- const threadSql = `UPDATE ${this.getTableName(TABLE_THREADS)} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
958
+ const threadSql = `UPDATE ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
1500
959
  await threadReq.query(threadSql);
1501
960
  }
1502
961
  await transaction.commit();
@@ -1524,137 +983,98 @@ ${columns}
1524
983
  return message;
1525
984
  });
1526
985
  }
1527
- async close() {
1528
- if (this.pool) {
986
+ async deleteMessages(messageIds) {
987
+ if (!messageIds || messageIds.length === 0) {
988
+ return;
989
+ }
990
+ try {
991
+ const messageTableName = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
992
+ const threadTableName = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
993
+ const placeholders = messageIds.map((_, idx) => `@p${idx + 1}`).join(",");
994
+ const request = this.pool.request();
995
+ messageIds.forEach((id, idx) => {
996
+ request.input(`p${idx + 1}`, id);
997
+ });
998
+ const messages = await request.query(
999
+ `SELECT DISTINCT [thread_id] FROM ${messageTableName} WHERE [id] IN (${placeholders})`
1000
+ );
1001
+ const threadIds = messages.recordset?.map((msg) => msg.thread_id).filter(Boolean) || [];
1002
+ const transaction = this.pool.transaction();
1003
+ await transaction.begin();
1529
1004
  try {
1530
- if (this.pool.connected) {
1531
- await this.pool.close();
1532
- } else if (this.pool.connecting) {
1533
- await this.pool.connect();
1534
- await this.pool.close();
1005
+ const deleteRequest = transaction.request();
1006
+ messageIds.forEach((id, idx) => {
1007
+ deleteRequest.input(`p${idx + 1}`, id);
1008
+ });
1009
+ await deleteRequest.query(`DELETE FROM ${messageTableName} WHERE [id] IN (${placeholders})`);
1010
+ if (threadIds.length > 0) {
1011
+ for (const threadId of threadIds) {
1012
+ const updateRequest = transaction.request();
1013
+ updateRequest.input("p1", threadId);
1014
+ await updateRequest.query(`UPDATE ${threadTableName} SET [updatedAt] = GETDATE() WHERE [id] = @p1`);
1015
+ }
1535
1016
  }
1536
- } catch (err) {
1537
- if (err.message && err.message.includes("Cannot close a pool while it is connecting")) ; else {
1538
- throw err;
1539
- }
1540
- }
1541
- }
1542
- }
1543
- async getEvals(options = {}) {
1544
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
1545
- const fromDate = dateRange?.start;
1546
- const toDate = dateRange?.end;
1547
- const where = [];
1548
- const params = {};
1549
- if (agentName) {
1550
- where.push("agent_name = @agentName");
1551
- params["agentName"] = agentName;
1552
- }
1553
- if (type === "test") {
1554
- where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
1555
- } else if (type === "live") {
1556
- where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
1557
- }
1558
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1559
- where.push(`[created_at] >= @fromDate`);
1560
- params[`fromDate`] = fromDate.toISOString();
1561
- }
1562
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1563
- where.push(`[created_at] <= @toDate`);
1564
- params[`toDate`] = toDate.toISOString();
1565
- }
1566
- const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
1567
- const tableName = this.getTableName(TABLE_EVALS);
1568
- const offset = page * perPage;
1569
- const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
1570
- const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
1571
- try {
1572
- const countReq = this.pool.request();
1573
- Object.entries(params).forEach(([key, value]) => {
1574
- if (value instanceof Date) {
1575
- countReq.input(key, sql.DateTime, value);
1576
- } else {
1577
- countReq.input(key, value);
1017
+ await transaction.commit();
1018
+ } catch (error) {
1019
+ try {
1020
+ await transaction.rollback();
1021
+ } catch {
1578
1022
  }
1579
- });
1580
- const countResult = await countReq.query(countQuery);
1581
- const total = countResult.recordset[0]?.total || 0;
1582
- if (total === 0) {
1583
- return {
1584
- evals: [],
1585
- total: 0,
1586
- page,
1587
- perPage,
1588
- hasMore: false
1589
- };
1023
+ throw error;
1590
1024
  }
1591
- const req = this.pool.request();
1592
- Object.entries(params).forEach(([key, value]) => {
1593
- if (value instanceof Date) {
1594
- req.input(key, sql.DateTime, value);
1595
- } else {
1596
- req.input(key, value);
1597
- }
1598
- });
1599
- req.input("offset", offset);
1600
- req.input("perPage", perPage);
1601
- const result = await req.query(dataQuery);
1602
- const rows = result.recordset;
1603
- return {
1604
- evals: rows?.map((row) => this.transformEvalRow(row)) ?? [],
1605
- total,
1606
- page,
1607
- perPage,
1608
- hasMore: offset + (rows?.length ?? 0) < total
1609
- };
1610
1025
  } catch (error) {
1611
- const mastraError = new MastraError(
1026
+ throw new MastraError(
1612
1027
  {
1613
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
1028
+ id: "MASTRA_STORAGE_MSSQL_STORE_DELETE_MESSAGES_FAILED",
1614
1029
  domain: ErrorDomain.STORAGE,
1615
1030
  category: ErrorCategory.THIRD_PARTY,
1616
- details: {
1617
- agentName: agentName || "all",
1618
- type: type || "all",
1619
- page,
1620
- perPage
1621
- }
1031
+ details: { messageIds: messageIds.join(", ") }
1622
1032
  },
1623
1033
  error
1624
1034
  );
1625
- this.logger?.error?.(mastraError.toString());
1626
- this.logger?.trackException(mastraError);
1627
- throw mastraError;
1628
1035
  }
1629
1036
  }
1630
- async saveResource({ resource }) {
1631
- const tableName = this.getTableName(TABLE_RESOURCES);
1037
+ async getResourceById({ resourceId }) {
1038
+ const tableName = getTableName({ indexName: TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
1632
1039
  try {
1633
1040
  const req = this.pool.request();
1634
- req.input("id", resource.id);
1635
- req.input("workingMemory", resource.workingMemory);
1636
- req.input("metadata", JSON.stringify(resource.metadata));
1637
- req.input("createdAt", resource.createdAt.toISOString());
1638
- req.input("updatedAt", resource.updatedAt.toISOString());
1639
- await req.query(
1640
- `INSERT INTO ${tableName} (id, workingMemory, metadata, createdAt, updatedAt) VALUES (@id, @workingMemory, @metadata, @createdAt, @updatedAt)`
1641
- );
1642
- return resource;
1041
+ req.input("resourceId", resourceId);
1042
+ const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
1043
+ if (!result) {
1044
+ return null;
1045
+ }
1046
+ return {
1047
+ id: result.id,
1048
+ createdAt: result.createdAt,
1049
+ updatedAt: result.updatedAt,
1050
+ workingMemory: result.workingMemory,
1051
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
1052
+ };
1643
1053
  } catch (error) {
1644
1054
  const mastraError = new MastraError(
1645
1055
  {
1646
- id: "MASTRA_STORAGE_MSSQL_SAVE_RESOURCE_FAILED",
1056
+ id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
1647
1057
  domain: ErrorDomain.STORAGE,
1648
1058
  category: ErrorCategory.THIRD_PARTY,
1649
- details: { resourceId: resource.id }
1059
+ details: { resourceId }
1650
1060
  },
1651
1061
  error
1652
1062
  );
1653
1063
  this.logger?.error?.(mastraError.toString());
1654
- this.logger?.trackException(mastraError);
1064
+ this.logger?.trackException?.(mastraError);
1655
1065
  throw mastraError;
1656
1066
  }
1657
1067
  }
1068
+ async saveResource({ resource }) {
1069
+ await this.operations.insert({
1070
+ tableName: TABLE_RESOURCES,
1071
+ record: {
1072
+ ...resource,
1073
+ metadata: resource.metadata
1074
+ }
1075
+ });
1076
+ return resource;
1077
+ }
1658
1078
  async updateResource({
1659
1079
  resourceId,
1660
1080
  workingMemory,
@@ -1681,7 +1101,7 @@ ${columns}
1681
1101
  },
1682
1102
  updatedAt: /* @__PURE__ */ new Date()
1683
1103
  };
1684
- const tableName = this.getTableName(TABLE_RESOURCES);
1104
+ const tableName = getTableName({ indexName: TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
1685
1105
  const updates = [];
1686
1106
  const req = this.pool.request();
1687
1107
  if (workingMemory !== void 0) {
@@ -1708,39 +1128,2326 @@ ${columns}
1708
1128
  error
1709
1129
  );
1710
1130
  this.logger?.error?.(mastraError.toString());
1711
- this.logger?.trackException(mastraError);
1131
+ this.logger?.trackException?.(mastraError);
1712
1132
  throw mastraError;
1713
1133
  }
1714
1134
  }
1715
- async getResourceById({ resourceId }) {
1716
- const tableName = this.getTableName(TABLE_RESOURCES);
1135
+ };
1136
+ var ObservabilityMSSQL = class extends ObservabilityStorage {
1137
+ pool;
1138
+ operations;
1139
+ schema;
1140
+ constructor({
1141
+ pool,
1142
+ operations,
1143
+ schema
1144
+ }) {
1145
+ super();
1146
+ this.pool = pool;
1147
+ this.operations = operations;
1148
+ this.schema = schema;
1149
+ }
1150
+ get aiTracingStrategy() {
1151
+ return {
1152
+ preferred: "batch-with-updates",
1153
+ supported: ["batch-with-updates", "insert-only"]
1154
+ };
1155
+ }
1156
+ async createAISpan(span) {
1717
1157
  try {
1718
- const req = this.pool.request();
1719
- req.input("resourceId", resourceId);
1720
- const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
1721
- if (!result) {
1158
+ const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
1159
+ const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
1160
+ const record = {
1161
+ ...span,
1162
+ startedAt,
1163
+ endedAt
1164
+ // Note: createdAt/updatedAt will be set by default values
1165
+ };
1166
+ return this.operations.insert({ tableName: TABLE_AI_SPANS, record });
1167
+ } catch (error) {
1168
+ throw new MastraError(
1169
+ {
1170
+ id: "MSSQL_STORE_CREATE_AI_SPAN_FAILED",
1171
+ domain: ErrorDomain.STORAGE,
1172
+ category: ErrorCategory.USER,
1173
+ details: {
1174
+ spanId: span.spanId,
1175
+ traceId: span.traceId,
1176
+ spanType: span.spanType,
1177
+ spanName: span.name
1178
+ }
1179
+ },
1180
+ error
1181
+ );
1182
+ }
1183
+ }
1184
+ async getAITrace(traceId) {
1185
+ try {
1186
+ const tableName = getTableName({
1187
+ indexName: TABLE_AI_SPANS,
1188
+ schemaName: getSchemaName(this.schema)
1189
+ });
1190
+ const request = this.pool.request();
1191
+ request.input("traceId", traceId);
1192
+ const result = await request.query(
1193
+ `SELECT
1194
+ [traceId], [spanId], [parentSpanId], [name], [scope], [spanType],
1195
+ [attributes], [metadata], [links], [input], [output], [error], [isEvent],
1196
+ [startedAt], [endedAt], [createdAt], [updatedAt]
1197
+ FROM ${tableName}
1198
+ WHERE [traceId] = @traceId
1199
+ ORDER BY [startedAt] DESC`
1200
+ );
1201
+ if (!result.recordset || result.recordset.length === 0) {
1722
1202
  return null;
1723
1203
  }
1724
1204
  return {
1725
- ...result,
1726
- workingMemory: typeof result.workingMemory === "object" ? JSON.stringify(result.workingMemory) : result.workingMemory,
1727
- metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
1205
+ traceId,
1206
+ spans: result.recordset.map(
1207
+ (span) => transformFromSqlRow({
1208
+ tableName: TABLE_AI_SPANS,
1209
+ sqlRow: span
1210
+ })
1211
+ )
1728
1212
  };
1729
1213
  } catch (error) {
1730
- const mastraError = new MastraError(
1214
+ throw new MastraError(
1731
1215
  {
1732
- id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
1216
+ id: "MSSQL_STORE_GET_AI_TRACE_FAILED",
1733
1217
  domain: ErrorDomain.STORAGE,
1734
- category: ErrorCategory.THIRD_PARTY,
1735
- details: { resourceId }
1218
+ category: ErrorCategory.USER,
1219
+ details: {
1220
+ traceId
1221
+ }
1222
+ },
1223
+ error
1224
+ );
1225
+ }
1226
+ }
1227
+ async updateAISpan({
1228
+ spanId,
1229
+ traceId,
1230
+ updates
1231
+ }) {
1232
+ try {
1233
+ const data = { ...updates };
1234
+ if (data.endedAt instanceof Date) {
1235
+ data.endedAt = data.endedAt.toISOString();
1236
+ }
1237
+ if (data.startedAt instanceof Date) {
1238
+ data.startedAt = data.startedAt.toISOString();
1239
+ }
1240
+ await this.operations.update({
1241
+ tableName: TABLE_AI_SPANS,
1242
+ keys: { spanId, traceId },
1243
+ data
1244
+ });
1245
+ } catch (error) {
1246
+ throw new MastraError(
1247
+ {
1248
+ id: "MSSQL_STORE_UPDATE_AI_SPAN_FAILED",
1249
+ domain: ErrorDomain.STORAGE,
1250
+ category: ErrorCategory.USER,
1251
+ details: {
1252
+ spanId,
1253
+ traceId
1254
+ }
1255
+ },
1256
+ error
1257
+ );
1258
+ }
1259
+ }
1260
+ async getAITracesPaginated({
1261
+ filters,
1262
+ pagination
1263
+ }) {
1264
+ const page = pagination?.page ?? 0;
1265
+ const perPage = pagination?.perPage ?? 10;
1266
+ const { entityId, entityType, ...actualFilters } = filters || {};
1267
+ const filtersWithDateRange = {
1268
+ ...actualFilters,
1269
+ ...buildDateRangeFilter(pagination?.dateRange, "startedAt"),
1270
+ parentSpanId: null
1271
+ // Only get root spans for traces
1272
+ };
1273
+ const whereClause = prepareWhereClause(filtersWithDateRange);
1274
+ let actualWhereClause = whereClause.sql;
1275
+ const params = { ...whereClause.params };
1276
+ let currentParamIndex = Object.keys(params).length + 1;
1277
+ if (entityId && entityType) {
1278
+ let name = "";
1279
+ if (entityType === "workflow") {
1280
+ name = `workflow run: '${entityId}'`;
1281
+ } else if (entityType === "agent") {
1282
+ name = `agent run: '${entityId}'`;
1283
+ } else {
1284
+ const error = new MastraError({
1285
+ id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1286
+ domain: ErrorDomain.STORAGE,
1287
+ category: ErrorCategory.USER,
1288
+ details: {
1289
+ entityType
1290
+ },
1291
+ text: `Cannot filter by entity type: ${entityType}`
1292
+ });
1293
+ throw error;
1294
+ }
1295
+ const entityParam = `p${currentParamIndex++}`;
1296
+ if (actualWhereClause) {
1297
+ actualWhereClause += ` AND [name] = @${entityParam}`;
1298
+ } else {
1299
+ actualWhereClause = ` WHERE [name] = @${entityParam}`;
1300
+ }
1301
+ params[entityParam] = name;
1302
+ }
1303
+ const tableName = getTableName({
1304
+ indexName: TABLE_AI_SPANS,
1305
+ schemaName: getSchemaName(this.schema)
1306
+ });
1307
+ try {
1308
+ const countRequest = this.pool.request();
1309
+ Object.entries(params).forEach(([key, value]) => {
1310
+ countRequest.input(key, value);
1311
+ });
1312
+ const countResult = await countRequest.query(
1313
+ `SELECT COUNT(*) as count FROM ${tableName}${actualWhereClause}`
1314
+ );
1315
+ const total = countResult.recordset[0]?.count ?? 0;
1316
+ if (total === 0) {
1317
+ return {
1318
+ pagination: {
1319
+ total: 0,
1320
+ page,
1321
+ perPage,
1322
+ hasMore: false
1323
+ },
1324
+ spans: []
1325
+ };
1326
+ }
1327
+ const dataRequest = this.pool.request();
1328
+ Object.entries(params).forEach(([key, value]) => {
1329
+ dataRequest.input(key, value);
1330
+ });
1331
+ dataRequest.input("offset", page * perPage);
1332
+ dataRequest.input("limit", perPage);
1333
+ const dataResult = await dataRequest.query(
1334
+ `SELECT * FROM ${tableName}${actualWhereClause} ORDER BY [startedAt] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`
1335
+ );
1336
+ const spans = dataResult.recordset.map(
1337
+ (row) => transformFromSqlRow({
1338
+ tableName: TABLE_AI_SPANS,
1339
+ sqlRow: row
1340
+ })
1341
+ );
1342
+ return {
1343
+ pagination: {
1344
+ total,
1345
+ page,
1346
+ perPage,
1347
+ hasMore: (page + 1) * perPage < total
1348
+ },
1349
+ spans
1350
+ };
1351
+ } catch (error) {
1352
+ throw new MastraError(
1353
+ {
1354
+ id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1355
+ domain: ErrorDomain.STORAGE,
1356
+ category: ErrorCategory.USER
1357
+ },
1358
+ error
1359
+ );
1360
+ }
1361
+ }
1362
+ async batchCreateAISpans(args) {
1363
+ if (!args.records || args.records.length === 0) {
1364
+ return;
1365
+ }
1366
+ try {
1367
+ await this.operations.batchInsert({
1368
+ tableName: TABLE_AI_SPANS,
1369
+ records: args.records.map((span) => ({
1370
+ ...span,
1371
+ startedAt: span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt,
1372
+ endedAt: span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt
1373
+ }))
1374
+ });
1375
+ } catch (error) {
1376
+ throw new MastraError(
1377
+ {
1378
+ id: "MSSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1379
+ domain: ErrorDomain.STORAGE,
1380
+ category: ErrorCategory.USER,
1381
+ details: {
1382
+ count: args.records.length
1383
+ }
1384
+ },
1385
+ error
1386
+ );
1387
+ }
1388
+ }
1389
+ async batchUpdateAISpans(args) {
1390
+ if (!args.records || args.records.length === 0) {
1391
+ return;
1392
+ }
1393
+ try {
1394
+ const updates = args.records.map(({ traceId, spanId, updates: data }) => {
1395
+ const processedData = { ...data };
1396
+ if (processedData.endedAt instanceof Date) {
1397
+ processedData.endedAt = processedData.endedAt.toISOString();
1398
+ }
1399
+ if (processedData.startedAt instanceof Date) {
1400
+ processedData.startedAt = processedData.startedAt.toISOString();
1401
+ }
1402
+ return {
1403
+ keys: { spanId, traceId },
1404
+ data: processedData
1405
+ };
1406
+ });
1407
+ await this.operations.batchUpdate({
1408
+ tableName: TABLE_AI_SPANS,
1409
+ updates
1410
+ });
1411
+ } catch (error) {
1412
+ throw new MastraError(
1413
+ {
1414
+ id: "MSSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
1415
+ domain: ErrorDomain.STORAGE,
1416
+ category: ErrorCategory.USER,
1417
+ details: {
1418
+ count: args.records.length
1419
+ }
1420
+ },
1421
+ error
1422
+ );
1423
+ }
1424
+ }
1425
+ async batchDeleteAITraces(args) {
1426
+ if (!args.traceIds || args.traceIds.length === 0) {
1427
+ return;
1428
+ }
1429
+ try {
1430
+ const keys = args.traceIds.map((traceId) => ({ traceId }));
1431
+ await this.operations.batchDelete({
1432
+ tableName: TABLE_AI_SPANS,
1433
+ keys
1434
+ });
1435
+ } catch (error) {
1436
+ throw new MastraError(
1437
+ {
1438
+ id: "MSSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
1439
+ domain: ErrorDomain.STORAGE,
1440
+ category: ErrorCategory.USER,
1441
+ details: {
1442
+ count: args.traceIds.length
1443
+ }
1736
1444
  },
1737
1445
  error
1738
1446
  );
1739
- this.logger?.error?.(mastraError.toString());
1740
- this.logger?.trackException(mastraError);
1741
- throw mastraError;
1742
1447
  }
1743
1448
  }
1744
1449
  };
1450
+ var StoreOperationsMSSQL = class extends StoreOperations {
1451
+ pool;
1452
+ schemaName;
1453
+ setupSchemaPromise = null;
1454
+ schemaSetupComplete = void 0;
1455
+ getSqlType(type, isPrimaryKey = false, useLargeStorage = false) {
1456
+ switch (type) {
1457
+ case "text":
1458
+ if (useLargeStorage) {
1459
+ return "NVARCHAR(MAX)";
1460
+ }
1461
+ return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(400)";
1462
+ case "timestamp":
1463
+ return "DATETIME2(7)";
1464
+ case "uuid":
1465
+ return "UNIQUEIDENTIFIER";
1466
+ case "jsonb":
1467
+ return "NVARCHAR(MAX)";
1468
+ case "integer":
1469
+ return "INT";
1470
+ case "bigint":
1471
+ return "BIGINT";
1472
+ case "float":
1473
+ return "FLOAT";
1474
+ case "boolean":
1475
+ return "BIT";
1476
+ default:
1477
+ throw new MastraError({
1478
+ id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
1479
+ domain: ErrorDomain.STORAGE,
1480
+ category: ErrorCategory.THIRD_PARTY
1481
+ });
1482
+ }
1483
+ }
1484
+ constructor({ pool, schemaName }) {
1485
+ super();
1486
+ this.pool = pool;
1487
+ this.schemaName = schemaName;
1488
+ }
1489
+ async hasColumn(table, column) {
1490
+ const schema = this.schemaName || "dbo";
1491
+ const request = this.pool.request();
1492
+ request.input("schema", schema);
1493
+ request.input("table", table);
1494
+ request.input("column", column);
1495
+ request.input("columnLower", column.toLowerCase());
1496
+ const result = await request.query(
1497
+ `SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
1498
+ );
1499
+ return result.recordset.length > 0;
1500
+ }
1501
+ async setupSchema() {
1502
+ if (!this.schemaName || this.schemaSetupComplete) {
1503
+ return;
1504
+ }
1505
+ if (!this.setupSchemaPromise) {
1506
+ this.setupSchemaPromise = (async () => {
1507
+ try {
1508
+ const checkRequest = this.pool.request();
1509
+ checkRequest.input("schemaName", this.schemaName);
1510
+ const checkResult = await checkRequest.query(`
1511
+ SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
1512
+ `);
1513
+ const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
1514
+ if (!schemaExists) {
1515
+ try {
1516
+ await this.pool.request().query(`CREATE SCHEMA [${this.schemaName}]`);
1517
+ this.logger?.info?.(`Schema "${this.schemaName}" created successfully`);
1518
+ } catch (error) {
1519
+ this.logger?.error?.(`Failed to create schema "${this.schemaName}"`, { error });
1520
+ throw new Error(
1521
+ `Unable to create schema "${this.schemaName}". This requires CREATE privilege on the database. Either create the schema manually or grant CREATE privilege to the user.`
1522
+ );
1523
+ }
1524
+ }
1525
+ this.schemaSetupComplete = true;
1526
+ this.logger?.debug?.(`Schema "${this.schemaName}" is ready for use`);
1527
+ } catch (error) {
1528
+ this.schemaSetupComplete = void 0;
1529
+ this.setupSchemaPromise = null;
1530
+ throw error;
1531
+ } finally {
1532
+ this.setupSchemaPromise = null;
1533
+ }
1534
+ })();
1535
+ }
1536
+ await this.setupSchemaPromise;
1537
+ }
1538
+ async insert({
1539
+ tableName,
1540
+ record,
1541
+ transaction
1542
+ }) {
1543
+ try {
1544
+ const columns = Object.keys(record);
1545
+ const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
1546
+ const paramNames = columns.map((_, i) => `@param${i}`);
1547
+ const insertSql = `INSERT INTO ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (${parsedColumns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
1548
+ const request = transaction ? transaction.request() : this.pool.request();
1549
+ columns.forEach((col, i) => {
1550
+ const value = record[col];
1551
+ const preparedValue = this.prepareValue(value, col, tableName);
1552
+ if (preparedValue instanceof Date) {
1553
+ request.input(`param${i}`, sql3.DateTime2, preparedValue);
1554
+ } else if (preparedValue === null || preparedValue === void 0) {
1555
+ request.input(`param${i}`, this.getMssqlType(tableName, col), null);
1556
+ } else {
1557
+ request.input(`param${i}`, preparedValue);
1558
+ }
1559
+ });
1560
+ await request.query(insertSql);
1561
+ } catch (error) {
1562
+ throw new MastraError(
1563
+ {
1564
+ id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
1565
+ domain: ErrorDomain.STORAGE,
1566
+ category: ErrorCategory.THIRD_PARTY,
1567
+ details: {
1568
+ tableName
1569
+ }
1570
+ },
1571
+ error
1572
+ );
1573
+ }
1574
+ }
1575
+ async clearTable({ tableName }) {
1576
+ const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1577
+ try {
1578
+ try {
1579
+ await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
1580
+ } catch (truncateError) {
1581
+ if (truncateError?.number === 4712) {
1582
+ await this.pool.request().query(`DELETE FROM ${fullTableName}`);
1583
+ } else {
1584
+ throw truncateError;
1585
+ }
1586
+ }
1587
+ } catch (error) {
1588
+ throw new MastraError(
1589
+ {
1590
+ id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
1591
+ domain: ErrorDomain.STORAGE,
1592
+ category: ErrorCategory.THIRD_PARTY,
1593
+ details: {
1594
+ tableName
1595
+ }
1596
+ },
1597
+ error
1598
+ );
1599
+ }
1600
+ }
1601
+ getDefaultValue(type) {
1602
+ switch (type) {
1603
+ case "timestamp":
1604
+ return "DEFAULT SYSUTCDATETIME()";
1605
+ case "jsonb":
1606
+ return "DEFAULT N'{}'";
1607
+ case "boolean":
1608
+ return "DEFAULT 0";
1609
+ default:
1610
+ return super.getDefaultValue(type);
1611
+ }
1612
+ }
1613
+ async createTable({
1614
+ tableName,
1615
+ schema
1616
+ }) {
1617
+ try {
1618
+ const uniqueConstraintColumns = tableName === TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
1619
+ const largeDataColumns = [
1620
+ "workingMemory",
1621
+ "snapshot",
1622
+ "metadata",
1623
+ "content",
1624
+ // messages.content - can be very long conversation content
1625
+ "input",
1626
+ // evals.input - test input data
1627
+ "output",
1628
+ // evals.output - test output data
1629
+ "instructions",
1630
+ // evals.instructions - evaluation instructions
1631
+ "other"
1632
+ // traces.other - additional trace data
1633
+ ];
1634
+ const columns = Object.entries(schema).map(([name, def]) => {
1635
+ const parsedName = parseSqlIdentifier(name, "column name");
1636
+ const constraints = [];
1637
+ if (def.primaryKey) constraints.push("PRIMARY KEY");
1638
+ if (!def.nullable) constraints.push("NOT NULL");
1639
+ const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
1640
+ const useLargeStorage = largeDataColumns.includes(name);
1641
+ return `[${parsedName}] ${this.getSqlType(def.type, isIndexed, useLargeStorage)} ${constraints.join(" ")}`.trim();
1642
+ }).join(",\n");
1643
+ if (this.schemaName) {
1644
+ await this.setupSchema();
1645
+ }
1646
+ const checkTableRequest = this.pool.request();
1647
+ checkTableRequest.input(
1648
+ "tableName",
1649
+ getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
1650
+ );
1651
+ const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
1652
+ checkTableRequest.input("schema", this.schemaName || "dbo");
1653
+ const checkTableResult = await checkTableRequest.query(checkTableSql);
1654
+ const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
1655
+ if (!tableExists) {
1656
+ const createSql = `CREATE TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (
1657
+ ${columns}
1658
+ )`;
1659
+ await this.pool.request().query(createSql);
1660
+ }
1661
+ const columnCheckSql = `
1662
+ SELECT 1 AS found
1663
+ FROM INFORMATION_SCHEMA.COLUMNS
1664
+ WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
1665
+ `;
1666
+ const checkColumnRequest = this.pool.request();
1667
+ checkColumnRequest.input("schema", this.schemaName || "dbo");
1668
+ checkColumnRequest.input(
1669
+ "tableName",
1670
+ getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
1671
+ );
1672
+ const columnResult = await checkColumnRequest.query(columnCheckSql);
1673
+ const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
1674
+ if (!columnExists) {
1675
+ const alterSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD seq_id BIGINT IDENTITY(1,1)`;
1676
+ await this.pool.request().query(alterSql);
1677
+ }
1678
+ if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
1679
+ const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
1680
+ const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
1681
+ const checkConstraintRequest = this.pool.request();
1682
+ checkConstraintRequest.input("constraintName", constraintName);
1683
+ const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
1684
+ const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
1685
+ if (!constraintExists) {
1686
+ const addConstraintSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
1687
+ await this.pool.request().query(addConstraintSql);
1688
+ }
1689
+ }
1690
+ } catch (error) {
1691
+ throw new MastraError(
1692
+ {
1693
+ id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
1694
+ domain: ErrorDomain.STORAGE,
1695
+ category: ErrorCategory.THIRD_PARTY,
1696
+ details: {
1697
+ tableName
1698
+ }
1699
+ },
1700
+ error
1701
+ );
1702
+ }
1703
+ }
1704
+ /**
1705
+ * Alters table schema to add columns if they don't exist
1706
+ * @param tableName Name of the table
1707
+ * @param schema Schema of the table
1708
+ * @param ifNotExists Array of column names to add if they don't exist
1709
+ */
1710
+ async alterTable({
1711
+ tableName,
1712
+ schema,
1713
+ ifNotExists
1714
+ }) {
1715
+ const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1716
+ try {
1717
+ for (const columnName of ifNotExists) {
1718
+ if (schema[columnName]) {
1719
+ const columnCheckRequest = this.pool.request();
1720
+ columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
1721
+ columnCheckRequest.input("columnName", columnName);
1722
+ columnCheckRequest.input("schema", this.schemaName || "dbo");
1723
+ const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
1724
+ const checkResult = await columnCheckRequest.query(checkSql);
1725
+ const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
1726
+ if (!columnExists) {
1727
+ const columnDef = schema[columnName];
1728
+ const largeDataColumns = [
1729
+ "workingMemory",
1730
+ "snapshot",
1731
+ "metadata",
1732
+ "content",
1733
+ "input",
1734
+ "output",
1735
+ "instructions",
1736
+ "other"
1737
+ ];
1738
+ const useLargeStorage = largeDataColumns.includes(columnName);
1739
+ const isIndexed = !!columnDef.primaryKey;
1740
+ const sqlType = this.getSqlType(columnDef.type, isIndexed, useLargeStorage);
1741
+ const nullable = columnDef.nullable === false ? "NOT NULL" : "";
1742
+ const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
1743
+ const parsedColumnName = parseSqlIdentifier(columnName, "column name");
1744
+ const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
1745
+ await this.pool.request().query(alterSql);
1746
+ this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
1747
+ }
1748
+ }
1749
+ }
1750
+ } catch (error) {
1751
+ throw new MastraError(
1752
+ {
1753
+ id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
1754
+ domain: ErrorDomain.STORAGE,
1755
+ category: ErrorCategory.THIRD_PARTY,
1756
+ details: {
1757
+ tableName
1758
+ }
1759
+ },
1760
+ error
1761
+ );
1762
+ }
1763
+ }
1764
+ async load({ tableName, keys }) {
1765
+ try {
1766
+ const keyEntries = Object.entries(keys).map(([key, value]) => [parseSqlIdentifier(key, "column name"), value]);
1767
+ const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
1768
+ const sql6 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1769
+ const request = this.pool.request();
1770
+ keyEntries.forEach(([key, value], i) => {
1771
+ const preparedValue = this.prepareValue(value, key, tableName);
1772
+ if (preparedValue === null || preparedValue === void 0) {
1773
+ request.input(`param${i}`, this.getMssqlType(tableName, key), null);
1774
+ } else {
1775
+ request.input(`param${i}`, preparedValue);
1776
+ }
1777
+ });
1778
+ const resultSet = await request.query(sql6);
1779
+ const result = resultSet.recordset[0] || null;
1780
+ if (!result) {
1781
+ return null;
1782
+ }
1783
+ if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
1784
+ const snapshot = result;
1785
+ if (typeof snapshot.snapshot === "string") {
1786
+ snapshot.snapshot = JSON.parse(snapshot.snapshot);
1787
+ }
1788
+ return snapshot;
1789
+ }
1790
+ return result;
1791
+ } catch (error) {
1792
+ throw new MastraError(
1793
+ {
1794
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
1795
+ domain: ErrorDomain.STORAGE,
1796
+ category: ErrorCategory.THIRD_PARTY,
1797
+ details: {
1798
+ tableName
1799
+ }
1800
+ },
1801
+ error
1802
+ );
1803
+ }
1804
+ }
1805
+ async batchInsert({ tableName, records }) {
1806
+ const transaction = this.pool.transaction();
1807
+ try {
1808
+ await transaction.begin();
1809
+ for (const record of records) {
1810
+ await this.insert({ tableName, record, transaction });
1811
+ }
1812
+ await transaction.commit();
1813
+ } catch (error) {
1814
+ await transaction.rollback();
1815
+ throw new MastraError(
1816
+ {
1817
+ id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
1818
+ domain: ErrorDomain.STORAGE,
1819
+ category: ErrorCategory.THIRD_PARTY,
1820
+ details: {
1821
+ tableName,
1822
+ numberOfRecords: records.length
1823
+ }
1824
+ },
1825
+ error
1826
+ );
1827
+ }
1828
+ }
1829
+ async dropTable({ tableName }) {
1830
+ try {
1831
+ const tableNameWithSchema = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1832
+ await this.pool.request().query(`DROP TABLE IF EXISTS ${tableNameWithSchema}`);
1833
+ } catch (error) {
1834
+ throw new MastraError(
1835
+ {
1836
+ id: "MASTRA_STORAGE_MSSQL_STORE_DROP_TABLE_FAILED",
1837
+ domain: ErrorDomain.STORAGE,
1838
+ category: ErrorCategory.THIRD_PARTY,
1839
+ details: {
1840
+ tableName
1841
+ }
1842
+ },
1843
+ error
1844
+ );
1845
+ }
1846
+ }
1847
+ /**
1848
+ * Prepares a value for database operations, handling Date objects and JSON serialization
1849
+ */
1850
+ prepareValue(value, columnName, tableName) {
1851
+ if (value === null || value === void 0) {
1852
+ return value;
1853
+ }
1854
+ if (value instanceof Date) {
1855
+ return value;
1856
+ }
1857
+ const schema = TABLE_SCHEMAS[tableName];
1858
+ const columnSchema = schema?.[columnName];
1859
+ if (columnSchema?.type === "boolean") {
1860
+ return value ? 1 : 0;
1861
+ }
1862
+ if (columnSchema?.type === "jsonb") {
1863
+ return JSON.stringify(value);
1864
+ }
1865
+ if (typeof value === "object") {
1866
+ return JSON.stringify(value);
1867
+ }
1868
+ return value;
1869
+ }
1870
+ /**
1871
+ * Maps TABLE_SCHEMAS types to mssql param types (used when value is null)
1872
+ */
1873
+ getMssqlType(tableName, columnName) {
1874
+ const col = TABLE_SCHEMAS[tableName]?.[columnName];
1875
+ switch (col?.type) {
1876
+ case "text":
1877
+ return sql3.NVarChar;
1878
+ case "timestamp":
1879
+ return sql3.DateTime2;
1880
+ case "uuid":
1881
+ return sql3.UniqueIdentifier;
1882
+ case "jsonb":
1883
+ return sql3.NVarChar;
1884
+ case "integer":
1885
+ return sql3.Int;
1886
+ case "bigint":
1887
+ return sql3.BigInt;
1888
+ case "float":
1889
+ return sql3.Float;
1890
+ case "boolean":
1891
+ return sql3.Bit;
1892
+ default:
1893
+ return sql3.NVarChar;
1894
+ }
1895
+ }
1896
+ /**
1897
+ * Update a single record in the database
1898
+ */
1899
+ async update({
1900
+ tableName,
1901
+ keys,
1902
+ data,
1903
+ transaction
1904
+ }) {
1905
+ try {
1906
+ if (!data || Object.keys(data).length === 0) {
1907
+ throw new MastraError({
1908
+ id: "MASTRA_STORAGE_MSSQL_UPDATE_EMPTY_DATA",
1909
+ domain: ErrorDomain.STORAGE,
1910
+ category: ErrorCategory.USER,
1911
+ text: "Cannot update with empty data payload"
1912
+ });
1913
+ }
1914
+ if (!keys || Object.keys(keys).length === 0) {
1915
+ throw new MastraError({
1916
+ id: "MASTRA_STORAGE_MSSQL_UPDATE_EMPTY_KEYS",
1917
+ domain: ErrorDomain.STORAGE,
1918
+ category: ErrorCategory.USER,
1919
+ text: "Cannot update without keys to identify records"
1920
+ });
1921
+ }
1922
+ const setClauses = [];
1923
+ const request = transaction ? transaction.request() : this.pool.request();
1924
+ let paramIndex = 0;
1925
+ Object.entries(data).forEach(([key, value]) => {
1926
+ const parsedKey = parseSqlIdentifier(key, "column name");
1927
+ const paramName = `set${paramIndex++}`;
1928
+ setClauses.push(`[${parsedKey}] = @${paramName}`);
1929
+ const preparedValue = this.prepareValue(value, key, tableName);
1930
+ if (preparedValue === null || preparedValue === void 0) {
1931
+ request.input(paramName, this.getMssqlType(tableName, key), null);
1932
+ } else {
1933
+ request.input(paramName, preparedValue);
1934
+ }
1935
+ });
1936
+ const whereConditions = [];
1937
+ Object.entries(keys).forEach(([key, value]) => {
1938
+ const parsedKey = parseSqlIdentifier(key, "column name");
1939
+ const paramName = `where${paramIndex++}`;
1940
+ whereConditions.push(`[${parsedKey}] = @${paramName}`);
1941
+ const preparedValue = this.prepareValue(value, key, tableName);
1942
+ if (preparedValue === null || preparedValue === void 0) {
1943
+ request.input(paramName, this.getMssqlType(tableName, key), null);
1944
+ } else {
1945
+ request.input(paramName, preparedValue);
1946
+ }
1947
+ });
1948
+ const tableName_ = getTableName({
1949
+ indexName: tableName,
1950
+ schemaName: getSchemaName(this.schemaName)
1951
+ });
1952
+ const updateSql = `UPDATE ${tableName_} SET ${setClauses.join(", ")} WHERE ${whereConditions.join(" AND ")}`;
1953
+ await request.query(updateSql);
1954
+ } catch (error) {
1955
+ throw new MastraError(
1956
+ {
1957
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_FAILED",
1958
+ domain: ErrorDomain.STORAGE,
1959
+ category: ErrorCategory.THIRD_PARTY,
1960
+ details: {
1961
+ tableName
1962
+ }
1963
+ },
1964
+ error
1965
+ );
1966
+ }
1967
+ }
1968
+ /**
1969
+ * Update multiple records in a single batch transaction
1970
+ */
1971
+ async batchUpdate({
1972
+ tableName,
1973
+ updates
1974
+ }) {
1975
+ const transaction = this.pool.transaction();
1976
+ try {
1977
+ await transaction.begin();
1978
+ for (const { keys, data } of updates) {
1979
+ await this.update({ tableName, keys, data, transaction });
1980
+ }
1981
+ await transaction.commit();
1982
+ } catch (error) {
1983
+ await transaction.rollback();
1984
+ throw new MastraError(
1985
+ {
1986
+ id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_UPDATE_FAILED",
1987
+ domain: ErrorDomain.STORAGE,
1988
+ category: ErrorCategory.THIRD_PARTY,
1989
+ details: {
1990
+ tableName,
1991
+ numberOfRecords: updates.length
1992
+ }
1993
+ },
1994
+ error
1995
+ );
1996
+ }
1997
+ }
1998
+ /**
1999
+ * Delete multiple records by keys
2000
+ */
2001
+ async batchDelete({ tableName, keys }) {
2002
+ if (keys.length === 0) {
2003
+ return;
2004
+ }
2005
+ const tableName_ = getTableName({
2006
+ indexName: tableName,
2007
+ schemaName: getSchemaName(this.schemaName)
2008
+ });
2009
+ const transaction = this.pool.transaction();
2010
+ try {
2011
+ await transaction.begin();
2012
+ for (const keySet of keys) {
2013
+ const conditions = [];
2014
+ const request = transaction.request();
2015
+ let paramIndex = 0;
2016
+ Object.entries(keySet).forEach(([key, value]) => {
2017
+ const parsedKey = parseSqlIdentifier(key, "column name");
2018
+ const paramName = `p${paramIndex++}`;
2019
+ conditions.push(`[${parsedKey}] = @${paramName}`);
2020
+ const preparedValue = this.prepareValue(value, key, tableName);
2021
+ if (preparedValue === null || preparedValue === void 0) {
2022
+ request.input(paramName, this.getMssqlType(tableName, key), null);
2023
+ } else {
2024
+ request.input(paramName, preparedValue);
2025
+ }
2026
+ });
2027
+ const deleteSql = `DELETE FROM ${tableName_} WHERE ${conditions.join(" AND ")}`;
2028
+ await request.query(deleteSql);
2029
+ }
2030
+ await transaction.commit();
2031
+ } catch (error) {
2032
+ await transaction.rollback();
2033
+ throw new MastraError(
2034
+ {
2035
+ id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_DELETE_FAILED",
2036
+ domain: ErrorDomain.STORAGE,
2037
+ category: ErrorCategory.THIRD_PARTY,
2038
+ details: {
2039
+ tableName,
2040
+ numberOfRecords: keys.length
2041
+ }
2042
+ },
2043
+ error
2044
+ );
2045
+ }
2046
+ }
2047
+ /**
2048
+ * Create a new index on a table
2049
+ */
2050
+ async createIndex(options) {
2051
+ try {
2052
+ const { name, table, columns, unique = false, where } = options;
2053
+ const schemaName = this.schemaName || "dbo";
2054
+ const fullTableName = getTableName({
2055
+ indexName: table,
2056
+ schemaName: getSchemaName(this.schemaName)
2057
+ });
2058
+ const indexNameSafe = parseSqlIdentifier(name, "index name");
2059
+ const checkRequest = this.pool.request();
2060
+ checkRequest.input("indexName", indexNameSafe);
2061
+ checkRequest.input("schemaName", schemaName);
2062
+ checkRequest.input("tableName", table);
2063
+ const indexExists = await checkRequest.query(`
2064
+ SELECT 1 as found
2065
+ FROM sys.indexes i
2066
+ INNER JOIN sys.tables t ON i.object_id = t.object_id
2067
+ INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
2068
+ WHERE i.name = @indexName
2069
+ AND s.name = @schemaName
2070
+ AND t.name = @tableName
2071
+ `);
2072
+ if (indexExists.recordset && indexExists.recordset.length > 0) {
2073
+ return;
2074
+ }
2075
+ const uniqueStr = unique ? "UNIQUE " : "";
2076
+ const columnsStr = columns.map((col) => {
2077
+ if (col.includes(" DESC") || col.includes(" ASC")) {
2078
+ const [colName, ...modifiers] = col.split(" ");
2079
+ if (!colName) {
2080
+ throw new Error(`Invalid column specification: ${col}`);
2081
+ }
2082
+ return `[${parseSqlIdentifier(colName, "column name")}] ${modifiers.join(" ")}`;
2083
+ }
2084
+ return `[${parseSqlIdentifier(col, "column name")}]`;
2085
+ }).join(", ");
2086
+ const whereStr = where ? ` WHERE ${where}` : "";
2087
+ const createIndexSql = `CREATE ${uniqueStr}INDEX [${indexNameSafe}] ON ${fullTableName} (${columnsStr})${whereStr}`;
2088
+ await this.pool.request().query(createIndexSql);
2089
+ } catch (error) {
2090
+ throw new MastraError(
2091
+ {
2092
+ id: "MASTRA_STORAGE_MSSQL_INDEX_CREATE_FAILED",
2093
+ domain: ErrorDomain.STORAGE,
2094
+ category: ErrorCategory.THIRD_PARTY,
2095
+ details: {
2096
+ indexName: options.name,
2097
+ tableName: options.table
2098
+ }
2099
+ },
2100
+ error
2101
+ );
2102
+ }
2103
+ }
2104
+ /**
2105
+ * Drop an existing index
2106
+ */
2107
+ async dropIndex(indexName) {
2108
+ try {
2109
+ const schemaName = this.schemaName || "dbo";
2110
+ const indexNameSafe = parseSqlIdentifier(indexName, "index name");
2111
+ const checkRequest = this.pool.request();
2112
+ checkRequest.input("indexName", indexNameSafe);
2113
+ checkRequest.input("schemaName", schemaName);
2114
+ const result = await checkRequest.query(`
2115
+ SELECT t.name as table_name
2116
+ FROM sys.indexes i
2117
+ INNER JOIN sys.tables t ON i.object_id = t.object_id
2118
+ INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
2119
+ WHERE i.name = @indexName
2120
+ AND s.name = @schemaName
2121
+ `);
2122
+ if (!result.recordset || result.recordset.length === 0) {
2123
+ return;
2124
+ }
2125
+ if (result.recordset.length > 1) {
2126
+ const tables = result.recordset.map((r) => r.table_name).join(", ");
2127
+ throw new MastraError({
2128
+ id: "MASTRA_STORAGE_MSSQL_INDEX_AMBIGUOUS",
2129
+ domain: ErrorDomain.STORAGE,
2130
+ category: ErrorCategory.USER,
2131
+ text: `Index "${indexNameSafe}" exists on multiple tables (${tables}) in schema "${schemaName}". Please drop indexes manually or ensure unique index names.`
2132
+ });
2133
+ }
2134
+ const tableName = result.recordset[0].table_name;
2135
+ const fullTableName = getTableName({
2136
+ indexName: tableName,
2137
+ schemaName: getSchemaName(this.schemaName)
2138
+ });
2139
+ const dropSql = `DROP INDEX [${indexNameSafe}] ON ${fullTableName}`;
2140
+ await this.pool.request().query(dropSql);
2141
+ } catch (error) {
2142
+ throw new MastraError(
2143
+ {
2144
+ id: "MASTRA_STORAGE_MSSQL_INDEX_DROP_FAILED",
2145
+ domain: ErrorDomain.STORAGE,
2146
+ category: ErrorCategory.THIRD_PARTY,
2147
+ details: {
2148
+ indexName
2149
+ }
2150
+ },
2151
+ error
2152
+ );
2153
+ }
2154
+ }
2155
+ /**
2156
+ * List indexes for a specific table or all tables
2157
+ */
2158
+ async listIndexes(tableName) {
2159
+ try {
2160
+ const schemaName = this.schemaName || "dbo";
2161
+ let query;
2162
+ const request = this.pool.request();
2163
+ request.input("schemaName", schemaName);
2164
+ if (tableName) {
2165
+ query = `
2166
+ SELECT
2167
+ i.name as name,
2168
+ o.name as [table],
2169
+ i.is_unique as is_unique,
2170
+ CAST(SUM(s.used_page_count) * 8 / 1024.0 AS VARCHAR(50)) + ' MB' as size
2171
+ FROM sys.indexes i
2172
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2173
+ INNER JOIN sys.schemas sch ON o.schema_id = sch.schema_id
2174
+ LEFT JOIN sys.dm_db_partition_stats s ON i.object_id = s.object_id AND i.index_id = s.index_id
2175
+ WHERE sch.name = @schemaName
2176
+ AND o.name = @tableName
2177
+ AND i.name IS NOT NULL
2178
+ GROUP BY i.name, o.name, i.is_unique
2179
+ `;
2180
+ request.input("tableName", tableName);
2181
+ } else {
2182
+ query = `
2183
+ SELECT
2184
+ i.name as name,
2185
+ o.name as [table],
2186
+ i.is_unique as is_unique,
2187
+ CAST(SUM(s.used_page_count) * 8 / 1024.0 AS VARCHAR(50)) + ' MB' as size
2188
+ FROM sys.indexes i
2189
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2190
+ INNER JOIN sys.schemas sch ON o.schema_id = sch.schema_id
2191
+ LEFT JOIN sys.dm_db_partition_stats s ON i.object_id = s.object_id AND i.index_id = s.index_id
2192
+ WHERE sch.name = @schemaName
2193
+ AND i.name IS NOT NULL
2194
+ GROUP BY i.name, o.name, i.is_unique
2195
+ `;
2196
+ }
2197
+ const result = await request.query(query);
2198
+ const indexes = [];
2199
+ for (const row of result.recordset) {
2200
+ const colRequest = this.pool.request();
2201
+ colRequest.input("indexName", row.name);
2202
+ colRequest.input("schemaName", schemaName);
2203
+ const colResult = await colRequest.query(`
2204
+ SELECT c.name as column_name
2205
+ FROM sys.indexes i
2206
+ INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
2207
+ INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
2208
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2209
+ INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
2210
+ WHERE i.name = @indexName
2211
+ AND s.name = @schemaName
2212
+ ORDER BY ic.key_ordinal
2213
+ `);
2214
+ indexes.push({
2215
+ name: row.name,
2216
+ table: row.table,
2217
+ columns: colResult.recordset.map((c) => c.column_name),
2218
+ unique: row.is_unique || false,
2219
+ size: row.size || "0 MB",
2220
+ definition: ""
2221
+ // MSSQL doesn't store definition like PG
2222
+ });
2223
+ }
2224
+ return indexes;
2225
+ } catch (error) {
2226
+ throw new MastraError(
2227
+ {
2228
+ id: "MASTRA_STORAGE_MSSQL_INDEX_LIST_FAILED",
2229
+ domain: ErrorDomain.STORAGE,
2230
+ category: ErrorCategory.THIRD_PARTY,
2231
+ details: tableName ? {
2232
+ tableName
2233
+ } : {}
2234
+ },
2235
+ error
2236
+ );
2237
+ }
2238
+ }
2239
+ /**
2240
+ * Get detailed statistics for a specific index
2241
+ */
2242
+ async describeIndex(indexName) {
2243
+ try {
2244
+ const schemaName = this.schemaName || "dbo";
2245
+ const request = this.pool.request();
2246
+ request.input("indexName", indexName);
2247
+ request.input("schemaName", schemaName);
2248
+ const query = `
2249
+ SELECT
2250
+ i.name as name,
2251
+ o.name as [table],
2252
+ i.is_unique as is_unique,
2253
+ CAST(SUM(s.used_page_count) * 8 / 1024.0 AS VARCHAR(50)) + ' MB' as size,
2254
+ i.type_desc as method,
2255
+ ISNULL(us.user_scans, 0) as scans,
2256
+ ISNULL(us.user_seeks + us.user_scans, 0) as tuples_read,
2257
+ ISNULL(us.user_lookups, 0) as tuples_fetched
2258
+ FROM sys.indexes i
2259
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2260
+ INNER JOIN sys.schemas sch ON o.schema_id = sch.schema_id
2261
+ LEFT JOIN sys.dm_db_partition_stats s ON i.object_id = s.object_id AND i.index_id = s.index_id
2262
+ LEFT JOIN sys.dm_db_index_usage_stats us ON i.object_id = us.object_id AND i.index_id = us.index_id
2263
+ WHERE i.name = @indexName
2264
+ AND sch.name = @schemaName
2265
+ GROUP BY i.name, o.name, i.is_unique, i.type_desc, us.user_seeks, us.user_scans, us.user_lookups
2266
+ `;
2267
+ const result = await request.query(query);
2268
+ if (!result.recordset || result.recordset.length === 0) {
2269
+ throw new Error(`Index "${indexName}" not found in schema "${schemaName}"`);
2270
+ }
2271
+ const row = result.recordset[0];
2272
+ const colRequest = this.pool.request();
2273
+ colRequest.input("indexName", indexName);
2274
+ colRequest.input("schemaName", schemaName);
2275
+ const colResult = await colRequest.query(`
2276
+ SELECT c.name as column_name
2277
+ FROM sys.indexes i
2278
+ INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
2279
+ INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
2280
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2281
+ INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
2282
+ WHERE i.name = @indexName
2283
+ AND s.name = @schemaName
2284
+ ORDER BY ic.key_ordinal
2285
+ `);
2286
+ return {
2287
+ name: row.name,
2288
+ table: row.table,
2289
+ columns: colResult.recordset.map((c) => c.column_name),
2290
+ unique: row.is_unique || false,
2291
+ size: row.size || "0 MB",
2292
+ definition: "",
2293
+ method: row.method?.toLowerCase() || "nonclustered",
2294
+ scans: Number(row.scans) || 0,
2295
+ tuples_read: Number(row.tuples_read) || 0,
2296
+ tuples_fetched: Number(row.tuples_fetched) || 0
2297
+ };
2298
+ } catch (error) {
2299
+ throw new MastraError(
2300
+ {
2301
+ id: "MASTRA_STORAGE_MSSQL_INDEX_DESCRIBE_FAILED",
2302
+ domain: ErrorDomain.STORAGE,
2303
+ category: ErrorCategory.THIRD_PARTY,
2304
+ details: {
2305
+ indexName
2306
+ }
2307
+ },
2308
+ error
2309
+ );
2310
+ }
2311
+ }
2312
+ /**
2313
+ * Returns definitions for automatic performance indexes
2314
+ * IMPORTANT: Uses seq_id DESC instead of createdAt DESC for MSSQL due to millisecond accuracy limitations
2315
+ * NOTE: Using NVARCHAR(400) for text columns (800 bytes) leaves room for composite indexes
2316
+ */
2317
+ getAutomaticIndexDefinitions() {
2318
+ const schemaPrefix = this.schemaName ? `${this.schemaName}_` : "";
2319
+ return [
2320
+ // Composite indexes for optimal filtering + sorting performance
2321
+ // NVARCHAR(400) = 800 bytes, plus BIGINT (8 bytes) = 808 bytes total (under 900-byte limit)
2322
+ {
2323
+ name: `${schemaPrefix}mastra_threads_resourceid_seqid_idx`,
2324
+ table: TABLE_THREADS,
2325
+ columns: ["resourceId", "seq_id DESC"]
2326
+ },
2327
+ {
2328
+ name: `${schemaPrefix}mastra_messages_thread_id_seqid_idx`,
2329
+ table: TABLE_MESSAGES,
2330
+ columns: ["thread_id", "seq_id DESC"]
2331
+ },
2332
+ {
2333
+ name: `${schemaPrefix}mastra_traces_name_seqid_idx`,
2334
+ table: TABLE_TRACES,
2335
+ columns: ["name", "seq_id DESC"]
2336
+ },
2337
+ {
2338
+ name: `${schemaPrefix}mastra_evals_agent_name_seqid_idx`,
2339
+ table: TABLE_EVALS,
2340
+ columns: ["agent_name", "seq_id DESC"]
2341
+ },
2342
+ {
2343
+ name: `${schemaPrefix}mastra_scores_trace_id_span_id_seqid_idx`,
2344
+ table: TABLE_SCORERS,
2345
+ columns: ["traceId", "spanId", "seq_id DESC"]
2346
+ },
2347
+ // AI Spans indexes for optimal trace querying
2348
+ {
2349
+ name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
2350
+ table: TABLE_AI_SPANS,
2351
+ columns: ["traceId", "startedAt DESC"]
2352
+ },
2353
+ {
2354
+ name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
2355
+ table: TABLE_AI_SPANS,
2356
+ columns: ["parentSpanId", "startedAt DESC"]
2357
+ },
2358
+ {
2359
+ name: `${schemaPrefix}mastra_ai_spans_name_idx`,
2360
+ table: TABLE_AI_SPANS,
2361
+ columns: ["name"]
2362
+ },
2363
+ {
2364
+ name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
2365
+ table: TABLE_AI_SPANS,
2366
+ columns: ["spanType", "startedAt DESC"]
2367
+ }
2368
+ ];
2369
+ }
2370
+ /**
2371
+ * Creates automatic indexes for optimal query performance
2372
+ * Uses getAutomaticIndexDefinitions() to determine which indexes to create
2373
+ */
2374
+ async createAutomaticIndexes() {
2375
+ try {
2376
+ const indexes = this.getAutomaticIndexDefinitions();
2377
+ for (const indexOptions of indexes) {
2378
+ try {
2379
+ await this.createIndex(indexOptions);
2380
+ } catch (error) {
2381
+ this.logger?.warn?.(`Failed to create index ${indexOptions.name}:`, error);
2382
+ }
2383
+ }
2384
+ } catch (error) {
2385
+ throw new MastraError(
2386
+ {
2387
+ id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_PERFORMANCE_INDEXES_FAILED",
2388
+ domain: ErrorDomain.STORAGE,
2389
+ category: ErrorCategory.THIRD_PARTY
2390
+ },
2391
+ error
2392
+ );
2393
+ }
2394
+ }
2395
+ };
2396
+ function transformScoreRow(row) {
2397
+ return {
2398
+ ...row,
2399
+ input: safelyParseJSON(row.input),
2400
+ scorer: safelyParseJSON(row.scorer),
2401
+ preprocessStepResult: safelyParseJSON(row.preprocessStepResult),
2402
+ analyzeStepResult: safelyParseJSON(row.analyzeStepResult),
2403
+ metadata: safelyParseJSON(row.metadata),
2404
+ output: safelyParseJSON(row.output),
2405
+ additionalContext: safelyParseJSON(row.additionalContext),
2406
+ runtimeContext: safelyParseJSON(row.runtimeContext),
2407
+ entity: safelyParseJSON(row.entity),
2408
+ createdAt: row.createdAt,
2409
+ updatedAt: row.updatedAt
2410
+ };
2411
+ }
2412
+ var ScoresMSSQL = class extends ScoresStorage {
2413
+ pool;
2414
+ operations;
2415
+ schema;
2416
+ constructor({
2417
+ pool,
2418
+ operations,
2419
+ schema
2420
+ }) {
2421
+ super();
2422
+ this.pool = pool;
2423
+ this.operations = operations;
2424
+ this.schema = schema;
2425
+ }
2426
+ async getScoreById({ id }) {
2427
+ try {
2428
+ const request = this.pool.request();
2429
+ request.input("p1", id);
2430
+ const result = await request.query(
2431
+ `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE id = @p1`
2432
+ );
2433
+ if (result.recordset.length === 0) {
2434
+ return null;
2435
+ }
2436
+ return transformScoreRow(result.recordset[0]);
2437
+ } catch (error) {
2438
+ throw new MastraError(
2439
+ {
2440
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORE_BY_ID_FAILED",
2441
+ domain: ErrorDomain.STORAGE,
2442
+ category: ErrorCategory.THIRD_PARTY,
2443
+ details: { id }
2444
+ },
2445
+ error
2446
+ );
2447
+ }
2448
+ }
2449
+ async saveScore(score) {
2450
+ let validatedScore;
2451
+ try {
2452
+ validatedScore = saveScorePayloadSchema.parse(score);
2453
+ } catch (error) {
2454
+ throw new MastraError(
2455
+ {
2456
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_VALIDATION_FAILED",
2457
+ domain: ErrorDomain.STORAGE,
2458
+ category: ErrorCategory.THIRD_PARTY
2459
+ },
2460
+ error
2461
+ );
2462
+ }
2463
+ try {
2464
+ const scoreId = randomUUID();
2465
+ const {
2466
+ scorer,
2467
+ preprocessStepResult,
2468
+ analyzeStepResult,
2469
+ metadata,
2470
+ input,
2471
+ output,
2472
+ additionalContext,
2473
+ runtimeContext,
2474
+ entity,
2475
+ ...rest
2476
+ } = validatedScore;
2477
+ await this.operations.insert({
2478
+ tableName: TABLE_SCORERS,
2479
+ record: {
2480
+ id: scoreId,
2481
+ ...rest,
2482
+ input: input || "",
2483
+ output: output || "",
2484
+ preprocessStepResult: preprocessStepResult || null,
2485
+ analyzeStepResult: analyzeStepResult || null,
2486
+ metadata: metadata || null,
2487
+ additionalContext: additionalContext || null,
2488
+ runtimeContext: runtimeContext || null,
2489
+ entity: entity || null,
2490
+ scorer: scorer || null,
2491
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2492
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2493
+ }
2494
+ });
2495
+ const scoreFromDb = await this.getScoreById({ id: scoreId });
2496
+ return { score: scoreFromDb };
2497
+ } catch (error) {
2498
+ throw new MastraError(
2499
+ {
2500
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_FAILED",
2501
+ domain: ErrorDomain.STORAGE,
2502
+ category: ErrorCategory.THIRD_PARTY
2503
+ },
2504
+ error
2505
+ );
2506
+ }
2507
+ }
2508
+ async getScoresByScorerId({
2509
+ scorerId,
2510
+ pagination,
2511
+ entityId,
2512
+ entityType,
2513
+ source
2514
+ }) {
2515
+ try {
2516
+ const conditions = ["[scorerId] = @p1"];
2517
+ const params = { p1: scorerId };
2518
+ let paramIndex = 2;
2519
+ if (entityId) {
2520
+ conditions.push(`[entityId] = @p${paramIndex}`);
2521
+ params[`p${paramIndex}`] = entityId;
2522
+ paramIndex++;
2523
+ }
2524
+ if (entityType) {
2525
+ conditions.push(`[entityType] = @p${paramIndex}`);
2526
+ params[`p${paramIndex}`] = entityType;
2527
+ paramIndex++;
2528
+ }
2529
+ if (source) {
2530
+ conditions.push(`[source] = @p${paramIndex}`);
2531
+ params[`p${paramIndex}`] = source;
2532
+ paramIndex++;
2533
+ }
2534
+ const whereClause = conditions.join(" AND ");
2535
+ const tableName = getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) });
2536
+ const countRequest = this.pool.request();
2537
+ Object.entries(params).forEach(([key, value]) => {
2538
+ countRequest.input(key, value);
2539
+ });
2540
+ const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
2541
+ const total = totalResult.recordset[0]?.count || 0;
2542
+ if (total === 0) {
2543
+ return {
2544
+ pagination: {
2545
+ total: 0,
2546
+ page: pagination.page,
2547
+ perPage: pagination.perPage,
2548
+ hasMore: false
2549
+ },
2550
+ scores: []
2551
+ };
2552
+ }
2553
+ const dataRequest = this.pool.request();
2554
+ Object.entries(params).forEach(([key, value]) => {
2555
+ dataRequest.input(key, value);
2556
+ });
2557
+ dataRequest.input("perPage", pagination.perPage);
2558
+ dataRequest.input("offset", pagination.page * pagination.perPage);
2559
+ const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2560
+ const result = await dataRequest.query(dataQuery);
2561
+ return {
2562
+ pagination: {
2563
+ total: Number(total),
2564
+ page: pagination.page,
2565
+ perPage: pagination.perPage,
2566
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2567
+ },
2568
+ scores: result.recordset.map((row) => transformScoreRow(row))
2569
+ };
2570
+ } catch (error) {
2571
+ throw new MastraError(
2572
+ {
2573
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
2574
+ domain: ErrorDomain.STORAGE,
2575
+ category: ErrorCategory.THIRD_PARTY,
2576
+ details: { scorerId }
2577
+ },
2578
+ error
2579
+ );
2580
+ }
2581
+ }
2582
+ async getScoresByRunId({
2583
+ runId,
2584
+ pagination
2585
+ }) {
2586
+ try {
2587
+ const request = this.pool.request();
2588
+ request.input("p1", runId);
2589
+ const totalResult = await request.query(
2590
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
2591
+ );
2592
+ const total = totalResult.recordset[0]?.count || 0;
2593
+ if (total === 0) {
2594
+ return {
2595
+ pagination: {
2596
+ total: 0,
2597
+ page: pagination.page,
2598
+ perPage: pagination.perPage,
2599
+ hasMore: false
2600
+ },
2601
+ scores: []
2602
+ };
2603
+ }
2604
+ const dataRequest = this.pool.request();
2605
+ dataRequest.input("p1", runId);
2606
+ dataRequest.input("p2", pagination.perPage);
2607
+ dataRequest.input("p3", pagination.page * pagination.perPage);
2608
+ const result = await dataRequest.query(
2609
+ `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1 ORDER BY [createdAt] DESC OFFSET @p3 ROWS FETCH NEXT @p2 ROWS ONLY`
2610
+ );
2611
+ return {
2612
+ pagination: {
2613
+ total: Number(total),
2614
+ page: pagination.page,
2615
+ perPage: pagination.perPage,
2616
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2617
+ },
2618
+ scores: result.recordset.map((row) => transformScoreRow(row))
2619
+ };
2620
+ } catch (error) {
2621
+ throw new MastraError(
2622
+ {
2623
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_RUN_ID_FAILED",
2624
+ domain: ErrorDomain.STORAGE,
2625
+ category: ErrorCategory.THIRD_PARTY,
2626
+ details: { runId }
2627
+ },
2628
+ error
2629
+ );
2630
+ }
2631
+ }
2632
+ async getScoresByEntityId({
2633
+ entityId,
2634
+ entityType,
2635
+ pagination
2636
+ }) {
2637
+ try {
2638
+ const request = this.pool.request();
2639
+ request.input("p1", entityId);
2640
+ request.input("p2", entityType);
2641
+ const totalResult = await request.query(
2642
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
2643
+ );
2644
+ const total = totalResult.recordset[0]?.count || 0;
2645
+ if (total === 0) {
2646
+ return {
2647
+ pagination: {
2648
+ total: 0,
2649
+ page: pagination.page,
2650
+ perPage: pagination.perPage,
2651
+ hasMore: false
2652
+ },
2653
+ scores: []
2654
+ };
2655
+ }
2656
+ const dataRequest = this.pool.request();
2657
+ dataRequest.input("p1", entityId);
2658
+ dataRequest.input("p2", entityType);
2659
+ dataRequest.input("p3", pagination.perPage);
2660
+ dataRequest.input("p4", pagination.page * pagination.perPage);
2661
+ const result = await dataRequest.query(
2662
+ `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
2663
+ );
2664
+ return {
2665
+ pagination: {
2666
+ total: Number(total),
2667
+ page: pagination.page,
2668
+ perPage: pagination.perPage,
2669
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2670
+ },
2671
+ scores: result.recordset.map((row) => transformScoreRow(row))
2672
+ };
2673
+ } catch (error) {
2674
+ throw new MastraError(
2675
+ {
2676
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
2677
+ domain: ErrorDomain.STORAGE,
2678
+ category: ErrorCategory.THIRD_PARTY,
2679
+ details: { entityId, entityType }
2680
+ },
2681
+ error
2682
+ );
2683
+ }
2684
+ }
2685
+ async getScoresBySpan({
2686
+ traceId,
2687
+ spanId,
2688
+ pagination
2689
+ }) {
2690
+ try {
2691
+ const request = this.pool.request();
2692
+ request.input("p1", traceId);
2693
+ request.input("p2", spanId);
2694
+ const totalResult = await request.query(
2695
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
2696
+ );
2697
+ const total = totalResult.recordset[0]?.count || 0;
2698
+ if (total === 0) {
2699
+ return {
2700
+ pagination: {
2701
+ total: 0,
2702
+ page: pagination.page,
2703
+ perPage: pagination.perPage,
2704
+ hasMore: false
2705
+ },
2706
+ scores: []
2707
+ };
2708
+ }
2709
+ const limit = pagination.perPage + 1;
2710
+ const dataRequest = this.pool.request();
2711
+ dataRequest.input("p1", traceId);
2712
+ dataRequest.input("p2", spanId);
2713
+ dataRequest.input("p3", limit);
2714
+ dataRequest.input("p4", pagination.page * pagination.perPage);
2715
+ const result = await dataRequest.query(
2716
+ `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
2717
+ );
2718
+ return {
2719
+ pagination: {
2720
+ total: Number(total),
2721
+ page: pagination.page,
2722
+ perPage: pagination.perPage,
2723
+ hasMore: result.recordset.length > pagination.perPage
2724
+ },
2725
+ scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
2726
+ };
2727
+ } catch (error) {
2728
+ throw new MastraError(
2729
+ {
2730
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SPAN_FAILED",
2731
+ domain: ErrorDomain.STORAGE,
2732
+ category: ErrorCategory.THIRD_PARTY,
2733
+ details: { traceId, spanId }
2734
+ },
2735
+ error
2736
+ );
2737
+ }
2738
+ }
2739
+ };
2740
+ var WorkflowsMSSQL = class extends WorkflowsStorage {
2741
+ pool;
2742
+ operations;
2743
+ schema;
2744
+ constructor({
2745
+ pool,
2746
+ operations,
2747
+ schema
2748
+ }) {
2749
+ super();
2750
+ this.pool = pool;
2751
+ this.operations = operations;
2752
+ this.schema = schema;
2753
+ }
2754
+ parseWorkflowRun(row) {
2755
+ let parsedSnapshot = row.snapshot;
2756
+ if (typeof parsedSnapshot === "string") {
2757
+ try {
2758
+ parsedSnapshot = JSON.parse(row.snapshot);
2759
+ } catch (e) {
2760
+ this.logger?.warn?.(`Failed to parse snapshot for workflow ${row.workflow_name}:`, e);
2761
+ }
2762
+ }
2763
+ return {
2764
+ workflowName: row.workflow_name,
2765
+ runId: row.run_id,
2766
+ snapshot: parsedSnapshot,
2767
+ createdAt: row.createdAt,
2768
+ updatedAt: row.updatedAt,
2769
+ resourceId: row.resourceId
2770
+ };
2771
+ }
2772
+ async updateWorkflowResults({
2773
+ workflowName,
2774
+ runId,
2775
+ stepId,
2776
+ result,
2777
+ runtimeContext
2778
+ }) {
2779
+ const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2780
+ const transaction = this.pool.transaction();
2781
+ try {
2782
+ await transaction.begin();
2783
+ const selectRequest = new sql3.Request(transaction);
2784
+ selectRequest.input("workflow_name", workflowName);
2785
+ selectRequest.input("run_id", runId);
2786
+ const existingSnapshotResult = await selectRequest.query(
2787
+ `SELECT snapshot FROM ${table} WITH (UPDLOCK, HOLDLOCK) WHERE workflow_name = @workflow_name AND run_id = @run_id`
2788
+ );
2789
+ let snapshot;
2790
+ if (!existingSnapshotResult.recordset || existingSnapshotResult.recordset.length === 0) {
2791
+ snapshot = {
2792
+ context: {},
2793
+ activePaths: [],
2794
+ timestamp: Date.now(),
2795
+ suspendedPaths: {},
2796
+ resumeLabels: {},
2797
+ serializedStepGraph: [],
2798
+ value: {},
2799
+ waitingPaths: {},
2800
+ status: "pending",
2801
+ runId,
2802
+ runtimeContext: {}
2803
+ };
2804
+ } else {
2805
+ const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
2806
+ snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
2807
+ }
2808
+ snapshot.context[stepId] = result;
2809
+ snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
2810
+ const upsertReq = new sql3.Request(transaction);
2811
+ upsertReq.input("workflow_name", workflowName);
2812
+ upsertReq.input("run_id", runId);
2813
+ upsertReq.input("snapshot", JSON.stringify(snapshot));
2814
+ upsertReq.input("createdAt", sql3.DateTime2, /* @__PURE__ */ new Date());
2815
+ upsertReq.input("updatedAt", sql3.DateTime2, /* @__PURE__ */ new Date());
2816
+ await upsertReq.query(
2817
+ `MERGE ${table} AS target
2818
+ USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
2819
+ ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
2820
+ WHEN MATCHED THEN UPDATE SET snapshot = @snapshot, [updatedAt] = @updatedAt
2821
+ WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
2822
+ VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`
2823
+ );
2824
+ await transaction.commit();
2825
+ return snapshot.context;
2826
+ } catch (error) {
2827
+ try {
2828
+ await transaction.rollback();
2829
+ } catch {
2830
+ }
2831
+ throw new MastraError(
2832
+ {
2833
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_WORKFLOW_RESULTS_FAILED",
2834
+ domain: ErrorDomain.STORAGE,
2835
+ category: ErrorCategory.THIRD_PARTY,
2836
+ details: {
2837
+ workflowName,
2838
+ runId,
2839
+ stepId
2840
+ }
2841
+ },
2842
+ error
2843
+ );
2844
+ }
2845
+ }
2846
+ async updateWorkflowState({
2847
+ workflowName,
2848
+ runId,
2849
+ opts
2850
+ }) {
2851
+ const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2852
+ const transaction = this.pool.transaction();
2853
+ try {
2854
+ await transaction.begin();
2855
+ const selectRequest = new sql3.Request(transaction);
2856
+ selectRequest.input("workflow_name", workflowName);
2857
+ selectRequest.input("run_id", runId);
2858
+ const existingSnapshotResult = await selectRequest.query(
2859
+ `SELECT snapshot FROM ${table} WITH (UPDLOCK, HOLDLOCK) WHERE workflow_name = @workflow_name AND run_id = @run_id`
2860
+ );
2861
+ if (!existingSnapshotResult.recordset || existingSnapshotResult.recordset.length === 0) {
2862
+ await transaction.rollback();
2863
+ return void 0;
2864
+ }
2865
+ const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
2866
+ const snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
2867
+ if (!snapshot || !snapshot?.context) {
2868
+ await transaction.rollback();
2869
+ throw new MastraError(
2870
+ {
2871
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_WORKFLOW_STATE_SNAPSHOT_NOT_FOUND",
2872
+ domain: ErrorDomain.STORAGE,
2873
+ category: ErrorCategory.SYSTEM,
2874
+ details: {
2875
+ workflowName,
2876
+ runId
2877
+ }
2878
+ },
2879
+ new Error(`Snapshot not found for runId ${runId}`)
2880
+ );
2881
+ }
2882
+ const updatedSnapshot = { ...snapshot, ...opts };
2883
+ const updateRequest = new sql3.Request(transaction);
2884
+ updateRequest.input("snapshot", JSON.stringify(updatedSnapshot));
2885
+ updateRequest.input("workflow_name", workflowName);
2886
+ updateRequest.input("run_id", runId);
2887
+ updateRequest.input("updatedAt", sql3.DateTime2, /* @__PURE__ */ new Date());
2888
+ await updateRequest.query(
2889
+ `UPDATE ${table} SET snapshot = @snapshot, [updatedAt] = @updatedAt WHERE workflow_name = @workflow_name AND run_id = @run_id`
2890
+ );
2891
+ await transaction.commit();
2892
+ return updatedSnapshot;
2893
+ } catch (error) {
2894
+ try {
2895
+ await transaction.rollback();
2896
+ } catch {
2897
+ }
2898
+ throw new MastraError(
2899
+ {
2900
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_WORKFLOW_STATE_FAILED",
2901
+ domain: ErrorDomain.STORAGE,
2902
+ category: ErrorCategory.THIRD_PARTY,
2903
+ details: {
2904
+ workflowName,
2905
+ runId
2906
+ }
2907
+ },
2908
+ error
2909
+ );
2910
+ }
2911
+ }
2912
+ async persistWorkflowSnapshot({
2913
+ workflowName,
2914
+ runId,
2915
+ resourceId,
2916
+ snapshot
2917
+ }) {
2918
+ const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2919
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2920
+ try {
2921
+ const request = this.pool.request();
2922
+ request.input("workflow_name", workflowName);
2923
+ request.input("run_id", runId);
2924
+ request.input("resourceId", resourceId);
2925
+ request.input("snapshot", JSON.stringify(snapshot));
2926
+ request.input("createdAt", sql3.DateTime2, new Date(now));
2927
+ request.input("updatedAt", sql3.DateTime2, new Date(now));
2928
+ const mergeSql = `MERGE INTO ${table} AS target
2929
+ USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
2930
+ ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
2931
+ WHEN MATCHED THEN UPDATE SET
2932
+ resourceId = @resourceId,
2933
+ snapshot = @snapshot,
2934
+ [updatedAt] = @updatedAt
2935
+ WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, resourceId, snapshot, [createdAt], [updatedAt])
2936
+ VALUES (@workflow_name, @run_id, @resourceId, @snapshot, @createdAt, @updatedAt);`;
2937
+ await request.query(mergeSql);
2938
+ } catch (error) {
2939
+ throw new MastraError(
2940
+ {
2941
+ id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
2942
+ domain: ErrorDomain.STORAGE,
2943
+ category: ErrorCategory.THIRD_PARTY,
2944
+ details: {
2945
+ workflowName,
2946
+ runId
2947
+ }
2948
+ },
2949
+ error
2950
+ );
2951
+ }
2952
+ }
2953
+ async loadWorkflowSnapshot({
2954
+ workflowName,
2955
+ runId
2956
+ }) {
2957
+ try {
2958
+ const result = await this.operations.load({
2959
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
2960
+ keys: {
2961
+ workflow_name: workflowName,
2962
+ run_id: runId
2963
+ }
2964
+ });
2965
+ if (!result) {
2966
+ return null;
2967
+ }
2968
+ return result.snapshot;
2969
+ } catch (error) {
2970
+ throw new MastraError(
2971
+ {
2972
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
2973
+ domain: ErrorDomain.STORAGE,
2974
+ category: ErrorCategory.THIRD_PARTY,
2975
+ details: {
2976
+ workflowName,
2977
+ runId
2978
+ }
2979
+ },
2980
+ error
2981
+ );
2982
+ }
2983
+ }
2984
+ async getWorkflowRunById({
2985
+ runId,
2986
+ workflowName
2987
+ }) {
2988
+ try {
2989
+ const conditions = [];
2990
+ const paramMap = {};
2991
+ if (runId) {
2992
+ conditions.push(`[run_id] = @runId`);
2993
+ paramMap["runId"] = runId;
2994
+ }
2995
+ if (workflowName) {
2996
+ conditions.push(`[workflow_name] = @workflowName`);
2997
+ paramMap["workflowName"] = workflowName;
2998
+ }
2999
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3000
+ const tableName = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
3001
+ const query = `SELECT * FROM ${tableName} ${whereClause}`;
3002
+ const request = this.pool.request();
3003
+ Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
3004
+ const result = await request.query(query);
3005
+ if (!result.recordset || result.recordset.length === 0) {
3006
+ return null;
3007
+ }
3008
+ return this.parseWorkflowRun(result.recordset[0]);
3009
+ } catch (error) {
3010
+ throw new MastraError(
3011
+ {
3012
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
3013
+ domain: ErrorDomain.STORAGE,
3014
+ category: ErrorCategory.THIRD_PARTY,
3015
+ details: {
3016
+ runId,
3017
+ workflowName: workflowName || ""
3018
+ }
3019
+ },
3020
+ error
3021
+ );
3022
+ }
3023
+ }
3024
+ async getWorkflowRuns({
3025
+ workflowName,
3026
+ fromDate,
3027
+ toDate,
3028
+ limit,
3029
+ offset,
3030
+ resourceId
3031
+ } = {}) {
3032
+ try {
3033
+ const conditions = [];
3034
+ const paramMap = {};
3035
+ if (workflowName) {
3036
+ conditions.push(`[workflow_name] = @workflowName`);
3037
+ paramMap["workflowName"] = workflowName;
3038
+ }
3039
+ if (resourceId) {
3040
+ const hasResourceId = await this.operations.hasColumn(TABLE_WORKFLOW_SNAPSHOT, "resourceId");
3041
+ if (hasResourceId) {
3042
+ conditions.push(`[resourceId] = @resourceId`);
3043
+ paramMap["resourceId"] = resourceId;
3044
+ } else {
3045
+ this.logger?.warn?.(`[${TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
3046
+ }
3047
+ }
3048
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
3049
+ conditions.push(`[createdAt] >= @fromDate`);
3050
+ paramMap[`fromDate`] = fromDate.toISOString();
3051
+ }
3052
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
3053
+ conditions.push(`[createdAt] <= @toDate`);
3054
+ paramMap[`toDate`] = toDate.toISOString();
3055
+ }
3056
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3057
+ let total = 0;
3058
+ const tableName = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
3059
+ const request = this.pool.request();
3060
+ Object.entries(paramMap).forEach(([key, value]) => {
3061
+ if (value instanceof Date) {
3062
+ request.input(key, sql3.DateTime, value);
3063
+ } else {
3064
+ request.input(key, value);
3065
+ }
3066
+ });
3067
+ if (limit !== void 0 && offset !== void 0) {
3068
+ const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
3069
+ const countResult = await request.query(countQuery);
3070
+ total = Number(countResult.recordset[0]?.count || 0);
3071
+ }
3072
+ let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
3073
+ if (limit !== void 0 && offset !== void 0) {
3074
+ query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
3075
+ request.input("limit", limit);
3076
+ request.input("offset", offset);
3077
+ }
3078
+ const result = await request.query(query);
3079
+ const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
3080
+ return { runs, total: total || runs.length };
3081
+ } catch (error) {
3082
+ throw new MastraError(
3083
+ {
3084
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
3085
+ domain: ErrorDomain.STORAGE,
3086
+ category: ErrorCategory.THIRD_PARTY,
3087
+ details: {
3088
+ workflowName: workflowName || "all"
3089
+ }
3090
+ },
3091
+ error
3092
+ );
3093
+ }
3094
+ }
3095
+ };
3096
+
3097
+ // src/storage/index.ts
3098
+ var MSSQLStore = class extends MastraStorage {
3099
+ pool;
3100
+ schema;
3101
+ isConnected = null;
3102
+ stores;
3103
+ constructor(config) {
3104
+ super({ name: "MSSQLStore" });
3105
+ try {
3106
+ if ("connectionString" in config) {
3107
+ if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
3108
+ throw new Error("MSSQLStore: connectionString must be provided and cannot be empty.");
3109
+ }
3110
+ } else {
3111
+ const required = ["server", "database", "user", "password"];
3112
+ for (const key of required) {
3113
+ if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
3114
+ throw new Error(`MSSQLStore: ${key} must be provided and cannot be empty.`);
3115
+ }
3116
+ }
3117
+ }
3118
+ this.schema = config.schemaName || "dbo";
3119
+ this.pool = "connectionString" in config ? new sql3.ConnectionPool(config.connectionString) : new sql3.ConnectionPool({
3120
+ server: config.server,
3121
+ database: config.database,
3122
+ user: config.user,
3123
+ password: config.password,
3124
+ port: config.port,
3125
+ options: config.options || { encrypt: true, trustServerCertificate: true }
3126
+ });
3127
+ const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
3128
+ const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
3129
+ const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
3130
+ const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
3131
+ const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
3132
+ const observability = new ObservabilityMSSQL({ pool: this.pool, operations, schema: this.schema });
3133
+ this.stores = {
3134
+ operations,
3135
+ scores,
3136
+ workflows,
3137
+ legacyEvals,
3138
+ memory,
3139
+ observability
3140
+ };
3141
+ } catch (e) {
3142
+ throw new MastraError(
3143
+ {
3144
+ id: "MASTRA_STORAGE_MSSQL_STORE_INITIALIZATION_FAILED",
3145
+ domain: ErrorDomain.STORAGE,
3146
+ category: ErrorCategory.USER
3147
+ },
3148
+ e
3149
+ );
3150
+ }
3151
+ }
3152
+ async init() {
3153
+ if (this.isConnected === null) {
3154
+ this.isConnected = this._performInitializationAndStore();
3155
+ }
3156
+ try {
3157
+ await this.isConnected;
3158
+ await super.init();
3159
+ try {
3160
+ await this.stores.operations.createAutomaticIndexes();
3161
+ } catch (indexError) {
3162
+ this.logger?.warn?.("Failed to create indexes:", indexError);
3163
+ }
3164
+ } catch (error) {
3165
+ this.isConnected = null;
3166
+ throw new MastraError(
3167
+ {
3168
+ id: "MASTRA_STORAGE_MSSQL_STORE_INIT_FAILED",
3169
+ domain: ErrorDomain.STORAGE,
3170
+ category: ErrorCategory.THIRD_PARTY
3171
+ },
3172
+ error
3173
+ );
3174
+ }
3175
+ }
3176
+ async _performInitializationAndStore() {
3177
+ try {
3178
+ await this.pool.connect();
3179
+ return true;
3180
+ } catch (err) {
3181
+ throw err;
3182
+ }
3183
+ }
3184
+ get supports() {
3185
+ return {
3186
+ selectByIncludeResourceScope: true,
3187
+ resourceWorkingMemory: true,
3188
+ hasColumn: true,
3189
+ createTable: true,
3190
+ deleteMessages: true,
3191
+ getScoresBySpan: true,
3192
+ aiTracing: true,
3193
+ indexManagement: true
3194
+ };
3195
+ }
3196
+ /** @deprecated use getEvals instead */
3197
+ async getEvalsByAgentName(agentName, type) {
3198
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3199
+ }
3200
+ async getEvals(options = {}) {
3201
+ return this.stores.legacyEvals.getEvals(options);
3202
+ }
3203
+ async createTable({
3204
+ tableName,
3205
+ schema
3206
+ }) {
3207
+ return this.stores.operations.createTable({ tableName, schema });
3208
+ }
3209
+ async alterTable({
3210
+ tableName,
3211
+ schema,
3212
+ ifNotExists
3213
+ }) {
3214
+ return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
3215
+ }
3216
+ async clearTable({ tableName }) {
3217
+ return this.stores.operations.clearTable({ tableName });
3218
+ }
3219
+ async dropTable({ tableName }) {
3220
+ return this.stores.operations.dropTable({ tableName });
3221
+ }
3222
+ async insert({ tableName, record }) {
3223
+ return this.stores.operations.insert({ tableName, record });
3224
+ }
3225
+ async batchInsert({ tableName, records }) {
3226
+ return this.stores.operations.batchInsert({ tableName, records });
3227
+ }
3228
+ async load({ tableName, keys }) {
3229
+ return this.stores.operations.load({ tableName, keys });
3230
+ }
3231
+ /**
3232
+ * Memory
3233
+ */
3234
+ async getThreadById({ threadId }) {
3235
+ return this.stores.memory.getThreadById({ threadId });
3236
+ }
3237
+ /**
3238
+ * @deprecated use getThreadsByResourceIdPaginated instead
3239
+ */
3240
+ async getThreadsByResourceId(args) {
3241
+ return this.stores.memory.getThreadsByResourceId(args);
3242
+ }
3243
+ async getThreadsByResourceIdPaginated(args) {
3244
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
3245
+ }
3246
+ async saveThread({ thread }) {
3247
+ return this.stores.memory.saveThread({ thread });
3248
+ }
3249
+ async updateThread({
3250
+ id,
3251
+ title,
3252
+ metadata
3253
+ }) {
3254
+ return this.stores.memory.updateThread({ id, title, metadata });
3255
+ }
3256
+ async deleteThread({ threadId }) {
3257
+ return this.stores.memory.deleteThread({ threadId });
3258
+ }
3259
+ async getMessages(args) {
3260
+ return this.stores.memory.getMessages(args);
3261
+ }
3262
+ async getMessagesById({
3263
+ messageIds,
3264
+ format
3265
+ }) {
3266
+ return this.stores.memory.getMessagesById({ messageIds, format });
3267
+ }
3268
+ async getMessagesPaginated(args) {
3269
+ return this.stores.memory.getMessagesPaginated(args);
3270
+ }
3271
+ async saveMessages(args) {
3272
+ return this.stores.memory.saveMessages(args);
3273
+ }
3274
+ async updateMessages({
3275
+ messages
3276
+ }) {
3277
+ return this.stores.memory.updateMessages({ messages });
3278
+ }
3279
+ async deleteMessages(messageIds) {
3280
+ return this.stores.memory.deleteMessages(messageIds);
3281
+ }
3282
+ async getResourceById({ resourceId }) {
3283
+ return this.stores.memory.getResourceById({ resourceId });
3284
+ }
3285
+ async saveResource({ resource }) {
3286
+ return this.stores.memory.saveResource({ resource });
3287
+ }
3288
+ async updateResource({
3289
+ resourceId,
3290
+ workingMemory,
3291
+ metadata
3292
+ }) {
3293
+ return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
3294
+ }
3295
+ /**
3296
+ * Workflows
3297
+ */
3298
+ async updateWorkflowResults({
3299
+ workflowName,
3300
+ runId,
3301
+ stepId,
3302
+ result,
3303
+ runtimeContext
3304
+ }) {
3305
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3306
+ }
3307
+ async updateWorkflowState({
3308
+ workflowName,
3309
+ runId,
3310
+ opts
3311
+ }) {
3312
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
3313
+ }
3314
+ async persistWorkflowSnapshot({
3315
+ workflowName,
3316
+ runId,
3317
+ resourceId,
3318
+ snapshot
3319
+ }) {
3320
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
3321
+ }
3322
+ async loadWorkflowSnapshot({
3323
+ workflowName,
3324
+ runId
3325
+ }) {
3326
+ return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3327
+ }
3328
+ async getWorkflowRuns({
3329
+ workflowName,
3330
+ fromDate,
3331
+ toDate,
3332
+ limit,
3333
+ offset,
3334
+ resourceId
3335
+ } = {}) {
3336
+ return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
3337
+ }
3338
+ async getWorkflowRunById({
3339
+ runId,
3340
+ workflowName
3341
+ }) {
3342
+ return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
3343
+ }
3344
+ async close() {
3345
+ await this.pool.close();
3346
+ }
3347
+ /**
3348
+ * Index Management
3349
+ */
3350
+ async createIndex(options) {
3351
+ return this.stores.operations.createIndex(options);
3352
+ }
3353
+ async listIndexes(tableName) {
3354
+ return this.stores.operations.listIndexes(tableName);
3355
+ }
3356
+ async describeIndex(indexName) {
3357
+ return this.stores.operations.describeIndex(indexName);
3358
+ }
3359
+ async dropIndex(indexName) {
3360
+ return this.stores.operations.dropIndex(indexName);
3361
+ }
3362
+ /**
3363
+ * AI Tracing / Observability
3364
+ */
3365
+ getObservabilityStore() {
3366
+ if (!this.stores.observability) {
3367
+ throw new MastraError({
3368
+ id: "MSSQL_STORE_OBSERVABILITY_NOT_INITIALIZED",
3369
+ domain: ErrorDomain.STORAGE,
3370
+ category: ErrorCategory.SYSTEM,
3371
+ text: "Observability storage is not initialized"
3372
+ });
3373
+ }
3374
+ return this.stores.observability;
3375
+ }
3376
+ async createAISpan(span) {
3377
+ return this.getObservabilityStore().createAISpan(span);
3378
+ }
3379
+ async updateAISpan({
3380
+ spanId,
3381
+ traceId,
3382
+ updates
3383
+ }) {
3384
+ return this.getObservabilityStore().updateAISpan({ spanId, traceId, updates });
3385
+ }
3386
+ async getAITrace(traceId) {
3387
+ return this.getObservabilityStore().getAITrace(traceId);
3388
+ }
3389
+ async getAITracesPaginated(args) {
3390
+ return this.getObservabilityStore().getAITracesPaginated(args);
3391
+ }
3392
+ async batchCreateAISpans(args) {
3393
+ return this.getObservabilityStore().batchCreateAISpans(args);
3394
+ }
3395
+ async batchUpdateAISpans(args) {
3396
+ return this.getObservabilityStore().batchUpdateAISpans(args);
3397
+ }
3398
+ async batchDeleteAITraces(args) {
3399
+ return this.getObservabilityStore().batchDeleteAITraces(args);
3400
+ }
3401
+ /**
3402
+ * Scorers
3403
+ */
3404
+ async getScoreById({ id: _id }) {
3405
+ return this.stores.scores.getScoreById({ id: _id });
3406
+ }
3407
+ async getScoresByScorerId({
3408
+ scorerId: _scorerId,
3409
+ pagination: _pagination,
3410
+ entityId: _entityId,
3411
+ entityType: _entityType,
3412
+ source: _source
3413
+ }) {
3414
+ return this.stores.scores.getScoresByScorerId({
3415
+ scorerId: _scorerId,
3416
+ pagination: _pagination,
3417
+ entityId: _entityId,
3418
+ entityType: _entityType,
3419
+ source: _source
3420
+ });
3421
+ }
3422
+ async saveScore(_score) {
3423
+ return this.stores.scores.saveScore(_score);
3424
+ }
3425
+ async getScoresByRunId({
3426
+ runId: _runId,
3427
+ pagination: _pagination
3428
+ }) {
3429
+ return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3430
+ }
3431
+ async getScoresByEntityId({
3432
+ entityId: _entityId,
3433
+ entityType: _entityType,
3434
+ pagination: _pagination
3435
+ }) {
3436
+ return this.stores.scores.getScoresByEntityId({
3437
+ entityId: _entityId,
3438
+ entityType: _entityType,
3439
+ pagination: _pagination
3440
+ });
3441
+ }
3442
+ async getScoresBySpan({
3443
+ traceId,
3444
+ spanId,
3445
+ pagination: _pagination
3446
+ }) {
3447
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
3448
+ }
3449
+ };
1745
3450
 
1746
3451
  export { MSSQLStore };
3452
+ //# sourceMappingURL=index.js.map
3453
+ //# sourceMappingURL=index.js.map