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