@mastra/mssql 0.0.0-zod-v4-compat-part-2-20250822105954 → 0.0.0-zod-v4-stuff-20250825154219

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 (32) hide show
  1. package/CHANGELOG.md +129 -3
  2. package/dist/index.cjs +1617 -1104
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.ts +1 -1
  5. package/dist/index.js +1617 -1104
  6. package/dist/index.js.map +1 -1
  7. package/dist/storage/domains/legacy-evals/index.d.ts +20 -0
  8. package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
  9. package/dist/storage/domains/memory/index.d.ts +98 -0
  10. package/dist/storage/domains/memory/index.d.ts.map +1 -0
  11. package/dist/storage/domains/operations/index.d.ts +51 -0
  12. package/dist/storage/domains/operations/index.d.ts.map +1 -0
  13. package/dist/storage/domains/scores/index.d.ts +46 -0
  14. package/dist/storage/domains/scores/index.d.ts.map +1 -0
  15. package/dist/storage/domains/traces/index.d.ts +37 -0
  16. package/dist/storage/domains/traces/index.d.ts.map +1 -0
  17. package/dist/storage/domains/utils.d.ts +6 -0
  18. package/dist/storage/domains/utils.d.ts.map +1 -0
  19. package/dist/storage/domains/workflows/index.d.ts +36 -0
  20. package/dist/storage/domains/workflows/index.d.ts.map +1 -0
  21. package/dist/storage/index.d.ts +78 -82
  22. package/dist/storage/index.d.ts.map +1 -1
  23. package/package.json +7 -6
  24. package/src/storage/domains/legacy-evals/index.ts +175 -0
  25. package/src/storage/domains/memory/index.ts +1084 -0
  26. package/src/storage/domains/operations/index.ts +401 -0
  27. package/src/storage/domains/scores/index.ts +316 -0
  28. package/src/storage/domains/traces/index.ts +212 -0
  29. package/src/storage/domains/utils.ts +12 -0
  30. package/src/storage/domains/workflows/index.ts +259 -0
  31. package/src/storage/index.ts +158 -1834
  32. package/tsup.config.ts +2 -7
package/dist/index.js CHANGED
@@ -1,127 +1,60 @@
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';
2
+ import { MastraStorage, LegacyEvalsStorage, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, ScoresStorage, TABLE_SCORERS, TracesStorage, TABLE_TRACES, WorkflowsStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, TABLE_EVALS, TABLE_THREADS, TABLE_MESSAGES } from '@mastra/core/storage';
3
+ import sql2 from 'mssql';
4
4
  import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
5
- import sql from 'mssql';
5
+ import { MessageList } from '@mastra/core/agent';
6
6
 
7
7
  // 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
- }
48
- }
49
- async init() {
50
- if (this.isConnected === null) {
51
- this.isConnected = this._performInitializationAndStore();
52
- }
8
+ function getSchemaName(schema) {
9
+ return schema ? `[${parseSqlIdentifier(schema, "schema name")}]` : void 0;
10
+ }
11
+ function getTableName({ indexName, schemaName }) {
12
+ const parsedIndexName = parseSqlIdentifier(indexName, "index name");
13
+ const quotedIndexName = `[${parsedIndexName}]`;
14
+ const quotedSchemaName = schemaName;
15
+ return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
16
+ }
17
+
18
+ // src/storage/domains/legacy-evals/index.ts
19
+ function transformEvalRow(row) {
20
+ let testInfoValue = null, resultValue = null;
21
+ if (row.test_info) {
53
22
  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
- );
23
+ testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
24
+ } catch {
66
25
  }
67
26
  }
