@mastra/mssql 0.2.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1752 @@
1
+ 'use strict';
2
+
3
+ var agent = require('@mastra/core/agent');
4
+ var error = require('@mastra/core/error');
5
+ var storage = require('@mastra/core/storage');
6
+ var utils = require('@mastra/core/utils');
7
+ var sql = require('mssql');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var sql__default = /*#__PURE__*/_interopDefault(sql);
12
+
13
+ // src/storage/index.ts
14
+ var MSSQLStore = class extends storage.MastraStorage {
15
+ pool;
16
+ schema;
17
+ setupSchemaPromise = null;
18
+ schemaSetupComplete = void 0;
19
+ isConnected = null;
20
+ constructor(config) {
21
+ super({ name: "MSSQLStore" });
22
+ try {
23
+ if ("connectionString" in config) {
24
+ if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
25
+ throw new Error("MSSQLStore: connectionString must be provided and cannot be empty.");
26
+ }
27
+ } else {
28
+ const required = ["server", "database", "user", "password"];
29
+ for (const key of required) {
30
+ if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
31
+ throw new Error(`MSSQLStore: ${key} must be provided and cannot be empty.`);
32
+ }
33
+ }
34
+ }
35
+ this.schema = config.schemaName;
36
+ this.pool = "connectionString" in config ? new sql__default.default.ConnectionPool(config.connectionString) : new sql__default.default.ConnectionPool({
37
+ server: config.server,
38
+ database: config.database,
39
+ user: config.user,
40
+ password: config.password,
41
+ port: config.port,
42
+ options: config.options || { encrypt: true, trustServerCertificate: true }
43
+ });
44
+ } catch (e) {
45
+ throw new error.MastraError(
46
+ {
47
+ id: "MASTRA_STORAGE_MSSQL_STORE_INITIALIZATION_FAILED",
48
+ domain: error.ErrorDomain.STORAGE,
49
+ category: error.ErrorCategory.USER
50
+ },
51
+ e
52
+ );
53
+ }
54
+ }
55
+ async init() {
56
+ if (this.isConnected === null) {
57
+ this.isConnected = this._performInitializationAndStore();
58
+ }
59
+ try {
60
+ await this.isConnected;
61
+ await super.init();
62
+ } catch (error$1) {
63
+ this.isConnected = null;
64
+ throw new error.MastraError(
65
+ {
66
+ id: "MASTRA_STORAGE_MSSQL_STORE_INIT_FAILED",
67
+ domain: error.ErrorDomain.STORAGE,
68
+ category: error.ErrorCategory.THIRD_PARTY
69
+ },
70
+ error$1
71
+ );
72
+ }
73
+ }
74
+ async _performInitializationAndStore() {
75
+ try {
76
+ await this.pool.connect();
77
+ return true;
78
+ } catch (err) {
79
+ throw err;
80
+ }
81
+ }
82
+ get supports() {
83
+ return {
84
+ selectByIncludeResourceScope: true,
85
+ resourceWorkingMemory: true
86
+ };
87
+ }
88
+ getTableName(indexName) {
89
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
90
+ const quotedIndexName = `[${parsedIndexName}]`;
91
+ const quotedSchemaName = this.getSchemaName();
92
+ return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
93
+ }
94
+ getSchemaName() {
95
+ return this.schema ? `[${utils.parseSqlIdentifier(this.schema, "schema name")}]` : void 0;
96
+ }
97
+ transformEvalRow(row) {
98
+ let testInfoValue = null, resultValue = null;
99
+ if (row.test_info) {
100
+ try {
101
+ testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
102
+ } catch {
103
+ }
104
+ }
105
+ if (row.test_info) {
106
+ try {
107
+ resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
108
+ } catch {
109
+ }
110
+ }
111
+ return {
112
+ agentName: row.agent_name,
113
+ input: row.input,
114
+ output: row.output,
115
+ result: resultValue,
116
+ metricName: row.metric_name,
117
+ instructions: row.instructions,
118
+ testInfo: testInfoValue,
119
+ globalRunId: row.global_run_id,
120
+ runId: row.run_id,
121
+ createdAt: row.created_at
122
+ };
123
+ }
124
+ /** @deprecated use getEvals instead */
125
+ async getEvalsByAgentName(agentName, type) {
126
+ try {
127
+ let query = `SELECT * FROM ${this.getTableName(storage.TABLE_EVALS)} WHERE agent_name = @p1`;
128
+ if (type === "test") {
129
+ query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
130
+ } else if (type === "live") {
131
+ query += " AND (test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)";
132
+ }
133
+ query += " ORDER BY created_at DESC";
134
+ const request = this.pool.request();
135
+ request.input("p1", agentName);
136
+ const result = await request.query(query);
137
+ const rows = result.recordset;
138
+ return typeof this.transformEvalRow === "function" ? rows?.map((row) => this.transformEvalRow(row)) ?? [] : rows ?? [];
139
+ } catch (error) {
140
+ if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
141
+ return [];
142
+ }
143
+ console.error("Failed to get evals for the specified agent: " + error?.message);
144
+ throw error;
145
+ }
146
+ }
147
+ async batchInsert({ tableName, records }) {
148
+ const transaction = this.pool.transaction();
149
+ try {
150
+ await transaction.begin();
151
+ for (const record of records) {
152
+ await this.insert({ tableName, record });
153
+ }
154
+ await transaction.commit();
155
+ } catch (error$1) {
156
+ await transaction.rollback();
157
+ throw new error.MastraError(
158
+ {
159
+ id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
160
+ domain: error.ErrorDomain.STORAGE,
161
+ category: error.ErrorCategory.THIRD_PARTY,
162
+ details: {
163
+ tableName,
164
+ numberOfRecords: records.length
165
+ }
166
+ },
167
+ error$1
168
+ );
169
+ }
170
+ }
171
+ /** @deprecated use getTracesPaginated instead*/
172
+ async getTraces(args) {
173
+ if (args.fromDate || args.toDate) {
174
+ args.dateRange = {
175
+ start: args.fromDate,
176
+ end: args.toDate
177
+ };
178
+ }
179
+ const result = await this.getTracesPaginated(args);
180
+ return result.traces;
181
+ }
182
+ async getTracesPaginated(args) {
183
+ const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
184
+ const fromDate = dateRange?.start;
185
+ const toDate = dateRange?.end;
186
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
187
+ const currentOffset = page * perPage;
188
+ const paramMap = {};
189
+ const conditions = [];
190
+ let paramIndex = 1;
191
+ if (name) {
192
+ const paramName = `p${paramIndex++}`;
193
+ conditions.push(`[name] LIKE @${paramName}`);
194
+ paramMap[paramName] = `${name}%`;
195
+ }
196
+ if (scope) {
197
+ const paramName = `p${paramIndex++}`;
198
+ conditions.push(`[scope] = @${paramName}`);
199
+ paramMap[paramName] = scope;
200
+ }
201
+ if (attributes) {
202
+ Object.entries(attributes).forEach(([key, value]) => {
203
+ const parsedKey = utils.parseFieldKey(key);
204
+ const paramName = `p${paramIndex++}`;
205
+ conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
206
+ paramMap[paramName] = value;
207
+ });
208
+ }
209
+ if (filters) {
210
+ Object.entries(filters).forEach(([key, value]) => {
211
+ const parsedKey = utils.parseFieldKey(key);
212
+ const paramName = `p${paramIndex++}`;
213
+ conditions.push(`[${parsedKey}] = @${paramName}`);
214
+ paramMap[paramName] = value;
215
+ });
216
+ }
217
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
218
+ const paramName = `p${paramIndex++}`;
219
+ conditions.push(`[createdAt] >= @${paramName}`);
220
+ paramMap[paramName] = fromDate.toISOString();
221
+ }
222
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
223
+ const paramName = `p${paramIndex++}`;
224
+ conditions.push(`[createdAt] <= @${paramName}`);
225
+ paramMap[paramName] = toDate.toISOString();
226
+ }
227
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
228
+ const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(storage.TABLE_TRACES)} ${whereClause}`;
229
+ let total = 0;
230
+ try {
231
+ const countRequest = this.pool.request();
232
+ Object.entries(paramMap).forEach(([key, value]) => {
233
+ if (value instanceof Date) {
234
+ countRequest.input(key, sql__default.default.DateTime, value);
235
+ } else {
236
+ countRequest.input(key, value);
237
+ }
238
+ });
239
+ const countResult = await countRequest.query(countQuery);
240
+ total = parseInt(countResult.recordset[0].total, 10);
241
+ } catch (error$1) {
242
+ throw new error.MastraError(
243
+ {
244
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
245
+ domain: error.ErrorDomain.STORAGE,
246
+ category: error.ErrorCategory.THIRD_PARTY,
247
+ details: {
248
+ name: args.name ?? "",
249
+ scope: args.scope ?? ""
250
+ }
251
+ },
252
+ error$1
253
+ );
254
+ }
255
+ if (total === 0) {
256
+ return {
257
+ traces: [],
258
+ total: 0,
259
+ page,
260
+ perPage,
261
+ hasMore: false
262
+ };
263
+ }
264
+ const dataQuery = `SELECT * FROM ${this.getTableName(storage.TABLE_TRACES)} ${whereClause} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
265
+ const dataRequest = this.pool.request();
266
+ Object.entries(paramMap).forEach(([key, value]) => {
267
+ if (value instanceof Date) {
268
+ dataRequest.input(key, sql__default.default.DateTime, value);
269
+ } else {
270
+ dataRequest.input(key, value);
271
+ }
272
+ });
273
+ dataRequest.input("offset", currentOffset);
274
+ dataRequest.input("limit", perPage);
275
+ try {
276
+ const rowsResult = await dataRequest.query(dataQuery);
277
+ const rows = rowsResult.recordset;
278
+ const traces = rows.map((row) => ({
279
+ id: row.id,
280
+ parentSpanId: row.parentSpanId,
281
+ traceId: row.traceId,
282
+ name: row.name,
283
+ scope: row.scope,
284
+ kind: row.kind,
285
+ status: JSON.parse(row.status),
286
+ events: JSON.parse(row.events),
287
+ links: JSON.parse(row.links),
288
+ attributes: JSON.parse(row.attributes),
289
+ startTime: row.startTime,
290
+ endTime: row.endTime,
291
+ other: row.other,
292
+ createdAt: row.createdAt
293
+ }));
294
+ return {
295
+ traces,
296
+ total,
297
+ page,
298
+ perPage,
299
+ hasMore: currentOffset + traces.length < total
300
+ };
301
+ } catch (error$1) {
302
+ throw new error.MastraError(
303
+ {
304
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
305
+ domain: error.ErrorDomain.STORAGE,
306
+ category: error.ErrorCategory.THIRD_PARTY,
307
+ details: {
308
+ name: args.name ?? "",
309
+ scope: args.scope ?? ""
310
+ }
311
+ },
312
+ error$1
313
+ );
314
+ }
315
+ }
316
+ async setupSchema() {
317
+ if (!this.schema || this.schemaSetupComplete) {
318
+ return;
319
+ }
320
+ if (!this.setupSchemaPromise) {
321
+ this.setupSchemaPromise = (async () => {
322
+ try {
323
+ const checkRequest = this.pool.request();
324
+ checkRequest.input("schemaName", this.schema);
325
+ const checkResult = await checkRequest.query(`
326
+ SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
327
+ `);
328
+ const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
329
+ if (!schemaExists) {
330
+ try {
331
+ await this.pool.request().query(`CREATE SCHEMA [${this.schema}]`);
332
+ this.logger?.info?.(`Schema "${this.schema}" created successfully`);
333
+ } catch (error) {
334
+ this.logger?.error?.(`Failed to create schema "${this.schema}"`, { error });
335
+ throw new Error(
336
+ `Unable to create schema "${this.schema}". This requires CREATE privilege on the database. Either create the schema manually or grant CREATE privilege to the user.`
337
+ );
338
+ }
339
+ }
340
+ this.schemaSetupComplete = true;
341
+ this.logger?.debug?.(`Schema "${this.schema}" is ready for use`);
342
+ } catch (error) {
343
+ this.schemaSetupComplete = void 0;
344
+ this.setupSchemaPromise = null;
345
+ throw error;
346
+ } finally {
347
+ this.setupSchemaPromise = null;
348
+ }
349
+ })();
350
+ }
351
+ await this.setupSchemaPromise;
352
+ }
353
+ getSqlType(type, isPrimaryKey = false) {
354
+ switch (type) {
355
+ case "text":
356
+ return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(MAX)";
357
+ case "timestamp":
358
+ return "DATETIME2(7)";
359
+ case "uuid":
360
+ return "UNIQUEIDENTIFIER";
361
+ case "jsonb":
362
+ return "NVARCHAR(MAX)";
363
+ case "integer":
364
+ return "INT";
365
+ case "bigint":
366
+ return "BIGINT";
367
+ default:
368
+ throw new error.MastraError({
369
+ id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
370
+ domain: error.ErrorDomain.STORAGE,
371
+ category: error.ErrorCategory.THIRD_PARTY
372
+ });
373
+ }
374
+ }
375
+ async createTable({
376
+ tableName,
377
+ schema
378
+ }) {
379
+ try {
380
+ const uniqueConstraintColumns = tableName === storage.TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
381
+ const columns = Object.entries(schema).map(([name, def]) => {
382
+ const parsedName = utils.parseSqlIdentifier(name, "column name");
383
+ const constraints = [];
384
+ if (def.primaryKey) constraints.push("PRIMARY KEY");
385
+ if (!def.nullable) constraints.push("NOT NULL");
386
+ const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
387
+ return `[${parsedName}] ${this.getSqlType(def.type, isIndexed)} ${constraints.join(" ")}`.trim();
388
+ }).join(",\n");
389
+ if (this.schema) {
390
+ await this.setupSchema();
391
+ }
392
+ const checkTableRequest = this.pool.request();
393
+ checkTableRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
394
+ const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
395
+ checkTableRequest.input("schema", this.schema || "dbo");
396
+ const checkTableResult = await checkTableRequest.query(checkTableSql);
397
+ const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
398
+ if (!tableExists) {
399
+ const createSql = `CREATE TABLE ${this.getTableName(tableName)} (
400
+ ${columns}
401
+ )`;
402
+ await this.pool.request().query(createSql);
403
+ }
404
+ const columnCheckSql = `
405
+ SELECT 1 AS found
406
+ FROM INFORMATION_SCHEMA.COLUMNS
407
+ WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
408
+ `;
409
+ const checkColumnRequest = this.pool.request();
410
+ checkColumnRequest.input("schema", this.schema || "dbo");
411
+ checkColumnRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
412
+ const columnResult = await checkColumnRequest.query(columnCheckSql);
413
+ const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
414
+ if (!columnExists) {
415
+ const alterSql = `ALTER TABLE ${this.getTableName(tableName)} ADD seq_id BIGINT IDENTITY(1,1)`;
416
+ await this.pool.request().query(alterSql);
417
+ }
418
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
419
+ const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
420
+ const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
421
+ const checkConstraintRequest = this.pool.request();
422
+ checkConstraintRequest.input("constraintName", constraintName);
423
+ const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
424
+ const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
425
+ if (!constraintExists) {
426
+ const addConstraintSql = `ALTER TABLE ${this.getTableName(tableName)} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
427
+ await this.pool.request().query(addConstraintSql);
428
+ }
429
+ }
430
+ } catch (error$1) {
431
+ throw new error.MastraError(
432
+ {
433
+ id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
434
+ domain: error.ErrorDomain.STORAGE,
435
+ category: error.ErrorCategory.THIRD_PARTY,
436
+ details: {
437
+ tableName
438
+ }
439
+ },
440
+ error$1
441
+ );
442
+ }
443
+ }
444
+ getDefaultValue(type) {
445
+ switch (type) {
446
+ case "timestamp":
447
+ return "DEFAULT SYSDATETIMEOFFSET()";
448
+ case "jsonb":
449
+ return "DEFAULT N'{}'";
450
+ default:
451
+ return super.getDefaultValue(type);
452
+ }
453
+ }
454
+ async alterTable({
455
+ tableName,
456
+ schema,
457
+ ifNotExists
458
+ }) {
459
+ const fullTableName = this.getTableName(tableName);
460
+ try {
461
+ for (const columnName of ifNotExists) {
462
+ if (schema[columnName]) {
463
+ const columnCheckRequest = this.pool.request();
464
+ columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
465
+ columnCheckRequest.input("columnName", columnName);
466
+ columnCheckRequest.input("schema", this.schema || "dbo");
467
+ const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
468
+ const checkResult = await columnCheckRequest.query(checkSql);
469
+ const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
470
+ if (!columnExists) {
471
+ const columnDef = schema[columnName];
472
+ const sqlType = this.getSqlType(columnDef.type);
473
+ const nullable = columnDef.nullable === false ? "NOT NULL" : "";
474
+ const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
475
+ const parsedColumnName = utils.parseSqlIdentifier(columnName, "column name");
476
+ const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
477
+ await this.pool.request().query(alterSql);
478
+ this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
479
+ }
480
+ }
481
+ }
482
+ } catch (error$1) {
483
+ throw new error.MastraError(
484
+ {
485
+ id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
486
+ domain: error.ErrorDomain.STORAGE,
487
+ category: error.ErrorCategory.THIRD_PARTY,
488
+ details: {
489
+ tableName
490
+ }
491
+ },
492
+ error$1
493
+ );
494
+ }
495
+ }
496
+ async clearTable({ tableName }) {
497
+ const fullTableName = this.getTableName(tableName);
498
+ try {
499
+ const fkQuery = `
500
+ SELECT
501
+ OBJECT_SCHEMA_NAME(fk.parent_object_id) AS schema_name,
502
+ OBJECT_NAME(fk.parent_object_id) AS table_name
503
+ FROM sys.foreign_keys fk
504
+ WHERE fk.referenced_object_id = OBJECT_ID(@fullTableName)
505
+ `;
506
+ const fkResult = await this.pool.request().input("fullTableName", fullTableName).query(fkQuery);
507
+ const childTables = fkResult.recordset || [];
508
+ for (const child of childTables) {
509
+ const childTableName = this.schema ? `[${child.schema_name}].[${child.table_name}]` : `[${child.table_name}]`;
510
+ await this.clearTable({ tableName: childTableName });
511
+ }
512
+ await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
513
+ } catch (error$1) {
514
+ throw new error.MastraError(
515
+ {
516
+ id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
517
+ domain: error.ErrorDomain.STORAGE,
518
+ category: error.ErrorCategory.THIRD_PARTY,
519
+ details: {
520
+ tableName
521
+ }
522
+ },
523
+ error$1
524
+ );
525
+ }
526
+ }
527
+ async insert({ tableName, record }) {
528
+ try {
529
+ const columns = Object.keys(record).map((col) => utils.parseSqlIdentifier(col, "column name"));
530
+ const values = Object.values(record);
531
+ const paramNames = values.map((_, i) => `@param${i}`);
532
+ const insertSql = `INSERT INTO ${this.getTableName(tableName)} (${columns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
533
+ const request = this.pool.request();
534
+ values.forEach((value, i) => {
535
+ if (value instanceof Date) {
536
+ request.input(`param${i}`, sql__default.default.DateTime2, value);
537
+ } else if (typeof value === "object" && value !== null) {
538
+ request.input(`param${i}`, JSON.stringify(value));
539
+ } else {
540
+ request.input(`param${i}`, value);
541
+ }
542
+ });
543
+ await request.query(insertSql);
544
+ } catch (error$1) {
545
+ throw new error.MastraError(
546
+ {
547
+ id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
548
+ domain: error.ErrorDomain.STORAGE,
549
+ category: error.ErrorCategory.THIRD_PARTY,
550
+ details: {
551
+ tableName
552
+ }
553
+ },
554
+ error$1
555
+ );
556
+ }
557
+ }
558
+ async load({ tableName, keys }) {
559
+ try {
560
+ const keyEntries = Object.entries(keys).map(([key, value]) => [utils.parseSqlIdentifier(key, "column name"), value]);
561
+ const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
562
+ const values = keyEntries.map(([_, value]) => value);
563
+ const sql2 = `SELECT * FROM ${this.getTableName(tableName)} WHERE ${conditions}`;
564
+ const request = this.pool.request();
565
+ values.forEach((value, i) => {
566
+ request.input(`param${i}`, value);
567
+ });
568
+ const resultSet = await request.query(sql2);
569
+ const result = resultSet.recordset[0] || null;
570
+ if (!result) {
571
+ return null;
572
+ }
573
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
574
+ const snapshot = result;
575
+ if (typeof snapshot.snapshot === "string") {
576
+ snapshot.snapshot = JSON.parse(snapshot.snapshot);
577
+ }
578
+ return snapshot;
579
+ }
580
+ return result;
581
+ } catch (error$1) {
582
+ throw new error.MastraError(
583
+ {
584
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
585
+ domain: error.ErrorDomain.STORAGE,
586
+ category: error.ErrorCategory.THIRD_PARTY,
587
+ details: {
588
+ tableName
589
+ }
590
+ },
591
+ error$1
592
+ );
593
+ }
594
+ }
595
+ async getThreadById({ threadId }) {
596
+ try {
597
+ const sql2 = `SELECT
598
+ id,
599
+ [resourceId],
600
+ title,
601
+ metadata,
602
+ [createdAt],
603
+ [updatedAt]
604
+ FROM ${this.getTableName(storage.TABLE_THREADS)}
605
+ WHERE id = @threadId`;
606
+ const request = this.pool.request();
607
+ request.input("threadId", threadId);
608
+ const resultSet = await request.query(sql2);
609
+ const thread = resultSet.recordset[0] || null;
610
+ if (!thread) {
611
+ return null;
612
+ }
613
+ return {
614
+ ...thread,
615
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
616
+ createdAt: thread.createdAt,
617
+ updatedAt: thread.updatedAt
618
+ };
619
+ } catch (error$1) {
620
+ throw new error.MastraError(
621
+ {
622
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
623
+ domain: error.ErrorDomain.STORAGE,
624
+ category: error.ErrorCategory.THIRD_PARTY,
625
+ details: {
626
+ threadId
627
+ }
628
+ },
629
+ error$1
630
+ );
631
+ }
632
+ }
633
+ async getThreadsByResourceIdPaginated(args) {
634
+ const { resourceId, page = 0, perPage: perPageInput } = args;
635
+ try {
636
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
637
+ const currentOffset = page * perPage;
638
+ const baseQuery = `FROM ${this.getTableName(storage.TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
639
+ const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
640
+ const countRequest = this.pool.request();
641
+ countRequest.input("resourceId", resourceId);
642
+ const countResult = await countRequest.query(countQuery);
643
+ const total = parseInt(countResult.recordset[0]?.count ?? "0", 10);
644
+ if (total === 0) {
645
+ return {
646
+ threads: [],
647
+ total: 0,
648
+ page,
649
+ perPage,
650
+ hasMore: false
651
+ };
652
+ }
653
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
654
+ const dataRequest = this.pool.request();
655
+ dataRequest.input("resourceId", resourceId);
656
+ dataRequest.input("perPage", perPage);
657
+ dataRequest.input("offset", currentOffset);
658
+ const rowsResult = await dataRequest.query(dataQuery);
659
+ const rows = rowsResult.recordset || [];
660
+ const threads = rows.map((thread) => ({
661
+ ...thread,
662
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
663
+ createdAt: thread.createdAt,
664
+ updatedAt: thread.updatedAt
665
+ }));
666
+ return {
667
+ threads,
668
+ total,
669
+ page,
670
+ perPage,
671
+ hasMore: currentOffset + threads.length < total
672
+ };
673
+ } catch (error$1) {
674
+ const mastraError = new error.MastraError(
675
+ {
676
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
677
+ domain: error.ErrorDomain.STORAGE,
678
+ category: error.ErrorCategory.THIRD_PARTY,
679
+ details: {
680
+ resourceId,
681
+ page
682
+ }
683
+ },
684
+ error$1
685
+ );
686
+ this.logger?.error?.(mastraError.toString());
687
+ this.logger?.trackException?.(mastraError);
688
+ return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
689
+ }
690
+ }
691
+ async saveThread({ thread }) {
692
+ try {
693
+ const table = this.getTableName(storage.TABLE_THREADS);
694
+ const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
695
+ USING (SELECT @id AS id) AS source
696
+ ON (target.id = source.id)
697
+ WHEN MATCHED THEN
698
+ UPDATE SET
699
+ [resourceId] = @resourceId,
700
+ title = @title,
701
+ metadata = @metadata,
702
+ [createdAt] = @createdAt,
703
+ [updatedAt] = @updatedAt
704
+ WHEN NOT MATCHED THEN
705
+ INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
706
+ VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
707
+ const req = this.pool.request();
708
+ req.input("id", thread.id);
709
+ req.input("resourceId", thread.resourceId);
710
+ req.input("title", thread.title);
711
+ req.input("metadata", thread.metadata ? JSON.stringify(thread.metadata) : null);
712
+ req.input("createdAt", thread.createdAt);
713
+ req.input("updatedAt", thread.updatedAt);
714
+ await req.query(mergeSql);
715
+ return thread;
716
+ } catch (error$1) {
717
+ throw new error.MastraError(
718
+ {
719
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
720
+ domain: error.ErrorDomain.STORAGE,
721
+ category: error.ErrorCategory.THIRD_PARTY,
722
+ details: {
723
+ threadId: thread.id
724
+ }
725
+ },
726
+ error$1
727
+ );
728
+ }
729
+ }
730
+ /**
731
+ * @deprecated use getThreadsByResourceIdPaginated instead
732
+ */
733
+ async getThreadsByResourceId(args) {
734
+ const { resourceId } = args;
735
+ try {
736
+ const baseQuery = `FROM ${this.getTableName(storage.TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
737
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC`;
738
+ const request = this.pool.request();
739
+ request.input("resourceId", resourceId);
740
+ const resultSet = await request.query(dataQuery);
741
+ const rows = resultSet.recordset || [];
742
+ return rows.map((thread) => ({
743
+ ...thread,
744
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
745
+ createdAt: thread.createdAt,
746
+ updatedAt: thread.updatedAt
747
+ }));
748
+ } catch (error) {
749
+ this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
750
+ return [];
751
+ }
752
+ }
753
+ /**
754
+ * Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
755
+ */
756
+ async updateThread({
757
+ id,
758
+ title,
759
+ metadata
760
+ }) {
761
+ const existingThread = await this.getThreadById({ threadId: id });
762
+ if (!existingThread) {
763
+ throw new error.MastraError({
764
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED",
765
+ domain: error.ErrorDomain.STORAGE,
766
+ category: error.ErrorCategory.USER,
767
+ text: `Thread ${id} not found`,
768
+ details: {
769
+ threadId: id,
770
+ title
771
+ }
772
+ });
773
+ }
774
+ const mergedMetadata = {
775
+ ...existingThread.metadata,
776
+ ...metadata
777
+ };
778
+ try {
779
+ const table = this.getTableName(storage.TABLE_THREADS);
780
+ const sql2 = `UPDATE ${table}
781
+ SET title = @title,
782
+ metadata = @metadata,
783
+ [updatedAt] = @updatedAt
784
+ OUTPUT INSERTED.*
785
+ WHERE id = @id`;
786
+ const req = this.pool.request();
787
+ req.input("id", id);
788
+ req.input("title", title);
789
+ req.input("metadata", JSON.stringify(mergedMetadata));
790
+ req.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
791
+ const result = await req.query(sql2);
792
+ let thread = result.recordset && result.recordset[0];
793
+ if (thread && "seq_id" in thread) {
794
+ const { seq_id, ...rest } = thread;
795
+ thread = rest;
796
+ }
797
+ if (!thread) {
798
+ throw new error.MastraError({
799
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED",
800
+ domain: error.ErrorDomain.STORAGE,
801
+ category: error.ErrorCategory.USER,
802
+ text: `Thread ${id} not found after update`,
803
+ details: {
804
+ threadId: id,
805
+ title
806
+ }
807
+ });
808
+ }
809
+ return {
810
+ ...thread,
811
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
812
+ createdAt: thread.createdAt,
813
+ updatedAt: thread.updatedAt
814
+ };
815
+ } catch (error$1) {
816
+ throw new error.MastraError(
817
+ {
818
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED",
819
+ domain: error.ErrorDomain.STORAGE,
820
+ category: error.ErrorCategory.THIRD_PARTY,
821
+ details: {
822
+ threadId: id,
823
+ title
824
+ }
825
+ },
826
+ error$1
827
+ );
828
+ }
829
+ }
830
+ async deleteThread({ threadId }) {
831
+ const messagesTable = this.getTableName(storage.TABLE_MESSAGES);
832
+ const threadsTable = this.getTableName(storage.TABLE_THREADS);
833
+ const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
834
+ const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
835
+ const tx = this.pool.transaction();
836
+ try {
837
+ await tx.begin();
838
+ const req = tx.request();
839
+ req.input("threadId", threadId);
840
+ await req.query(deleteMessagesSql);
841
+ await req.query(deleteThreadSql);
842
+ await tx.commit();
843
+ } catch (error$1) {
844
+ await tx.rollback().catch(() => {
845
+ });
846
+ throw new error.MastraError(
847
+ {
848
+ id: "MASTRA_STORAGE_MSSQL_STORE_DELETE_THREAD_FAILED",
849
+ domain: error.ErrorDomain.STORAGE,
850
+ category: error.ErrorCategory.THIRD_PARTY,
851
+ details: {
852
+ threadId
853
+ }
854
+ },
855
+ error$1
856
+ );
857
+ }
858
+ }
859
+ async _getIncludedMessages({
860
+ threadId,
861
+ selectBy,
862
+ orderByStatement
863
+ }) {
864
+ const include = selectBy?.include;
865
+ if (!include) return null;
866
+ const unionQueries = [];
867
+ const paramValues = [];
868
+ let paramIdx = 1;
869
+ const paramNames = [];
870
+ for (const inc of include) {
871
+ const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
872
+ const searchId = inc.threadId || threadId;
873
+ const pThreadId = `@p${paramIdx}`;
874
+ const pId = `@p${paramIdx + 1}`;
875
+ const pPrev = `@p${paramIdx + 2}`;
876
+ const pNext = `@p${paramIdx + 3}`;
877
+ unionQueries.push(
878
+ `
879
+ SELECT
880
+ m.id,
881
+ m.content,
882
+ m.role,
883
+ m.type,
884
+ m.[createdAt],
885
+ m.thread_id AS threadId,
886
+ m.[resourceId],
887
+ m.seq_id
888
+ FROM (
889
+ SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
890
+ FROM ${this.getTableName(storage.TABLE_MESSAGES)}
891
+ WHERE [thread_id] = ${pThreadId}
892
+ ) AS m
893
+ WHERE m.id = ${pId}
894
+ OR EXISTS (
895
+ SELECT 1
896
+ FROM (
897
+ SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
898
+ FROM ${this.getTableName(storage.TABLE_MESSAGES)}
899
+ WHERE [thread_id] = ${pThreadId}
900
+ ) AS target
901
+ WHERE target.id = ${pId}
902
+ AND (
903
+ (m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
904
+ OR
905
+ (m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
906
+ )
907
+ )
908
+ `
909
+ );
910
+ paramValues.push(searchId, id, withPreviousMessages, withNextMessages);
911
+ paramNames.push(`p${paramIdx}`, `p${paramIdx + 1}`, `p${paramIdx + 2}`, `p${paramIdx + 3}`);
912
+ paramIdx += 4;
913
+ }
914
+ const finalQuery = `
915
+ SELECT * FROM (
916
+ ${unionQueries.join(" UNION ALL ")}
917
+ ) AS union_result
918
+ ORDER BY [seq_id] ASC
919
+ `;
920
+ const req = this.pool.request();
921
+ for (let i = 0; i < paramValues.length; ++i) {
922
+ req.input(paramNames[i], paramValues[i]);
923
+ }
924
+ const result = await req.query(finalQuery);
925
+ const includedRows = result.recordset || [];
926
+ const seen = /* @__PURE__ */ new Set();
927
+ const dedupedRows = includedRows.filter((row) => {
928
+ if (seen.has(row.id)) return false;
929
+ seen.add(row.id);
930
+ return true;
931
+ });
932
+ return dedupedRows;
933
+ }
934
+ async getMessages(args) {
935
+ const { threadId, format, selectBy } = args;
936
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
937
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
938
+ const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
939
+ try {
940
+ let rows = [];
941
+ const include = selectBy?.include || [];
942
+ if (include?.length) {
943
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
944
+ if (includeMessages) {
945
+ rows.push(...includeMessages);
946
+ }
947
+ }
948
+ const excludeIds = rows.map((m) => m.id).filter(Boolean);
949
+ let query = `${selectStatement} FROM ${this.getTableName(storage.TABLE_MESSAGES)} WHERE [thread_id] = @threadId`;
950
+ const request = this.pool.request();
951
+ request.input("threadId", threadId);
952
+ if (excludeIds.length > 0) {
953
+ const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
954
+ query += ` AND id NOT IN (${excludeParams.join(", ")})`;
955
+ excludeIds.forEach((id, idx) => {
956
+ request.input(`id${idx}`, id);
957
+ });
958
+ }
959
+ query += ` ${orderByStatement} OFFSET 0 ROWS FETCH NEXT @limit ROWS ONLY`;
960
+ request.input("limit", limit);
961
+ const result = await request.query(query);
962
+ const remainingRows = result.recordset || [];
963
+ rows.push(...remainingRows);
964
+ rows.sort((a, b) => {
965
+ const timeDiff = a.seq_id - b.seq_id;
966
+ return timeDiff;
967
+ });
968
+ rows = rows.map(({ seq_id, ...rest }) => rest);
969
+ const fetchedMessages = (rows || []).map((message) => {
970
+ if (typeof message.content === "string") {
971
+ try {
972
+ message.content = JSON.parse(message.content);
973
+ } catch {
974
+ }
975
+ }
976
+ if (format === "v1") {
977
+ if (Array.isArray(message.content)) ; else if (typeof message.content === "object" && message.content && Array.isArray(message.content.parts)) {
978
+ message.content = message.content.parts;
979
+ } else {
980
+ message.content = [{ type: "text", text: "" }];
981
+ }
982
+ } else {
983
+ if (typeof message.content !== "object" || !message.content || !("parts" in message.content)) {
984
+ message.content = { format: 2, parts: [{ type: "text", text: "" }] };
985
+ }
986
+ }
987
+ if (message.type === "v2") delete message.type;
988
+ return message;
989
+ });
990
+ return format === "v2" ? fetchedMessages.map(
991
+ (m) => ({ ...m, content: m.content || { format: 2, parts: [{ type: "text", text: "" }] } })
992
+ ) : fetchedMessages;
993
+ } catch (error$1) {
994
+ const mastraError = new error.MastraError(
995
+ {
996
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_FAILED",
997
+ domain: error.ErrorDomain.STORAGE,
998
+ category: error.ErrorCategory.THIRD_PARTY,
999
+ details: {
1000
+ threadId
1001
+ }
1002
+ },
1003
+ error$1
1004
+ );
1005
+ this.logger?.error?.(mastraError.toString());
1006
+ this.logger?.trackException(mastraError);
1007
+ return [];
1008
+ }
1009
+ }
1010
+ async getMessagesPaginated(args) {
1011
+ const { threadId, selectBy } = args;
1012
+ const { page = 0, perPage: perPageInput } = selectBy?.pagination || {};
1013
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
1014
+ if (selectBy?.include?.length) {
1015
+ await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
1016
+ }
1017
+ try {
1018
+ const { threadId: threadId2, format, selectBy: selectBy2 } = args;
1019
+ const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
1020
+ const fromDate = dateRange?.start;
1021
+ const toDate = dateRange?.end;
1022
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
1023
+ const orderByStatement2 = `ORDER BY [seq_id] DESC`;
1024
+ let messages2 = [];
1025
+ if (selectBy2?.include?.length) {
1026
+ const includeMessages = await this._getIncludedMessages({ threadId: threadId2, selectBy: selectBy2, orderByStatement: orderByStatement2 });
1027
+ if (includeMessages) messages2.push(...includeMessages);
1028
+ }
1029
+ const perPage = perPageInput2 !== void 0 ? perPageInput2 : this.resolveMessageLimit({ last: selectBy2?.last, defaultLimit: 40 });
1030
+ const currentOffset = page2 * perPage;
1031
+ const conditions = ["[thread_id] = @threadId"];
1032
+ const request = this.pool.request();
1033
+ request.input("threadId", threadId2);
1034
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1035
+ conditions.push("[createdAt] >= @fromDate");
1036
+ request.input("fromDate", fromDate.toISOString());
1037
+ }
1038
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1039
+ conditions.push("[createdAt] <= @toDate");
1040
+ request.input("toDate", toDate.toISOString());
1041
+ }
1042
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
1043
+ const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(storage.TABLE_MESSAGES)} ${whereClause}`;
1044
+ const countResult = await request.query(countQuery);
1045
+ const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
1046
+ if (total === 0 && messages2.length > 0) {
1047
+ const parsedIncluded = this._parseAndFormatMessages(messages2, format);
1048
+ return {
1049
+ messages: parsedIncluded,
1050
+ total: parsedIncluded.length,
1051
+ page: page2,
1052
+ perPage,
1053
+ hasMore: false
1054
+ };
1055
+ }
1056
+ const excludeIds = messages2.map((m) => m.id);
1057
+ if (excludeIds.length > 0) {
1058
+ const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
1059
+ conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
1060
+ excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
1061
+ }
1062
+ const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
1063
+ const dataQuery = `${selectStatement} FROM ${this.getTableName(storage.TABLE_MESSAGES)} ${finalWhereClause} ${orderByStatement2} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1064
+ request.input("offset", currentOffset);
1065
+ request.input("limit", perPage);
1066
+ const rowsResult = await request.query(dataQuery);
1067
+ const rows = rowsResult.recordset || [];
1068
+ rows.sort((a, b) => a.seq_id - b.seq_id);
1069
+ messages2.push(...rows);
1070
+ const parsed = this._parseAndFormatMessages(messages2, format);
1071
+ return {
1072
+ messages: parsed,
1073
+ total: total + excludeIds.length,
1074
+ page: page2,
1075
+ perPage,
1076
+ hasMore: currentOffset + rows.length < total
1077
+ };
1078
+ } catch (error$1) {
1079
+ const mastraError = new error.MastraError(
1080
+ {
1081
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
1082
+ domain: error.ErrorDomain.STORAGE,
1083
+ category: error.ErrorCategory.THIRD_PARTY,
1084
+ details: {
1085
+ threadId,
1086
+ page
1087
+ }
1088
+ },
1089
+ error$1
1090
+ );
1091
+ this.logger?.error?.(mastraError.toString());
1092
+ this.logger?.trackException(mastraError);
1093
+ return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
1094
+ }
1095
+ }
1096
+ _parseAndFormatMessages(messages, format) {
1097
+ const parsedMessages = messages.map((message) => {
1098
+ let parsed = message;
1099
+ if (typeof parsed.content === "string") {
1100
+ try {
1101
+ parsed = { ...parsed, content: JSON.parse(parsed.content) };
1102
+ } catch {
1103
+ }
1104
+ }
1105
+ if (format === "v1") {
1106
+ if (Array.isArray(parsed.content)) ; else if (parsed.content?.parts) {
1107
+ parsed.content = parsed.content.parts;
1108
+ } else {
1109
+ parsed.content = [{ type: "text", text: "" }];
1110
+ }
1111
+ } else {
1112
+ if (!parsed.content?.parts) {
1113
+ parsed = { ...parsed, content: { format: 2, parts: [{ type: "text", text: "" }] } };
1114
+ }
1115
+ }
1116
+ return parsed;
1117
+ });
1118
+ const list = new agent.MessageList().add(parsedMessages, "memory");
1119
+ return format === "v2" ? list.get.all.v2() : list.get.all.v1();
1120
+ }
1121
+ async saveMessages({
1122
+ messages,
1123
+ format
1124
+ }) {
1125
+ if (messages.length === 0) return messages;
1126
+ const threadId = messages[0]?.threadId;
1127
+ if (!threadId) {
1128
+ throw new error.MastraError({
1129
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED",
1130
+ domain: error.ErrorDomain.STORAGE,
1131
+ category: error.ErrorCategory.THIRD_PARTY,
1132
+ text: `Thread ID is required`
1133
+ });
1134
+ }
1135
+ const thread = await this.getThreadById({ threadId });
1136
+ if (!thread) {
1137
+ throw new error.MastraError({
1138
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED",
1139
+ domain: error.ErrorDomain.STORAGE,
1140
+ category: error.ErrorCategory.THIRD_PARTY,
1141
+ text: `Thread ${threadId} not found`,
1142
+ details: { threadId }
1143
+ });
1144
+ }
1145
+ const tableMessages = this.getTableName(storage.TABLE_MESSAGES);
1146
+ const tableThreads = this.getTableName(storage.TABLE_THREADS);
1147
+ try {
1148
+ const transaction = this.pool.transaction();
1149
+ await transaction.begin();
1150
+ try {
1151
+ for (const message of messages) {
1152
+ if (!message.threadId) {
1153
+ throw new Error(
1154
+ `Expected to find a threadId for message, but couldn't find one. An unexpected error has occurred.`
1155
+ );
1156
+ }
1157
+ if (!message.resourceId) {
1158
+ throw new Error(
1159
+ `Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred.`
1160
+ );
1161
+ }
1162
+ const request = transaction.request();
1163
+ request.input("id", message.id);
1164
+ request.input("thread_id", message.threadId);
1165
+ request.input(
1166
+ "content",
1167
+ typeof message.content === "string" ? message.content : JSON.stringify(message.content)
1168
+ );
1169
+ request.input("createdAt", message.createdAt.toISOString() || (/* @__PURE__ */ new Date()).toISOString());
1170
+ request.input("role", message.role);
1171
+ request.input("type", message.type || "v2");
1172
+ request.input("resourceId", message.resourceId);
1173
+ const mergeSql = `MERGE INTO ${tableMessages} AS target
1174
+ USING (SELECT @id AS id) AS src
1175
+ ON target.id = src.id
1176
+ WHEN MATCHED THEN UPDATE SET
1177
+ thread_id = @thread_id,
1178
+ content = @content,
1179
+ [createdAt] = @createdAt,
1180
+ role = @role,
1181
+ type = @type,
1182
+ resourceId = @resourceId
1183
+ WHEN NOT MATCHED THEN INSERT (id, thread_id, content, [createdAt], role, type, resourceId)
1184
+ VALUES (@id, @thread_id, @content, @createdAt, @role, @type, @resourceId);`;
1185
+ await request.query(mergeSql);
1186
+ }
1187
+ const threadReq = transaction.request();
1188
+ threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
1189
+ threadReq.input("id", threadId);
1190
+ await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
1191
+ await transaction.commit();
1192
+ } catch (error) {
1193
+ await transaction.rollback();
1194
+ throw error;
1195
+ }
1196
+ const messagesWithParsedContent = messages.map((message) => {
1197
+ if (typeof message.content === "string") {
1198
+ try {
1199
+ return { ...message, content: JSON.parse(message.content) };
1200
+ } catch {
1201
+ return message;
1202
+ }
1203
+ }
1204
+ return message;
1205
+ });
1206
+ const list = new agent.MessageList().add(messagesWithParsedContent, "memory");
1207
+ if (format === "v2") return list.get.all.v2();
1208
+ return list.get.all.v1();
1209
+ } catch (error$1) {
1210
+ throw new error.MastraError(
1211
+ {
1212
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED",
1213
+ domain: error.ErrorDomain.STORAGE,
1214
+ category: error.ErrorCategory.THIRD_PARTY,
1215
+ details: { threadId }
1216
+ },
1217
+ error$1
1218
+ );
1219
+ }
1220
+ }
1221
+ async persistWorkflowSnapshot({
1222
+ workflowName,
1223
+ runId,
1224
+ snapshot
1225
+ }) {
1226
+ const table = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1227
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1228
+ try {
1229
+ const request = this.pool.request();
1230
+ request.input("workflow_name", workflowName);
1231
+ request.input("run_id", runId);
1232
+ request.input("snapshot", JSON.stringify(snapshot));
1233
+ request.input("createdAt", now);
1234
+ request.input("updatedAt", now);
1235
+ const mergeSql = `MERGE INTO ${table} AS target
1236
+ USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
1237
+ ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
1238
+ WHEN MATCHED THEN UPDATE SET
1239
+ snapshot = @snapshot,
1240
+ [updatedAt] = @updatedAt
1241
+ WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
1242
+ VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
1243
+ await request.query(mergeSql);
1244
+ } catch (error$1) {
1245
+ throw new error.MastraError(
1246
+ {
1247
+ id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1248
+ domain: error.ErrorDomain.STORAGE,
1249
+ category: error.ErrorCategory.THIRD_PARTY,
1250
+ details: {
1251
+ workflowName,
1252
+ runId
1253
+ }
1254
+ },
1255
+ error$1
1256
+ );
1257
+ }
1258
+ }
1259
+ async loadWorkflowSnapshot({
1260
+ workflowName,
1261
+ runId
1262
+ }) {
1263
+ try {
1264
+ const result = await this.load({
1265
+ tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
1266
+ keys: {
1267
+ workflow_name: workflowName,
1268
+ run_id: runId
1269
+ }
1270
+ });
1271
+ if (!result) {
1272
+ return null;
1273
+ }
1274
+ return result.snapshot;
1275
+ } catch (error$1) {
1276
+ throw new error.MastraError(
1277
+ {
1278
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1279
+ domain: error.ErrorDomain.STORAGE,
1280
+ category: error.ErrorCategory.THIRD_PARTY,
1281
+ details: {
1282
+ workflowName,
1283
+ runId
1284
+ }
1285
+ },
1286
+ error$1
1287
+ );
1288
+ }
1289
+ }
1290
+ async hasColumn(table, column) {
1291
+ const schema = this.schema || "dbo";
1292
+ const request = this.pool.request();
1293
+ request.input("schema", schema);
1294
+ request.input("table", table);
1295
+ request.input("column", column);
1296
+ request.input("columnLower", column.toLowerCase());
1297
+ const result = await request.query(
1298
+ `SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
1299
+ );
1300
+ return result.recordset.length > 0;
1301
+ }
1302
+ parseWorkflowRun(row) {
1303
+ let parsedSnapshot = row.snapshot;
1304
+ if (typeof parsedSnapshot === "string") {
1305
+ try {
1306
+ parsedSnapshot = JSON.parse(row.snapshot);
1307
+ } catch (e) {
1308
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1309
+ }
1310
+ }
1311
+ return {
1312
+ workflowName: row.workflow_name,
1313
+ runId: row.run_id,
1314
+ snapshot: parsedSnapshot,
1315
+ createdAt: row.createdAt,
1316
+ updatedAt: row.updatedAt,
1317
+ resourceId: row.resourceId
1318
+ };
1319
+ }
1320
+ async getWorkflowRuns({
1321
+ workflowName,
1322
+ fromDate,
1323
+ toDate,
1324
+ limit,
1325
+ offset,
1326
+ resourceId
1327
+ } = {}) {
1328
+ try {
1329
+ const conditions = [];
1330
+ const paramMap = {};
1331
+ if (workflowName) {
1332
+ conditions.push(`[workflow_name] = @workflowName`);
1333
+ paramMap["workflowName"] = workflowName;
1334
+ }
1335
+ if (resourceId) {
1336
+ const hasResourceId = await this.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
1337
+ if (hasResourceId) {
1338
+ conditions.push(`[resourceId] = @resourceId`);
1339
+ paramMap["resourceId"] = resourceId;
1340
+ } else {
1341
+ console.warn(`[${storage.TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
1342
+ }
1343
+ }
1344
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1345
+ conditions.push(`[createdAt] >= @fromDate`);
1346
+ paramMap[`fromDate`] = fromDate.toISOString();
1347
+ }
1348
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1349
+ conditions.push(`[createdAt] <= @toDate`);
1350
+ paramMap[`toDate`] = toDate.toISOString();
1351
+ }
1352
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1353
+ let total = 0;
1354
+ const tableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1355
+ const request = this.pool.request();
1356
+ Object.entries(paramMap).forEach(([key, value]) => {
1357
+ if (value instanceof Date) {
1358
+ request.input(key, sql__default.default.DateTime, value);
1359
+ } else {
1360
+ request.input(key, value);
1361
+ }
1362
+ });
1363
+ if (limit !== void 0 && offset !== void 0) {
1364
+ const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
1365
+ const countResult = await request.query(countQuery);
1366
+ total = Number(countResult.recordset[0]?.count || 0);
1367
+ }
1368
+ let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
1369
+ if (limit !== void 0 && offset !== void 0) {
1370
+ query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1371
+ request.input("limit", limit);
1372
+ request.input("offset", offset);
1373
+ }
1374
+ const result = await request.query(query);
1375
+ const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
1376
+ return { runs, total: total || runs.length };
1377
+ } catch (error$1) {
1378
+ throw new error.MastraError(
1379
+ {
1380
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
1381
+ domain: error.ErrorDomain.STORAGE,
1382
+ category: error.ErrorCategory.THIRD_PARTY,
1383
+ details: {
1384
+ workflowName: workflowName || "all"
1385
+ }
1386
+ },
1387
+ error$1
1388
+ );
1389
+ }
1390
+ }
1391
+ async getWorkflowRunById({
1392
+ runId,
1393
+ workflowName
1394
+ }) {
1395
+ try {
1396
+ const conditions = [];
1397
+ const paramMap = {};
1398
+ if (runId) {
1399
+ conditions.push(`[run_id] = @runId`);
1400
+ paramMap["runId"] = runId;
1401
+ }
1402
+ if (workflowName) {
1403
+ conditions.push(`[workflow_name] = @workflowName`);
1404
+ paramMap["workflowName"] = workflowName;
1405
+ }
1406
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1407
+ const tableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1408
+ const query = `SELECT * FROM ${tableName} ${whereClause}`;
1409
+ const request = this.pool.request();
1410
+ Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
1411
+ const result = await request.query(query);
1412
+ if (!result.recordset || result.recordset.length === 0) {
1413
+ return null;
1414
+ }
1415
+ return this.parseWorkflowRun(result.recordset[0]);
1416
+ } catch (error$1) {
1417
+ throw new error.MastraError(
1418
+ {
1419
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
1420
+ domain: error.ErrorDomain.STORAGE,
1421
+ category: error.ErrorCategory.THIRD_PARTY,
1422
+ details: {
1423
+ runId,
1424
+ workflowName: workflowName || ""
1425
+ }
1426
+ },
1427
+ error$1
1428
+ );
1429
+ }
1430
+ }
1431
+ async updateMessages({
1432
+ messages
1433
+ }) {
1434
+ if (!messages || messages.length === 0) {
1435
+ return [];
1436
+ }
1437
+ const messageIds = messages.map((m) => m.id);
1438
+ const idParams = messageIds.map((_, i) => `@id${i}`).join(", ");
1439
+ let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${this.getTableName(storage.TABLE_MESSAGES)}`;
1440
+ if (idParams.length > 0) {
1441
+ selectQuery += ` WHERE id IN (${idParams})`;
1442
+ } else {
1443
+ return [];
1444
+ }
1445
+ const selectReq = this.pool.request();
1446
+ messageIds.forEach((id, i) => selectReq.input(`id${i}`, id));
1447
+ const existingMessagesDb = (await selectReq.query(selectQuery)).recordset;
1448
+ if (!existingMessagesDb || existingMessagesDb.length === 0) {
1449
+ return [];
1450
+ }
1451
+ const existingMessages = existingMessagesDb.map((msg) => {
1452
+ if (typeof msg.content === "string") {
1453
+ try {
1454
+ msg.content = JSON.parse(msg.content);
1455
+ } catch {
1456
+ }
1457
+ }
1458
+ return msg;
1459
+ });
1460
+ const threadIdsToUpdate = /* @__PURE__ */ new Set();
1461
+ const transaction = this.pool.transaction();
1462
+ try {
1463
+ await transaction.begin();
1464
+ for (const existingMessage of existingMessages) {
1465
+ const updatePayload = messages.find((m) => m.id === existingMessage.id);
1466
+ if (!updatePayload) continue;
1467
+ const { id, ...fieldsToUpdate } = updatePayload;
1468
+ if (Object.keys(fieldsToUpdate).length === 0) continue;
1469
+ threadIdsToUpdate.add(existingMessage.threadId);
1470
+ if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
1471
+ threadIdsToUpdate.add(updatePayload.threadId);
1472
+ }
1473
+ const setClauses = [];
1474
+ const req = transaction.request();
1475
+ req.input("id", id);
1476
+ const columnMapping = { threadId: "thread_id" };
1477
+ const updatableFields = { ...fieldsToUpdate };
1478
+ if (updatableFields.content) {
1479
+ const newContent = {
1480
+ ...existingMessage.content,
1481
+ ...updatableFields.content,
1482
+ ...existingMessage.content?.metadata && updatableFields.content.metadata ? { metadata: { ...existingMessage.content.metadata, ...updatableFields.content.metadata } } : {}
1483
+ };
1484
+ setClauses.push(`content = @content`);
1485
+ req.input("content", JSON.stringify(newContent));
1486
+ delete updatableFields.content;
1487
+ }
1488
+ for (const key in updatableFields) {
1489
+ if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
1490
+ const dbColumn = columnMapping[key] || key;
1491
+ setClauses.push(`[${dbColumn}] = @${dbColumn}`);
1492
+ req.input(dbColumn, updatableFields[key]);
1493
+ }
1494
+ }
1495
+ if (setClauses.length > 0) {
1496
+ const updateSql = `UPDATE ${this.getTableName(storage.TABLE_MESSAGES)} SET ${setClauses.join(", ")} WHERE id = @id`;
1497
+ await req.query(updateSql);
1498
+ }
1499
+ }
1500
+ if (threadIdsToUpdate.size > 0) {
1501
+ const threadIdParams = Array.from(threadIdsToUpdate).map((_, i) => `@tid${i}`).join(", ");
1502
+ const threadReq = transaction.request();
1503
+ Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
1504
+ threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
1505
+ const threadSql = `UPDATE ${this.getTableName(storage.TABLE_THREADS)} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
1506
+ await threadReq.query(threadSql);
1507
+ }
1508
+ await transaction.commit();
1509
+ } catch (error$1) {
1510
+ await transaction.rollback();
1511
+ throw new error.MastraError(
1512
+ {
1513
+ id: "MASTRA_STORAGE_MSSQL_UPDATE_MESSAGES_FAILED",
1514
+ domain: error.ErrorDomain.STORAGE,
1515
+ category: error.ErrorCategory.THIRD_PARTY
1516
+ },
1517
+ error$1
1518
+ );
1519
+ }
1520
+ const refetchReq = this.pool.request();
1521
+ messageIds.forEach((id, i) => refetchReq.input(`id${i}`, id));
1522
+ const updatedMessages = (await refetchReq.query(selectQuery)).recordset;
1523
+ return (updatedMessages || []).map((message) => {
1524
+ if (typeof message.content === "string") {
1525
+ try {
1526
+ message.content = JSON.parse(message.content);
1527
+ } catch {
1528
+ }
1529
+ }
1530
+ return message;
1531
+ });
1532
+ }
1533
+ async close() {
1534
+ if (this.pool) {
1535
+ try {
1536
+ if (this.pool.connected) {
1537
+ await this.pool.close();
1538
+ } else if (this.pool.connecting) {
1539
+ await this.pool.connect();
1540
+ await this.pool.close();
1541
+ }
1542
+ } catch (err) {
1543
+ if (err.message && err.message.includes("Cannot close a pool while it is connecting")) ; else {
1544
+ throw err;
1545
+ }
1546
+ }
1547
+ }
1548
+ }
1549
+ async getEvals(options = {}) {
1550
+ const { agentName, type, page = 0, perPage = 100, dateRange } = options;
1551
+ const fromDate = dateRange?.start;
1552
+ const toDate = dateRange?.end;
1553
+ const where = [];
1554
+ const params = {};
1555
+ if (agentName) {
1556
+ where.push("agent_name = @agentName");
1557
+ params["agentName"] = agentName;
1558
+ }
1559
+ if (type === "test") {
1560
+ where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
1561
+ } else if (type === "live") {
1562
+ where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
1563
+ }
1564
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1565
+ where.push(`[created_at] >= @fromDate`);
1566
+ params[`fromDate`] = fromDate.toISOString();
1567
+ }
1568
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1569
+ where.push(`[created_at] <= @toDate`);
1570
+ params[`toDate`] = toDate.toISOString();
1571
+ }
1572
+ const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
1573
+ const tableName = this.getTableName(storage.TABLE_EVALS);
1574
+ const offset = page * perPage;
1575
+ const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
1576
+ const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
1577
+ try {
1578
+ const countReq = this.pool.request();
1579
+ Object.entries(params).forEach(([key, value]) => {
1580
+ if (value instanceof Date) {
1581
+ countReq.input(key, sql__default.default.DateTime, value);
1582
+ } else {
1583
+ countReq.input(key, value);
1584
+ }
1585
+ });
1586
+ const countResult = await countReq.query(countQuery);
1587
+ const total = countResult.recordset[0]?.total || 0;
1588
+ if (total === 0) {
1589
+ return {
1590
+ evals: [],
1591
+ total: 0,
1592
+ page,
1593
+ perPage,
1594
+ hasMore: false
1595
+ };
1596
+ }
1597
+ const req = this.pool.request();
1598
+ Object.entries(params).forEach(([key, value]) => {
1599
+ if (value instanceof Date) {
1600
+ req.input(key, sql__default.default.DateTime, value);
1601
+ } else {
1602
+ req.input(key, value);
1603
+ }
1604
+ });
1605
+ req.input("offset", offset);
1606
+ req.input("perPage", perPage);
1607
+ const result = await req.query(dataQuery);
1608
+ const rows = result.recordset;
1609
+ return {
1610
+ evals: rows?.map((row) => this.transformEvalRow(row)) ?? [],
1611
+ total,
1612
+ page,
1613
+ perPage,
1614
+ hasMore: offset + (rows?.length ?? 0) < total
1615
+ };
1616
+ } catch (error$1) {
1617
+ const mastraError = new error.MastraError(
1618
+ {
1619
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
1620
+ domain: error.ErrorDomain.STORAGE,
1621
+ category: error.ErrorCategory.THIRD_PARTY,
1622
+ details: {
1623
+ agentName: agentName || "all",
1624
+ type: type || "all",
1625
+ page,
1626
+ perPage
1627
+ }
1628
+ },
1629
+ error$1
1630
+ );
1631
+ this.logger?.error?.(mastraError.toString());
1632
+ this.logger?.trackException(mastraError);
1633
+ throw mastraError;
1634
+ }
1635
+ }
1636
+ async saveResource({ resource }) {
1637
+ const tableName = this.getTableName(storage.TABLE_RESOURCES);
1638
+ try {
1639
+ const req = this.pool.request();
1640
+ req.input("id", resource.id);
1641
+ req.input("workingMemory", resource.workingMemory);
1642
+ req.input("metadata", JSON.stringify(resource.metadata));
1643
+ req.input("createdAt", resource.createdAt.toISOString());
1644
+ req.input("updatedAt", resource.updatedAt.toISOString());
1645
+ await req.query(
1646
+ `INSERT INTO ${tableName} (id, workingMemory, metadata, createdAt, updatedAt) VALUES (@id, @workingMemory, @metadata, @createdAt, @updatedAt)`
1647
+ );
1648
+ return resource;
1649
+ } catch (error$1) {
1650
+ const mastraError = new error.MastraError(
1651
+ {
1652
+ id: "MASTRA_STORAGE_MSSQL_SAVE_RESOURCE_FAILED",
1653
+ domain: error.ErrorDomain.STORAGE,
1654
+ category: error.ErrorCategory.THIRD_PARTY,
1655
+ details: { resourceId: resource.id }
1656
+ },
1657
+ error$1
1658
+ );
1659
+ this.logger?.error?.(mastraError.toString());
1660
+ this.logger?.trackException(mastraError);
1661
+ throw mastraError;
1662
+ }
1663
+ }
1664
+ async updateResource({
1665
+ resourceId,
1666
+ workingMemory,
1667
+ metadata
1668
+ }) {
1669
+ try {
1670
+ const existingResource = await this.getResourceById({ resourceId });
1671
+ if (!existingResource) {
1672
+ const newResource = {
1673
+ id: resourceId,
1674
+ workingMemory,
1675
+ metadata: metadata || {},
1676
+ createdAt: /* @__PURE__ */ new Date(),
1677
+ updatedAt: /* @__PURE__ */ new Date()
1678
+ };
1679
+ return this.saveResource({ resource: newResource });
1680
+ }
1681
+ const updatedResource = {
1682
+ ...existingResource,
1683
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
1684
+ metadata: {
1685
+ ...existingResource.metadata,
1686
+ ...metadata
1687
+ },
1688
+ updatedAt: /* @__PURE__ */ new Date()
1689
+ };
1690
+ const tableName = this.getTableName(storage.TABLE_RESOURCES);
1691
+ const updates = [];
1692
+ const req = this.pool.request();
1693
+ if (workingMemory !== void 0) {
1694
+ updates.push("workingMemory = @workingMemory");
1695
+ req.input("workingMemory", workingMemory);
1696
+ }
1697
+ if (metadata) {
1698
+ updates.push("metadata = @metadata");
1699
+ req.input("metadata", JSON.stringify(updatedResource.metadata));
1700
+ }
1701
+ updates.push("updatedAt = @updatedAt");
1702
+ req.input("updatedAt", updatedResource.updatedAt.toISOString());
1703
+ req.input("id", resourceId);
1704
+ await req.query(`UPDATE ${tableName} SET ${updates.join(", ")} WHERE id = @id`);
1705
+ return updatedResource;
1706
+ } catch (error$1) {
1707
+ const mastraError = new error.MastraError(
1708
+ {
1709
+ id: "MASTRA_STORAGE_MSSQL_UPDATE_RESOURCE_FAILED",
1710
+ domain: error.ErrorDomain.STORAGE,
1711
+ category: error.ErrorCategory.THIRD_PARTY,
1712
+ details: { resourceId }
1713
+ },
1714
+ error$1
1715
+ );
1716
+ this.logger?.error?.(mastraError.toString());
1717
+ this.logger?.trackException(mastraError);
1718
+ throw mastraError;
1719
+ }
1720
+ }
1721
+ async getResourceById({ resourceId }) {
1722
+ const tableName = this.getTableName(storage.TABLE_RESOURCES);
1723
+ try {
1724
+ const req = this.pool.request();
1725
+ req.input("resourceId", resourceId);
1726
+ const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
1727
+ if (!result) {
1728
+ return null;
1729
+ }
1730
+ return {
1731
+ ...result,
1732
+ workingMemory: typeof result.workingMemory === "object" ? JSON.stringify(result.workingMemory) : result.workingMemory,
1733
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
1734
+ };
1735
+ } catch (error$1) {
1736
+ const mastraError = new error.MastraError(
1737
+ {
1738
+ id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
1739
+ domain: error.ErrorDomain.STORAGE,
1740
+ category: error.ErrorCategory.THIRD_PARTY,
1741
+ details: { resourceId }
1742
+ },
1743
+ error$1
1744
+ );
1745
+ this.logger?.error?.(mastraError.toString());
1746
+ this.logger?.trackException(mastraError);
1747
+ throw mastraError;
1748
+ }
1749
+ }
1750
+ };
1751
+
1752
+ exports.MSSQLStore = MSSQLStore;