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