68
- async _performInitializationAndStore() {
27
+ if (row.test_info) {
69
28
  try {
70
- await this.pool.connect();
71
- return true;
72
- } catch (err) {
73
- throw err;
29
+ resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
30
+ } catch {
74
31
  }
75
32
  }
76
- get supports() {
77
- return {
78
- selectByIncludeResourceScope: true,
79
- resourceWorkingMemory: true,
80
- hasColumn: true,
81
- createTable: true,
82
- deleteMessages: false
83
- };
84
- }
85
- getTableName(indexName) {
86
- const parsedIndexName = parseSqlIdentifier(indexName, "index name");
87
- const quotedIndexName = `[${parsedIndexName}]`;
88
- const quotedSchemaName = this.getSchemaName();
89
- return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
90
- }
91
- getSchemaName() {
92
- return this.schema ? `[${parseSqlIdentifier(this.schema, "schema name")}]` : void 0;
93
- }
94
- transformEvalRow(row) {
95
- let testInfoValue = null, resultValue = null;
96
- if (row.test_info) {
97
- try {
98
- testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
99
- } catch {
100
- }
101
- }
102
- if (row.test_info) {
103
- try {
104
- resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
105
- } catch {
106
- }
107
- }
108
- return {
109
- agentName: row.agent_name,
110
- input: row.input,
111
- output: row.output,
112
- result: resultValue,
113
- metricName: row.metric_name,
114
- instructions: row.instructions,
115
- testInfo: testInfoValue,
116
- globalRunId: row.global_run_id,
117
- runId: row.run_id,
118
- createdAt: row.created_at
119
- };
33
+ return {
34
+ agentName: row.agent_name,
35
+ input: row.input,
36
+ output: row.output,
37
+ result: resultValue,
38
+ metricName: row.metric_name,
39
+ instructions: row.instructions,
40
+ testInfo: testInfoValue,
41
+ globalRunId: row.global_run_id,
42
+ runId: row.run_id,
43
+ createdAt: row.created_at
44
+ };
45
+ }
46
+ var LegacyEvalsMSSQL = class extends LegacyEvalsStorage {
47
+ pool;
48
+ schema;
49
+ constructor({ pool, schema }) {
50
+ super();
51
+ this.pool = pool;
52
+ this.schema = schema;
120
53
  }
121
54
  /** @deprecated use getEvals instead */
122
55
  async getEvalsByAgentName(agentName, type) {
123
56
  try {
124
- let query = `SELECT * FROM ${this.getTableName(TABLE_EVALS)} WHERE agent_name = @p1`;
57
+ let query = `SELECT * FROM ${getTableName({ indexName: TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
125
58
  if (type === "test") {
126
59
  query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
127
60
  } else if (type === "live") {
@@ -132,7 +65,7 @@ var MSSQLStore = class extends MastraStorage {
132
65
  request.input("p1", agentName);
133
66
  const result = await request.query(query);
134
67
  const rows = result.recordset;
135
- return typeof this.transformEvalRow === "function" ? rows?.map((row) => this.transformEvalRow(row)) ?? [] : rows ?? [];
68
+ return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
136
69
  } catch (error) {
137
70
  if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
138
71
  return [];
@@ -141,597 +74,267 @@ var MSSQLStore = class extends MastraStorage {
141
74
  throw error;
142
75
  }
143
76
  }
144
- async batchInsert({ tableName, records }) {
145
- const transaction = this.pool.transaction();
146
- try {
147
- await transaction.begin();
148
- for (const record of records) {
149
- await this.insert({ tableName, record });
150
- }
151
- await transaction.commit();
152
- } catch (error) {
153
- await transaction.rollback();
154
- throw new MastraError(
155
- {
156
- id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
157
- domain: ErrorDomain.STORAGE,
158
- category: ErrorCategory.THIRD_PARTY,
159
- details: {
160
- tableName,
161
- numberOfRecords: records.length
162
- }
163
- },
164
- error
165
- );
166
- }
167
- }
168
- /** @deprecated use getTracesPaginated instead*/
169
- async getTraces(args) {
170
- if (args.fromDate || args.toDate) {
171
- args.dateRange = {
172
- start: args.fromDate,
173
- end: args.toDate
174
- };
175
- }
176
- const result = await this.getTracesPaginated(args);
177
- return result.traces;
178
- }
179
- async getTracesPaginated(args) {
180
- const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
77
+ async getEvals(options = {}) {
78
+ const { agentName, type, page = 0, perPage = 100, dateRange } = options;
181
79
  const fromDate = dateRange?.start;
182
80
  const toDate = dateRange?.end;
183
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
184
- const currentOffset = page * perPage;
185
- const paramMap = {};
186
- const conditions = [];
187
- let paramIndex = 1;
188
- if (name) {
189
- const paramName = `p${paramIndex++}`;
190
- conditions.push(`[name] LIKE @${paramName}`);
191
- paramMap[paramName] = `${name}%`;
192
- }
193
- if (scope) {
194
- const paramName = `p${paramIndex++}`;
195
- conditions.push(`[scope] = @${paramName}`);
196
- paramMap[paramName] = scope;
197
- }
198
- if (attributes) {
199
- Object.entries(attributes).forEach(([key, value]) => {
200
- const parsedKey = parseFieldKey(key);
201
- const paramName = `p${paramIndex++}`;
202
- conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
203
- paramMap[paramName] = value;
204
- });
81
+ const where = [];
82
+ const params = {};
83
+ if (agentName) {
84
+ where.push("agent_name = @agentName");
85
+ params["agentName"] = agentName;
205
86
  }
206
- if (filters) {
207
- Object.entries(filters).forEach(([key, value]) => {
208
- const parsedKey = parseFieldKey(key);
209
- const paramName = `p${paramIndex++}`;
210
- conditions.push(`[${parsedKey}] = @${paramName}`);
211
- paramMap[paramName] = value;
212
- });
87
+ if (type === "test") {
88
+ where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
89
+ } else if (type === "live") {
90
+ where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
213
91
  }
214
92
  if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
215
- const paramName = `p${paramIndex++}`;
216
- conditions.push(`[createdAt] >= @${paramName}`);
217
- paramMap[paramName] = fromDate.toISOString();
93
+ where.push(`[created_at] >= @fromDate`);
94
+ params[`fromDate`] = fromDate.toISOString();
218
95
  }
219
96
  if (toDate instanceof Date && !isNaN(toDate.getTime())) {
220
- const paramName = `p${paramIndex++}`;
221
- conditions.push(`[createdAt] <= @${paramName}`);
222
- paramMap[paramName] = toDate.toISOString();
97
+ where.push(`[created_at] <= @toDate`);
98
+ params[`toDate`] = toDate.toISOString();
223
99
  }
224
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
225
- const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(TABLE_TRACES)} ${whereClause}`;
226
- let total = 0;
100
+ const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
101
+ const tableName = getTableName({ indexName: TABLE_EVALS, schemaName: getSchemaName(this.schema) });
102
+ const offset = page * perPage;
103
+ const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
104
+ const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
227
105
  try {
228
- const countRequest = this.pool.request();
229
- Object.entries(paramMap).forEach(([key, value]) => {
106
+ const countReq = this.pool.request();
107
+ Object.entries(params).forEach(([key, value]) => {
230
108
  if (value instanceof Date) {
231
- countRequest.input(key, sql.DateTime, value);
109
+ countReq.input(key, sql2.DateTime, value);
232
110
  } else {
233
- countRequest.input(key, value);
111
+ countReq.input(key, value);
234
112
  }
235
113
  });
236
- const countResult = await countRequest.query(countQuery);
237
- total = parseInt(countResult.recordset[0].total, 10);
114
+ const countResult = await countReq.query(countQuery);
115
+ const total = countResult.recordset[0]?.total || 0;
116
+ if (total === 0) {
117
+ return {
118
+ evals: [],
119
+ total: 0,
120
+ page,
121
+ perPage,
122
+ hasMore: false
123
+ };
124
+ }
125
+ const req = this.pool.request();
126
+ Object.entries(params).forEach(([key, value]) => {
127
+ if (value instanceof Date) {
128
+ req.input(key, sql2.DateTime, value);
129
+ } else {
130
+ req.input(key, value);
131
+ }
132
+ });
133
+ req.input("offset", offset);
134
+ req.input("perPage", perPage);
135
+ const result = await req.query(dataQuery);
136
+ const rows = result.recordset;
137
+ return {
138
+ evals: rows?.map((row) => transformEvalRow(row)) ?? [],
139
+ total,
140
+ page,
141
+ perPage,
142
+ hasMore: offset + (rows?.length ?? 0) < total
143
+ };
238
144
  } catch (error) {
239
- throw new MastraError(
145
+ const mastraError = new MastraError(
240
146
  {
241
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
147
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
242
148
  domain: ErrorDomain.STORAGE,
243
149
  category: ErrorCategory.THIRD_PARTY,
244
150
  details: {
245
- name: args.name ?? "",
246
- scope: args.scope ?? ""
151
+ agentName: agentName || "all",
152
+ type: type || "all",
153
+ page,
154
+ perPage
247
155
  }
248
156
  },
249
157
  error
250
158
  );
159
+ this.logger?.error?.(mastraError.toString());
160
+ this.logger?.trackException(mastraError);
161
+ throw mastraError;
251
162
  }
252
- if (total === 0) {
253
- return {
254
- traces: [],
255
- total: 0,
256
- page,
257
- perPage,
258
- hasMore: false
259
- };
260
- }
261
- const dataQuery = `SELECT * FROM ${this.getTableName(TABLE_TRACES)} ${whereClause} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
262
- const dataRequest = this.pool.request();
263
- Object.entries(paramMap).forEach(([key, value]) => {
264
- if (value instanceof Date) {
265
- dataRequest.input(key, sql.DateTime, value);
266
- } else {
267
- dataRequest.input(key, value);
163
+ }
164
+ };
165
+ var MemoryMSSQL = class extends MemoryStorage {
166
+ pool;
167
+ schema;
168
+ operations;
169
+ _parseAndFormatMessages(messages, format) {
170
+ const messagesWithParsedContent = messages.map((message) => {
171
+ if (typeof message.content === "string") {
172
+ try {
173
+ return { ...message, content: JSON.parse(message.content) };
174
+ } catch {
175
+ return message;
176
+ }
268
177
  }
178
+ return message;
269
179
  });
270
- dataRequest.input("offset", currentOffset);
271
- dataRequest.input("limit", perPage);
272
- try {
273
- const rowsResult = await dataRequest.query(dataQuery);
274
- const rows = rowsResult.recordset;
275
- const traces = rows.map((row) => ({
276
- id: row.id,
277
- parentSpanId: row.parentSpanId,
278
- traceId: row.traceId,
279
- name: row.name,
280
- scope: row.scope,
281
- kind: row.kind,
282
- status: JSON.parse(row.status),
283
- events: JSON.parse(row.events),
284
- links: JSON.parse(row.links),
285
- attributes: JSON.parse(row.attributes),
286
- startTime: row.startTime,
287
- endTime: row.endTime,
288
- other: row.other,
289
- createdAt: row.createdAt
290
- }));
180
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
181
+ const list = new MessageList().add(cleanMessages, "memory");
182
+ return format === "v2" ? list.get.all.v2() : list.get.all.v1();
183
+ }
184
+ constructor({
185
+ pool,
186
+ schema,
187
+ operations
188
+ }) {
189
+ super();
190
+ this.pool = pool;
191
+ this.schema = schema;
192
+ this.operations = operations;
193
+ }
194
+ async getThreadById({ threadId }) {
195
+ try {
196
+ const sql7 = `SELECT
197
+ id,
198
+ [resourceId],
199
+ title,
200
+ metadata,
201
+ [createdAt],
202
+ [updatedAt]
203
+ FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })}
204
+ WHERE id = @threadId`;
205
+ const request = this.pool.request();
206
+ request.input("threadId", threadId);
207
+ const resultSet = await request.query(sql7);
208
+ const thread = resultSet.recordset[0] || null;
209
+ if (!thread) {
210
+ return null;
211
+ }
291
212
  return {
292
- traces,
293
- total,
294
- page,
295
- perPage,
296
- hasMore: currentOffset + traces.length < total
213
+ ...thread,
214
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
215
+ createdAt: thread.createdAt,
216
+ updatedAt: thread.updatedAt
297
217
  };
298
218
  } catch (error) {
299
219
  throw new MastraError(
300
220
  {
301
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
221
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
302
222
  domain: ErrorDomain.STORAGE,
303
223
  category: ErrorCategory.THIRD_PARTY,
304
224
  details: {
305
- name: args.name ?? "",
306
- scope: args.scope ?? ""
225
+ threadId
307
226
  }
308
227
  },
309
228
  error
310
229
  );
311
230
  }
312
231
  }
313
- async setupSchema() {
314
- if (!this.schema || this.schemaSetupComplete) {
315
- return;
316
- }
317
- if (!this.setupSchemaPromise) {
318
- this.setupSchemaPromise = (async () => {
319
- try {
320
- const checkRequest = this.pool.request();
321
- checkRequest.input("schemaName", this.schema);
322
- const checkResult = await checkRequest.query(`
323
- SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
324
- `);
325
- const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
326
- if (!schemaExists) {
327
- try {
328
- await this.pool.request().query(`CREATE SCHEMA [${this.schema}]`);
329
- this.logger?.info?.(`Schema "${this.schema}" created successfully`);
330
- } catch (error) {
331
- this.logger?.error?.(`Failed to create schema "${this.schema}"`, { error });
332
- throw new Error(
333
- `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.`
334
- );
335
- }
336
- }
337
- this.schemaSetupComplete = true;
338
- this.logger?.debug?.(`Schema "${this.schema}" is ready for use`);
339
- } catch (error) {
340
- this.schemaSetupComplete = void 0;
341
- this.setupSchemaPromise = null;
342
- throw error;
343
- } finally {
344
- this.setupSchemaPromise = null;
345
- }
346
- })();
347
- }
348
- await this.setupSchemaPromise;
349
- }
350
- getSqlType(type, isPrimaryKey = false) {
351
- switch (type) {
352
- case "text":
353
- return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(MAX)";
354
- case "timestamp":
355
- return "DATETIME2(7)";
356
- case "uuid":
357
- return "UNIQUEIDENTIFIER";
358
- case "jsonb":
359
- return "NVARCHAR(MAX)";
360
- case "integer":
361
- return "INT";
362
- case "bigint":
363
- return "BIGINT";
364
- default:
365
- throw new MastraError({
366
- id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
367
- domain: ErrorDomain.STORAGE,
368
- category: ErrorCategory.THIRD_PARTY
369
- });
370
- }
371
- }
372
- async createTable({
373
- tableName,
374
- schema
375
- }) {
232
+ async getThreadsByResourceIdPaginated(args) {
233
+ const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
376
234
  try {
377
- const uniqueConstraintColumns = tableName === TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
378
- const columns = Object.entries(schema).map(([name, def]) => {
379
- const parsedName = parseSqlIdentifier(name, "column name");
380
- const constraints = [];
381
- if (def.primaryKey) constraints.push("PRIMARY KEY");
382
- if (!def.nullable) constraints.push("NOT NULL");
383
- const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
384
- return `[${parsedName}] ${this.getSqlType(def.type, isIndexed)} ${constraints.join(" ")}`.trim();
385
- }).join(",\n");
386
- if (this.schema) {
387
- await this.setupSchema();
388
- }
389
- const checkTableRequest = this.pool.request();
390
- checkTableRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
391
- const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
392
- checkTableRequest.input("schema", this.schema || "dbo");
393
- const checkTableResult = await checkTableRequest.query(checkTableSql);
394
- const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
395
- if (!tableExists) {
396
- const createSql = `CREATE TABLE ${this.getTableName(tableName)} (
397
- ${columns}
398
- )`;
399
- await this.pool.request().query(createSql);
400
- }
401
- const columnCheckSql = `
402
- SELECT 1 AS found
403
- FROM INFORMATION_SCHEMA.COLUMNS
404
- WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
405
- `;
406
- const checkColumnRequest = this.pool.request();
407
- checkColumnRequest.input("schema", this.schema || "dbo");
408
- checkColumnRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
409
- const columnResult = await checkColumnRequest.query(columnCheckSql);
410
- const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
411
- if (!columnExists) {
412
- const alterSql = `ALTER TABLE ${this.getTableName(tableName)} ADD seq_id BIGINT IDENTITY(1,1)`;
413
- await this.pool.request().query(alterSql);
414
- }
415
- if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
416
- const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
417
- const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
418
- const checkConstraintRequest = this.pool.request();
419
- checkConstraintRequest.input("constraintName", constraintName);
420
- const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
421
- const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
422
- if (!constraintExists) {
423
- const addConstraintSql = `ALTER TABLE ${this.getTableName(tableName)} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
424
- await this.pool.request().query(addConstraintSql);
425
- }
235
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
236
+ const currentOffset = page * perPage;
237
+ const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
238
+ const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
239
+ const countRequest = this.pool.request();
240
+ countRequest.input("resourceId", resourceId);
241
+ const countResult = await countRequest.query(countQuery);
242
+ const total = parseInt(countResult.recordset[0]?.count ?? "0", 10);
243
+ if (total === 0) {
244
+ return {
245
+ threads: [],
246
+ total: 0,
247
+ page,
248
+ perPage,
249
+ hasMore: false
250
+ };
426
251
  }
252
+ const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
253
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${sortDirection} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
254
+ const dataRequest = this.pool.request();
255
+ dataRequest.input("resourceId", resourceId);
256
+ dataRequest.input("perPage", perPage);
257
+ dataRequest.input("offset", currentOffset);
258
+ const rowsResult = await dataRequest.query(dataQuery);
259
+ const rows = rowsResult.recordset || [];
260
+ const threads = rows.map((thread) => ({
261
+ ...thread,
262
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
263
+ createdAt: thread.createdAt,
264
+ updatedAt: thread.updatedAt
265
+ }));
266
+ return {
267
+ threads,
268
+ total,
269
+ page,
270
+ perPage,
271
+ hasMore: currentOffset + threads.length < total
272
+ };
427
273
  } catch (error) {
428
- throw new MastraError(
274
+ const mastraError = new MastraError(
429
275
  {
430
- id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
276
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
431
277
  domain: ErrorDomain.STORAGE,
432
278
  category: ErrorCategory.THIRD_PARTY,
433
279
  details: {
434
- tableName
280
+ resourceId,
281
+ page
435
282
  }
436
283
  },
437
284
  error
438
285
  );
286
+ this.logger?.error?.(mastraError.toString());
287
+ this.logger?.trackException?.(mastraError);
288
+ return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
439
289
  }
440
290
  }
441
- getDefaultValue(type) {
442
- switch (type) {
443
- case "timestamp":
444
- return "DEFAULT SYSDATETIMEOFFSET()";
445
- case "jsonb":
446
- return "DEFAULT N'{}'";
447
- default:
448
- return super.getDefaultValue(type);
449
- }
450
- }
451
- async alterTable({
452
- tableName,
453
- schema,
454
- ifNotExists
455
- }) {
456
- const fullTableName = this.getTableName(tableName);
291
+ async saveThread({ thread }) {
457
292
  try {
458
- for (const columnName of ifNotExists) {
459
- if (schema[columnName]) {
460
- const columnCheckRequest = this.pool.request();
461
- columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
462
- columnCheckRequest.input("columnName", columnName);
463
- columnCheckRequest.input("schema", this.schema || "dbo");
464
- const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
465
- const checkResult = await columnCheckRequest.query(checkSql);
466
- const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
467
- if (!columnExists) {
468
- const columnDef = schema[columnName];
469
- const sqlType = this.getSqlType(columnDef.type);
470
- const nullable = columnDef.nullable === false ? "NOT NULL" : "";
471
- const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
472
- const parsedColumnName = parseSqlIdentifier(columnName, "column name");
473
- const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
474
- await this.pool.request().query(alterSql);
475
- this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
476
- }
477
- }
478
- }
293
+ const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
294
+ const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
295
+ USING (SELECT @id AS id) AS source
296
+ ON (target.id = source.id)
297
+ WHEN MATCHED THEN
298
+ UPDATE SET
299
+ [resourceId] = @resourceId,
300
+ title = @title,
301
+ metadata = @metadata,
302
+ [updatedAt] = @updatedAt
303
+ WHEN NOT MATCHED THEN
304
+ INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
305
+ VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
306
+ const req = this.pool.request();
307
+ req.input("id", thread.id);
308
+ req.input("resourceId", thread.resourceId);
309
+ req.input("title", thread.title);
310
+ req.input("metadata", thread.metadata ? JSON.stringify(thread.metadata) : null);
311
+ req.input("createdAt", sql2.DateTime2, thread.createdAt);
312
+ req.input("updatedAt", sql2.DateTime2, thread.updatedAt);
313
+ await req.query(mergeSql);
314
+ return thread;
479
315
  } catch (error) {
480
316
  throw new MastraError(
481
317
  {
482
- id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
318
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
483
319
  domain: ErrorDomain.STORAGE,
484
320
  category: ErrorCategory.THIRD_PARTY,
485
321
  details: {
486
- tableName
322
+ threadId: thread.id
487
323
  }
488
324
  },
489
325
  error
490
326
  );
491
327
  }
492
328
  }
493
- async clearTable({ tableName }) {
494
- const fullTableName = this.getTableName(tableName);
329
+ /**
330
+ * @deprecated use getThreadsByResourceIdPaginated instead
331
+ */
332
+ async getThreadsByResourceId(args) {
333
+ const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
495
334
  try {
496
- const fkQuery = `
497
- SELECT
498
- OBJECT_SCHEMA_NAME(fk.parent_object_id) AS schema_name,
499
- OBJECT_NAME(fk.parent_object_id) AS table_name
500
- FROM sys.foreign_keys fk
501
- WHERE fk.referenced_object_id = OBJECT_ID(@fullTableName)
502
- `;
503
- const fkResult = await this.pool.request().input("fullTableName", fullTableName).query(fkQuery);
504
- const childTables = fkResult.recordset || [];
505
- for (const child of childTables) {
506
- const childTableName = this.schema ? `[${child.schema_name}].[${child.table_name}]` : `[${child.table_name}]`;
507
- await this.clearTable({ tableName: childTableName });
508
- }
509
- await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
510
- } catch (error) {
511
- throw new MastraError(
512
- {
513
- id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
514
- domain: ErrorDomain.STORAGE,
515
- category: ErrorCategory.THIRD_PARTY,
516
- details: {
517
- tableName
518
- }
519
- },
520
- error
521
- );
522
- }
523
- }
524
- async insert({ tableName, record }) {
525
- try {
526
- const columns = Object.keys(record).map((col) => parseSqlIdentifier(col, "column name"));
527
- const values = Object.values(record);
528
- const paramNames = values.map((_, i) => `@param${i}`);
529
- const insertSql = `INSERT INTO ${this.getTableName(tableName)} (${columns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
530
- const request = this.pool.request();
531
- values.forEach((value, i) => {
532
- if (value instanceof Date) {
533
- request.input(`param${i}`, sql.DateTime2, value);
534
- } else if (typeof value === "object" && value !== null) {
535
- request.input(`param${i}`, JSON.stringify(value));
536
- } else {
537
- request.input(`param${i}`, value);
538
- }
539
- });
540
- await request.query(insertSql);
541
- } catch (error) {
542
- throw new MastraError(
543
- {
544
- id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
545
- domain: ErrorDomain.STORAGE,
546
- category: ErrorCategory.THIRD_PARTY,
547
- details: {
548
- tableName
549
- }
550
- },
551
- error
552
- );
553
- }
554
- }
555
- async load({ tableName, keys }) {
556
- try {
557
- const keyEntries = Object.entries(keys).map(([key, value]) => [parseSqlIdentifier(key, "column name"), value]);
558
- const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
559
- const values = keyEntries.map(([_, value]) => value);
560
- const sql2 = `SELECT * FROM ${this.getTableName(tableName)} WHERE ${conditions}`;
561
- const request = this.pool.request();
562
- values.forEach((value, i) => {
563
- request.input(`param${i}`, value);
564
- });
565
- const resultSet = await request.query(sql2);
566
- const result = resultSet.recordset[0] || null;
567
- if (!result) {
568
- return null;
569
- }
570
- if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
571
- const snapshot = result;
572
- if (typeof snapshot.snapshot === "string") {
573
- snapshot.snapshot = JSON.parse(snapshot.snapshot);
574
- }
575
- return snapshot;
576
- }
577
- return result;
578
- } catch (error) {
579
- throw new MastraError(
580
- {
581
- id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
582
- domain: ErrorDomain.STORAGE,
583
- category: ErrorCategory.THIRD_PARTY,
584
- details: {
585
- tableName
586
- }
587
- },
588
- error
589
- );
590
- }
591
- }
592
- async getThreadById({ threadId }) {
593
- try {
594
- const sql2 = `SELECT
595
- id,
596
- [resourceId],
597
- title,
598
- metadata,
599
- [createdAt],
600
- [updatedAt]
601
- FROM ${this.getTableName(TABLE_THREADS)}
602
- WHERE id = @threadId`;
603
- const request = this.pool.request();
604
- request.input("threadId", threadId);
605
- const resultSet = await request.query(sql2);
606
- const thread = resultSet.recordset[0] || null;
607
- if (!thread) {
608
- return null;
609
- }
610
- return {
611
- ...thread,
612
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
613
- createdAt: thread.createdAt,
614
- updatedAt: thread.updatedAt
615
- };
616
- } catch (error) {
617
- throw new MastraError(
618
- {
619
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
620
- domain: ErrorDomain.STORAGE,
621
- category: ErrorCategory.THIRD_PARTY,
622
- details: {
623
- threadId
624
- }
625
- },
626
- error
627
- );
628
- }
629
- }
630
- async getThreadsByResourceIdPaginated(args) {
631
- const { resourceId, page = 0, perPage: perPageInput } = args;
632
- try {
633
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
634
- const currentOffset = page * perPage;
635
- const baseQuery = `FROM ${this.getTableName(TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
636
- const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
637
- const countRequest = this.pool.request();
638
- countRequest.input("resourceId", resourceId);
639
- const countResult = await countRequest.query(countQuery);
640
- const total = parseInt(countResult.recordset[0]?.count ?? "0", 10);
641
- if (total === 0) {
642
- return {
643
- threads: [],
644
- total: 0,
645
- page,
646
- perPage,
647
- hasMore: false
648
- };
649
- }
650
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
651
- const dataRequest = this.pool.request();
652
- dataRequest.input("resourceId", resourceId);
653
- dataRequest.input("perPage", perPage);
654
- dataRequest.input("offset", currentOffset);
655
- const rowsResult = await dataRequest.query(dataQuery);
656
- const rows = rowsResult.recordset || [];
657
- const threads = rows.map((thread) => ({
658
- ...thread,
659
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
660
- createdAt: thread.createdAt,
661
- updatedAt: thread.updatedAt
662
- }));
663
- return {
664
- threads,
665
- total,
666
- page,
667
- perPage,
668
- hasMore: currentOffset + threads.length < total
669
- };
670
- } catch (error) {
671
- const mastraError = new MastraError(
672
- {
673
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
674
- domain: ErrorDomain.STORAGE,
675
- category: ErrorCategory.THIRD_PARTY,
676
- details: {
677
- resourceId,
678
- page
679
- }
680
- },
681
- error
682
- );
683
- this.logger?.error?.(mastraError.toString());
684
- this.logger?.trackException?.(mastraError);
685
- return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
686
- }
687
- }
688
- async saveThread({ thread }) {
689
- try {
690
- const table = this.getTableName(TABLE_THREADS);
691
- const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
692
- USING (SELECT @id AS id) AS source
693
- ON (target.id = source.id)
694
- WHEN MATCHED THEN
695
- UPDATE SET
696
- [resourceId] = @resourceId,
697
- title = @title,
698
- metadata = @metadata,
699
- [createdAt] = @createdAt,
700
- [updatedAt] = @updatedAt
701
- WHEN NOT MATCHED THEN
702
- INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
703
- VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
704
- const req = this.pool.request();
705
- req.input("id", thread.id);
706
- req.input("resourceId", thread.resourceId);
707
- req.input("title", thread.title);
708
- req.input("metadata", thread.metadata ? JSON.stringify(thread.metadata) : null);
709
- req.input("createdAt", thread.createdAt);
710
- req.input("updatedAt", thread.updatedAt);
711
- await req.query(mergeSql);
712
- return thread;
713
- } catch (error) {
714
- throw new MastraError(
715
- {
716
- id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
717
- domain: ErrorDomain.STORAGE,
718
- category: ErrorCategory.THIRD_PARTY,
719
- details: {
720
- threadId: thread.id
721
- }
722
- },
723
- error
724
- );
725
- }
726
- }
727
- /**
728
- * @deprecated use getThreadsByResourceIdPaginated instead
729
- */
730
- async getThreadsByResourceId(args) {
731
- const { resourceId } = args;
732
- try {
733
- const baseQuery = `FROM ${this.getTableName(TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
734
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC`;
335
+ const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
336
+ const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
337
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${sortDirection}`;
735
338
  const request = this.pool.request();
736
339
  request.input("resourceId", resourceId);
737
340
  const resultSet = await request.query(dataQuery);
@@ -773,8 +376,8 @@ ${columns}
773
376
  ...metadata
774
377
  };
775
378
  try {
776
- const table = this.getTableName(TABLE_THREADS);
777
- const sql2 = `UPDATE ${table}
379
+ const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
380
+ const sql7 = `UPDATE ${table}
778
381
  SET title = @title,
779
382
  metadata = @metadata,
780
383
  [updatedAt] = @updatedAt
@@ -784,8 +387,8 @@ ${columns}
784
387
  req.input("id", id);
785
388
  req.input("title", title);
786
389
  req.input("metadata", JSON.stringify(mergedMetadata));
787
- req.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
788
- const result = await req.query(sql2);
390
+ req.input("updatedAt", /* @__PURE__ */ new Date());
391
+ const result = await req.query(sql7);
789
392
  let thread = result.recordset && result.recordset[0];
790
393
  if (thread && "seq_id" in thread) {
791
394
  const { seq_id, ...rest } = thread;
@@ -825,8 +428,8 @@ ${columns}
825
428
  }
826
429
  }
827
430
  async deleteThread({ threadId }) {
828
- const messagesTable = this.getTableName(TABLE_MESSAGES);
829
- const threadsTable = this.getTableName(TABLE_THREADS);
431
+ const messagesTable = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
432
+ const threadsTable = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
830
433
  const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
831
434
  const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
832
435
  const tx = this.pool.transaction();
@@ -884,7 +487,7 @@ ${columns}
884
487
  m.seq_id
885
488
  FROM (
886
489
  SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
887
- FROM ${this.getTableName(TABLE_MESSAGES)}
490
+ FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
888
491
  WHERE [thread_id] = ${pThreadId}
889
492
  ) AS m
890
493
  WHERE m.id = ${pId}
@@ -892,7 +495,7 @@ ${columns}
892
495
  SELECT 1
893
496
  FROM (
894
497
  SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
895
- FROM ${this.getTableName(TABLE_MESSAGES)}
498
+ FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
896
499
  WHERE [thread_id] = ${pThreadId}
897
500
  ) AS target
898
501
  WHERE target.id = ${pId}
@@ -930,9 +533,9 @@ ${columns}
930
533
  }
931
534
  async getMessages(args) {
932
535
  const { threadId, format, selectBy } = args;
933
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
536
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
934
537
  const orderByStatement = `ORDER BY [seq_id] DESC`;
935
- const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
538
+ const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
936
539
  try {
937
540
  let rows = [];
938
541
  const include = selectBy?.include || [];
@@ -943,7 +546,7 @@ ${columns}
943
546
  }
944
547
  }
945
548
  const excludeIds = rows.map((m) => m.id).filter(Boolean);
946
- let query = `${selectStatement} FROM ${this.getTableName(TABLE_MESSAGES)} WHERE [thread_id] = @threadId`;
549
+ let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
947
550
  const request = this.pool.request();
948
551
  request.input("threadId", threadId);
949
552
  if (excludeIds.length > 0) {
@@ -963,30 +566,7 @@ ${columns}
963
566
  return timeDiff;
964
567
  });
965
568
  rows = rows.map(({ seq_id, ...rest }) => rest);
966
- const fetchedMessages = (rows || []).map((message) => {
967
- if (typeof message.content === "string") {
968
- try {
969
- message.content = JSON.parse(message.content);
970
- } catch {
971
- }
972
- }
973
- if (format === "v1") {
974
- if (Array.isArray(message.content)) ; else if (typeof message.content === "object" && message.content && Array.isArray(message.content.parts)) {
975
- message.content = message.content.parts;
976
- } else {
977
- message.content = [{ type: "text", text: "" }];
978
- }
979
- } else {
980
- if (typeof message.content !== "object" || !message.content || !("parts" in message.content)) {
981
- message.content = { format: 2, parts: [{ type: "text", text: "" }] };
982
- }
983
- }
984
- if (message.type === "v2") delete message.type;
985
- return message;
986
- });
987
- return format === "v2" ? fetchedMessages.map(
988
- (m) => ({ ...m, content: m.content || { format: 2, parts: [{ type: "text", text: "" }] } })
989
- ) : fetchedMessages;
569
+ return this._parseAndFormatMessages(rows, format);
990
570
  } catch (error) {
991
571
  const mastraError = new MastraError(
992
572
  {
@@ -1004,6 +584,46 @@ ${columns}
1004
584
  return [];
1005
585
  }
1006
586
  }
587
+ async getMessagesById({
588
+ messageIds,
589
+ format
590
+ }) {
591
+ if (messageIds.length === 0) return [];
592
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
593
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
594
+ try {
595
+ let rows = [];
596
+ let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
597
+ const request = this.pool.request();
598
+ messageIds.forEach((id, i) => request.input(`id${i}`, id));
599
+ query += ` ${orderByStatement}`;
600
+ const result = await request.query(query);
601
+ const remainingRows = result.recordset || [];
602
+ rows.push(...remainingRows);
603
+ rows.sort((a, b) => {
604
+ const timeDiff = a.seq_id - b.seq_id;
605
+ return timeDiff;
606
+ });
607
+ rows = rows.map(({ seq_id, ...rest }) => rest);
608
+ if (format === `v1`) return this._parseAndFormatMessages(rows, format);
609
+ return this._parseAndFormatMessages(rows, `v2`);
610
+ } catch (error) {
611
+ const mastraError = new MastraError(
612
+ {
613
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
614
+ domain: ErrorDomain.STORAGE,
615
+ category: ErrorCategory.THIRD_PARTY,
616
+ details: {
617
+ messageIds: JSON.stringify(messageIds)
618
+ }
619
+ },
620
+ error
621
+ );
622
+ this.logger?.error?.(mastraError.toString());
623
+ this.logger?.trackException(mastraError);
624
+ return [];
625
+ }
626
+ }
1007
627
  async getMessagesPaginated(args) {
1008
628
  const { threadId, selectBy } = args;
1009
629
  const { page = 0, perPage: perPageInput } = selectBy?.pagination || {};
@@ -1016,14 +636,14 @@ ${columns}
1016
636
  const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
1017
637
  const fromDate = dateRange?.start;
1018
638
  const toDate = dateRange?.end;
1019
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
639
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
1020
640
  const orderByStatement2 = `ORDER BY [seq_id] DESC`;
1021
641
  let messages2 = [];
1022
642
  if (selectBy2?.include?.length) {
1023
643
  const includeMessages = await this._getIncludedMessages({ threadId: threadId2, selectBy: selectBy2, orderByStatement: orderByStatement2 });
1024
644
  if (includeMessages) messages2.push(...includeMessages);
1025
645
  }
1026
- const perPage = perPageInput2 !== void 0 ? perPageInput2 : this.resolveMessageLimit({ last: selectBy2?.last, defaultLimit: 40 });
646
+ const perPage = perPageInput2 !== void 0 ? perPageInput2 : resolveMessageLimit({ last: selectBy2?.last, defaultLimit: 40 });
1027
647
  const currentOffset = page2 * perPage;
1028
648
  const conditions = ["[thread_id] = @threadId"];
1029
649
  const request = this.pool.request();
@@ -1037,7 +657,7 @@ ${columns}
1037
657
  request.input("toDate", toDate.toISOString());
1038
658
  }
1039
659
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
1040
- const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(TABLE_MESSAGES)} ${whereClause}`;
660
+ const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
1041
661
  const countResult = await request.query(countQuery);
1042
662
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
1043
663
  if (total === 0 && messages2.length > 0) {
@@ -1057,7 +677,7 @@ ${columns}
1057
677
  excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
1058
678
  }
1059
679
  const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
1060
- const dataQuery = `${selectStatement} FROM ${this.getTableName(TABLE_MESSAGES)} ${finalWhereClause} ${orderByStatement2} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
680
+ const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement2} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1061
681
  request.input("offset", currentOffset);
1062
682
  request.input("limit", perPage);
1063
683
  const rowsResult = await request.query(dataQuery);
@@ -1090,31 +710,6 @@ ${columns}
1090
710
  return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
1091
711
  }
1092
712
  }
1093
- _parseAndFormatMessages(messages, format) {
1094
- const parsedMessages = messages.map((message) => {
1095
- let parsed = message;
1096
- if (typeof parsed.content === "string") {
1097
- try {
1098
- parsed = { ...parsed, content: JSON.parse(parsed.content) };
1099
- } catch {
1100
- }
1101
- }
1102
- if (format === "v1") {
1103
- if (Array.isArray(parsed.content)) ; else if (parsed.content?.parts) {
1104
- parsed.content = parsed.content.parts;
1105
- } else {
1106
- parsed.content = [{ type: "text", text: "" }];
1107
- }
1108
- } else {
1109
- if (!parsed.content?.parts) {
1110
- parsed = { ...parsed, content: { format: 2, parts: [{ type: "text", text: "" }] } };
1111
- }
1112
- }
1113
- return parsed;
1114
- });
1115
- const list = new MessageList().add(parsedMessages, "memory");
1116
- return format === "v2" ? list.get.all.v2() : list.get.all.v1();
1117
- }
1118
713
  async saveMessages({
1119
714
  messages,
1120
715
  format
@@ -1139,8 +734,8 @@ ${columns}
1139
734
  details: { threadId }
1140
735
  });
1141
736
  }
1142
- const tableMessages = this.getTableName(TABLE_MESSAGES);
1143
- const tableThreads = this.getTableName(TABLE_THREADS);
737
+ const tableMessages = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
738
+ const tableThreads = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
1144
739
  try {
1145
740
  const transaction = this.pool.transaction();
1146
741
  await transaction.begin();
@@ -1163,7 +758,7 @@ ${columns}
1163
758
  "content",
1164
759
  typeof message.content === "string" ? message.content : JSON.stringify(message.content)
1165
760
  );
1166
- request.input("createdAt", message.createdAt.toISOString() || (/* @__PURE__ */ new Date()).toISOString());
761
+ request.input("createdAt", sql2.DateTime2, message.createdAt);
1167
762
  request.input("role", message.role);
1168
763
  request.input("type", message.type || "v2");
1169
764
  request.input("resourceId", message.resourceId);
@@ -1182,7 +777,7 @@ ${columns}
1182
777
  await request.query(mergeSql);
1183
778
  }
1184
779
  const threadReq = transaction.request();
1185
- threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
780
+ threadReq.input("updatedAt", sql2.DateTime2, /* @__PURE__ */ new Date());
1186
781
  threadReq.input("id", threadId);
1187
782
  await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
1188
783
  await transaction.commit();
@@ -1215,216 +810,6 @@ ${columns}
1215
810
  );
1216
811
  }
1217
812
  }
1218
- async persistWorkflowSnapshot({
1219
- workflowName,
1220
- runId,
1221
- snapshot
1222
- }) {
1223
- const table = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1224
- const now = (/* @__PURE__ */ new Date()).toISOString();
1225
- try {
1226
- const request = this.pool.request();
1227
- request.input("workflow_name", workflowName);
1228
- request.input("run_id", runId);
1229
- request.input("snapshot", JSON.stringify(snapshot));
1230
- request.input("createdAt", now);
1231
- request.input("updatedAt", now);
1232
- const mergeSql = `MERGE INTO ${table} AS target
1233
- USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
1234
- ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
1235
- WHEN MATCHED THEN UPDATE SET
1236
- snapshot = @snapshot,
1237
- [updatedAt] = @updatedAt
1238
- WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
1239
- VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
1240
- await request.query(mergeSql);
1241
- } catch (error) {
1242
- throw new MastraError(
1243
- {
1244
- id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1245
- domain: ErrorDomain.STORAGE,
1246
- category: ErrorCategory.THIRD_PARTY,
1247
- details: {
1248
- workflowName,
1249
- runId
1250
- }
1251
- },
1252
- error
1253
- );
1254
- }
1255
- }
1256
- async loadWorkflowSnapshot({
1257
- workflowName,
1258
- runId
1259
- }) {
1260
- try {
1261
- const result = await this.load({
1262
- tableName: TABLE_WORKFLOW_SNAPSHOT,
1263
- keys: {
1264
- workflow_name: workflowName,
1265
- run_id: runId
1266
- }
1267
- });
1268
- if (!result) {
1269
- return null;
1270
- }
1271
- return result.snapshot;
1272
- } catch (error) {
1273
- throw new MastraError(
1274
- {
1275
- id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1276
- domain: ErrorDomain.STORAGE,
1277
- category: ErrorCategory.THIRD_PARTY,
1278
- details: {
1279
- workflowName,
1280
- runId
1281
- }
1282
- },
1283
- error
1284
- );
1285
- }
1286
- }
1287
- async hasColumn(table, column) {
1288
- const schema = this.schema || "dbo";
1289
- const request = this.pool.request();
1290
- request.input("schema", schema);
1291
- request.input("table", table);
1292
- request.input("column", column);
1293
- request.input("columnLower", column.toLowerCase());
1294
- const result = await request.query(
1295
- `SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
1296
- );
1297
- return result.recordset.length > 0;
1298
- }
1299
- parseWorkflowRun(row) {
1300
- let parsedSnapshot = row.snapshot;
1301
- if (typeof parsedSnapshot === "string") {
1302
- try {
1303
- parsedSnapshot = JSON.parse(row.snapshot);
1304
- } catch (e) {
1305
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1306
- }
1307
- }
1308
- return {
1309
- workflowName: row.workflow_name,
1310
- runId: row.run_id,
1311
- snapshot: parsedSnapshot,
1312
- createdAt: row.createdAt,
1313
- updatedAt: row.updatedAt,
1314
- resourceId: row.resourceId
1315
- };
1316
- }
1317
- async getWorkflowRuns({
1318
- workflowName,
1319
- fromDate,
1320
- toDate,
1321
- limit,
1322
- offset,
1323
- resourceId
1324
- } = {}) {
1325
- try {
1326
- const conditions = [];
1327
- const paramMap = {};
1328
- if (workflowName) {
1329
- conditions.push(`[workflow_name] = @workflowName`);
1330
- paramMap["workflowName"] = workflowName;
1331
- }
1332
- if (resourceId) {
1333
- const hasResourceId = await this.hasColumn(TABLE_WORKFLOW_SNAPSHOT, "resourceId");
1334
- if (hasResourceId) {
1335
- conditions.push(`[resourceId] = @resourceId`);
1336
- paramMap["resourceId"] = resourceId;
1337
- } else {
1338
- console.warn(`[${TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
1339
- }
1340
- }
1341
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1342
- conditions.push(`[createdAt] >= @fromDate`);
1343
- paramMap[`fromDate`] = fromDate.toISOString();
1344
- }
1345
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1346
- conditions.push(`[createdAt] <= @toDate`);
1347
- paramMap[`toDate`] = toDate.toISOString();
1348
- }
1349
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1350
- let total = 0;
1351
- const tableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1352
- const request = this.pool.request();
1353
- Object.entries(paramMap).forEach(([key, value]) => {
1354
- if (value instanceof Date) {
1355
- request.input(key, sql.DateTime, value);
1356
- } else {
1357
- request.input(key, value);
1358
- }
1359
- });
1360
- if (limit !== void 0 && offset !== void 0) {
1361
- const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
1362
- const countResult = await request.query(countQuery);
1363
- total = Number(countResult.recordset[0]?.count || 0);
1364
- }
1365
- let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
1366
- if (limit !== void 0 && offset !== void 0) {
1367
- query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1368
- request.input("limit", limit);
1369
- request.input("offset", offset);
1370
- }
1371
- const result = await request.query(query);
1372
- const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
1373
- return { runs, total: total || runs.length };
1374
- } catch (error) {
1375
- throw new MastraError(
1376
- {
1377
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
1378
- domain: ErrorDomain.STORAGE,
1379
- category: ErrorCategory.THIRD_PARTY,
1380
- details: {
1381
- workflowName: workflowName || "all"
1382
- }
1383
- },
1384
- error
1385
- );
1386
- }
1387
- }
1388
- async getWorkflowRunById({
1389
- runId,
1390
- workflowName
1391
- }) {
1392
- try {
1393
- const conditions = [];
1394
- const paramMap = {};
1395
- if (runId) {
1396
- conditions.push(`[run_id] = @runId`);
1397
- paramMap["runId"] = runId;
1398
- }
1399
- if (workflowName) {
1400
- conditions.push(`[workflow_name] = @workflowName`);
1401
- paramMap["workflowName"] = workflowName;
1402
- }
1403
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1404
- const tableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1405
- const query = `SELECT * FROM ${tableName} ${whereClause}`;
1406
- const request = this.pool.request();
1407
- Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
1408
- const result = await request.query(query);
1409
- if (!result.recordset || result.recordset.length === 0) {
1410
- return null;
1411
- }
1412
- return this.parseWorkflowRun(result.recordset[0]);
1413
- } catch (error) {
1414
- throw new MastraError(
1415
- {
1416
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
1417
- domain: ErrorDomain.STORAGE,
1418
- category: ErrorCategory.THIRD_PARTY,
1419
- details: {
1420
- runId,
1421
- workflowName: workflowName || ""
1422
- }
1423
- },
1424
- error
1425
- );
1426
- }
1427
- }
1428
813
  async updateMessages({
1429
814
  messages
1430
815
  }) {
@@ -1433,7 +818,7 @@ ${columns}
1433
818
  }
1434
819
  const messageIds = messages.map((m) => m.id);
1435
820
  const idParams = messageIds.map((_, i) => `@id${i}`).join(", ");
1436
- let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${this.getTableName(TABLE_MESSAGES)}`;
821
+ let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}`;
1437
822
  if (idParams.length > 0) {
1438
823
  selectQuery += ` WHERE id IN (${idParams})`;
1439
824
  } else {
@@ -1490,7 +875,7 @@ ${columns}
1490
875
  }
1491
876
  }
1492
877
  if (setClauses.length > 0) {
1493
- const updateSql = `UPDATE ${this.getTableName(TABLE_MESSAGES)} SET ${setClauses.join(", ")} WHERE id = @id`;
878
+ const updateSql = `UPDATE ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} SET ${setClauses.join(", ")} WHERE id = @id`;
1494
879
  await req.query(updateSql);
1495
880
  }
1496
881
  }
@@ -1499,7 +884,7 @@ ${columns}
1499
884
  const threadReq = transaction.request();
1500
885
  Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
1501
886
  threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
1502
- const threadSql = `UPDATE ${this.getTableName(TABLE_THREADS)} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
887
+ const threadSql = `UPDATE ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
1503
888
  await threadReq.query(threadSql);
1504
889
  }
1505
890
  await transaction.commit();
@@ -1527,101 +912,78 @@ ${columns}
1527
912
  return message;
1528
913
  });
