@mastra/mssql 0.0.0-share-agent-metadata-with-cloud-20250718123411 → 0.0.0-suspendRuntimeContextTypeFix-20250930142630

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