@mastra/mssql 0.2.3 → 0.3.0-alpha.0

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