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