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