@mastra/mssql 0.0.0-update-stores-peerDeps-20250723031338 → 0.0.0-vector-query-tool-provider-options-20250828222356

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