@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/.turbo/turbo-build.log +23 -0
- package/CHANGELOG.md +15 -0
- package/LICENSE.md +15 -0
- package/README.md +96 -0
- package/dist/_tsup-dts-rollup.d.cts +213 -0
- package/dist/_tsup-dts-rollup.d.ts +213 -0
- package/dist/index.cjs +1752 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1746 -0
- package/docker-compose.yaml +14 -0
- package/eslint.config.js +6 -0
- package/package.json +50 -0
- package/src/index.ts +2 -0
- package/src/storage/index.test.ts +2239 -0
- package/src/storage/index.ts +2044 -0
- package/tsconfig.json +5 -0
- package/vitest.config.ts +12 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1746 @@
|
|
|
1
|
+
import { MessageList } from '@mastra/core/agent';
|
|
2
|
+
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';
|
|
4
|
+
import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
|
|
5
|
+
import sql from 'mssql';
|
|
6
|
+
|
|
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
|
+
}
|
|
53
|
+
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
|
+
);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async _performInitializationAndStore() {
|
|
69
|
+
try {
|
|
70
|
+
await this.pool.connect();
|
|
71
|
+
return true;
|
|
72
|
+
} catch (err) {
|
|
73
|
+
throw err;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
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
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** @deprecated use getEvals instead */
|
|
119
|
+
async getEvalsByAgentName(agentName, type) {
|
|
120
|
+
try {
|
|
121
|
+
let query = `SELECT * FROM ${this.getTableName(TABLE_EVALS)} WHERE agent_name = @p1`;
|
|
122
|
+
if (type === "test") {
|
|
123
|
+
query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
|
|
124
|
+
} else if (type === "live") {
|
|
125
|
+
query += " AND (test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)";
|
|
126
|
+
}
|
|
127
|
+
query += " ORDER BY created_at DESC";
|
|
128
|
+
const request = this.pool.request();
|
|
129
|
+
request.input("p1", agentName);
|
|
130
|
+
const result = await request.query(query);
|
|
131
|
+
const rows = result.recordset;
|
|
132
|
+
return typeof this.transformEvalRow === "function" ? rows?.map((row) => this.transformEvalRow(row)) ?? [] : rows ?? [];
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
|
|
135
|
+
return [];
|
|
136
|
+
}
|
|
137
|
+
console.error("Failed to get evals for the specified agent: " + error?.message);
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
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;
|
|
178
|
+
const fromDate = dateRange?.start;
|
|
179
|
+
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
|
+
});
|
|
202
|
+
}
|
|
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
|
+
});
|
|
210
|
+
}
|
|
211
|
+
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
212
|
+
const paramName = `p${paramIndex++}`;
|
|
213
|
+
conditions.push(`[createdAt] >= @${paramName}`);
|
|
214
|
+
paramMap[paramName] = fromDate.toISOString();
|
|
215
|
+
}
|
|
216
|
+
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
217
|
+
const paramName = `p${paramIndex++}`;
|
|
218
|
+
conditions.push(`[createdAt] <= @${paramName}`);
|
|
219
|
+
paramMap[paramName] = toDate.toISOString();
|
|
220
|
+
}
|
|
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;
|
|
224
|
+
try {
|
|
225
|
+
const countRequest = this.pool.request();
|
|
226
|
+
Object.entries(paramMap).forEach(([key, value]) => {
|
|
227
|
+
if (value instanceof Date) {
|
|
228
|
+
countRequest.input(key, sql.DateTime, value);
|
|
229
|
+
} else {
|
|
230
|
+
countRequest.input(key, value);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
const countResult = await countRequest.query(countQuery);
|
|
234
|
+
total = parseInt(countResult.recordset[0].total, 10);
|
|
235
|
+
} catch (error) {
|
|
236
|
+
throw new MastraError(
|
|
237
|
+
{
|
|
238
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
|
|
239
|
+
domain: ErrorDomain.STORAGE,
|
|
240
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
241
|
+
details: {
|
|
242
|
+
name: args.name ?? "",
|
|
243
|
+
scope: args.scope ?? ""
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
error
|
|
247
|
+
);
|
|
248
|
+
}
|
|
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);
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
dataRequest.input("offset", currentOffset);
|
|
268
|
+
dataRequest.input("limit", perPage);
|
|
269
|
+
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
|
+
}));
|
|
288
|
+
return {
|
|
289
|
+
traces,
|
|
290
|
+
total,
|
|
291
|
+
page,
|
|
292
|
+
perPage,
|
|
293
|
+
hasMore: currentOffset + traces.length < total
|
|
294
|
+
};
|
|
295
|
+
} catch (error) {
|
|
296
|
+
throw new MastraError(
|
|
297
|
+
{
|
|
298
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
|
|
299
|
+
domain: ErrorDomain.STORAGE,
|
|
300
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
301
|
+
details: {
|
|
302
|
+
name: args.name ?? "",
|
|
303
|
+
scope: args.scope ?? ""
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
error
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
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
|
+
}) {
|
|
373
|
+
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
|
+
}
|
|
423
|
+
}
|
|
424
|
+
} catch (error) {
|
|
425
|
+
throw new MastraError(
|
|
426
|
+
{
|
|
427
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
|
|
428
|
+
domain: ErrorDomain.STORAGE,
|
|
429
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
430
|
+
details: {
|
|
431
|
+
tableName
|
|
432
|
+
}
|
|
433
|
+
},
|
|
434
|
+
error
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
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);
|
|
454
|
+
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
|
+
}
|
|
476
|
+
} catch (error) {
|
|
477
|
+
throw new MastraError(
|
|
478
|
+
{
|
|
479
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
|
|
480
|
+
domain: ErrorDomain.STORAGE,
|
|
481
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
482
|
+
details: {
|
|
483
|
+
tableName
|
|
484
|
+
}
|
|
485
|
+
},
|
|
486
|
+
error
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
async clearTable({ tableName }) {
|
|
491
|
+
const fullTableName = this.getTableName(tableName);
|
|
492
|
+
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`;
|
|
732
|
+
const request = this.pool.request();
|
|
733
|
+
request.input("resourceId", resourceId);
|
|
734
|
+
const resultSet = await request.query(dataQuery);
|
|
735
|
+
const rows = resultSet.recordset || [];
|
|
736
|
+
return rows.map((thread) => ({
|
|
737
|
+
...thread,
|
|
738
|
+
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
739
|
+
createdAt: thread.createdAt,
|
|
740
|
+
updatedAt: thread.updatedAt
|
|
741
|
+
}));
|
|
742
|
+
} catch (error) {
|
|
743
|
+
this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
|
|
744
|
+
return [];
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
|
|
749
|
+
*/
|
|
750
|
+
async updateThread({
|
|
751
|
+
id,
|
|
752
|
+
title,
|
|
753
|
+
metadata
|
|
754
|
+
}) {
|
|
755
|
+
const existingThread = await this.getThreadById({ threadId: id });
|
|
756
|
+
if (!existingThread) {
|
|
757
|
+
throw new MastraError({
|
|
758
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED",
|
|
759
|
+
domain: ErrorDomain.STORAGE,
|
|
760
|
+
category: ErrorCategory.USER,
|
|
761
|
+
text: `Thread ${id} not found`,
|
|
762
|
+
details: {
|
|
763
|
+
threadId: id,
|
|
764
|
+
title
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
const mergedMetadata = {
|
|
769
|
+
...existingThread.metadata,
|
|
770
|
+
...metadata
|
|
771
|
+
};
|
|
772
|
+
try {
|
|
773
|
+
const table = this.getTableName(TABLE_THREADS);
|
|
774
|
+
const sql2 = `UPDATE ${table}
|
|
775
|
+
SET title = @title,
|
|
776
|
+
metadata = @metadata,
|
|
777
|
+
[updatedAt] = @updatedAt
|
|
778
|
+
OUTPUT INSERTED.*
|
|
779
|
+
WHERE id = @id`;
|
|
780
|
+
const req = this.pool.request();
|
|
781
|
+
req.input("id", id);
|
|
782
|
+
req.input("title", title);
|
|
783
|
+
req.input("metadata", JSON.stringify(mergedMetadata));
|
|
784
|
+
req.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
|
|
785
|
+
const result = await req.query(sql2);
|
|
786
|
+
let thread = result.recordset && result.recordset[0];
|
|
787
|
+
if (thread && "seq_id" in thread) {
|
|
788
|
+
const { seq_id, ...rest } = thread;
|
|
789
|
+
thread = rest;
|
|
790
|
+
}
|
|
791
|
+
if (!thread) {
|
|
792
|
+
throw new MastraError({
|
|
793
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED",
|
|
794
|
+
domain: ErrorDomain.STORAGE,
|
|
795
|
+
category: ErrorCategory.USER,
|
|
796
|
+
text: `Thread ${id} not found after update`,
|
|
797
|
+
details: {
|
|
798
|
+
threadId: id,
|
|
799
|
+
title
|
|
800
|
+
}
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
return {
|
|
804
|
+
...thread,
|
|
805
|
+
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
806
|
+
createdAt: thread.createdAt,
|
|
807
|
+
updatedAt: thread.updatedAt
|
|
808
|
+
};
|
|
809
|
+
} catch (error) {
|
|
810
|
+
throw new MastraError(
|
|
811
|
+
{
|
|
812
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED",
|
|
813
|
+
domain: ErrorDomain.STORAGE,
|
|
814
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
815
|
+
details: {
|
|
816
|
+
threadId: id,
|
|
817
|
+
title
|
|
818
|
+
}
|
|
819
|
+
},
|
|
820
|
+
error
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
async deleteThread({ threadId }) {
|
|
825
|
+
const messagesTable = this.getTableName(TABLE_MESSAGES);
|
|
826
|
+
const threadsTable = this.getTableName(TABLE_THREADS);
|
|
827
|
+
const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
|
|
828
|
+
const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
|
|
829
|
+
const tx = this.pool.transaction();
|
|
830
|
+
try {
|
|
831
|
+
await tx.begin();
|
|
832
|
+
const req = tx.request();
|
|
833
|
+
req.input("threadId", threadId);
|
|
834
|
+
await req.query(deleteMessagesSql);
|
|
835
|
+
await req.query(deleteThreadSql);
|
|
836
|
+
await tx.commit();
|
|
837
|
+
} catch (error) {
|
|
838
|
+
await tx.rollback().catch(() => {
|
|
839
|
+
});
|
|
840
|
+
throw new MastraError(
|
|
841
|
+
{
|
|
842
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_DELETE_THREAD_FAILED",
|
|
843
|
+
domain: ErrorDomain.STORAGE,
|
|
844
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
845
|
+
details: {
|
|
846
|
+
threadId
|
|
847
|
+
}
|
|
848
|
+
},
|
|
849
|
+
error
|
|
850
|
+
);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
async _getIncludedMessages({
|
|
854
|
+
threadId,
|
|
855
|
+
selectBy,
|
|
856
|
+
orderByStatement
|
|
857
|
+
}) {
|
|
858
|
+
const include = selectBy?.include;
|
|
859
|
+
if (!include) return null;
|
|
860
|
+
const unionQueries = [];
|
|
861
|
+
const paramValues = [];
|
|
862
|
+
let paramIdx = 1;
|
|
863
|
+
const paramNames = [];
|
|
864
|
+
for (const inc of include) {
|
|
865
|
+
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
866
|
+
const searchId = inc.threadId || threadId;
|
|
867
|
+
const pThreadId = `@p${paramIdx}`;
|
|
868
|
+
const pId = `@p${paramIdx + 1}`;
|
|
869
|
+
const pPrev = `@p${paramIdx + 2}`;
|
|
870
|
+
const pNext = `@p${paramIdx + 3}`;
|
|
871
|
+
unionQueries.push(
|
|
872
|
+
`
|
|
873
|
+
SELECT
|
|
874
|
+
m.id,
|
|
875
|
+
m.content,
|
|
876
|
+
m.role,
|
|
877
|
+
m.type,
|
|
878
|
+
m.[createdAt],
|
|
879
|
+
m.thread_id AS threadId,
|
|
880
|
+
m.[resourceId],
|
|
881
|
+
m.seq_id
|
|
882
|
+
FROM (
|
|
883
|
+
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
884
|
+
FROM ${this.getTableName(TABLE_MESSAGES)}
|
|
885
|
+
WHERE [thread_id] = ${pThreadId}
|
|
886
|
+
) AS m
|
|
887
|
+
WHERE m.id = ${pId}
|
|
888
|
+
OR EXISTS (
|
|
889
|
+
SELECT 1
|
|
890
|
+
FROM (
|
|
891
|
+
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
892
|
+
FROM ${this.getTableName(TABLE_MESSAGES)}
|
|
893
|
+
WHERE [thread_id] = ${pThreadId}
|
|
894
|
+
) AS target
|
|
895
|
+
WHERE target.id = ${pId}
|
|
896
|
+
AND (
|
|
897
|
+
(m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
|
|
898
|
+
OR
|
|
899
|
+
(m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
|
|
900
|
+
)
|
|
901
|
+
)
|
|
902
|
+
`
|
|
903
|
+
);
|
|
904
|
+
paramValues.push(searchId, id, withPreviousMessages, withNextMessages);
|
|
905
|
+
paramNames.push(`p${paramIdx}`, `p${paramIdx + 1}`, `p${paramIdx + 2}`, `p${paramIdx + 3}`);
|
|
906
|
+
paramIdx += 4;
|
|
907
|
+
}
|
|
908
|
+
const finalQuery = `
|
|
909
|
+
SELECT * FROM (
|
|
910
|
+
${unionQueries.join(" UNION ALL ")}
|
|
911
|
+
) AS union_result
|
|
912
|
+
ORDER BY [seq_id] ASC
|
|
913
|
+
`;
|
|
914
|
+
const req = this.pool.request();
|
|
915
|
+
for (let i = 0; i < paramValues.length; ++i) {
|
|
916
|
+
req.input(paramNames[i], paramValues[i]);
|
|
917
|
+
}
|
|
918
|
+
const result = await req.query(finalQuery);
|
|
919
|
+
const includedRows = result.recordset || [];
|
|
920
|
+
const seen = /* @__PURE__ */ new Set();
|
|
921
|
+
const dedupedRows = includedRows.filter((row) => {
|
|
922
|
+
if (seen.has(row.id)) return false;
|
|
923
|
+
seen.add(row.id);
|
|
924
|
+
return true;
|
|
925
|
+
});
|
|
926
|
+
return dedupedRows;
|
|
927
|
+
}
|
|
928
|
+
async getMessages(args) {
|
|
929
|
+
const { threadId, format, selectBy } = args;
|
|
930
|
+
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
|
|
931
|
+
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
932
|
+
const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
933
|
+
try {
|
|
934
|
+
let rows = [];
|
|
935
|
+
const include = selectBy?.include || [];
|
|
936
|
+
if (include?.length) {
|
|
937
|
+
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
938
|
+
if (includeMessages) {
|
|
939
|
+
rows.push(...includeMessages);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
const excludeIds = rows.map((m) => m.id).filter(Boolean);
|
|
943
|
+
let query = `${selectStatement} FROM ${this.getTableName(TABLE_MESSAGES)} WHERE [thread_id] = @threadId`;
|
|
944
|
+
const request = this.pool.request();
|
|
945
|
+
request.input("threadId", threadId);
|
|
946
|
+
if (excludeIds.length > 0) {
|
|
947
|
+
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
948
|
+
query += ` AND id NOT IN (${excludeParams.join(", ")})`;
|
|
949
|
+
excludeIds.forEach((id, idx) => {
|
|
950
|
+
request.input(`id${idx}`, id);
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
query += ` ${orderByStatement} OFFSET 0 ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
954
|
+
request.input("limit", limit);
|
|
955
|
+
const result = await request.query(query);
|
|
956
|
+
const remainingRows = result.recordset || [];
|
|
957
|
+
rows.push(...remainingRows);
|
|
958
|
+
rows.sort((a, b) => {
|
|
959
|
+
const timeDiff = a.seq_id - b.seq_id;
|
|
960
|
+
return timeDiff;
|
|
961
|
+
});
|
|
962
|
+
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;
|
|
987
|
+
} catch (error) {
|
|
988
|
+
const mastraError = new MastraError(
|
|
989
|
+
{
|
|
990
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_FAILED",
|
|
991
|
+
domain: ErrorDomain.STORAGE,
|
|
992
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
993
|
+
details: {
|
|
994
|
+
threadId
|
|
995
|
+
}
|
|
996
|
+
},
|
|
997
|
+
error
|
|
998
|
+
);
|
|
999
|
+
this.logger?.error?.(mastraError.toString());
|
|
1000
|
+
this.logger?.trackException(mastraError);
|
|
1001
|
+
return [];
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
async getMessagesPaginated(args) {
|
|
1005
|
+
const { threadId, selectBy } = args;
|
|
1006
|
+
const { page = 0, perPage: perPageInput } = selectBy?.pagination || {};
|
|
1007
|
+
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
1008
|
+
if (selectBy?.include?.length) {
|
|
1009
|
+
await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
1010
|
+
}
|
|
1011
|
+
try {
|
|
1012
|
+
const { threadId: threadId2, format, selectBy: selectBy2 } = args;
|
|
1013
|
+
const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
|
|
1014
|
+
const fromDate = dateRange?.start;
|
|
1015
|
+
const toDate = dateRange?.end;
|
|
1016
|
+
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
|
|
1017
|
+
const orderByStatement2 = `ORDER BY [seq_id] DESC`;
|
|
1018
|
+
let messages2 = [];
|
|
1019
|
+
if (selectBy2?.include?.length) {
|
|
1020
|
+
const includeMessages = await this._getIncludedMessages({ threadId: threadId2, selectBy: selectBy2, orderByStatement: orderByStatement2 });
|
|
1021
|
+
if (includeMessages) messages2.push(...includeMessages);
|
|
1022
|
+
}
|
|
1023
|
+
const perPage = perPageInput2 !== void 0 ? perPageInput2 : this.resolveMessageLimit({ last: selectBy2?.last, defaultLimit: 40 });
|
|
1024
|
+
const currentOffset = page2 * perPage;
|
|
1025
|
+
const conditions = ["[thread_id] = @threadId"];
|
|
1026
|
+
const request = this.pool.request();
|
|
1027
|
+
request.input("threadId", threadId2);
|
|
1028
|
+
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1029
|
+
conditions.push("[createdAt] >= @fromDate");
|
|
1030
|
+
request.input("fromDate", fromDate.toISOString());
|
|
1031
|
+
}
|
|
1032
|
+
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1033
|
+
conditions.push("[createdAt] <= @toDate");
|
|
1034
|
+
request.input("toDate", toDate.toISOString());
|
|
1035
|
+
}
|
|
1036
|
+
const whereClause = `WHERE ${conditions.join(" AND ")}`;
|
|
1037
|
+
const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(TABLE_MESSAGES)} ${whereClause}`;
|
|
1038
|
+
const countResult = await request.query(countQuery);
|
|
1039
|
+
const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
|
|
1040
|
+
if (total === 0 && messages2.length > 0) {
|
|
1041
|
+
const parsedIncluded = this._parseAndFormatMessages(messages2, format);
|
|
1042
|
+
return {
|
|
1043
|
+
messages: parsedIncluded,
|
|
1044
|
+
total: parsedIncluded.length,
|
|
1045
|
+
page: page2,
|
|
1046
|
+
perPage,
|
|
1047
|
+
hasMore: false
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
const excludeIds = messages2.map((m) => m.id);
|
|
1051
|
+
if (excludeIds.length > 0) {
|
|
1052
|
+
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
1053
|
+
conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
|
|
1054
|
+
excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
|
|
1055
|
+
}
|
|
1056
|
+
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`;
|
|
1058
|
+
request.input("offset", currentOffset);
|
|
1059
|
+
request.input("limit", perPage);
|
|
1060
|
+
const rowsResult = await request.query(dataQuery);
|
|
1061
|
+
const rows = rowsResult.recordset || [];
|
|
1062
|
+
rows.sort((a, b) => a.seq_id - b.seq_id);
|
|
1063
|
+
messages2.push(...rows);
|
|
1064
|
+
const parsed = this._parseAndFormatMessages(messages2, format);
|
|
1065
|
+
return {
|
|
1066
|
+
messages: parsed,
|
|
1067
|
+
total: total + excludeIds.length,
|
|
1068
|
+
page: page2,
|
|
1069
|
+
perPage,
|
|
1070
|
+
hasMore: currentOffset + rows.length < total
|
|
1071
|
+
};
|
|
1072
|
+
} catch (error) {
|
|
1073
|
+
const mastraError = new MastraError(
|
|
1074
|
+
{
|
|
1075
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
|
|
1076
|
+
domain: ErrorDomain.STORAGE,
|
|
1077
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1078
|
+
details: {
|
|
1079
|
+
threadId,
|
|
1080
|
+
page
|
|
1081
|
+
}
|
|
1082
|
+
},
|
|
1083
|
+
error
|
|
1084
|
+
);
|
|
1085
|
+
this.logger?.error?.(mastraError.toString());
|
|
1086
|
+
this.logger?.trackException(mastraError);
|
|
1087
|
+
return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
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
|
+
async saveMessages({
|
|
1116
|
+
messages,
|
|
1117
|
+
format
|
|
1118
|
+
}) {
|
|
1119
|
+
if (messages.length === 0) return messages;
|
|
1120
|
+
const threadId = messages[0]?.threadId;
|
|
1121
|
+
if (!threadId) {
|
|
1122
|
+
throw new MastraError({
|
|
1123
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED",
|
|
1124
|
+
domain: ErrorDomain.STORAGE,
|
|
1125
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1126
|
+
text: `Thread ID is required`
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
const thread = await this.getThreadById({ threadId });
|
|
1130
|
+
if (!thread) {
|
|
1131
|
+
throw new MastraError({
|
|
1132
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED",
|
|
1133
|
+
domain: ErrorDomain.STORAGE,
|
|
1134
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1135
|
+
text: `Thread ${threadId} not found`,
|
|
1136
|
+
details: { threadId }
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
const tableMessages = this.getTableName(TABLE_MESSAGES);
|
|
1140
|
+
const tableThreads = this.getTableName(TABLE_THREADS);
|
|
1141
|
+
try {
|
|
1142
|
+
const transaction = this.pool.transaction();
|
|
1143
|
+
await transaction.begin();
|
|
1144
|
+
try {
|
|
1145
|
+
for (const message of messages) {
|
|
1146
|
+
if (!message.threadId) {
|
|
1147
|
+
throw new Error(
|
|
1148
|
+
`Expected to find a threadId for message, but couldn't find one. An unexpected error has occurred.`
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
if (!message.resourceId) {
|
|
1152
|
+
throw new Error(
|
|
1153
|
+
`Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred.`
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
const request = transaction.request();
|
|
1157
|
+
request.input("id", message.id);
|
|
1158
|
+
request.input("thread_id", message.threadId);
|
|
1159
|
+
request.input(
|
|
1160
|
+
"content",
|
|
1161
|
+
typeof message.content === "string" ? message.content : JSON.stringify(message.content)
|
|
1162
|
+
);
|
|
1163
|
+
request.input("createdAt", message.createdAt.toISOString() || (/* @__PURE__ */ new Date()).toISOString());
|
|
1164
|
+
request.input("role", message.role);
|
|
1165
|
+
request.input("type", message.type || "v2");
|
|
1166
|
+
request.input("resourceId", message.resourceId);
|
|
1167
|
+
const mergeSql = `MERGE INTO ${tableMessages} AS target
|
|
1168
|
+
USING (SELECT @id AS id) AS src
|
|
1169
|
+
ON target.id = src.id
|
|
1170
|
+
WHEN MATCHED THEN UPDATE SET
|
|
1171
|
+
thread_id = @thread_id,
|
|
1172
|
+
content = @content,
|
|
1173
|
+
[createdAt] = @createdAt,
|
|
1174
|
+
role = @role,
|
|
1175
|
+
type = @type,
|
|
1176
|
+
resourceId = @resourceId
|
|
1177
|
+
WHEN NOT MATCHED THEN INSERT (id, thread_id, content, [createdAt], role, type, resourceId)
|
|
1178
|
+
VALUES (@id, @thread_id, @content, @createdAt, @role, @type, @resourceId);`;
|
|
1179
|
+
await request.query(mergeSql);
|
|
1180
|
+
}
|
|
1181
|
+
const threadReq = transaction.request();
|
|
1182
|
+
threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
|
|
1183
|
+
threadReq.input("id", threadId);
|
|
1184
|
+
await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
|
|
1185
|
+
await transaction.commit();
|
|
1186
|
+
} catch (error) {
|
|
1187
|
+
await transaction.rollback();
|
|
1188
|
+
throw error;
|
|
1189
|
+
}
|
|
1190
|
+
const messagesWithParsedContent = messages.map((message) => {
|
|
1191
|
+
if (typeof message.content === "string") {
|
|
1192
|
+
try {
|
|
1193
|
+
return { ...message, content: JSON.parse(message.content) };
|
|
1194
|
+
} catch {
|
|
1195
|
+
return message;
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
return message;
|
|
1199
|
+
});
|
|
1200
|
+
const list = new MessageList().add(messagesWithParsedContent, "memory");
|
|
1201
|
+
if (format === "v2") return list.get.all.v2();
|
|
1202
|
+
return list.get.all.v1();
|
|
1203
|
+
} catch (error) {
|
|
1204
|
+
throw new MastraError(
|
|
1205
|
+
{
|
|
1206
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED",
|
|
1207
|
+
domain: ErrorDomain.STORAGE,
|
|
1208
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1209
|
+
details: { threadId }
|
|
1210
|
+
},
|
|
1211
|
+
error
|
|
1212
|
+
);
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
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
|
|
1427
|
+
}) {
|
|
1428
|
+
if (!messages || messages.length === 0) {
|
|
1429
|
+
return [];
|
|
1430
|
+
}
|
|
1431
|
+
const messageIds = messages.map((m) => m.id);
|
|
1432
|
+
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)}`;
|
|
1434
|
+
if (idParams.length > 0) {
|
|
1435
|
+
selectQuery += ` WHERE id IN (${idParams})`;
|
|
1436
|
+
} else {
|
|
1437
|
+
return [];
|
|
1438
|
+
}
|
|
1439
|
+
const selectReq = this.pool.request();
|
|
1440
|
+
messageIds.forEach((id, i) => selectReq.input(`id${i}`, id));
|
|
1441
|
+
const existingMessagesDb = (await selectReq.query(selectQuery)).recordset;
|
|
1442
|
+
if (!existingMessagesDb || existingMessagesDb.length === 0) {
|
|
1443
|
+
return [];
|
|
1444
|
+
}
|
|
1445
|
+
const existingMessages = existingMessagesDb.map((msg) => {
|
|
1446
|
+
if (typeof msg.content === "string") {
|
|
1447
|
+
try {
|
|
1448
|
+
msg.content = JSON.parse(msg.content);
|
|
1449
|
+
} catch {
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
return msg;
|
|
1453
|
+
});
|
|
1454
|
+
const threadIdsToUpdate = /* @__PURE__ */ new Set();
|
|
1455
|
+
const transaction = this.pool.transaction();
|
|
1456
|
+
try {
|
|
1457
|
+
await transaction.begin();
|
|
1458
|
+
for (const existingMessage of existingMessages) {
|
|
1459
|
+
const updatePayload = messages.find((m) => m.id === existingMessage.id);
|
|
1460
|
+
if (!updatePayload) continue;
|
|
1461
|
+
const { id, ...fieldsToUpdate } = updatePayload;
|
|
1462
|
+
if (Object.keys(fieldsToUpdate).length === 0) continue;
|
|
1463
|
+
threadIdsToUpdate.add(existingMessage.threadId);
|
|
1464
|
+
if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
|
|
1465
|
+
threadIdsToUpdate.add(updatePayload.threadId);
|
|
1466
|
+
}
|
|
1467
|
+
const setClauses = [];
|
|
1468
|
+
const req = transaction.request();
|
|
1469
|
+
req.input("id", id);
|
|
1470
|
+
const columnMapping = { threadId: "thread_id" };
|
|
1471
|
+
const updatableFields = { ...fieldsToUpdate };
|
|
1472
|
+
if (updatableFields.content) {
|
|
1473
|
+
const newContent = {
|
|
1474
|
+
...existingMessage.content,
|
|
1475
|
+
...updatableFields.content,
|
|
1476
|
+
...existingMessage.content?.metadata && updatableFields.content.metadata ? { metadata: { ...existingMessage.content.metadata, ...updatableFields.content.metadata } } : {}
|
|
1477
|
+
};
|
|
1478
|
+
setClauses.push(`content = @content`);
|
|
1479
|
+
req.input("content", JSON.stringify(newContent));
|
|
1480
|
+
delete updatableFields.content;
|
|
1481
|
+
}
|
|
1482
|
+
for (const key in updatableFields) {
|
|
1483
|
+
if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
|
|
1484
|
+
const dbColumn = columnMapping[key] || key;
|
|
1485
|
+
setClauses.push(`[${dbColumn}] = @${dbColumn}`);
|
|
1486
|
+
req.input(dbColumn, updatableFields[key]);
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
if (setClauses.length > 0) {
|
|
1490
|
+
const updateSql = `UPDATE ${this.getTableName(TABLE_MESSAGES)} SET ${setClauses.join(", ")} WHERE id = @id`;
|
|
1491
|
+
await req.query(updateSql);
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
if (threadIdsToUpdate.size > 0) {
|
|
1495
|
+
const threadIdParams = Array.from(threadIdsToUpdate).map((_, i) => `@tid${i}`).join(", ");
|
|
1496
|
+
const threadReq = transaction.request();
|
|
1497
|
+
Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
|
|
1498
|
+
threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
|
|
1499
|
+
const threadSql = `UPDATE ${this.getTableName(TABLE_THREADS)} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
|
|
1500
|
+
await threadReq.query(threadSql);
|
|
1501
|
+
}
|
|
1502
|
+
await transaction.commit();
|
|
1503
|
+
} catch (error) {
|
|
1504
|
+
await transaction.rollback();
|
|
1505
|
+
throw new MastraError(
|
|
1506
|
+
{
|
|
1507
|
+
id: "MASTRA_STORAGE_MSSQL_UPDATE_MESSAGES_FAILED",
|
|
1508
|
+
domain: ErrorDomain.STORAGE,
|
|
1509
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1510
|
+
},
|
|
1511
|
+
error
|
|
1512
|
+
);
|
|
1513
|
+
}
|
|
1514
|
+
const refetchReq = this.pool.request();
|
|
1515
|
+
messageIds.forEach((id, i) => refetchReq.input(`id${i}`, id));
|
|
1516
|
+
const updatedMessages = (await refetchReq.query(selectQuery)).recordset;
|
|
1517
|
+
return (updatedMessages || []).map((message) => {
|
|
1518
|
+
if (typeof message.content === "string") {
|
|
1519
|
+
try {
|
|
1520
|
+
message.content = JSON.parse(message.content);
|
|
1521
|
+
} catch {
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return message;
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
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();
|
|
1565
|
+
}
|
|
1566
|
+
const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
|
|
1567
|
+
const tableName = this.getTableName(TABLE_EVALS);
|
|
1568
|
+
const offset = page * perPage;
|
|
1569
|
+
const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
|
|
1570
|
+
const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
1571
|
+
try {
|
|
1572
|
+
const countReq = this.pool.request();
|
|
1573
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
1574
|
+
if (value instanceof Date) {
|
|
1575
|
+
countReq.input(key, sql.DateTime, value);
|
|
1576
|
+
} else {
|
|
1577
|
+
countReq.input(key, value);
|
|
1578
|
+
}
|
|
1579
|
+
});
|
|
1580
|
+
const countResult = await countReq.query(countQuery);
|
|
1581
|
+
const total = countResult.recordset[0]?.total || 0;
|
|
1582
|
+
if (total === 0) {
|
|
1583
|
+
return {
|
|
1584
|
+
evals: [],
|
|
1585
|
+
total: 0,
|
|
1586
|
+
page,
|
|
1587
|
+
perPage,
|
|
1588
|
+
hasMore: false
|
|
1589
|
+
};
|
|
1590
|
+
}
|
|
1591
|
+
const req = this.pool.request();
|
|
1592
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
1593
|
+
if (value instanceof Date) {
|
|
1594
|
+
req.input(key, sql.DateTime, value);
|
|
1595
|
+
} else {
|
|
1596
|
+
req.input(key, value);
|
|
1597
|
+
}
|
|
1598
|
+
});
|
|
1599
|
+
req.input("offset", offset);
|
|
1600
|
+
req.input("perPage", perPage);
|
|
1601
|
+
const result = await req.query(dataQuery);
|
|
1602
|
+
const rows = result.recordset;
|
|
1603
|
+
return {
|
|
1604
|
+
evals: rows?.map((row) => this.transformEvalRow(row)) ?? [],
|
|
1605
|
+
total,
|
|
1606
|
+
page,
|
|
1607
|
+
perPage,
|
|
1608
|
+
hasMore: offset + (rows?.length ?? 0) < total
|
|
1609
|
+
};
|
|
1610
|
+
} catch (error) {
|
|
1611
|
+
const mastraError = new MastraError(
|
|
1612
|
+
{
|
|
1613
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
|
|
1614
|
+
domain: ErrorDomain.STORAGE,
|
|
1615
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1616
|
+
details: {
|
|
1617
|
+
agentName: agentName || "all",
|
|
1618
|
+
type: type || "all",
|
|
1619
|
+
page,
|
|
1620
|
+
perPage
|
|
1621
|
+
}
|
|
1622
|
+
},
|
|
1623
|
+
error
|
|
1624
|
+
);
|
|
1625
|
+
this.logger?.error?.(mastraError.toString());
|
|
1626
|
+
this.logger?.trackException(mastraError);
|
|
1627
|
+
throw mastraError;
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
async saveResource({ resource }) {
|
|
1631
|
+
const tableName = this.getTableName(TABLE_RESOURCES);
|
|
1632
|
+
try {
|
|
1633
|
+
const req = this.pool.request();
|
|
1634
|
+
req.input("id", resource.id);
|
|
1635
|
+
req.input("workingMemory", resource.workingMemory);
|
|
1636
|
+
req.input("metadata", JSON.stringify(resource.metadata));
|
|
1637
|
+
req.input("createdAt", resource.createdAt.toISOString());
|
|
1638
|
+
req.input("updatedAt", resource.updatedAt.toISOString());
|
|
1639
|
+
await req.query(
|
|
1640
|
+
`INSERT INTO ${tableName} (id, workingMemory, metadata, createdAt, updatedAt) VALUES (@id, @workingMemory, @metadata, @createdAt, @updatedAt)`
|
|
1641
|
+
);
|
|
1642
|
+
return resource;
|
|
1643
|
+
} catch (error) {
|
|
1644
|
+
const mastraError = new MastraError(
|
|
1645
|
+
{
|
|
1646
|
+
id: "MASTRA_STORAGE_MSSQL_SAVE_RESOURCE_FAILED",
|
|
1647
|
+
domain: ErrorDomain.STORAGE,
|
|
1648
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1649
|
+
details: { resourceId: resource.id }
|
|
1650
|
+
},
|
|
1651
|
+
error
|
|
1652
|
+
);
|
|
1653
|
+
this.logger?.error?.(mastraError.toString());
|
|
1654
|
+
this.logger?.trackException(mastraError);
|
|
1655
|
+
throw mastraError;
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
async updateResource({
|
|
1659
|
+
resourceId,
|
|
1660
|
+
workingMemory,
|
|
1661
|
+
metadata
|
|
1662
|
+
}) {
|
|
1663
|
+
try {
|
|
1664
|
+
const existingResource = await this.getResourceById({ resourceId });
|
|
1665
|
+
if (!existingResource) {
|
|
1666
|
+
const newResource = {
|
|
1667
|
+
id: resourceId,
|
|
1668
|
+
workingMemory,
|
|
1669
|
+
metadata: metadata || {},
|
|
1670
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1671
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1672
|
+
};
|
|
1673
|
+
return this.saveResource({ resource: newResource });
|
|
1674
|
+
}
|
|
1675
|
+
const updatedResource = {
|
|
1676
|
+
...existingResource,
|
|
1677
|
+
workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
|
|
1678
|
+
metadata: {
|
|
1679
|
+
...existingResource.metadata,
|
|
1680
|
+
...metadata
|
|
1681
|
+
},
|
|
1682
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1683
|
+
};
|
|
1684
|
+
const tableName = this.getTableName(TABLE_RESOURCES);
|
|
1685
|
+
const updates = [];
|
|
1686
|
+
const req = this.pool.request();
|
|
1687
|
+
if (workingMemory !== void 0) {
|
|
1688
|
+
updates.push("workingMemory = @workingMemory");
|
|
1689
|
+
req.input("workingMemory", workingMemory);
|
|
1690
|
+
}
|
|
1691
|
+
if (metadata) {
|
|
1692
|
+
updates.push("metadata = @metadata");
|
|
1693
|
+
req.input("metadata", JSON.stringify(updatedResource.metadata));
|
|
1694
|
+
}
|
|
1695
|
+
updates.push("updatedAt = @updatedAt");
|
|
1696
|
+
req.input("updatedAt", updatedResource.updatedAt.toISOString());
|
|
1697
|
+
req.input("id", resourceId);
|
|
1698
|
+
await req.query(`UPDATE ${tableName} SET ${updates.join(", ")} WHERE id = @id`);
|
|
1699
|
+
return updatedResource;
|
|
1700
|
+
} catch (error) {
|
|
1701
|
+
const mastraError = new MastraError(
|
|
1702
|
+
{
|
|
1703
|
+
id: "MASTRA_STORAGE_MSSQL_UPDATE_RESOURCE_FAILED",
|
|
1704
|
+
domain: ErrorDomain.STORAGE,
|
|
1705
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1706
|
+
details: { resourceId }
|
|
1707
|
+
},
|
|
1708
|
+
error
|
|
1709
|
+
);
|
|
1710
|
+
this.logger?.error?.(mastraError.toString());
|
|
1711
|
+
this.logger?.trackException(mastraError);
|
|
1712
|
+
throw mastraError;
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
async getResourceById({ resourceId }) {
|
|
1716
|
+
const tableName = this.getTableName(TABLE_RESOURCES);
|
|
1717
|
+
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;
|
|
1723
|
+
}
|
|
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
|
+
} catch (error) {
|
|
1730
|
+
const mastraError = new MastraError(
|
|
1731
|
+
{
|
|
1732
|
+
id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
|
|
1733
|
+
domain: ErrorDomain.STORAGE,
|
|
1734
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1735
|
+
details: { resourceId }
|
|
1736
|
+
},
|
|
1737
|
+
error
|
|
1738
|
+
);
|
|
1739
|
+
this.logger?.error?.(mastraError.toString());
|
|
1740
|
+
this.logger?.trackException(mastraError);
|
|
1741
|
+
throw mastraError;
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
};
|
|
1745
|
+
|
|
1746
|
+
export { MSSQLStore };
|