@mastra/mssql 0.0.0-share-agent-metadata-with-cloud-20250718123411 → 0.0.0-taofeeq-fix-tool-call-showing-after-message-20250806162745

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