1529
914
  }
1530
- async close() {
1531
- if (this.pool) {
915
+ async deleteMessages(messageIds) {
916
+ if (!messageIds || messageIds.length === 0) {
917
+ return;
918
+ }
919
+ try {
920
+ const messageTableName = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
921
+ const threadTableName = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
922
+ const placeholders = messageIds.map((_, idx) => `@p${idx + 1}`).join(",");
923
+ const request = this.pool.request();
924
+ messageIds.forEach((id, idx) => {
925
+ request.input(`p${idx + 1}`, id);
926
+ });
927
+ const messages = await request.query(
928
+ `SELECT DISTINCT [thread_id] FROM ${messageTableName} WHERE [id] IN (${placeholders})`
929
+ );
930
+ const threadIds = messages.recordset?.map((msg) => msg.thread_id).filter(Boolean) || [];
931
+ const transaction = this.pool.transaction();
932
+ await transaction.begin();
1532
933
  try {
1533
- if (this.pool.connected) {
1534
- await this.pool.close();
1535
- } else if (this.pool.connecting) {
1536
- await this.pool.connect();
1537
- await this.pool.close();
934
+ const deleteRequest = transaction.request();
935
+ messageIds.forEach((id, idx) => {
936
+ deleteRequest.input(`p${idx + 1}`, id);
937
+ });
938
+ await deleteRequest.query(`DELETE FROM ${messageTableName} WHERE [id] IN (${placeholders})`);
939
+ if (threadIds.length > 0) {
940
+ for (const threadId of threadIds) {
941
+ const updateRequest = transaction.request();
942
+ updateRequest.input("p1", threadId);
943
+ await updateRequest.query(`UPDATE ${threadTableName} SET [updatedAt] = GETDATE() WHERE [id] = @p1`);
944
+ }
1538
945
  }
1539
- } catch (err) {
1540
- if (err.message && err.message.includes("Cannot close a pool while it is connecting")) ; else {
1541
- throw err;
946
+ await transaction.commit();
947
+ } catch (error) {
948
+ try {
949
+ await transaction.rollback();
950
+ } catch {
1542
951
  }
952
+ throw error;
1543
953
  }
954
+ } catch (error) {
955
+ throw new MastraError(
956
+ {
957
+ id: "MASTRA_STORAGE_MSSQL_STORE_DELETE_MESSAGES_FAILED",
958
+ domain: ErrorDomain.STORAGE,
959
+ category: ErrorCategory.THIRD_PARTY,
960
+ details: { messageIds: messageIds.join(", ") }
961
+ },
962
+ error
963
+ );
1544
964
  }
1545
965
  }
1546
- async getEvals(options = {}) {
1547
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
1548
- const fromDate = dateRange?.start;
1549
- const toDate = dateRange?.end;
1550
- const where = [];
1551
- const params = {};
1552
- if (agentName) {
1553
- where.push("agent_name = @agentName");
1554
- params["agentName"] = agentName;
1555
- }
1556
- if (type === "test") {
1557
- where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
1558
- } else if (type === "live") {
1559
- where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
1560
- }
1561
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1562
- where.push(`[created_at] >= @fromDate`);
1563
- params[`fromDate`] = fromDate.toISOString();
1564
- }
1565
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1566
- where.push(`[created_at] <= @toDate`);
1567
- params[`toDate`] = toDate.toISOString();
1568
- }
1569
- const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
1570
- const tableName = this.getTableName(TABLE_EVALS);
1571
- const offset = page * perPage;
1572
- const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
1573
- const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
966
+ async getResourceById({ resourceId }) {
967
+ const tableName = getTableName({ indexName: TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
1574
968
  try {
1575
- const countReq = this.pool.request();
1576
- Object.entries(params).forEach(([key, value]) => {
1577
- if (value instanceof Date) {
1578
- countReq.input(key, sql.DateTime, value);
1579
- } else {
1580
- countReq.input(key, value);
1581
- }
1582
- });
1583
- const countResult = await countReq.query(countQuery);
1584
- const total = countResult.recordset[0]?.total || 0;
1585
- if (total === 0) {
1586
- return {
1587
- evals: [],
1588
- total: 0,
1589
- page,
1590
- perPage,
1591
- hasMore: false
1592
- };
1593
- }
1594
969
  const req = this.pool.request();
1595
- Object.entries(params).forEach(([key, value]) => {
1596
- if (value instanceof Date) {
1597
- req.input(key, sql.DateTime, value);
1598
- } else {
1599
- req.input(key, value);
1600
- }
1601
- });
1602
- req.input("offset", offset);
1603
- req.input("perPage", perPage);
1604
- const result = await req.query(dataQuery);
1605
- const rows = result.recordset;
970
+ req.input("resourceId", resourceId);
971
+ const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
972
+ if (!result) {
973
+ return null;
974
+ }
1606
975
  return {
1607
- evals: rows?.map((row) => this.transformEvalRow(row)) ?? [],
1608
- total,
1609
- page,
1610
- perPage,
1611
- hasMore: offset + (rows?.length ?? 0) < total
976
+ ...result,
977
+ workingMemory: typeof result.workingMemory === "object" ? JSON.stringify(result.workingMemory) : result.workingMemory,
978
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
1612
979
  };
1613
980
  } catch (error) {
1614
981
  const mastraError = new MastraError(
1615
982
  {
1616
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
983
+ id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
1617
984
  domain: ErrorDomain.STORAGE,
1618
985
  category: ErrorCategory.THIRD_PARTY,
1619
- details: {
1620
- agentName: agentName || "all",
1621
- type: type || "all",
1622
- page,
1623
- perPage
1624
- }
986
+ details: { resourceId }
1625
987
  },
1626
988
  error
1627
989
  );
@@ -1631,32 +993,14 @@ ${columns}
1631
993
  }
1632
994
  }
1633
995
  async saveResource({ resource }) {
1634
- const tableName = this.getTableName(TABLE_RESOURCES);
1635
- try {
1636
- const req = this.pool.request();
1637
- req.input("id", resource.id);
1638
- req.input("workingMemory", resource.workingMemory);
1639
- req.input("metadata", JSON.stringify(resource.metadata));
1640
- req.input("createdAt", resource.createdAt.toISOString());
1641
- req.input("updatedAt", resource.updatedAt.toISOString());
1642
- await req.query(
1643
- `INSERT INTO ${tableName} (id, workingMemory, metadata, createdAt, updatedAt) VALUES (@id, @workingMemory, @metadata, @createdAt, @updatedAt)`
1644
- );
1645
- return resource;
1646
- } catch (error) {
1647
- const mastraError = new MastraError(
1648
- {
1649
- id: "MASTRA_STORAGE_MSSQL_SAVE_RESOURCE_FAILED",
1650
- domain: ErrorDomain.STORAGE,
1651
- category: ErrorCategory.THIRD_PARTY,
1652
- details: { resourceId: resource.id }
1653
- },
1654
- error
1655
- );
1656
- this.logger?.error?.(mastraError.toString());
1657
- this.logger?.trackException(mastraError);
1658
- throw mastraError;
1659
- }
996
+ await this.operations.insert({
997
+ tableName: TABLE_RESOURCES,
998
+ record: {
999
+ ...resource,
1000
+ metadata: JSON.stringify(resource.metadata)
1001
+ }
1002
+ });
1003
+ return resource;
1660
1004
  }
1661
1005
  async updateResource({
1662
1006
  resourceId,
@@ -1684,7 +1028,7 @@ ${columns}
1684
1028
  },
1685
1029
  updatedAt: /* @__PURE__ */ new Date()
1686
1030
  };
1687
- const tableName = this.getTableName(TABLE_RESOURCES);
1031
+ const tableName = getTableName({ indexName: TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
1688
1032
  const updates = [];
1689
1033
  const req = this.pool.request();
1690
1034
  if (workingMemory !== void 0) {
@@ -1715,99 +1059,1268 @@ ${columns}
1715
1059
  throw mastraError;
1716
1060
  }
1717
1061
  }
1718
- async getResourceById({ resourceId }) {
1719
- const tableName = this.getTableName(TABLE_RESOURCES);
1062
+ };
1063
+ var StoreOperationsMSSQL = class extends StoreOperations {
1064
+ pool;
1065
+ schemaName;
1066
+ setupSchemaPromise = null;
1067
+ schemaSetupComplete = void 0;
1068
+ getSqlType(type, isPrimaryKey = false) {
1069
+ switch (type) {
1070
+ case "text":
1071
+ return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(MAX)";
1072
+ case "timestamp":
1073
+ return "DATETIME2(7)";
1074
+ case "uuid":
1075
+ return "UNIQUEIDENTIFIER";
1076
+ case "jsonb":
1077
+ return "NVARCHAR(MAX)";
1078
+ case "integer":
1079
+ return "INT";
1080
+ case "bigint":
1081
+ return "BIGINT";
1082
+ case "float":
1083
+ return "FLOAT";
1084
+ default:
1085
+ throw new MastraError({
1086
+ id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
1087
+ domain: ErrorDomain.STORAGE,
1088
+ category: ErrorCategory.THIRD_PARTY
1089
+ });
1090
+ }
1091
+ }
1092
+ constructor({ pool, schemaName }) {
1093
+ super();
1094
+ this.pool = pool;
1095
+ this.schemaName = schemaName;
1096
+ }
1097
+ async hasColumn(table, column) {
1098
+ const schema = this.schemaName || "dbo";
1099
+ const request = this.pool.request();
1100
+ request.input("schema", schema);
1101
+ request.input("table", table);
1102
+ request.input("column", column);
1103
+ request.input("columnLower", column.toLowerCase());
1104
+ const result = await request.query(
1105
+ `SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
1106
+ );
1107
+ return result.recordset.length > 0;
1108
+ }
1109
+ async setupSchema() {
1110
+ if (!this.schemaName || this.schemaSetupComplete) {
1111
+ return;
1112
+ }
1113
+ if (!this.setupSchemaPromise) {
1114
+ this.setupSchemaPromise = (async () => {
1115
+ try {
1116
+ const checkRequest = this.pool.request();
1117
+ checkRequest.input("schemaName", this.schemaName);
1118
+ const checkResult = await checkRequest.query(`
1119
+ SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
1120
+ `);
1121
+ const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
1122
+ if (!schemaExists) {
1123
+ try {
1124
+ await this.pool.request().query(`CREATE SCHEMA [${this.schemaName}]`);
1125
+ this.logger?.info?.(`Schema "${this.schemaName}" created successfully`);
1126
+ } catch (error) {
1127
+ this.logger?.error?.(`Failed to create schema "${this.schemaName}"`, { error });
1128
+ throw new Error(
1129
+ `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.`
1130
+ );
1131
+ }
1132
+ }
1133
+ this.schemaSetupComplete = true;
1134
+ this.logger?.debug?.(`Schema "${this.schemaName}" is ready for use`);
1135
+ } catch (error) {
1136
+ this.schemaSetupComplete = void 0;
1137
+ this.setupSchemaPromise = null;
1138
+ throw error;
1139
+ } finally {
1140
+ this.setupSchemaPromise = null;
1141
+ }
1142
+ })();
1143
+ }
1144
+ await this.setupSchemaPromise;
1145
+ }
1146
+ async insert({ tableName, record }) {
1720
1147
  try {
1721
- const req = this.pool.request();
1722
- req.input("resourceId", resourceId);
1723
- const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
1724
- if (!result) {
1725
- return null;
1726
- }
1727
- return {
1728
- ...result,
1729
- workingMemory: typeof result.workingMemory === "object" ? JSON.stringify(result.workingMemory) : result.workingMemory,
1730
- metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
1731
- };
1148
+ const columns = Object.keys(record).map((col) => parseSqlIdentifier(col, "column name"));
1149
+ const values = Object.values(record);
1150
+ const paramNames = values.map((_, i) => `@param${i}`);
1151
+ const insertSql = `INSERT INTO ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (${columns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
1152
+ const request = this.pool.request();
1153
+ values.forEach((value, i) => {
1154
+ if (value instanceof Date) {
1155
+ request.input(`param${i}`, sql2.DateTime2, value);
1156
+ } else if (typeof value === "object" && value !== null) {
1157
+ request.input(`param${i}`, JSON.stringify(value));
1158
+ } else {
1159
+ request.input(`param${i}`, value);
1160
+ }
1161
+ });
1162
+ await request.query(insertSql);
1732
1163
  } catch (error) {
1733
- const mastraError = new MastraError(
1164
+ throw new MastraError(
1734
1165
  {
1735
- id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
1166
+ id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
1736
1167
  domain: ErrorDomain.STORAGE,
1737
1168
  category: ErrorCategory.THIRD_PARTY,
1738
- details: { resourceId }
1169
+ details: {
1170
+ tableName
1171
+ }
1739
1172
  },
1740
1173
  error
1741
1174
  );
1742
- this.logger?.error?.(mastraError.toString());
1743
- this.logger?.trackException(mastraError);
1744
- throw mastraError;
1745
1175
  }
1746
1176
  }
1747
- async getScoreById({ id }) {
1748
- throw new MastraError({
1749
- id: "STORAGE_MONGODB_STORE_GET_SCORE_BY_ID_FAILED",
1750
- domain: ErrorDomain.STORAGE,
1751
- category: ErrorCategory.THIRD_PARTY,
1752
- details: { id },
1753
- text: "getScoreById is not implemented yet in MongoDBStore"
1754
- });
1755
- }
1756
- async saveScore(_score) {
1757
- throw new MastraError({
1758
- id: "STORAGE_MONGODB_STORE_SAVE_SCORE_FAILED",
1759
- domain: ErrorDomain.STORAGE,
1760
- category: ErrorCategory.THIRD_PARTY,
1761
- details: {},
1762
- text: "saveScore is not implemented yet in MongoDBStore"
1763
- });
1764
- }
1765
- async getScoresByScorerId({
1766
- scorerId,
1767
- pagination: _pagination,
1768
- entityId,
1769
- entityType
1770
- }) {
1771
- throw new MastraError({
1772
- id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
1773
- domain: ErrorDomain.STORAGE,
1774
- category: ErrorCategory.THIRD_PARTY,
1775
- details: { scorerId, entityId: entityId || "", entityType: entityType || "" },
1776
- text: "getScoresByScorerId is not implemented yet in MongoDBStore"
1777
- });
1177
+ async clearTable({ tableName }) {
1178
+ const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1179
+ try {
1180
+ try {
1181
+ await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
1182
+ } catch (truncateError) {
1183
+ if (truncateError.message && truncateError.message.includes("foreign key")) {
1184
+ await this.pool.request().query(`DELETE FROM ${fullTableName}`);
1185
+ } else {
1186
+ throw truncateError;
1187
+ }
1188
+ }
1189
+ } catch (error) {
1190
+ throw new MastraError(
1191
+ {
1192
+ id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
1193
+ domain: ErrorDomain.STORAGE,
1194
+ category: ErrorCategory.THIRD_PARTY,
1195
+ details: {
1196
+ tableName
1197
+ }
1198
+ },
1199
+ error
1200
+ );
1201
+ }
1778
1202
  }
1779
- async getScoresByRunId({
1780
- runId,
1781
- pagination: _pagination
1782
- }) {
1783
- throw new MastraError({
1784
- id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_RUN_ID_FAILED",
1785
- domain: ErrorDomain.STORAGE,
1786
- category: ErrorCategory.THIRD_PARTY,
1787
- details: { runId },
1788
- text: "getScoresByRunId is not implemented yet in MongoDBStore"
1789
- });
1203
+ getDefaultValue(type) {
1204
+ switch (type) {
1205
+ case "timestamp":
1206
+ return "DEFAULT SYSDATETIMEOFFSET()";
1207
+ case "jsonb":
1208
+ return "DEFAULT N'{}'";
1209
+ default:
1210
+ return super.getDefaultValue(type);
1211
+ }
1790
1212
  }
1791
- async getScoresByEntityId({
1792
- entityId,
1793
- entityType,
1794
- pagination: _pagination
1213
+ async createTable({
1214
+ tableName,
1215
+ schema
1795
1216
  }) {
1796
- throw new MastraError({
1797
- id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
1798
- domain: ErrorDomain.STORAGE,
1799
- category: ErrorCategory.THIRD_PARTY,
1800
- details: { entityId, entityType },
1801
- text: "getScoresByEntityId is not implemented yet in MongoDBStore"
1802
- });
1803
- }
1804
- async dropTable({ tableName }) {
1805
- throw new MastraError({
1806
- id: "STORAGE_MONGODB_STORE_DROP_TABLE_FAILED",
1807
- domain: ErrorDomain.STORAGE,
1808
- category: ErrorCategory.THIRD_PARTY,
1809
- details: { tableName },
1810
- text: "dropTable is not implemented yet in MongoDBStore"
1217
+ try {
1218
+ const uniqueConstraintColumns = tableName === TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
1219
+ const columns = Object.entries(schema).map(([name, def]) => {
1220
+ const parsedName = parseSqlIdentifier(name, "column name");
1221
+ const constraints = [];
1222
+ if (def.primaryKey) constraints.push("PRIMARY KEY");
1223
+ if (!def.nullable) constraints.push("NOT NULL");
1224
+ const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
1225
+ return `[${parsedName}] ${this.getSqlType(def.type, isIndexed)} ${constraints.join(" ")}`.trim();
1226
+ }).join(",\n");
1227
+ if (this.schemaName) {
1228
+ await this.setupSchema();
1229
+ }
1230
+ const checkTableRequest = this.pool.request();
1231
+ checkTableRequest.input(
1232
+ "tableName",
1233
+ getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
1234
+ );
1235
+ const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
1236
+ checkTableRequest.input("schema", this.schemaName || "dbo");
1237
+ const checkTableResult = await checkTableRequest.query(checkTableSql);
1238
+ const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
1239
+ if (!tableExists) {
1240
+ const createSql = `CREATE TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (
1241
+ ${columns}
1242
+ )`;
1243
+ await this.pool.request().query(createSql);
1244
+ }
1245
+ const columnCheckSql = `
1246
+ SELECT 1 AS found
1247
+ FROM INFORMATION_SCHEMA.COLUMNS
1248
+ WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
1249
+ `;
1250
+ const checkColumnRequest = this.pool.request();
1251
+ checkColumnRequest.input("schema", this.schemaName || "dbo");
1252
+ checkColumnRequest.input(
1253
+ "tableName",
1254
+ getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
1255
+ );
1256
+ const columnResult = await checkColumnRequest.query(columnCheckSql);
1257
+ const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
1258
+ if (!columnExists) {
1259
+ const alterSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD seq_id BIGINT IDENTITY(1,1)`;
1260
+ await this.pool.request().query(alterSql);
1261
+ }
1262
+ if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
1263
+ const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
1264
+ const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
1265
+ const checkConstraintRequest = this.pool.request();
1266
+ checkConstraintRequest.input("constraintName", constraintName);
1267
+ const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
1268
+ const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
1269
+ if (!constraintExists) {
1270
+ const addConstraintSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
1271
+ await this.pool.request().query(addConstraintSql);
1272
+ }
1273
+ }
1274
+ } catch (error) {
1275
+ throw new MastraError(
1276
+ {
1277
+ id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
1278
+ domain: ErrorDomain.STORAGE,
1279
+ category: ErrorCategory.THIRD_PARTY,
1280
+ details: {
1281
+ tableName
1282
+ }
1283
+ },
1284
+ error
1285
+ );
1286
+ }
1287
+ }
1288
+ /**
1289
+ * Alters table schema to add columns if they don't exist
1290
+ * @param tableName Name of the table
1291
+ * @param schema Schema of the table
1292
+ * @param ifNotExists Array of column names to add if they don't exist
1293
+ */
1294
+ async alterTable({
1295
+ tableName,
1296
+ schema,
1297
+ ifNotExists
1298
+ }) {
1299
+ const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1300
+ try {
1301
+ for (const columnName of ifNotExists) {
1302
+ if (schema[columnName]) {
1303
+ const columnCheckRequest = this.pool.request();
1304
+ columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
1305
+ columnCheckRequest.input("columnName", columnName);
1306
+ columnCheckRequest.input("schema", this.schemaName || "dbo");
1307
+ const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
1308
+ const checkResult = await columnCheckRequest.query(checkSql);
1309
+ const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
1310
+ if (!columnExists) {
1311
+ const columnDef = schema[columnName];
1312
+ const sqlType = this.getSqlType(columnDef.type);
1313
+ const nullable = columnDef.nullable === false ? "NOT NULL" : "";
1314
+ const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
1315
+ const parsedColumnName = parseSqlIdentifier(columnName, "column name");
1316
+ const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
1317
+ await this.pool.request().query(alterSql);
1318
+ this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
1319
+ }
1320
+ }
1321
+ }
1322
+ } catch (error) {
1323
+ throw new MastraError(
1324
+ {
1325
+ id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
1326
+ domain: ErrorDomain.STORAGE,
1327
+ category: ErrorCategory.THIRD_PARTY,
1328
+ details: {
1329
+ tableName
1330
+ }
1331
+ },
1332
+ error
1333
+ );
1334
+ }
1335
+ }
1336
+ async load({ tableName, keys }) {
1337
+ try {
1338
+ const keyEntries = Object.entries(keys).map(([key, value]) => [parseSqlIdentifier(key, "column name"), value]);
1339
+ const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
1340
+ const values = keyEntries.map(([_, value]) => value);
1341
+ const sql7 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1342
+ const request = this.pool.request();
1343
+ values.forEach((value, i) => {
1344
+ request.input(`param${i}`, value);
1345
+ });
1346
+ const resultSet = await request.query(sql7);
1347
+ const result = resultSet.recordset[0] || null;
1348
+ if (!result) {
1349
+ return null;
1350
+ }
1351
+ if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
1352
+ const snapshot = result;
1353
+ if (typeof snapshot.snapshot === "string") {
1354
+ snapshot.snapshot = JSON.parse(snapshot.snapshot);
1355
+ }
1356
+ return snapshot;
1357
+ }
1358
+ return result;
1359
+ } catch (error) {
1360
+ throw new MastraError(
1361
+ {
1362
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
1363
+ domain: ErrorDomain.STORAGE,
1364
+ category: ErrorCategory.THIRD_PARTY,
1365
+ details: {
1366
+ tableName
1367
+ }
1368
+ },
1369
+ error
1370
+ );
1371
+ }
1372
+ }
1373
+ async batchInsert({ tableName, records }) {
1374
+ const transaction = this.pool.transaction();
1375
+ try {
1376
+ await transaction.begin();
1377
+ for (const record of records) {
1378
+ await this.insert({ tableName, record });
1379
+ }
1380
+ await transaction.commit();
1381
+ } catch (error) {
1382
+ await transaction.rollback();
1383
+ throw new MastraError(
1384
+ {
1385
+ id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
1386
+ domain: ErrorDomain.STORAGE,
1387
+ category: ErrorCategory.THIRD_PARTY,
1388
+ details: {
1389
+ tableName,
1390
+ numberOfRecords: records.length
1391
+ }
1392
+ },
1393
+ error
1394
+ );
1395
+ }
1396
+ }
1397
+ async dropTable({ tableName }) {
1398
+ try {
1399
+ const tableNameWithSchema = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1400
+ await this.pool.request().query(`DROP TABLE IF EXISTS ${tableNameWithSchema}`);
1401
+ } catch (error) {
1402
+ throw new MastraError(
1403
+ {
1404
+ id: "MASTRA_STORAGE_MSSQL_STORE_DROP_TABLE_FAILED",
1405
+ domain: ErrorDomain.STORAGE,
1406
+ category: ErrorCategory.THIRD_PARTY,
1407
+ details: {
1408
+ tableName
1409
+ }
1410
+ },
1411
+ error
1412
+ );
1413
+ }
1414
+ }
1415
+ };
1416
+ function parseJSON(jsonString) {
1417
+ try {
1418
+ return JSON.parse(jsonString);
1419
+ } catch {
1420
+ return jsonString;
1421
+ }
1422
+ }
1423
+ function transformScoreRow(row) {
1424
+ return {
1425
+ ...row,
1426
+ input: parseJSON(row.input),
1427
+ scorer: parseJSON(row.scorer),
1428
+ preprocessStepResult: parseJSON(row.preprocessStepResult),
1429
+ analyzeStepResult: parseJSON(row.analyzeStepResult),
1430
+ metadata: parseJSON(row.metadata),
1431
+ output: parseJSON(row.output),
1432
+ additionalContext: parseJSON(row.additionalContext),
1433
+ runtimeContext: parseJSON(row.runtimeContext),
1434
+ entity: parseJSON(row.entity),
1435
+ createdAt: row.createdAt,
1436
+ updatedAt: row.updatedAt
1437
+ };
1438
+ }
1439
+ var ScoresMSSQL = class extends ScoresStorage {
1440
+ pool;
1441
+ operations;
1442
+ schema;
1443
+ constructor({
1444
+ pool,
1445
+ operations,
1446
+ schema
1447
+ }) {
1448
+ super();
1449
+ this.pool = pool;
1450
+ this.operations = operations;
1451
+ this.schema = schema;
1452
+ }
1453
+ async getScoreById({ id }) {
1454
+ try {
1455
+ const request = this.pool.request();
1456
+ request.input("p1", id);
1457
+ const result = await request.query(
1458
+ `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE id = @p1`
1459
+ );
1460
+ if (result.recordset.length === 0) {
1461
+ return null;
1462
+ }
1463
+ return transformScoreRow(result.recordset[0]);
1464
+ } catch (error) {
1465
+ throw new MastraError(
1466
+ {
1467
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORE_BY_ID_FAILED",
1468
+ domain: ErrorDomain.STORAGE,
1469
+ category: ErrorCategory.THIRD_PARTY,
1470
+ details: { id }
1471
+ },
1472
+ error
1473
+ );
1474
+ }
1475
+ }
1476
+ async saveScore(score) {
1477
+ try {
1478
+ const scoreId = crypto.randomUUID();
1479
+ const {
1480
+ scorer,
1481
+ preprocessStepResult,
1482
+ analyzeStepResult,
1483
+ metadata,
1484
+ input,
1485
+ output,
1486
+ additionalContext,
1487
+ runtimeContext,
1488
+ entity,
1489
+ ...rest
1490
+ } = score;
1491
+ await this.operations.insert({
1492
+ tableName: TABLE_SCORERS,
1493
+ record: {
1494
+ id: scoreId,
1495
+ ...rest,
1496
+ input: JSON.stringify(input) || "",
1497
+ output: JSON.stringify(output) || "",
1498
+ preprocessStepResult: preprocessStepResult ? JSON.stringify(preprocessStepResult) : null,
1499
+ analyzeStepResult: analyzeStepResult ? JSON.stringify(analyzeStepResult) : null,
1500
+ metadata: metadata ? JSON.stringify(metadata) : null,
1501
+ additionalContext: additionalContext ? JSON.stringify(additionalContext) : null,
1502
+ runtimeContext: runtimeContext ? JSON.stringify(runtimeContext) : null,
1503
+ entity: entity ? JSON.stringify(entity) : null,
1504
+ scorer: scorer ? JSON.stringify(scorer) : null,
1505
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1506
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1507
+ }
1508
+ });
1509
+ const scoreFromDb = await this.getScoreById({ id: scoreId });
1510
+ return { score: scoreFromDb };
1511
+ } catch (error) {
1512
+ throw new MastraError(
1513
+ {
1514
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_FAILED",
1515
+ domain: ErrorDomain.STORAGE,
1516
+ category: ErrorCategory.THIRD_PARTY
1517
+ },
1518
+ error
1519
+ );
1520
+ }
1521
+ }
1522
+ async getScoresByScorerId({
1523
+ scorerId,
1524
+ pagination
1525
+ }) {
1526
+ try {
1527
+ const request = this.pool.request();
1528
+ request.input("p1", scorerId);
1529
+ const totalResult = await request.query(
1530
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [scorerId] = @p1`
1531
+ );
1532
+ const total = totalResult.recordset[0]?.count || 0;
1533
+ if (total === 0) {
1534
+ return {
1535
+ pagination: {
1536
+ total: 0,
1537
+ page: pagination.page,
1538
+ perPage: pagination.perPage,
1539
+ hasMore: false
1540
+ },
1541
+ scores: []
1542
+ };
1543
+ }
1544
+ const dataRequest = this.pool.request();
1545
+ dataRequest.input("p1", scorerId);
1546
+ dataRequest.input("p2", pagination.perPage);
1547
+ dataRequest.input("p3", pagination.page * pagination.perPage);
1548
+ const result = await dataRequest.query(
1549
+ `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [scorerId] = @p1 ORDER BY [createdAt] DESC OFFSET @p3 ROWS FETCH NEXT @p2 ROWS ONLY`
1550
+ );
1551
+ return {
1552
+ pagination: {
1553
+ total: Number(total),
1554
+ page: pagination.page,
1555
+ perPage: pagination.perPage,
1556
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
1557
+ },
1558
+ scores: result.recordset.map((row) => transformScoreRow(row))
1559
+ };
1560
+ } catch (error) {
1561
+ throw new MastraError(
1562
+ {
1563
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
1564
+ domain: ErrorDomain.STORAGE,
1565
+ category: ErrorCategory.THIRD_PARTY,
1566
+ details: { scorerId }
1567
+ },
1568
+ error
1569
+ );
1570
+ }
1571
+ }
1572
+ async getScoresByRunId({
1573
+ runId,
1574
+ pagination
1575
+ }) {
1576
+ try {
1577
+ const request = this.pool.request();
1578
+ request.input("p1", runId);
1579
+ const totalResult = await request.query(
1580
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
1581
+ );
1582
+ const total = totalResult.recordset[0]?.count || 0;
1583
+ if (total === 0) {
1584
+ return {
1585
+ pagination: {
1586
+ total: 0,
1587
+ page: pagination.page,
1588
+ perPage: pagination.perPage,
1589
+ hasMore: false
1590
+ },
1591
+ scores: []
1592
+ };
1593
+ }
1594
+ const dataRequest = this.pool.request();
1595
+ dataRequest.input("p1", runId);
1596
+ dataRequest.input("p2", pagination.perPage);
1597
+ dataRequest.input("p3", pagination.page * pagination.perPage);
1598
+ const result = await dataRequest.query(
1599
+ `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`
1600
+ );
1601
+ return {
1602
+ pagination: {
1603
+ total: Number(total),
1604
+ page: pagination.page,
1605
+ perPage: pagination.perPage,
1606
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
1607
+ },
1608
+ scores: result.recordset.map((row) => transformScoreRow(row))
1609
+ };
1610
+ } catch (error) {
1611
+ throw new MastraError(
1612
+ {
1613
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_RUN_ID_FAILED",
1614
+ domain: ErrorDomain.STORAGE,
1615
+ category: ErrorCategory.THIRD_PARTY,
1616
+ details: { runId }
1617
+ },
1618
+ error
1619
+ );
1620
+ }
1621
+ }
1622
+ async getScoresByEntityId({
1623
+ entityId,
1624
+ entityType,
1625
+ pagination
1626
+ }) {
1627
+ try {
1628
+ const request = this.pool.request();
1629
+ request.input("p1", entityId);
1630
+ request.input("p2", entityType);
1631
+ const totalResult = await request.query(
1632
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
1633
+ );
1634
+ const total = totalResult.recordset[0]?.count || 0;
1635
+ if (total === 0) {
1636
+ return {
1637
+ pagination: {
1638
+ total: 0,
1639
+ page: pagination.page,
1640
+ perPage: pagination.perPage,
1641
+ hasMore: false
1642
+ },
1643
+ scores: []
1644
+ };
1645
+ }
1646
+ const dataRequest = this.pool.request();
1647
+ dataRequest.input("p1", entityId);
1648
+ dataRequest.input("p2", entityType);
1649
+ dataRequest.input("p3", pagination.perPage);
1650
+ dataRequest.input("p4", pagination.page * pagination.perPage);
1651
+ const result = await dataRequest.query(
1652
+ `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`
1653
+ );
1654
+ return {
1655
+ pagination: {
1656
+ total: Number(total),
1657
+ page: pagination.page,
1658
+ perPage: pagination.perPage,
1659
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
1660
+ },
1661
+ scores: result.recordset.map((row) => transformScoreRow(row))
1662
+ };
1663
+ } catch (error) {
1664
+ throw new MastraError(
1665
+ {
1666
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
1667
+ domain: ErrorDomain.STORAGE,
1668
+ category: ErrorCategory.THIRD_PARTY,
1669
+ details: { entityId, entityType }
1670
+ },
1671
+ error
1672
+ );
1673
+ }
1674
+ }
1675
+ };
1676
+ var TracesMSSQL = class extends TracesStorage {
1677
+ pool;
1678
+ operations;
1679
+ schema;
1680
+ constructor({
1681
+ pool,
1682
+ operations,
1683
+ schema
1684
+ }) {
1685
+ super();
1686
+ this.pool = pool;
1687
+ this.operations = operations;
1688
+ this.schema = schema;
1689
+ }
1690
+ /** @deprecated use getTracesPaginated instead*/
1691
+ async getTraces(args) {
1692
+ if (args.fromDate || args.toDate) {
1693
+ args.dateRange = {
1694
+ start: args.fromDate,
1695
+ end: args.toDate
1696
+ };
1697
+ }
1698
+ const result = await this.getTracesPaginated(args);
1699
+ return result.traces;
1700
+ }
1701
+ async getTracesPaginated(args) {
1702
+ const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
1703
+ const fromDate = dateRange?.start;
1704
+ const toDate = dateRange?.end;
1705
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
1706
+ const currentOffset = page * perPage;
1707
+ const paramMap = {};
1708
+ const conditions = [];
1709
+ let paramIndex = 1;
1710
+ if (name) {
1711
+ const paramName = `p${paramIndex++}`;
1712
+ conditions.push(`[name] LIKE @${paramName}`);
1713
+ paramMap[paramName] = `${name}%`;
1714
+ }
1715
+ if (scope) {
1716
+ const paramName = `p${paramIndex++}`;
1717
+ conditions.push(`[scope] = @${paramName}`);
1718
+ paramMap[paramName] = scope;
1719
+ }
1720
+ if (attributes) {
1721
+ Object.entries(attributes).forEach(([key, value]) => {
1722
+ const parsedKey = parseFieldKey(key);
1723
+ const paramName = `p${paramIndex++}`;
1724
+ conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
1725
+ paramMap[paramName] = value;
1726
+ });
1727
+ }
1728
+ if (filters) {
1729
+ Object.entries(filters).forEach(([key, value]) => {
1730
+ const parsedKey = parseFieldKey(key);
1731
+ const paramName = `p${paramIndex++}`;
1732
+ conditions.push(`[${parsedKey}] = @${paramName}`);
1733
+ paramMap[paramName] = value;
1734
+ });
1735
+ }
1736
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1737
+ const paramName = `p${paramIndex++}`;
1738
+ conditions.push(`[createdAt] >= @${paramName}`);
1739
+ paramMap[paramName] = fromDate.toISOString();
1740
+ }
1741
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1742
+ const paramName = `p${paramIndex++}`;
1743
+ conditions.push(`[createdAt] <= @${paramName}`);
1744
+ paramMap[paramName] = toDate.toISOString();
1745
+ }
1746
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1747
+ const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
1748
+ let total = 0;
1749
+ try {
1750
+ const countRequest = this.pool.request();
1751
+ Object.entries(paramMap).forEach(([key, value]) => {
1752
+ if (value instanceof Date) {
1753
+ countRequest.input(key, sql2.DateTime, value);
1754
+ } else {
1755
+ countRequest.input(key, value);
1756
+ }
1757
+ });
1758
+ const countResult = await countRequest.query(countQuery);
1759
+ total = parseInt(countResult.recordset[0].total, 10);
1760
+ } catch (error) {
1761
+ throw new MastraError(
1762
+ {
1763
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
1764
+ domain: ErrorDomain.STORAGE,
1765
+ category: ErrorCategory.THIRD_PARTY,
1766
+ details: {
1767
+ name: args.name ?? "",
1768
+ scope: args.scope ?? ""
1769
+ }
1770
+ },
1771
+ error
1772
+ );
1773
+ }
1774
+ if (total === 0) {
1775
+ return {
1776
+ traces: [],
1777
+ total: 0,
1778
+ page,
1779
+ perPage,
1780
+ hasMore: false
1781
+ };
1782
+ }
1783
+ const dataQuery = `SELECT * FROM ${getTableName({ indexName: TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1784
+ const dataRequest = this.pool.request();
1785
+ Object.entries(paramMap).forEach(([key, value]) => {
1786
+ if (value instanceof Date) {
1787
+ dataRequest.input(key, sql2.DateTime, value);
1788
+ } else {
1789
+ dataRequest.input(key, value);
1790
+ }
1791
+ });
1792
+ dataRequest.input("offset", currentOffset);
1793
+ dataRequest.input("limit", perPage);
1794
+ try {
1795
+ const rowsResult = await dataRequest.query(dataQuery);
1796
+ const rows = rowsResult.recordset;
1797
+ const traces = rows.map((row) => ({
1798
+ id: row.id,
1799
+ parentSpanId: row.parentSpanId,
1800
+ traceId: row.traceId,
1801
+ name: row.name,
1802
+ scope: row.scope,
1803
+ kind: row.kind,
1804
+ status: JSON.parse(row.status),
1805
+ events: JSON.parse(row.events),
1806
+ links: JSON.parse(row.links),
1807
+ attributes: JSON.parse(row.attributes),
1808
+ startTime: row.startTime,
1809
+ endTime: row.endTime,
1810
+ other: row.other,
1811
+ createdAt: row.createdAt
1812
+ }));
1813
+ return {
1814
+ traces,
1815
+ total,
1816
+ page,
1817
+ perPage,
1818
+ hasMore: currentOffset + traces.length < total
1819
+ };
1820
+ } catch (error) {
1821
+ throw new MastraError(
1822
+ {
1823
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
1824
+ domain: ErrorDomain.STORAGE,
1825
+ category: ErrorCategory.THIRD_PARTY,
1826
+ details: {
1827
+ name: args.name ?? "",
1828
+ scope: args.scope ?? ""
1829
+ }
1830
+ },
1831
+ error
1832
+ );
1833
+ }
1834
+ }
1835
+ async batchTraceInsert({ records }) {
1836
+ this.logger.debug("Batch inserting traces", { count: records.length });
1837
+ await this.operations.batchInsert({
1838
+ tableName: TABLE_TRACES,
1839
+ records
1840
+ });
1841
+ }
1842
+ };
1843
+ function parseWorkflowRun(row) {
1844
+ let parsedSnapshot = row.snapshot;
1845
+ if (typeof parsedSnapshot === "string") {
1846
+ try {
1847
+ parsedSnapshot = JSON.parse(row.snapshot);
1848
+ } catch (e) {
1849
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1850
+ }
1851
+ }
1852
+ return {
1853
+ workflowName: row.workflow_name,
1854
+ runId: row.run_id,
1855
+ snapshot: parsedSnapshot,
1856
+ createdAt: row.createdAt,
1857
+ updatedAt: row.updatedAt,
1858
+ resourceId: row.resourceId
1859
+ };
1860
+ }
1861
+ var WorkflowsMSSQL = class extends WorkflowsStorage {
1862
+ pool;
1863
+ operations;
1864
+ schema;
1865
+ constructor({
1866
+ pool,
1867
+ operations,
1868
+ schema
1869
+ }) {
1870
+ super();
1871
+ this.pool = pool;
1872
+ this.operations = operations;
1873
+ this.schema = schema;
1874
+ }
1875
+ async persistWorkflowSnapshot({
1876
+ workflowName,
1877
+ runId,
1878
+ snapshot
1879
+ }) {
1880
+ const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
1881
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1882
+ try {
1883
+ const request = this.pool.request();
1884
+ request.input("workflow_name", workflowName);
1885
+ request.input("run_id", runId);
1886
+ request.input("snapshot", JSON.stringify(snapshot));
1887
+ request.input("createdAt", sql2.DateTime2, new Date(now));
1888
+ request.input("updatedAt", sql2.DateTime2, new Date(now));
1889
+ const mergeSql = `MERGE INTO ${table} AS target
1890
+ USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
1891
+ ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
1892
+ WHEN MATCHED THEN UPDATE SET
1893
+ snapshot = @snapshot,
1894
+ [updatedAt] = @updatedAt
1895
+ WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
1896
+ VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
1897
+ await request.query(mergeSql);
1898
+ } catch (error) {
1899
+ throw new MastraError(
1900
+ {
1901
+ id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1902
+ domain: ErrorDomain.STORAGE,
1903
+ category: ErrorCategory.THIRD_PARTY,
1904
+ details: {
1905
+ workflowName,
1906
+ runId
1907
+ }
1908
+ },
1909
+ error
1910
+ );
1911
+ }
1912
+ }
1913
+ async loadWorkflowSnapshot({
1914
+ workflowName,
1915
+ runId
1916
+ }) {
1917
+ try {
1918
+ const result = await this.operations.load({
1919
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
1920
+ keys: {
1921
+ workflow_name: workflowName,
1922
+ run_id: runId
1923
+ }
1924
+ });
1925
+ if (!result) {
1926
+ return null;
1927
+ }
1928
+ return result.snapshot;
1929
+ } catch (error) {
1930
+ throw new MastraError(
1931
+ {
1932
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1933
+ domain: ErrorDomain.STORAGE,
1934
+ category: ErrorCategory.THIRD_PARTY,
1935
+ details: {
1936
+ workflowName,
1937
+ runId
1938
+ }
1939
+ },
1940
+ error
1941
+ );
1942
+ }
1943
+ }
1944
+ async getWorkflowRunById({
1945
+ runId,
1946
+ workflowName
1947
+ }) {
1948
+ try {
1949
+ const conditions = [];
1950
+ const paramMap = {};
1951
+ if (runId) {
1952
+ conditions.push(`[run_id] = @runId`);
1953
+ paramMap["runId"] = runId;
1954
+ }
1955
+ if (workflowName) {
1956
+ conditions.push(`[workflow_name] = @workflowName`);
1957
+ paramMap["workflowName"] = workflowName;
1958
+ }
1959
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1960
+ const tableName = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
1961
+ const query = `SELECT * FROM ${tableName} ${whereClause}`;
1962
+ const request = this.pool.request();
1963
+ Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
1964
+ const result = await request.query(query);
1965
+ if (!result.recordset || result.recordset.length === 0) {
1966
+ return null;
1967
+ }
1968
+ return parseWorkflowRun(result.recordset[0]);
1969
+ } catch (error) {
1970
+ throw new MastraError(
1971
+ {
1972
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
1973
+ domain: ErrorDomain.STORAGE,
1974
+ category: ErrorCategory.THIRD_PARTY,
1975
+ details: {
1976
+ runId,
1977
+ workflowName: workflowName || ""
1978
+ }
1979
+ },
1980
+ error
1981
+ );
1982
+ }
1983
+ }
1984
+ async getWorkflowRuns({
1985
+ workflowName,
1986
+ fromDate,
1987
+ toDate,
1988
+ limit,
1989
+ offset,
1990
+ resourceId
1991
+ } = {}) {
1992
+ try {
1993
+ const conditions = [];
1994
+ const paramMap = {};
1995
+ if (workflowName) {
1996
+ conditions.push(`[workflow_name] = @workflowName`);
1997
+ paramMap["workflowName"] = workflowName;
1998
+ }
1999
+ if (resourceId) {
2000
+ const hasResourceId = await this.operations.hasColumn(TABLE_WORKFLOW_SNAPSHOT, "resourceId");
2001
+ if (hasResourceId) {
2002
+ conditions.push(`[resourceId] = @resourceId`);
2003
+ paramMap["resourceId"] = resourceId;
2004
+ } else {
2005
+ console.warn(`[${TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
2006
+ }
2007
+ }
2008
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
2009
+ conditions.push(`[createdAt] >= @fromDate`);
2010
+ paramMap[`fromDate`] = fromDate.toISOString();
2011
+ }
2012
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
2013
+ conditions.push(`[createdAt] <= @toDate`);
2014
+ paramMap[`toDate`] = toDate.toISOString();
2015
+ }
2016
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2017
+ let total = 0;
2018
+ const tableName = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2019
+ const request = this.pool.request();
2020
+ Object.entries(paramMap).forEach(([key, value]) => {
2021
+ if (value instanceof Date) {
2022
+ request.input(key, sql2.DateTime, value);
2023
+ } else {
2024
+ request.input(key, value);
2025
+ }
2026
+ });
2027
+ if (limit !== void 0 && offset !== void 0) {
2028
+ const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
2029
+ const countResult = await request.query(countQuery);
2030
+ total = Number(countResult.recordset[0]?.count || 0);
2031
+ }
2032
+ let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
2033
+ if (limit !== void 0 && offset !== void 0) {
2034
+ query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
2035
+ request.input("limit", limit);
2036
+ request.input("offset", offset);
2037
+ }
2038
+ const result = await request.query(query);
2039
+ const runs = (result.recordset || []).map((row) => parseWorkflowRun(row));
2040
+ return { runs, total: total || runs.length };
2041
+ } catch (error) {
2042
+ throw new MastraError(
2043
+ {
2044
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
2045
+ domain: ErrorDomain.STORAGE,
2046
+ category: ErrorCategory.THIRD_PARTY,
2047
+ details: {
2048
+ workflowName: workflowName || "all"
2049
+ }
2050
+ },
2051
+ error
2052
+ );
2053
+ }
2054
+ }
2055
+ };
2056
+
2057
+ // src/storage/index.ts
2058
+ var MSSQLStore = class extends MastraStorage {
2059
+ pool;
2060
+ schema;
2061
+ isConnected = null;
2062
+ stores;
2063
+ constructor(config) {
2064
+ super({ name: "MSSQLStore" });
2065
+ try {
2066
+ if ("connectionString" in config) {
2067
+ if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
2068
+ throw new Error("MSSQLStore: connectionString must be provided and cannot be empty.");
2069
+ }
2070
+ } else {
2071
+ const required = ["server", "database", "user", "password"];
2072
+ for (const key of required) {
2073
+ if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
2074
+ throw new Error(`MSSQLStore: ${key} must be provided and cannot be empty.`);
2075
+ }
2076
+ }
2077
+ }
2078
+ this.schema = config.schemaName || "dbo";
2079
+ this.pool = "connectionString" in config ? new sql2.ConnectionPool(config.connectionString) : new sql2.ConnectionPool({
2080
+ server: config.server,
2081
+ database: config.database,
2082
+ user: config.user,
2083
+ password: config.password,
2084
+ port: config.port,
2085
+ options: config.options || { encrypt: true, trustServerCertificate: true }
2086
+ });
2087
+ const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
2088
+ const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
2089
+ const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
2090
+ const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
2091
+ const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
2092
+ const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
2093
+ this.stores = {
2094
+ operations,
2095
+ scores,
2096
+ traces,
2097
+ workflows,
2098
+ legacyEvals,
2099
+ memory
2100
+ };
2101
+ } catch (e) {
2102
+ throw new MastraError(
2103
+ {
2104
+ id: "MASTRA_STORAGE_MSSQL_STORE_INITIALIZATION_FAILED",
2105
+ domain: ErrorDomain.STORAGE,
2106
+ category: ErrorCategory.USER
2107
+ },
2108
+ e
2109
+ );
2110
+ }
2111
+ }
2112
+ async init() {
2113
+ if (this.isConnected === null) {
2114
+ this.isConnected = this._performInitializationAndStore();
2115
+ }
2116
+ try {
2117
+ await this.isConnected;
2118
+ await super.init();
2119
+ } catch (error) {
2120
+ this.isConnected = null;
2121
+ throw new MastraError(
2122
+ {
2123
+ id: "MASTRA_STORAGE_MSSQL_STORE_INIT_FAILED",
2124
+ domain: ErrorDomain.STORAGE,
2125
+ category: ErrorCategory.THIRD_PARTY
2126
+ },
2127
+ error
2128
+ );
2129
+ }
2130
+ }
2131
+ async _performInitializationAndStore() {
2132
+ try {
2133
+ await this.pool.connect();
2134
+ return true;
2135
+ } catch (err) {
2136
+ throw err;
2137
+ }
2138
+ }
2139
+ get supports() {
2140
+ return {
2141
+ selectByIncludeResourceScope: true,
2142
+ resourceWorkingMemory: true,
2143
+ hasColumn: true,
2144
+ createTable: true,
2145
+ deleteMessages: true
2146
+ };
2147
+ }
2148
+ /** @deprecated use getEvals instead */
2149
+ async getEvalsByAgentName(agentName, type) {
2150
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2151
+ }
2152
+ async getEvals(options = {}) {
2153
+ return this.stores.legacyEvals.getEvals(options);
2154
+ }
2155
+ /**
2156
+ * @deprecated use getTracesPaginated instead
2157
+ */
2158
+ async getTraces(args) {
2159
+ return this.stores.traces.getTraces(args);
2160
+ }
2161
+ async getTracesPaginated(args) {
2162
+ return this.stores.traces.getTracesPaginated(args);
2163
+ }
2164
+ async batchTraceInsert({ records }) {
2165
+ return this.stores.traces.batchTraceInsert({ records });
2166
+ }
2167
+ async createTable({
2168
+ tableName,
2169
+ schema
2170
+ }) {
2171
+ return this.stores.operations.createTable({ tableName, schema });
2172
+ }
2173
+ async alterTable({
2174
+ tableName,
2175
+ schema,
2176
+ ifNotExists
2177
+ }) {
2178
+ return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
2179
+ }
2180
+ async clearTable({ tableName }) {
2181
+ return this.stores.operations.clearTable({ tableName });
2182
+ }
2183
+ async dropTable({ tableName }) {
2184
+ return this.stores.operations.dropTable({ tableName });
2185
+ }
2186
+ async insert({ tableName, record }) {
2187
+ return this.stores.operations.insert({ tableName, record });
2188
+ }
2189
+ async batchInsert({ tableName, records }) {
2190
+ return this.stores.operations.batchInsert({ tableName, records });
2191
+ }
2192
+ async load({ tableName, keys }) {
2193
+ return this.stores.operations.load({ tableName, keys });
2194
+ }
2195
+ /**
2196
+ * Memory
2197
+ */
2198
+ async getThreadById({ threadId }) {
2199
+ return this.stores.memory.getThreadById({ threadId });
2200
+ }
2201
+ /**
2202
+ * @deprecated use getThreadsByResourceIdPaginated instead
2203
+ */
2204
+ async getThreadsByResourceId(args) {
2205
+ return this.stores.memory.getThreadsByResourceId(args);
2206
+ }
2207
+ async getThreadsByResourceIdPaginated(args) {
2208
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
2209
+ }
2210
+ async saveThread({ thread }) {
2211
+ return this.stores.memory.saveThread({ thread });
2212
+ }
2213
+ async updateThread({
2214
+ id,
2215
+ title,
2216
+ metadata
2217
+ }) {
2218
+ return this.stores.memory.updateThread({ id, title, metadata });
2219
+ }
2220
+ async deleteThread({ threadId }) {
2221
+ return this.stores.memory.deleteThread({ threadId });
2222
+ }
2223
+ async getMessages(args) {
2224
+ return this.stores.memory.getMessages(args);
2225
+ }
2226
+ async getMessagesById({
2227
+ messageIds,
2228
+ format
2229
+ }) {
2230
+ return this.stores.memory.getMessagesById({ messageIds, format });
2231
+ }
2232
+ async getMessagesPaginated(args) {
2233
+ return this.stores.memory.getMessagesPaginated(args);
2234
+ }
2235
+ async saveMessages(args) {
2236
+ return this.stores.memory.saveMessages(args);
2237
+ }
2238
+ async updateMessages({
2239
+ messages
2240
+ }) {
2241
+ return this.stores.memory.updateMessages({ messages });
2242
+ }
2243
+ async deleteMessages(messageIds) {
2244
+ return this.stores.memory.deleteMessages(messageIds);
2245
+ }
2246
+ async getResourceById({ resourceId }) {
2247
+ return this.stores.memory.getResourceById({ resourceId });
2248
+ }
2249
+ async saveResource({ resource }) {
2250
+ return this.stores.memory.saveResource({ resource });
2251
+ }
2252
+ async updateResource({
2253
+ resourceId,
2254
+ workingMemory,
2255
+ metadata
2256
+ }) {
2257
+ return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
2258
+ }
2259
+ /**
2260
+ * Workflows
2261
+ */
2262
+ async persistWorkflowSnapshot({
2263
+ workflowName,
2264
+ runId,
2265
+ snapshot
2266
+ }) {
2267
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2268
+ }
2269
+ async loadWorkflowSnapshot({
2270
+ workflowName,
2271
+ runId
2272
+ }) {
2273
+ return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
2274
+ }
2275
+ async getWorkflowRuns({
2276
+ workflowName,
2277
+ fromDate,
2278
+ toDate,
2279
+ limit,
2280
+ offset,
2281
+ resourceId
2282
+ } = {}) {
2283
+ return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2284
+ }
2285
+ async getWorkflowRunById({
2286
+ runId,
2287
+ workflowName
2288
+ }) {
2289
+ return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2290
+ }
2291
+ async close() {
2292
+ await this.pool.close();
2293
+ }
2294
+ /**
2295
+ * Scorers
2296
+ */
2297
+ async getScoreById({ id: _id }) {
2298
+ return this.stores.scores.getScoreById({ id: _id });
2299
+ }
2300
+ async getScoresByScorerId({
2301
+ scorerId: _scorerId,
2302
+ pagination: _pagination
2303
+ }) {
2304
+ return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2305
+ }
2306
+ async saveScore(_score) {
2307
+ return this.stores.scores.saveScore(_score);
2308
+ }
2309
+ async getScoresByRunId({
2310
+ runId: _runId,
2311
+ pagination: _pagination
2312
+ }) {
2313
+ return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2314
+ }
2315
+ async getScoresByEntityId({
2316
+ entityId: _entityId,
2317
+ entityType: _entityType,
2318
+ pagination: _pagination
2319
+ }) {
2320
+ return this.stores.scores.getScoresByEntityId({
2321
+ entityId: _entityId,
2322
+ entityType: _entityType,
2323
+ pagination: _pagination
1811
2324
  });
1812
2325
  }
1813
2326
  };