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

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