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