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