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