@mastra/mssql 0.0.0-share-agent-metadata-with-cloud-20250718110128 → 0.0.0-stream-vnext-usage-20250908171242

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