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