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