@mastra/mssql 0.0.0-transpile-packages-20250730132657 → 0.0.0-unified-sidebar-20251010130811
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 +428 -4
- package/dist/index.cjs +1753 -1126
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +2 -4
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1753 -1126
- package/dist/index.js.map +1 -0
- package/dist/storage/domains/legacy-evals/index.d.ts +20 -0
- package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +98 -0
- package/dist/storage/domains/memory/index.d.ts.map +1 -0
- package/dist/storage/domains/operations/index.d.ts +51 -0
- package/dist/storage/domains/operations/index.d.ts.map +1 -0
- package/dist/storage/domains/scores/index.d.ts +54 -0
- package/dist/storage/domains/scores/index.d.ts.map +1 -0
- package/dist/storage/domains/traces/index.d.ts +37 -0
- package/dist/storage/domains/traces/index.d.ts.map +1 -0
- package/dist/storage/domains/utils.d.ts +6 -0
- package/dist/storage/domains/utils.d.ts.map +1 -0
- package/dist/storage/domains/workflows/index.d.ts +55 -0
- package/dist/storage/domains/workflows/index.d.ts.map +1 -0
- package/dist/{_tsup-dts-rollup.d.cts → storage/index.d.ts} +119 -118
- package/dist/storage/index.d.ts.map +1 -0
- package/package.json +26 -12
- package/dist/_tsup-dts-rollup.d.ts +0 -250
- package/dist/index.d.cts +0 -4
- package/docker-compose.yaml +0 -14
- package/eslint.config.js +0 -6
- package/src/index.ts +0 -2
- package/src/storage/index.test.ts +0 -2228
- package/src/storage/index.ts +0 -2134
- package/tsconfig.json +0 -5
- package/vitest.config.ts +0 -12
package/dist/index.cjs
CHANGED
|
@@ -1,132 +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
|
-
try {
|
|
103
|
-
testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
|
|
104
|
-
} catch {
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
if (row.test_info) {
|
|
108
|
-
try {
|
|
109
|
-
resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
|
|
110
|
-
} catch {
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
return {
|
|
114
|
-
agentName: row.agent_name,
|
|
115
|
-
input: row.input,
|
|
116
|
-
output: row.output,
|
|
117
|
-
result: resultValue,
|
|
118
|
-
metricName: row.metric_name,
|
|
119
|
-
instructions: row.instructions,
|
|
120
|
-
testInfo: testInfoValue,
|
|
121
|
-
globalRunId: row.global_run_id,
|
|
122
|
-
runId: row.run_id,
|
|
123
|
-
createdAt: row.created_at
|
|
124
|
-
};
|
|
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;
|
|
125
60
|
}
|
|
126
61
|
/** @deprecated use getEvals instead */
|
|
127
62
|
async getEvalsByAgentName(agentName, type) {
|
|
128
63
|
try {
|
|
129
|
-
let query = `SELECT * FROM ${
|
|
64
|
+
let query = `SELECT * FROM ${getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
|
|
130
65
|
if (type === "test") {
|
|
131
66
|
query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
|
|
132
67
|
} else if (type === "live") {
|
|
@@ -137,7 +72,7 @@ var MSSQLStore = class extends storage.MastraStorage {
|
|
|
137
72
|
request.input("p1", agentName);
|
|
138
73
|
const result = await request.query(query);
|
|
139
74
|
const rows = result.recordset;
|
|
140
|
-
return typeof
|
|
75
|
+
return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
|
|
141
76
|
} catch (error) {
|
|
142
77
|
if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
|
|
143
78
|
return [];
|
|
@@ -146,597 +81,267 @@ var MSSQLStore = class extends storage.MastraStorage {
|
|
|
146
81
|
throw error;
|
|
147
82
|
}
|
|
148
83
|
}
|
|
149
|
-
async
|
|
150
|
-
const
|
|
151
|
-
try {
|
|
152
|
-
await transaction.begin();
|
|
153
|
-
for (const record of records) {
|
|
154
|
-
await this.insert({ tableName, record });
|
|
155
|
-
}
|
|
156
|
-
await transaction.commit();
|
|
157
|
-
} catch (error$1) {
|
|
158
|
-
await transaction.rollback();
|
|
159
|
-
throw new error.MastraError(
|
|
160
|
-
{
|
|
161
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
|
|
162
|
-
domain: error.ErrorDomain.STORAGE,
|
|
163
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
164
|
-
details: {
|
|
165
|
-
tableName,
|
|
166
|
-
numberOfRecords: records.length
|
|
167
|
-
}
|
|
168
|
-
},
|
|
169
|
-
error$1
|
|
170
|
-
);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
/** @deprecated use getTracesPaginated instead*/
|
|
174
|
-
async getTraces(args) {
|
|
175
|
-
if (args.fromDate || args.toDate) {
|
|
176
|
-
args.dateRange = {
|
|
177
|
-
start: args.fromDate,
|
|
178
|
-
end: args.toDate
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
const result = await this.getTracesPaginated(args);
|
|
182
|
-
return result.traces;
|
|
183
|
-
}
|
|
184
|
-
async getTracesPaginated(args) {
|
|
185
|
-
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;
|
|
186
86
|
const fromDate = dateRange?.start;
|
|
187
87
|
const toDate = dateRange?.end;
|
|
188
|
-
const
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
if (name) {
|
|
194
|
-
const paramName = `p${paramIndex++}`;
|
|
195
|
-
conditions.push(`[name] LIKE @${paramName}`);
|
|
196
|
-
paramMap[paramName] = `${name}%`;
|
|
197
|
-
}
|
|
198
|
-
if (scope) {
|
|
199
|
-
const paramName = `p${paramIndex++}`;
|
|
200
|
-
conditions.push(`[scope] = @${paramName}`);
|
|
201
|
-
paramMap[paramName] = scope;
|
|
202
|
-
}
|
|
203
|
-
if (attributes) {
|
|
204
|
-
Object.entries(attributes).forEach(([key, value]) => {
|
|
205
|
-
const parsedKey = utils.parseFieldKey(key);
|
|
206
|
-
const paramName = `p${paramIndex++}`;
|
|
207
|
-
conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
|
|
208
|
-
paramMap[paramName] = value;
|
|
209
|
-
});
|
|
88
|
+
const where = [];
|
|
89
|
+
const params = {};
|
|
90
|
+
if (agentName) {
|
|
91
|
+
where.push("agent_name = @agentName");
|
|
92
|
+
params["agentName"] = agentName;
|
|
210
93
|
}
|
|
211
|
-
if (
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
conditions.push(`[${parsedKey}] = @${paramName}`);
|
|
216
|
-
paramMap[paramName] = value;
|
|
217
|
-
});
|
|
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)");
|
|
218
98
|
}
|
|
219
99
|
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
paramMap[paramName] = fromDate.toISOString();
|
|
100
|
+
where.push(`[created_at] >= @fromDate`);
|
|
101
|
+
params[`fromDate`] = fromDate.toISOString();
|
|
223
102
|
}
|
|
224
103
|
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
paramMap[paramName] = toDate.toISOString();
|
|
104
|
+
where.push(`[created_at] <= @toDate`);
|
|
105
|
+
params[`toDate`] = toDate.toISOString();
|
|
228
106
|
}
|
|
229
|
-
const whereClause =
|
|
230
|
-
const
|
|
231
|
-
|
|
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`;
|
|
232
112
|
try {
|
|
233
|
-
const
|
|
234
|
-
Object.entries(
|
|
113
|
+
const countReq = this.pool.request();
|
|
114
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
235
115
|
if (value instanceof Date) {
|
|
236
|
-
|
|
116
|
+
countReq.input(key, sql2__default.default.DateTime, value);
|
|
237
117
|
} else {
|
|
238
|
-
|
|
118
|
+
countReq.input(key, value);
|
|
239
119
|
}
|
|
240
120
|
});
|
|
241
|
-
const countResult = await
|
|
242
|
-
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
|
+
};
|
|
243
151
|
} catch (error$1) {
|
|
244
|
-
|
|
152
|
+
const mastraError = new error.MastraError(
|
|
245
153
|
{
|
|
246
|
-
id: "
|
|
154
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
|
|
247
155
|
domain: error.ErrorDomain.STORAGE,
|
|
248
156
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
249
157
|
details: {
|
|
250
|
-
|
|
251
|
-
|
|
158
|
+
agentName: agentName || "all",
|
|
159
|
+
type: type || "all",
|
|
160
|
+
page,
|
|
161
|
+
perPage
|
|
252
162
|
}
|
|
253
163
|
},
|
|
254
164
|
error$1
|
|
255
165
|
);
|
|
166
|
+
this.logger?.error?.(mastraError.toString());
|
|
167
|
+
this.logger?.trackException(mastraError);
|
|
168
|
+
throw mastraError;
|
|
256
169
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
} else {
|
|
272
|
-
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
|
+
}
|
|
273
184
|
}
|
|
185
|
+
return message;
|
|
274
186
|
});
|
|
275
|
-
|
|
276
|
-
|
|
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 }) {
|
|
277
202
|
try {
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
createdAt: row.createdAt
|
|
295
|
-
}));
|
|
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
|
+
}
|
|
296
219
|
return {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
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
|
|
302
224
|
};
|
|
303
225
|
} catch (error$1) {
|
|
304
226
|
throw new error.MastraError(
|
|
305
227
|
{
|
|
306
|
-
id: "
|
|
228
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
|
|
307
229
|
domain: error.ErrorDomain.STORAGE,
|
|
308
230
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
309
231
|
details: {
|
|
310
|
-
|
|
311
|
-
scope: args.scope ?? ""
|
|
232
|
+
threadId
|
|
312
233
|
}
|
|
313
234
|
},
|
|
314
235
|
error$1
|
|
315
236
|
);
|
|
316
237
|
}
|
|
317
238
|
}
|
|
318
|
-
async
|
|
319
|
-
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
if (!this.setupSchemaPromise) {
|
|
323
|
-
this.setupSchemaPromise = (async () => {
|
|
324
|
-
try {
|
|
325
|
-
const checkRequest = this.pool.request();
|
|
326
|
-
checkRequest.input("schemaName", this.schema);
|
|
327
|
-
const checkResult = await checkRequest.query(`
|
|
328
|
-
SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
|
|
329
|
-
`);
|
|
330
|
-
const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
|
|
331
|
-
if (!schemaExists) {
|
|
332
|
-
try {
|
|
333
|
-
await this.pool.request().query(`CREATE SCHEMA [${this.schema}]`);
|
|
334
|
-
this.logger?.info?.(`Schema "${this.schema}" created successfully`);
|
|
335
|
-
} catch (error) {
|
|
336
|
-
this.logger?.error?.(`Failed to create schema "${this.schema}"`, { error });
|
|
337
|
-
throw new Error(
|
|
338
|
-
`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.`
|
|
339
|
-
);
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
this.schemaSetupComplete = true;
|
|
343
|
-
this.logger?.debug?.(`Schema "${this.schema}" is ready for use`);
|
|
344
|
-
} catch (error) {
|
|
345
|
-
this.schemaSetupComplete = void 0;
|
|
346
|
-
this.setupSchemaPromise = null;
|
|
347
|
-
throw error;
|
|
348
|
-
} finally {
|
|
349
|
-
this.setupSchemaPromise = null;
|
|
350
|
-
}
|
|
351
|
-
})();
|
|
352
|
-
}
|
|
353
|
-
await this.setupSchemaPromise;
|
|
354
|
-
}
|
|
355
|
-
getSqlType(type, isPrimaryKey = false) {
|
|
356
|
-
switch (type) {
|
|
357
|
-
case "text":
|
|
358
|
-
return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(MAX)";
|
|
359
|
-
case "timestamp":
|
|
360
|
-
return "DATETIME2(7)";
|
|
361
|
-
case "uuid":
|
|
362
|
-
return "UNIQUEIDENTIFIER";
|
|
363
|
-
case "jsonb":
|
|
364
|
-
return "NVARCHAR(MAX)";
|
|
365
|
-
case "integer":
|
|
366
|
-
return "INT";
|
|
367
|
-
case "bigint":
|
|
368
|
-
return "BIGINT";
|
|
369
|
-
default:
|
|
370
|
-
throw new error.MastraError({
|
|
371
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
|
|
372
|
-
domain: error.ErrorDomain.STORAGE,
|
|
373
|
-
category: error.ErrorCategory.THIRD_PARTY
|
|
374
|
-
});
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
async createTable({
|
|
378
|
-
tableName,
|
|
379
|
-
schema
|
|
380
|
-
}) {
|
|
239
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
240
|
+
const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
|
|
381
241
|
try {
|
|
382
|
-
const
|
|
383
|
-
const
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
const checkTableResult = await checkTableRequest.query(checkTableSql);
|
|
399
|
-
const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
|
|
400
|
-
if (!tableExists) {
|
|
401
|
-
const createSql = `CREATE TABLE ${this.getTableName(tableName)} (
|
|
402
|
-
${columns}
|
|
403
|
-
)`;
|
|
404
|
-
await this.pool.request().query(createSql);
|
|
405
|
-
}
|
|
406
|
-
const columnCheckSql = `
|
|
407
|
-
SELECT 1 AS found
|
|
408
|
-
FROM INFORMATION_SCHEMA.COLUMNS
|
|
409
|
-
WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
|
|
410
|
-
`;
|
|
411
|
-
const checkColumnRequest = this.pool.request();
|
|
412
|
-
checkColumnRequest.input("schema", this.schema || "dbo");
|
|
413
|
-
checkColumnRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
|
|
414
|
-
const columnResult = await checkColumnRequest.query(columnCheckSql);
|
|
415
|
-
const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
|
|
416
|
-
if (!columnExists) {
|
|
417
|
-
const alterSql = `ALTER TABLE ${this.getTableName(tableName)} ADD seq_id BIGINT IDENTITY(1,1)`;
|
|
418
|
-
await this.pool.request().query(alterSql);
|
|
419
|
-
}
|
|
420
|
-
if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
|
|
421
|
-
const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
|
|
422
|
-
const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
|
|
423
|
-
const checkConstraintRequest = this.pool.request();
|
|
424
|
-
checkConstraintRequest.input("constraintName", constraintName);
|
|
425
|
-
const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
|
|
426
|
-
const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
|
|
427
|
-
if (!constraintExists) {
|
|
428
|
-
const addConstraintSql = `ALTER TABLE ${this.getTableName(tableName)} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
|
|
429
|
-
await this.pool.request().query(addConstraintSql);
|
|
430
|
-
}
|
|
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
|
+
};
|
|
431
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
|
+
};
|
|
432
280
|
} catch (error$1) {
|
|
433
|
-
|
|
281
|
+
const mastraError = new error.MastraError(
|
|
434
282
|
{
|
|
435
|
-
id: "
|
|
283
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
|
|
436
284
|
domain: error.ErrorDomain.STORAGE,
|
|
437
285
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
438
286
|
details: {
|
|
439
|
-
|
|
287
|
+
resourceId,
|
|
288
|
+
page
|
|
440
289
|
}
|
|
441
290
|
},
|
|
442
291
|
error$1
|
|
443
292
|
);
|
|
293
|
+
this.logger?.error?.(mastraError.toString());
|
|
294
|
+
this.logger?.trackException?.(mastraError);
|
|
295
|
+
return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
|
|
444
296
|
}
|
|
445
297
|
}
|
|
446
|
-
|
|
447
|
-
switch (type) {
|
|
448
|
-
case "timestamp":
|
|
449
|
-
return "DEFAULT SYSDATETIMEOFFSET()";
|
|
450
|
-
case "jsonb":
|
|
451
|
-
return "DEFAULT N'{}'";
|
|
452
|
-
default:
|
|
453
|
-
return super.getDefaultValue(type);
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
async alterTable({
|
|
457
|
-
tableName,
|
|
458
|
-
schema,
|
|
459
|
-
ifNotExists
|
|
460
|
-
}) {
|
|
461
|
-
const fullTableName = this.getTableName(tableName);
|
|
298
|
+
async saveThread({ thread }) {
|
|
462
299
|
try {
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
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;
|
|
484
322
|
} catch (error$1) {
|
|
485
323
|
throw new error.MastraError(
|
|
486
324
|
{
|
|
487
|
-
id: "
|
|
325
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
|
|
488
326
|
domain: error.ErrorDomain.STORAGE,
|
|
489
327
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
490
328
|
details: {
|
|
491
|
-
|
|
329
|
+
threadId: thread.id
|
|
492
330
|
}
|
|
493
331
|
},
|
|
494
332
|
error$1
|
|
495
333
|
);
|
|
496
334
|
}
|
|
497
335
|
}
|
|
498
|
-
|
|
499
|
-
|
|
336
|
+
/**
|
|
337
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
338
|
+
*/
|
|
339
|
+
async getThreadsByResourceId(args) {
|
|
340
|
+
const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
|
|
500
341
|
try {
|
|
501
|
-
const
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
OBJECT_NAME(fk.parent_object_id) AS table_name
|
|
505
|
-
FROM sys.foreign_keys fk
|
|
506
|
-
WHERE fk.referenced_object_id = OBJECT_ID(@fullTableName)
|
|
507
|
-
`;
|
|
508
|
-
const fkResult = await this.pool.request().input("fullTableName", fullTableName).query(fkQuery);
|
|
509
|
-
const childTables = fkResult.recordset || [];
|
|
510
|
-
for (const child of childTables) {
|
|
511
|
-
const childTableName = this.schema ? `[${child.schema_name}].[${child.table_name}]` : `[${child.table_name}]`;
|
|
512
|
-
await this.clearTable({ tableName: childTableName });
|
|
513
|
-
}
|
|
514
|
-
await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
|
|
515
|
-
} catch (error$1) {
|
|
516
|
-
throw new error.MastraError(
|
|
517
|
-
{
|
|
518
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
|
|
519
|
-
domain: error.ErrorDomain.STORAGE,
|
|
520
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
521
|
-
details: {
|
|
522
|
-
tableName
|
|
523
|
-
}
|
|
524
|
-
},
|
|
525
|
-
error$1
|
|
526
|
-
);
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
async insert({ tableName, record }) {
|
|
530
|
-
try {
|
|
531
|
-
const columns = Object.keys(record).map((col) => utils.parseSqlIdentifier(col, "column name"));
|
|
532
|
-
const values = Object.values(record);
|
|
533
|
-
const paramNames = values.map((_, i) => `@param${i}`);
|
|
534
|
-
const insertSql = `INSERT INTO ${this.getTableName(tableName)} (${columns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
|
|
535
|
-
const request = this.pool.request();
|
|
536
|
-
values.forEach((value, i) => {
|
|
537
|
-
if (value instanceof Date) {
|
|
538
|
-
request.input(`param${i}`, sql__default.default.DateTime2, value);
|
|
539
|
-
} else if (typeof value === "object" && value !== null) {
|
|
540
|
-
request.input(`param${i}`, JSON.stringify(value));
|
|
541
|
-
} else {
|
|
542
|
-
request.input(`param${i}`, value);
|
|
543
|
-
}
|
|
544
|
-
});
|
|
545
|
-
await request.query(insertSql);
|
|
546
|
-
} catch (error$1) {
|
|
547
|
-
throw new error.MastraError(
|
|
548
|
-
{
|
|
549
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
|
|
550
|
-
domain: error.ErrorDomain.STORAGE,
|
|
551
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
552
|
-
details: {
|
|
553
|
-
tableName
|
|
554
|
-
}
|
|
555
|
-
},
|
|
556
|
-
error$1
|
|
557
|
-
);
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
async load({ tableName, keys }) {
|
|
561
|
-
try {
|
|
562
|
-
const keyEntries = Object.entries(keys).map(([key, value]) => [utils.parseSqlIdentifier(key, "column name"), value]);
|
|
563
|
-
const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
|
|
564
|
-
const values = keyEntries.map(([_, value]) => value);
|
|
565
|
-
const sql2 = `SELECT * FROM ${this.getTableName(tableName)} WHERE ${conditions}`;
|
|
566
|
-
const request = this.pool.request();
|
|
567
|
-
values.forEach((value, i) => {
|
|
568
|
-
request.input(`param${i}`, value);
|
|
569
|
-
});
|
|
570
|
-
const resultSet = await request.query(sql2);
|
|
571
|
-
const result = resultSet.recordset[0] || null;
|
|
572
|
-
if (!result) {
|
|
573
|
-
return null;
|
|
574
|
-
}
|
|
575
|
-
if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
|
|
576
|
-
const snapshot = result;
|
|
577
|
-
if (typeof snapshot.snapshot === "string") {
|
|
578
|
-
snapshot.snapshot = JSON.parse(snapshot.snapshot);
|
|
579
|
-
}
|
|
580
|
-
return snapshot;
|
|
581
|
-
}
|
|
582
|
-
return result;
|
|
583
|
-
} catch (error$1) {
|
|
584
|
-
throw new error.MastraError(
|
|
585
|
-
{
|
|
586
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
|
|
587
|
-
domain: error.ErrorDomain.STORAGE,
|
|
588
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
589
|
-
details: {
|
|
590
|
-
tableName
|
|
591
|
-
}
|
|
592
|
-
},
|
|
593
|
-
error$1
|
|
594
|
-
);
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
async getThreadById({ threadId }) {
|
|
598
|
-
try {
|
|
599
|
-
const sql2 = `SELECT
|
|
600
|
-
id,
|
|
601
|
-
[resourceId],
|
|
602
|
-
title,
|
|
603
|
-
metadata,
|
|
604
|
-
[createdAt],
|
|
605
|
-
[updatedAt]
|
|
606
|
-
FROM ${this.getTableName(storage.TABLE_THREADS)}
|
|
607
|
-
WHERE id = @threadId`;
|
|
608
|
-
const request = this.pool.request();
|
|
609
|
-
request.input("threadId", threadId);
|
|
610
|
-
const resultSet = await request.query(sql2);
|
|
611
|
-
const thread = resultSet.recordset[0] || null;
|
|
612
|
-
if (!thread) {
|
|
613
|
-
return null;
|
|
614
|
-
}
|
|
615
|
-
return {
|
|
616
|
-
...thread,
|
|
617
|
-
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
618
|
-
createdAt: thread.createdAt,
|
|
619
|
-
updatedAt: thread.updatedAt
|
|
620
|
-
};
|
|
621
|
-
} catch (error$1) {
|
|
622
|
-
throw new error.MastraError(
|
|
623
|
-
{
|
|
624
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
|
|
625
|
-
domain: error.ErrorDomain.STORAGE,
|
|
626
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
627
|
-
details: {
|
|
628
|
-
threadId
|
|
629
|
-
}
|
|
630
|
-
},
|
|
631
|
-
error$1
|
|
632
|
-
);
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
async getThreadsByResourceIdPaginated(args) {
|
|
636
|
-
const { resourceId, page = 0, perPage: perPageInput } = args;
|
|
637
|
-
try {
|
|
638
|
-
const perPage = perPageInput !== void 0 ? perPageInput : 100;
|
|
639
|
-
const currentOffset = page * perPage;
|
|
640
|
-
const baseQuery = `FROM ${this.getTableName(storage.TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
|
|
641
|
-
const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
|
|
642
|
-
const countRequest = this.pool.request();
|
|
643
|
-
countRequest.input("resourceId", resourceId);
|
|
644
|
-
const countResult = await countRequest.query(countQuery);
|
|
645
|
-
const total = parseInt(countResult.recordset[0]?.count ?? "0", 10);
|
|
646
|
-
if (total === 0) {
|
|
647
|
-
return {
|
|
648
|
-
threads: [],
|
|
649
|
-
total: 0,
|
|
650
|
-
page,
|
|
651
|
-
perPage,
|
|
652
|
-
hasMore: false
|
|
653
|
-
};
|
|
654
|
-
}
|
|
655
|
-
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
656
|
-
const dataRequest = this.pool.request();
|
|
657
|
-
dataRequest.input("resourceId", resourceId);
|
|
658
|
-
dataRequest.input("perPage", perPage);
|
|
659
|
-
dataRequest.input("offset", currentOffset);
|
|
660
|
-
const rowsResult = await dataRequest.query(dataQuery);
|
|
661
|
-
const rows = rowsResult.recordset || [];
|
|
662
|
-
const threads = rows.map((thread) => ({
|
|
663
|
-
...thread,
|
|
664
|
-
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
665
|
-
createdAt: thread.createdAt,
|
|
666
|
-
updatedAt: thread.updatedAt
|
|
667
|
-
}));
|
|
668
|
-
return {
|
|
669
|
-
threads,
|
|
670
|
-
total,
|
|
671
|
-
page,
|
|
672
|
-
perPage,
|
|
673
|
-
hasMore: currentOffset + threads.length < total
|
|
674
|
-
};
|
|
675
|
-
} catch (error$1) {
|
|
676
|
-
const mastraError = new error.MastraError(
|
|
677
|
-
{
|
|
678
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
|
|
679
|
-
domain: error.ErrorDomain.STORAGE,
|
|
680
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
681
|
-
details: {
|
|
682
|
-
resourceId,
|
|
683
|
-
page
|
|
684
|
-
}
|
|
685
|
-
},
|
|
686
|
-
error$1
|
|
687
|
-
);
|
|
688
|
-
this.logger?.error?.(mastraError.toString());
|
|
689
|
-
this.logger?.trackException?.(mastraError);
|
|
690
|
-
return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
async saveThread({ thread }) {
|
|
694
|
-
try {
|
|
695
|
-
const table = this.getTableName(storage.TABLE_THREADS);
|
|
696
|
-
const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
|
|
697
|
-
USING (SELECT @id AS id) AS source
|
|
698
|
-
ON (target.id = source.id)
|
|
699
|
-
WHEN MATCHED THEN
|
|
700
|
-
UPDATE SET
|
|
701
|
-
[resourceId] = @resourceId,
|
|
702
|
-
title = @title,
|
|
703
|
-
metadata = @metadata,
|
|
704
|
-
[createdAt] = @createdAt,
|
|
705
|
-
[updatedAt] = @updatedAt
|
|
706
|
-
WHEN NOT MATCHED THEN
|
|
707
|
-
INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
|
|
708
|
-
VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
|
|
709
|
-
const req = this.pool.request();
|
|
710
|
-
req.input("id", thread.id);
|
|
711
|
-
req.input("resourceId", thread.resourceId);
|
|
712
|
-
req.input("title", thread.title);
|
|
713
|
-
req.input("metadata", thread.metadata ? JSON.stringify(thread.metadata) : null);
|
|
714
|
-
req.input("createdAt", thread.createdAt);
|
|
715
|
-
req.input("updatedAt", thread.updatedAt);
|
|
716
|
-
await req.query(mergeSql);
|
|
717
|
-
return thread;
|
|
718
|
-
} catch (error$1) {
|
|
719
|
-
throw new error.MastraError(
|
|
720
|
-
{
|
|
721
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
|
|
722
|
-
domain: error.ErrorDomain.STORAGE,
|
|
723
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
724
|
-
details: {
|
|
725
|
-
threadId: thread.id
|
|
726
|
-
}
|
|
727
|
-
},
|
|
728
|
-
error$1
|
|
729
|
-
);
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
/**
|
|
733
|
-
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
734
|
-
*/
|
|
735
|
-
async getThreadsByResourceId(args) {
|
|
736
|
-
const { resourceId } = args;
|
|
737
|
-
try {
|
|
738
|
-
const baseQuery = `FROM ${this.getTableName(storage.TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
|
|
739
|
-
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}`;
|
|
740
345
|
const request = this.pool.request();
|
|
741
346
|
request.input("resourceId", resourceId);
|
|
742
347
|
const resultSet = await request.query(dataQuery);
|
|
@@ -778,8 +383,8 @@ ${columns}
|
|
|
778
383
|
...metadata
|
|
779
384
|
};
|
|
780
385
|
try {
|
|
781
|
-
const table =
|
|
782
|
-
const
|
|
386
|
+
const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
387
|
+
const sql7 = `UPDATE ${table}
|
|
783
388
|
SET title = @title,
|
|
784
389
|
metadata = @metadata,
|
|
785
390
|
[updatedAt] = @updatedAt
|
|
@@ -789,8 +394,8 @@ ${columns}
|
|
|
789
394
|
req.input("id", id);
|
|
790
395
|
req.input("title", title);
|
|
791
396
|
req.input("metadata", JSON.stringify(mergedMetadata));
|
|
792
|
-
req.input("updatedAt",
|
|
793
|
-
const result = await req.query(
|
|
397
|
+
req.input("updatedAt", /* @__PURE__ */ new Date());
|
|
398
|
+
const result = await req.query(sql7);
|
|
794
399
|
let thread = result.recordset && result.recordset[0];
|
|
795
400
|
if (thread && "seq_id" in thread) {
|
|
796
401
|
const { seq_id, ...rest } = thread;
|
|
@@ -830,8 +435,8 @@ ${columns}
|
|
|
830
435
|
}
|
|
831
436
|
}
|
|
832
437
|
async deleteThread({ threadId }) {
|
|
833
|
-
const messagesTable =
|
|
834
|
-
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) });
|
|
835
440
|
const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
|
|
836
441
|
const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
|
|
837
442
|
const tx = this.pool.transaction();
|
|
@@ -863,6 +468,7 @@ ${columns}
|
|
|
863
468
|
selectBy,
|
|
864
469
|
orderByStatement
|
|
865
470
|
}) {
|
|
471
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
866
472
|
const include = selectBy?.include;
|
|
867
473
|
if (!include) return null;
|
|
868
474
|
const unionQueries = [];
|
|
@@ -889,7 +495,7 @@ ${columns}
|
|
|
889
495
|
m.seq_id
|
|
890
496
|
FROM (
|
|
891
497
|
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
892
|
-
FROM ${
|
|
498
|
+
FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
|
|
893
499
|
WHERE [thread_id] = ${pThreadId}
|
|
894
500
|
) AS m
|
|
895
501
|
WHERE m.id = ${pId}
|
|
@@ -897,7 +503,7 @@ ${columns}
|
|
|
897
503
|
SELECT 1
|
|
898
504
|
FROM (
|
|
899
505
|
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
900
|
-
FROM ${
|
|
506
|
+
FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
|
|
901
507
|
WHERE [thread_id] = ${pThreadId}
|
|
902
508
|
) AS target
|
|
903
509
|
WHERE target.id = ${pId}
|
|
@@ -934,11 +540,12 @@ ${columns}
|
|
|
934
540
|
return dedupedRows;
|
|
935
541
|
}
|
|
936
542
|
async getMessages(args) {
|
|
937
|
-
const { threadId, format, selectBy } = args;
|
|
938
|
-
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`;
|
|
939
545
|
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
940
|
-
const limit =
|
|
546
|
+
const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
941
547
|
try {
|
|
548
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
942
549
|
let rows = [];
|
|
943
550
|
const include = selectBy?.include || [];
|
|
944
551
|
if (include?.length) {
|
|
@@ -948,7 +555,7 @@ ${columns}
|
|
|
948
555
|
}
|
|
949
556
|
}
|
|
950
557
|
const excludeIds = rows.map((m) => m.id).filter(Boolean);
|
|
951
|
-
let query = `${selectStatement} FROM ${
|
|
558
|
+
let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
|
|
952
559
|
const request = this.pool.request();
|
|
953
560
|
request.input("threadId", threadId);
|
|
954
561
|
if (excludeIds.length > 0) {
|
|
@@ -968,30 +575,7 @@ ${columns}
|
|
|
968
575
|
return timeDiff;
|
|
969
576
|
});
|
|
970
577
|
rows = rows.map(({ seq_id, ...rest }) => rest);
|
|
971
|
-
|
|
972
|
-
if (typeof message.content === "string") {
|
|
973
|
-
try {
|
|
974
|
-
message.content = JSON.parse(message.content);
|
|
975
|
-
} catch {
|
|
976
|
-
}
|
|
977
|
-
}
|
|
978
|
-
if (format === "v1") {
|
|
979
|
-
if (Array.isArray(message.content)) ; else if (typeof message.content === "object" && message.content && Array.isArray(message.content.parts)) {
|
|
980
|
-
message.content = message.content.parts;
|
|
981
|
-
} else {
|
|
982
|
-
message.content = [{ type: "text", text: "" }];
|
|
983
|
-
}
|
|
984
|
-
} else {
|
|
985
|
-
if (typeof message.content !== "object" || !message.content || !("parts" in message.content)) {
|
|
986
|
-
message.content = { format: 2, parts: [{ type: "text", text: "" }] };
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
if (message.type === "v2") delete message.type;
|
|
990
|
-
return message;
|
|
991
|
-
});
|
|
992
|
-
return format === "v2" ? fetchedMessages.map(
|
|
993
|
-
(m) => ({ ...m, content: m.content || { format: 2, parts: [{ type: "text", text: "" }] } })
|
|
994
|
-
) : fetchedMessages;
|
|
578
|
+
return this._parseAndFormatMessages(rows, format);
|
|
995
579
|
} catch (error$1) {
|
|
996
580
|
const mastraError = new error.MastraError(
|
|
997
581
|
{
|
|
@@ -999,7 +583,8 @@ ${columns}
|
|
|
999
583
|
domain: error.ErrorDomain.STORAGE,
|
|
1000
584
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1001
585
|
details: {
|
|
1002
|
-
threadId
|
|
586
|
+
threadId,
|
|
587
|
+
resourceId: resourceId ?? ""
|
|
1003
588
|
}
|
|
1004
589
|
},
|
|
1005
590
|
error$1
|
|
@@ -1009,30 +594,65 @@ ${columns}
|
|
|
1009
594
|
return [];
|
|
1010
595
|
}
|
|
1011
596
|
}
|
|
1012
|
-
async
|
|
1013
|
-
|
|
1014
|
-
|
|
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`;
|
|
1015
603
|
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
1016
|
-
|
|
1017
|
-
|
|
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 [];
|
|
1018
635
|
}
|
|
636
|
+
}
|
|
637
|
+
async getMessagesPaginated(args) {
|
|
638
|
+
const { threadId, resourceId, format, selectBy } = args;
|
|
639
|
+
const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
|
|
1019
640
|
try {
|
|
1020
|
-
|
|
1021
|
-
const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
|
|
641
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
1022
642
|
const fromDate = dateRange?.start;
|
|
1023
643
|
const toDate = dateRange?.end;
|
|
1024
|
-
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
|
|
1025
|
-
const
|
|
1026
|
-
let
|
|
1027
|
-
if (
|
|
1028
|
-
const includeMessages = await this._getIncludedMessages({ threadId
|
|
1029
|
-
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);
|
|
1030
650
|
}
|
|
1031
|
-
const perPage =
|
|
1032
|
-
const currentOffset =
|
|
651
|
+
const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
652
|
+
const currentOffset = page * perPage;
|
|
1033
653
|
const conditions = ["[thread_id] = @threadId"];
|
|
1034
654
|
const request = this.pool.request();
|
|
1035
|
-
request.input("threadId",
|
|
655
|
+
request.input("threadId", threadId);
|
|
1036
656
|
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1037
657
|
conditions.push("[createdAt] >= @fromDate");
|
|
1038
658
|
request.input("fromDate", fromDate.toISOString());
|
|
@@ -1042,38 +662,38 @@ ${columns}
|
|
|
1042
662
|
request.input("toDate", toDate.toISOString());
|
|
1043
663
|
}
|
|
1044
664
|
const whereClause = `WHERE ${conditions.join(" AND ")}`;
|
|
1045
|
-
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}`;
|
|
1046
666
|
const countResult = await request.query(countQuery);
|
|
1047
667
|
const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
|
|
1048
|
-
if (total === 0 &&
|
|
1049
|
-
const parsedIncluded = this._parseAndFormatMessages(
|
|
668
|
+
if (total === 0 && messages.length > 0) {
|
|
669
|
+
const parsedIncluded = this._parseAndFormatMessages(messages, format);
|
|
1050
670
|
return {
|
|
1051
671
|
messages: parsedIncluded,
|
|
1052
672
|
total: parsedIncluded.length,
|
|
1053
|
-
page
|
|
673
|
+
page,
|
|
1054
674
|
perPage,
|
|
1055
675
|
hasMore: false
|
|
1056
676
|
};
|
|
1057
677
|
}
|
|
1058
|
-
const excludeIds =
|
|
678
|
+
const excludeIds = messages.map((m) => m.id);
|
|
1059
679
|
if (excludeIds.length > 0) {
|
|
1060
680
|
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
1061
681
|
conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
|
|
1062
682
|
excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
|
|
1063
683
|
}
|
|
1064
684
|
const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
|
|
1065
|
-
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`;
|
|
1066
686
|
request.input("offset", currentOffset);
|
|
1067
687
|
request.input("limit", perPage);
|
|
1068
688
|
const rowsResult = await request.query(dataQuery);
|
|
1069
689
|
const rows = rowsResult.recordset || [];
|
|
1070
690
|
rows.sort((a, b) => a.seq_id - b.seq_id);
|
|
1071
|
-
|
|
1072
|
-
const parsed = this._parseAndFormatMessages(
|
|
691
|
+
messages.push(...rows);
|
|
692
|
+
const parsed = this._parseAndFormatMessages(messages, format);
|
|
1073
693
|
return {
|
|
1074
694
|
messages: parsed,
|
|
1075
695
|
total: total + excludeIds.length,
|
|
1076
|
-
page
|
|
696
|
+
page,
|
|
1077
697
|
perPage,
|
|
1078
698
|
hasMore: currentOffset + rows.length < total
|
|
1079
699
|
};
|
|
@@ -1085,6 +705,7 @@ ${columns}
|
|
|
1085
705
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1086
706
|
details: {
|
|
1087
707
|
threadId,
|
|
708
|
+
resourceId: resourceId ?? "",
|
|
1088
709
|
page
|
|
1089
710
|
}
|
|
1090
711
|
},
|
|
@@ -1095,31 +716,6 @@ ${columns}
|
|
|
1095
716
|
return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
|
|
1096
717
|
}
|
|
1097
718
|
}
|
|
1098
|
-
_parseAndFormatMessages(messages, format) {
|
|
1099
|
-
const parsedMessages = messages.map((message) => {
|
|
1100
|
-
let parsed = message;
|
|
1101
|
-
if (typeof parsed.content === "string") {
|
|
1102
|
-
try {
|
|
1103
|
-
parsed = { ...parsed, content: JSON.parse(parsed.content) };
|
|
1104
|
-
} catch {
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
if (format === "v1") {
|
|
1108
|
-
if (Array.isArray(parsed.content)) ; else if (parsed.content?.parts) {
|
|
1109
|
-
parsed.content = parsed.content.parts;
|
|
1110
|
-
} else {
|
|
1111
|
-
parsed.content = [{ type: "text", text: "" }];
|
|
1112
|
-
}
|
|
1113
|
-
} else {
|
|
1114
|
-
if (!parsed.content?.parts) {
|
|
1115
|
-
parsed = { ...parsed, content: { format: 2, parts: [{ type: "text", text: "" }] } };
|
|
1116
|
-
}
|
|
1117
|
-
}
|
|
1118
|
-
return parsed;
|
|
1119
|
-
});
|
|
1120
|
-
const list = new agent.MessageList().add(parsedMessages, "memory");
|
|
1121
|
-
return format === "v2" ? list.get.all.v2() : list.get.all.v1();
|
|
1122
|
-
}
|
|
1123
719
|
async saveMessages({
|
|
1124
720
|
messages,
|
|
1125
721
|
format
|
|
@@ -1144,8 +740,8 @@ ${columns}
|
|
|
1144
740
|
details: { threadId }
|
|
1145
741
|
});
|
|
1146
742
|
}
|
|
1147
|
-
const tableMessages =
|
|
1148
|
-
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) });
|
|
1149
745
|
try {
|
|
1150
746
|
const transaction = this.pool.transaction();
|
|
1151
747
|
await transaction.begin();
|
|
@@ -1168,7 +764,7 @@ ${columns}
|
|
|
1168
764
|
"content",
|
|
1169
765
|
typeof message.content === "string" ? message.content : JSON.stringify(message.content)
|
|
1170
766
|
);
|
|
1171
|
-
request.input("createdAt",
|
|
767
|
+
request.input("createdAt", sql2__default.default.DateTime2, message.createdAt);
|
|
1172
768
|
request.input("role", message.role);
|
|
1173
769
|
request.input("type", message.type || "v2");
|
|
1174
770
|
request.input("resourceId", message.resourceId);
|
|
@@ -1187,7 +783,7 @@ ${columns}
|
|
|
1187
783
|
await request.query(mergeSql);
|
|
1188
784
|
}
|
|
1189
785
|
const threadReq = transaction.request();
|
|
1190
|
-
threadReq.input("updatedAt",
|
|
786
|
+
threadReq.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
|
|
1191
787
|
threadReq.input("id", threadId);
|
|
1192
788
|
await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
|
|
1193
789
|
await transaction.commit();
|
|
@@ -1220,216 +816,6 @@ ${columns}
|
|
|
1220
816
|
);
|
|
1221
817
|
}
|
|
1222
818
|
}
|
|
1223
|
-
async persistWorkflowSnapshot({
|
|
1224
|
-
workflowName,
|
|
1225
|
-
runId,
|
|
1226
|
-
snapshot
|
|
1227
|
-
}) {
|
|
1228
|
-
const table = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
1229
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1230
|
-
try {
|
|
1231
|
-
const request = this.pool.request();
|
|
1232
|
-
request.input("workflow_name", workflowName);
|
|
1233
|
-
request.input("run_id", runId);
|
|
1234
|
-
request.input("snapshot", JSON.stringify(snapshot));
|
|
1235
|
-
request.input("createdAt", now);
|
|
1236
|
-
request.input("updatedAt", now);
|
|
1237
|
-
const mergeSql = `MERGE INTO ${table} AS target
|
|
1238
|
-
USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
|
|
1239
|
-
ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
|
|
1240
|
-
WHEN MATCHED THEN UPDATE SET
|
|
1241
|
-
snapshot = @snapshot,
|
|
1242
|
-
[updatedAt] = @updatedAt
|
|
1243
|
-
WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
|
|
1244
|
-
VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
|
|
1245
|
-
await request.query(mergeSql);
|
|
1246
|
-
} catch (error$1) {
|
|
1247
|
-
throw new error.MastraError(
|
|
1248
|
-
{
|
|
1249
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
|
|
1250
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1251
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1252
|
-
details: {
|
|
1253
|
-
workflowName,
|
|
1254
|
-
runId
|
|
1255
|
-
}
|
|
1256
|
-
},
|
|
1257
|
-
error$1
|
|
1258
|
-
);
|
|
1259
|
-
}
|
|
1260
|
-
}
|
|
1261
|
-
async loadWorkflowSnapshot({
|
|
1262
|
-
workflowName,
|
|
1263
|
-
runId
|
|
1264
|
-
}) {
|
|
1265
|
-
try {
|
|
1266
|
-
const result = await this.load({
|
|
1267
|
-
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
1268
|
-
keys: {
|
|
1269
|
-
workflow_name: workflowName,
|
|
1270
|
-
run_id: runId
|
|
1271
|
-
}
|
|
1272
|
-
});
|
|
1273
|
-
if (!result) {
|
|
1274
|
-
return null;
|
|
1275
|
-
}
|
|
1276
|
-
return result.snapshot;
|
|
1277
|
-
} catch (error$1) {
|
|
1278
|
-
throw new error.MastraError(
|
|
1279
|
-
{
|
|
1280
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
|
|
1281
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1282
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1283
|
-
details: {
|
|
1284
|
-
workflowName,
|
|
1285
|
-
runId
|
|
1286
|
-
}
|
|
1287
|
-
},
|
|
1288
|
-
error$1
|
|
1289
|
-
);
|
|
1290
|
-
}
|
|
1291
|
-
}
|
|
1292
|
-
async hasColumn(table, column) {
|
|
1293
|
-
const schema = this.schema || "dbo";
|
|
1294
|
-
const request = this.pool.request();
|
|
1295
|
-
request.input("schema", schema);
|
|
1296
|
-
request.input("table", table);
|
|
1297
|
-
request.input("column", column);
|
|
1298
|
-
request.input("columnLower", column.toLowerCase());
|
|
1299
|
-
const result = await request.query(
|
|
1300
|
-
`SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
|
|
1301
|
-
);
|
|
1302
|
-
return result.recordset.length > 0;
|
|
1303
|
-
}
|
|
1304
|
-
parseWorkflowRun(row) {
|
|
1305
|
-
let parsedSnapshot = row.snapshot;
|
|
1306
|
-
if (typeof parsedSnapshot === "string") {
|
|
1307
|
-
try {
|
|
1308
|
-
parsedSnapshot = JSON.parse(row.snapshot);
|
|
1309
|
-
} catch (e) {
|
|
1310
|
-
console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
|
|
1311
|
-
}
|
|
1312
|
-
}
|
|
1313
|
-
return {
|
|
1314
|
-
workflowName: row.workflow_name,
|
|
1315
|
-
runId: row.run_id,
|
|
1316
|
-
snapshot: parsedSnapshot,
|
|
1317
|
-
createdAt: row.createdAt,
|
|
1318
|
-
updatedAt: row.updatedAt,
|
|
1319
|
-
resourceId: row.resourceId
|
|
1320
|
-
};
|
|
1321
|
-
}
|
|
1322
|
-
async getWorkflowRuns({
|
|
1323
|
-
workflowName,
|
|
1324
|
-
fromDate,
|
|
1325
|
-
toDate,
|
|
1326
|
-
limit,
|
|
1327
|
-
offset,
|
|
1328
|
-
resourceId
|
|
1329
|
-
} = {}) {
|
|
1330
|
-
try {
|
|
1331
|
-
const conditions = [];
|
|
1332
|
-
const paramMap = {};
|
|
1333
|
-
if (workflowName) {
|
|
1334
|
-
conditions.push(`[workflow_name] = @workflowName`);
|
|
1335
|
-
paramMap["workflowName"] = workflowName;
|
|
1336
|
-
}
|
|
1337
|
-
if (resourceId) {
|
|
1338
|
-
const hasResourceId = await this.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
|
|
1339
|
-
if (hasResourceId) {
|
|
1340
|
-
conditions.push(`[resourceId] = @resourceId`);
|
|
1341
|
-
paramMap["resourceId"] = resourceId;
|
|
1342
|
-
} else {
|
|
1343
|
-
console.warn(`[${storage.TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1347
|
-
conditions.push(`[createdAt] >= @fromDate`);
|
|
1348
|
-
paramMap[`fromDate`] = fromDate.toISOString();
|
|
1349
|
-
}
|
|
1350
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1351
|
-
conditions.push(`[createdAt] <= @toDate`);
|
|
1352
|
-
paramMap[`toDate`] = toDate.toISOString();
|
|
1353
|
-
}
|
|
1354
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1355
|
-
let total = 0;
|
|
1356
|
-
const tableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
1357
|
-
const request = this.pool.request();
|
|
1358
|
-
Object.entries(paramMap).forEach(([key, value]) => {
|
|
1359
|
-
if (value instanceof Date) {
|
|
1360
|
-
request.input(key, sql__default.default.DateTime, value);
|
|
1361
|
-
} else {
|
|
1362
|
-
request.input(key, value);
|
|
1363
|
-
}
|
|
1364
|
-
});
|
|
1365
|
-
if (limit !== void 0 && offset !== void 0) {
|
|
1366
|
-
const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
|
|
1367
|
-
const countResult = await request.query(countQuery);
|
|
1368
|
-
total = Number(countResult.recordset[0]?.count || 0);
|
|
1369
|
-
}
|
|
1370
|
-
let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
|
|
1371
|
-
if (limit !== void 0 && offset !== void 0) {
|
|
1372
|
-
query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
1373
|
-
request.input("limit", limit);
|
|
1374
|
-
request.input("offset", offset);
|
|
1375
|
-
}
|
|
1376
|
-
const result = await request.query(query);
|
|
1377
|
-
const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
|
|
1378
|
-
return { runs, total: total || runs.length };
|
|
1379
|
-
} catch (error$1) {
|
|
1380
|
-
throw new error.MastraError(
|
|
1381
|
-
{
|
|
1382
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
|
|
1383
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1384
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1385
|
-
details: {
|
|
1386
|
-
workflowName: workflowName || "all"
|
|
1387
|
-
}
|
|
1388
|
-
},
|
|
1389
|
-
error$1
|
|
1390
|
-
);
|
|
1391
|
-
}
|
|
1392
|
-
}
|
|
1393
|
-
async getWorkflowRunById({
|
|
1394
|
-
runId,
|
|
1395
|
-
workflowName
|
|
1396
|
-
}) {
|
|
1397
|
-
try {
|
|
1398
|
-
const conditions = [];
|
|
1399
|
-
const paramMap = {};
|
|
1400
|
-
if (runId) {
|
|
1401
|
-
conditions.push(`[run_id] = @runId`);
|
|
1402
|
-
paramMap["runId"] = runId;
|
|
1403
|
-
}
|
|
1404
|
-
if (workflowName) {
|
|
1405
|
-
conditions.push(`[workflow_name] = @workflowName`);
|
|
1406
|
-
paramMap["workflowName"] = workflowName;
|
|
1407
|
-
}
|
|
1408
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1409
|
-
const tableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
1410
|
-
const query = `SELECT * FROM ${tableName} ${whereClause}`;
|
|
1411
|
-
const request = this.pool.request();
|
|
1412
|
-
Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
|
|
1413
|
-
const result = await request.query(query);
|
|
1414
|
-
if (!result.recordset || result.recordset.length === 0) {
|
|
1415
|
-
return null;
|
|
1416
|
-
}
|
|
1417
|
-
return this.parseWorkflowRun(result.recordset[0]);
|
|
1418
|
-
} catch (error$1) {
|
|
1419
|
-
throw new error.MastraError(
|
|
1420
|
-
{
|
|
1421
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
|
|
1422
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1423
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1424
|
-
details: {
|
|
1425
|
-
runId,
|
|
1426
|
-
workflowName: workflowName || ""
|
|
1427
|
-
}
|
|
1428
|
-
},
|
|
1429
|
-
error$1
|
|
1430
|
-
);
|
|
1431
|
-
}
|
|
1432
|
-
}
|
|
1433
819
|
async updateMessages({
|
|
1434
820
|
messages
|
|
1435
821
|
}) {
|
|
@@ -1438,7 +824,7 @@ ${columns}
|
|
|
1438
824
|
}
|
|
1439
825
|
const messageIds = messages.map((m) => m.id);
|
|
1440
826
|
const idParams = messageIds.map((_, i) => `@id${i}`).join(", ");
|
|
1441
|
-
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) })}`;
|
|
1442
828
|
if (idParams.length > 0) {
|
|
1443
829
|
selectQuery += ` WHERE id IN (${idParams})`;
|
|
1444
830
|
} else {
|
|
@@ -1495,7 +881,7 @@ ${columns}
|
|
|
1495
881
|
}
|
|
1496
882
|
}
|
|
1497
883
|
if (setClauses.length > 0) {
|
|
1498
|
-
const updateSql = `UPDATE ${
|
|
884
|
+
const updateSql = `UPDATE ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} SET ${setClauses.join(", ")} WHERE id = @id`;
|
|
1499
885
|
await req.query(updateSql);
|
|
1500
886
|
}
|
|
1501
887
|
}
|
|
@@ -1504,7 +890,7 @@ ${columns}
|
|
|
1504
890
|
const threadReq = transaction.request();
|
|
1505
891
|
Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
|
|
1506
892
|
threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
|
|
1507
|
-
const threadSql = `UPDATE ${
|
|
893
|
+
const threadSql = `UPDATE ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
|
|
1508
894
|
await threadReq.query(threadSql);
|
|
1509
895
|
}
|
|
1510
896
|
await transaction.commit();
|
|
@@ -1532,101 +918,78 @@ ${columns}
|
|
|
1532
918
|
return message;
|
|
1533
919
|
});
|
|
1534
920
|
}
|
|
1535
|
-
async
|
|
1536
|
-
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();
|
|
1537
939
|
try {
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
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
|
+
}
|
|
1543
951
|
}
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
952
|
+
await transaction.commit();
|
|
953
|
+
} catch (error) {
|
|
954
|
+
try {
|
|
955
|
+
await transaction.rollback();
|
|
956
|
+
} catch {
|
|
1547
957
|
}
|
|
958
|
+
throw error;
|
|
1548
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
|
+
);
|
|
1549
970
|
}
|
|
1550
971
|
}
|
|
1551
|
-
async
|
|
1552
|
-
const
|
|
1553
|
-
const fromDate = dateRange?.start;
|
|
1554
|
-
const toDate = dateRange?.end;
|
|
1555
|
-
const where = [];
|
|
1556
|
-
const params = {};
|
|
1557
|
-
if (agentName) {
|
|
1558
|
-
where.push("agent_name = @agentName");
|
|
1559
|
-
params["agentName"] = agentName;
|
|
1560
|
-
}
|
|
1561
|
-
if (type === "test") {
|
|
1562
|
-
where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
|
|
1563
|
-
} else if (type === "live") {
|
|
1564
|
-
where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
|
|
1565
|
-
}
|
|
1566
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1567
|
-
where.push(`[created_at] >= @fromDate`);
|
|
1568
|
-
params[`fromDate`] = fromDate.toISOString();
|
|
1569
|
-
}
|
|
1570
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1571
|
-
where.push(`[created_at] <= @toDate`);
|
|
1572
|
-
params[`toDate`] = toDate.toISOString();
|
|
1573
|
-
}
|
|
1574
|
-
const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
|
|
1575
|
-
const tableName = this.getTableName(storage.TABLE_EVALS);
|
|
1576
|
-
const offset = page * perPage;
|
|
1577
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
|
|
1578
|
-
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) });
|
|
1579
974
|
try {
|
|
1580
|
-
const countReq = this.pool.request();
|
|
1581
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
1582
|
-
if (value instanceof Date) {
|
|
1583
|
-
countReq.input(key, sql__default.default.DateTime, value);
|
|
1584
|
-
} else {
|
|
1585
|
-
countReq.input(key, value);
|
|
1586
|
-
}
|
|
1587
|
-
});
|
|
1588
|
-
const countResult = await countReq.query(countQuery);
|
|
1589
|
-
const total = countResult.recordset[0]?.total || 0;
|
|
1590
|
-
if (total === 0) {
|
|
1591
|
-
return {
|
|
1592
|
-
evals: [],
|
|
1593
|
-
total: 0,
|
|
1594
|
-
page,
|
|
1595
|
-
perPage,
|
|
1596
|
-
hasMore: false
|
|
1597
|
-
};
|
|
1598
|
-
}
|
|
1599
975
|
const req = this.pool.request();
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
}
|
|
1606
|
-
});
|
|
1607
|
-
req.input("offset", offset);
|
|
1608
|
-
req.input("perPage", perPage);
|
|
1609
|
-
const result = await req.query(dataQuery);
|
|
1610
|
-
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
|
+
}
|
|
1611
981
|
return {
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
perPage,
|
|
1616
|
-
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
|
|
1617
985
|
};
|
|
1618
986
|
} catch (error$1) {
|
|
1619
987
|
const mastraError = new error.MastraError(
|
|
1620
988
|
{
|
|
1621
|
-
id: "
|
|
989
|
+
id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
|
|
1622
990
|
domain: error.ErrorDomain.STORAGE,
|
|
1623
991
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1624
|
-
details: {
|
|
1625
|
-
agentName: agentName || "all",
|
|
1626
|
-
type: type || "all",
|
|
1627
|
-
page,
|
|
1628
|
-
perPage
|
|
1629
|
-
}
|
|
992
|
+
details: { resourceId }
|
|
1630
993
|
},
|
|
1631
994
|
error$1
|
|
1632
995
|
);
|
|
@@ -1636,32 +999,14 @@ ${columns}
|
|
|
1636
999
|
}
|
|
1637
1000
|
}
|
|
1638
1001
|
async saveResource({ resource }) {
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
await req.query(
|
|
1648
|
-
`INSERT INTO ${tableName} (id, workingMemory, metadata, createdAt, updatedAt) VALUES (@id, @workingMemory, @metadata, @createdAt, @updatedAt)`
|
|
1649
|
-
);
|
|
1650
|
-
return resource;
|
|
1651
|
-
} catch (error$1) {
|
|
1652
|
-
const mastraError = new error.MastraError(
|
|
1653
|
-
{
|
|
1654
|
-
id: "MASTRA_STORAGE_MSSQL_SAVE_RESOURCE_FAILED",
|
|
1655
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1656
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1657
|
-
details: { resourceId: resource.id }
|
|
1658
|
-
},
|
|
1659
|
-
error$1
|
|
1660
|
-
);
|
|
1661
|
-
this.logger?.error?.(mastraError.toString());
|
|
1662
|
-
this.logger?.trackException(mastraError);
|
|
1663
|
-
throw mastraError;
|
|
1664
|
-
}
|
|
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;
|
|
1665
1010
|
}
|
|
1666
1011
|
async updateResource({
|
|
1667
1012
|
resourceId,
|
|
@@ -1689,7 +1034,7 @@ ${columns}
|
|
|
1689
1034
|
},
|
|
1690
1035
|
updatedAt: /* @__PURE__ */ new Date()
|
|
1691
1036
|
};
|
|
1692
|
-
const tableName =
|
|
1037
|
+
const tableName = getTableName({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
|
|
1693
1038
|
const updates = [];
|
|
1694
1039
|
const req = this.pool.request();
|
|
1695
1040
|
if (workingMemory !== void 0) {
|
|
@@ -1720,101 +1065,1383 @@ ${columns}
|
|
|
1720
1065
|
throw mastraError;
|
|
1721
1066
|
}
|
|
1722
1067
|
}
|
|
1723
|
-
|
|
1724
|
-
|
|
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 }) {
|
|
1725
1153
|
try {
|
|
1726
|
-
const
|
|
1727
|
-
|
|
1728
|
-
const
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
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);
|
|
1737
1169
|
} catch (error$1) {
|
|
1738
|
-
|
|
1170
|
+
throw new error.MastraError(
|
|
1739
1171
|
{
|
|
1740
|
-
id: "
|
|
1172
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
|
|
1741
1173
|
domain: error.ErrorDomain.STORAGE,
|
|
1742
1174
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1743
|
-
details: {
|
|
1175
|
+
details: {
|
|
1176
|
+
tableName
|
|
1177
|
+
}
|
|
1744
1178
|
},
|
|
1745
1179
|
error$1
|
|
1746
1180
|
);
|
|
1747
|
-
this.logger?.error?.(mastraError.toString());
|
|
1748
|
-
this.logger?.trackException(mastraError);
|
|
1749
|
-
throw mastraError;
|
|
1750
1181
|
}
|
|
1751
1182
|
}
|
|
1752
|
-
async
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
|
|
1778
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1779
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1780
|
-
details: { scorerId, entityId: entityId || "", entityType: entityType || "" },
|
|
1781
|
-
text: "getScoresByScorerId is not implemented yet in MongoDBStore"
|
|
1782
|
-
});
|
|
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
|
+
}
|
|
1783
1208
|
}
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
text: "getScoresByRunId is not implemented yet in MongoDBStore"
|
|
1794
|
-
});
|
|
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
|
+
}
|
|
1795
1218
|
}
|
|
1796
|
-
async
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
pagination: _pagination
|
|
1219
|
+
async createTable({
|
|
1220
|
+
tableName,
|
|
1221
|
+
schema
|
|
1800
1222
|
}) {
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
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 });
|
|
1817
2442
|
}
|
|
1818
2443
|
};
|
|
1819
2444
|
|
|
1820
2445
|
exports.MSSQLStore = MSSQLStore;
|
|
2446
|
+
//# sourceMappingURL=index.cjs.map
|
|
2447
|
+
//# sourceMappingURL=index.cjs.map
|