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