@mastra/mssql 0.0.0-fix-backport-setserver-20251201151948 → 0.0.0-fix-request-context-as-query-key-20251209130646
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 +588 -53
- package/README.md +28 -20
- package/dist/index.cjs +470 -776
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +469 -775
- package/dist/index.js.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +14 -43
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/observability/index.d.ts +16 -16
- package/dist/storage/domains/observability/index.d.ts.map +1 -1
- package/dist/storage/domains/operations/index.d.ts.map +1 -1
- package/dist/storage/domains/scores/index.d.ts +6 -6
- package/dist/storage/domains/scores/index.d.ts.map +1 -1
- package/dist/storage/domains/utils.d.ts.map +1 -1
- package/dist/storage/domains/workflows/index.d.ts +5 -11
- package/dist/storage/domains/workflows/index.d.ts.map +1 -1
- package/dist/storage/index.d.ts +58 -96
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +12 -14
- package/dist/storage/domains/legacy-evals/index.d.ts +0 -20
- package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
- package/dist/storage/domains/traces/index.d.ts +0 -37
- package/dist/storage/domains/traces/index.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
|
|
2
|
-
import { MastraStorage,
|
|
3
|
-
import
|
|
4
|
-
import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
|
|
2
|
+
import { MastraStorage, createStorageErrorId, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_TRACES, TABLE_SCORERS, TABLE_SPANS, ScoresStorage, normalizePerPage, calculatePagination, WorkflowsStorage, MemoryStorage, TABLE_RESOURCES, ObservabilityStorage, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
|
|
3
|
+
import sql2 from 'mssql';
|
|
5
4
|
import { MessageList } from '@mastra/core/agent';
|
|
5
|
+
import { parseSqlIdentifier } from '@mastra/core/utils';
|
|
6
6
|
import { randomUUID } from 'crypto';
|
|
7
|
-
import { saveScorePayloadSchema } from '@mastra/core/
|
|
7
|
+
import { saveScorePayloadSchema } from '@mastra/core/evals';
|
|
8
8
|
|
|
9
9
|
// src/storage/index.ts
|
|
10
10
|
function getSchemaName(schema) {
|
|
@@ -26,24 +26,62 @@ function buildDateRangeFilter(dateRange, fieldName) {
|
|
|
26
26
|
}
|
|
27
27
|
return filters;
|
|
28
28
|
}
|
|
29
|
+
function isInOperator(value) {
|
|
30
|
+
return typeof value === "object" && value !== null && "$in" in value && Array.isArray(value.$in);
|
|
31
|
+
}
|
|
29
32
|
function prepareWhereClause(filters, _schema) {
|
|
30
33
|
const conditions = [];
|
|
31
34
|
const params = {};
|
|
32
35
|
let paramIndex = 1;
|
|
33
36
|
Object.entries(filters).forEach(([key, value]) => {
|
|
34
37
|
if (value === void 0) return;
|
|
35
|
-
const paramName = `p${paramIndex++}`;
|
|
36
38
|
if (key.endsWith("_gte")) {
|
|
39
|
+
const paramName = `p${paramIndex++}`;
|
|
37
40
|
const fieldName = key.slice(0, -4);
|
|
38
41
|
conditions.push(`[${parseSqlIdentifier(fieldName, "field name")}] >= @${paramName}`);
|
|
39
42
|
params[paramName] = value instanceof Date ? value.toISOString() : value;
|
|
40
43
|
} else if (key.endsWith("_lte")) {
|
|
44
|
+
const paramName = `p${paramIndex++}`;
|
|
41
45
|
const fieldName = key.slice(0, -4);
|
|
42
46
|
conditions.push(`[${parseSqlIdentifier(fieldName, "field name")}] <= @${paramName}`);
|
|
43
47
|
params[paramName] = value instanceof Date ? value.toISOString() : value;
|
|
44
48
|
} else if (value === null) {
|
|
45
49
|
conditions.push(`[${parseSqlIdentifier(key, "field name")}] IS NULL`);
|
|
50
|
+
} else if (isInOperator(value)) {
|
|
51
|
+
const inValues = value.$in;
|
|
52
|
+
if (inValues.length === 0) {
|
|
53
|
+
conditions.push("1 = 0");
|
|
54
|
+
} else if (inValues.length === 1) {
|
|
55
|
+
const paramName = `p${paramIndex++}`;
|
|
56
|
+
conditions.push(`[${parseSqlIdentifier(key, "field name")}] = @${paramName}`);
|
|
57
|
+
params[paramName] = inValues[0] instanceof Date ? inValues[0].toISOString() : inValues[0];
|
|
58
|
+
} else {
|
|
59
|
+
const inParamNames = [];
|
|
60
|
+
for (const item of inValues) {
|
|
61
|
+
const paramName = `p${paramIndex++}`;
|
|
62
|
+
inParamNames.push(`@${paramName}`);
|
|
63
|
+
params[paramName] = item instanceof Date ? item.toISOString() : item;
|
|
64
|
+
}
|
|
65
|
+
conditions.push(`[${parseSqlIdentifier(key, "field name")}] IN (${inParamNames.join(", ")})`);
|
|
66
|
+
}
|
|
67
|
+
} else if (Array.isArray(value)) {
|
|
68
|
+
if (value.length === 0) {
|
|
69
|
+
conditions.push("1 = 0");
|
|
70
|
+
} else if (value.length === 1) {
|
|
71
|
+
const paramName = `p${paramIndex++}`;
|
|
72
|
+
conditions.push(`[${parseSqlIdentifier(key, "field name")}] = @${paramName}`);
|
|
73
|
+
params[paramName] = value[0] instanceof Date ? value[0].toISOString() : value[0];
|
|
74
|
+
} else {
|
|
75
|
+
const inParamNames = [];
|
|
76
|
+
for (const item of value) {
|
|
77
|
+
const paramName = `p${paramIndex++}`;
|
|
78
|
+
inParamNames.push(`@${paramName}`);
|
|
79
|
+
params[paramName] = item instanceof Date ? item.toISOString() : item;
|
|
80
|
+
}
|
|
81
|
+
conditions.push(`[${parseSqlIdentifier(key, "field name")}] IN (${inParamNames.join(", ")})`);
|
|
82
|
+
}
|
|
46
83
|
} else {
|
|
84
|
+
const paramName = `p${paramIndex++}`;
|
|
47
85
|
conditions.push(`[${parseSqlIdentifier(key, "field name")}] = @${paramName}`);
|
|
48
86
|
params[paramName] = value instanceof Date ? value.toISOString() : value;
|
|
49
87
|
}
|
|
@@ -80,153 +118,7 @@ function transformFromSqlRow({
|
|
|
80
118
|
return result;
|
|
81
119
|
}
|
|
82
120
|
|
|
83
|
-
// src/storage/domains/
|
|
84
|
-
function transformEvalRow(row) {
|
|
85
|
-
let testInfoValue = null, resultValue = null;
|
|
86
|
-
if (row.test_info) {
|
|
87
|
-
try {
|
|
88
|
-
testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
|
|
89
|
-
} catch {
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
if (row.result) {
|
|
93
|
-
try {
|
|
94
|
-
resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
|
|
95
|
-
} catch {
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
return {
|
|
99
|
-
agentName: row.agent_name,
|
|
100
|
-
input: row.input,
|
|
101
|
-
output: row.output,
|
|
102
|
-
result: resultValue,
|
|
103
|
-
metricName: row.metric_name,
|
|
104
|
-
instructions: row.instructions,
|
|
105
|
-
testInfo: testInfoValue,
|
|
106
|
-
globalRunId: row.global_run_id,
|
|
107
|
-
runId: row.run_id,
|
|
108
|
-
createdAt: row.created_at
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
var LegacyEvalsMSSQL = class extends LegacyEvalsStorage {
|
|
112
|
-
pool;
|
|
113
|
-
schema;
|
|
114
|
-
constructor({ pool, schema }) {
|
|
115
|
-
super();
|
|
116
|
-
this.pool = pool;
|
|
117
|
-
this.schema = schema;
|
|
118
|
-
}
|
|
119
|
-
/** @deprecated use getEvals instead */
|
|
120
|
-
async getEvalsByAgentName(agentName, type) {
|
|
121
|
-
try {
|
|
122
|
-
let query = `SELECT * FROM ${getTableName({ indexName: TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
|
|
123
|
-
if (type === "test") {
|
|
124
|
-
query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
|
|
125
|
-
} else if (type === "live") {
|
|
126
|
-
query += " AND (test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)";
|
|
127
|
-
}
|
|
128
|
-
query += " ORDER BY created_at DESC";
|
|
129
|
-
const request = this.pool.request();
|
|
130
|
-
request.input("p1", agentName);
|
|
131
|
-
const result = await request.query(query);
|
|
132
|
-
const rows = result.recordset;
|
|
133
|
-
return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
|
|
134
|
-
} catch (error) {
|
|
135
|
-
if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
|
|
136
|
-
return [];
|
|
137
|
-
}
|
|
138
|
-
this.logger?.error?.("Failed to get evals for the specified agent:", error);
|
|
139
|
-
throw error;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
async getEvals(options = {}) {
|
|
143
|
-
const { agentName, type, page = 0, perPage = 100, dateRange } = options;
|
|
144
|
-
const fromDate = dateRange?.start;
|
|
145
|
-
const toDate = dateRange?.end;
|
|
146
|
-
const where = [];
|
|
147
|
-
const params = {};
|
|
148
|
-
if (agentName) {
|
|
149
|
-
where.push("agent_name = @agentName");
|
|
150
|
-
params["agentName"] = agentName;
|
|
151
|
-
}
|
|
152
|
-
if (type === "test") {
|
|
153
|
-
where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
|
|
154
|
-
} else if (type === "live") {
|
|
155
|
-
where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
|
|
156
|
-
}
|
|
157
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
158
|
-
where.push(`[created_at] >= @fromDate`);
|
|
159
|
-
params[`fromDate`] = fromDate.toISOString();
|
|
160
|
-
}
|
|
161
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
162
|
-
where.push(`[created_at] <= @toDate`);
|
|
163
|
-
params[`toDate`] = toDate.toISOString();
|
|
164
|
-
}
|
|
165
|
-
const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
|
|
166
|
-
const tableName = getTableName({ indexName: TABLE_EVALS, schemaName: getSchemaName(this.schema) });
|
|
167
|
-
const offset = page * perPage;
|
|
168
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
|
|
169
|
-
const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
170
|
-
try {
|
|
171
|
-
const countReq = this.pool.request();
|
|
172
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
173
|
-
if (value instanceof Date) {
|
|
174
|
-
countReq.input(key, sql3.DateTime, value);
|
|
175
|
-
} else {
|
|
176
|
-
countReq.input(key, value);
|
|
177
|
-
}
|
|
178
|
-
});
|
|
179
|
-
const countResult = await countReq.query(countQuery);
|
|
180
|
-
const total = countResult.recordset[0]?.total || 0;
|
|
181
|
-
if (total === 0) {
|
|
182
|
-
return {
|
|
183
|
-
evals: [],
|
|
184
|
-
total: 0,
|
|
185
|
-
page,
|
|
186
|
-
perPage,
|
|
187
|
-
hasMore: false
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
const req = this.pool.request();
|
|
191
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
192
|
-
if (value instanceof Date) {
|
|
193
|
-
req.input(key, sql3.DateTime, value);
|
|
194
|
-
} else {
|
|
195
|
-
req.input(key, value);
|
|
196
|
-
}
|
|
197
|
-
});
|
|
198
|
-
req.input("offset", offset);
|
|
199
|
-
req.input("perPage", perPage);
|
|
200
|
-
const result = await req.query(dataQuery);
|
|
201
|
-
const rows = result.recordset;
|
|
202
|
-
return {
|
|
203
|
-
evals: rows?.map((row) => transformEvalRow(row)) ?? [],
|
|
204
|
-
total,
|
|
205
|
-
page,
|
|
206
|
-
perPage,
|
|
207
|
-
hasMore: offset + (rows?.length ?? 0) < total
|
|
208
|
-
};
|
|
209
|
-
} catch (error) {
|
|
210
|
-
const mastraError = new MastraError(
|
|
211
|
-
{
|
|
212
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
|
|
213
|
-
domain: ErrorDomain.STORAGE,
|
|
214
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
215
|
-
details: {
|
|
216
|
-
agentName: agentName || "all",
|
|
217
|
-
type: type || "all",
|
|
218
|
-
page,
|
|
219
|
-
perPage
|
|
220
|
-
}
|
|
221
|
-
},
|
|
222
|
-
error
|
|
223
|
-
);
|
|
224
|
-
this.logger?.error?.(mastraError.toString());
|
|
225
|
-
this.logger?.trackException?.(mastraError);
|
|
226
|
-
throw mastraError;
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
};
|
|
121
|
+
// src/storage/domains/memory/index.ts
|
|
230
122
|
var MemoryMSSQL = class extends MemoryStorage {
|
|
231
123
|
pool;
|
|
232
124
|
schema;
|
|
@@ -244,7 +136,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
244
136
|
});
|
|
245
137
|
const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
|
|
246
138
|
const list = new MessageList().add(cleanMessages, "memory");
|
|
247
|
-
return format === "v2" ? list.get.all.
|
|
139
|
+
return format === "v2" ? list.get.all.db() : list.get.all.v1();
|
|
248
140
|
}
|
|
249
141
|
constructor({
|
|
250
142
|
pool,
|
|
@@ -258,7 +150,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
258
150
|
}
|
|
259
151
|
async getThreadById({ threadId }) {
|
|
260
152
|
try {
|
|
261
|
-
const
|
|
153
|
+
const sql5 = `SELECT
|
|
262
154
|
id,
|
|
263
155
|
[resourceId],
|
|
264
156
|
title,
|
|
@@ -269,7 +161,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
269
161
|
WHERE id = @threadId`;
|
|
270
162
|
const request = this.pool.request();
|
|
271
163
|
request.input("threadId", threadId);
|
|
272
|
-
const resultSet = await request.query(
|
|
164
|
+
const resultSet = await request.query(sql5);
|
|
273
165
|
const thread = resultSet.recordset[0] || null;
|
|
274
166
|
if (!thread) {
|
|
275
167
|
return null;
|
|
@@ -283,7 +175,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
283
175
|
} catch (error) {
|
|
284
176
|
throw new MastraError(
|
|
285
177
|
{
|
|
286
|
-
id: "
|
|
178
|
+
id: createStorageErrorId("MSSQL", "GET_THREAD_BY_ID", "FAILED"),
|
|
287
179
|
domain: ErrorDomain.STORAGE,
|
|
288
180
|
category: ErrorCategory.THIRD_PARTY,
|
|
289
181
|
details: {
|
|
@@ -294,11 +186,24 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
294
186
|
);
|
|
295
187
|
}
|
|
296
188
|
}
|
|
297
|
-
async
|
|
298
|
-
const { resourceId, page = 0, perPage: perPageInput, orderBy
|
|
189
|
+
async listThreadsByResourceId(args) {
|
|
190
|
+
const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
|
|
191
|
+
if (page < 0) {
|
|
192
|
+
throw new MastraError({
|
|
193
|
+
id: createStorageErrorId("MSSQL", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
|
|
194
|
+
domain: ErrorDomain.STORAGE,
|
|
195
|
+
category: ErrorCategory.USER,
|
|
196
|
+
text: "Page number must be non-negative",
|
|
197
|
+
details: {
|
|
198
|
+
resourceId,
|
|
199
|
+
page
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
204
|
+
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
205
|
+
const { field, direction } = this.parseOrderBy(orderBy);
|
|
299
206
|
try {
|
|
300
|
-
const perPage = perPageInput !== void 0 ? perPageInput : 100;
|
|
301
|
-
const currentOffset = page * perPage;
|
|
302
207
|
const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
|
|
303
208
|
const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
|
|
304
209
|
const countRequest = this.pool.request();
|
|
@@ -310,17 +215,22 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
310
215
|
threads: [],
|
|
311
216
|
total: 0,
|
|
312
217
|
page,
|
|
313
|
-
perPage,
|
|
218
|
+
perPage: perPageForResponse,
|
|
314
219
|
hasMore: false
|
|
315
220
|
};
|
|
316
221
|
}
|
|
317
|
-
const orderByField =
|
|
318
|
-
const dir = (
|
|
222
|
+
const orderByField = field === "createdAt" ? "[createdAt]" : "[updatedAt]";
|
|
223
|
+
const dir = (direction || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
|
|
224
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
319
225
|
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
320
226
|
const dataRequest = this.pool.request();
|
|
321
227
|
dataRequest.input("resourceId", resourceId);
|
|
322
|
-
dataRequest.input("
|
|
323
|
-
|
|
228
|
+
dataRequest.input("offset", offset);
|
|
229
|
+
if (limitValue > 2147483647) {
|
|
230
|
+
dataRequest.input("perPage", sql2.BigInt, limitValue);
|
|
231
|
+
} else {
|
|
232
|
+
dataRequest.input("perPage", limitValue);
|
|
233
|
+
}
|
|
324
234
|
const rowsResult = await dataRequest.query(dataQuery);
|
|
325
235
|
const rows = rowsResult.recordset || [];
|
|
326
236
|
const threads = rows.map((thread) => ({
|
|
@@ -333,13 +243,13 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
333
243
|
threads,
|
|
334
244
|
total,
|
|
335
245
|
page,
|
|
336
|
-
perPage,
|
|
337
|
-
hasMore:
|
|
246
|
+
perPage: perPageForResponse,
|
|
247
|
+
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
338
248
|
};
|
|
339
249
|
} catch (error) {
|
|
340
250
|
const mastraError = new MastraError(
|
|
341
251
|
{
|
|
342
|
-
id: "
|
|
252
|
+
id: createStorageErrorId("MSSQL", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
|
|
343
253
|
domain: ErrorDomain.STORAGE,
|
|
344
254
|
category: ErrorCategory.THIRD_PARTY,
|
|
345
255
|
details: {
|
|
@@ -351,7 +261,13 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
351
261
|
);
|
|
352
262
|
this.logger?.error?.(mastraError.toString());
|
|
353
263
|
this.logger?.trackException?.(mastraError);
|
|
354
|
-
return {
|
|
264
|
+
return {
|
|
265
|
+
threads: [],
|
|
266
|
+
total: 0,
|
|
267
|
+
page,
|
|
268
|
+
perPage: perPageForResponse,
|
|
269
|
+
hasMore: false
|
|
270
|
+
};
|
|
355
271
|
}
|
|
356
272
|
}
|
|
357
273
|
async saveThread({ thread }) {
|
|
@@ -375,18 +291,18 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
375
291
|
req.input("title", thread.title);
|
|
376
292
|
const metadata = thread.metadata ? JSON.stringify(thread.metadata) : null;
|
|
377
293
|
if (metadata === null) {
|
|
378
|
-
req.input("metadata",
|
|
294
|
+
req.input("metadata", sql2.NVarChar, null);
|
|
379
295
|
} else {
|
|
380
296
|
req.input("metadata", metadata);
|
|
381
297
|
}
|
|
382
|
-
req.input("createdAt",
|
|
383
|
-
req.input("updatedAt",
|
|
298
|
+
req.input("createdAt", sql2.DateTime2, thread.createdAt);
|
|
299
|
+
req.input("updatedAt", sql2.DateTime2, thread.updatedAt);
|
|
384
300
|
await req.query(mergeSql);
|
|
385
301
|
return thread;
|
|
386
302
|
} catch (error) {
|
|
387
303
|
throw new MastraError(
|
|
388
304
|
{
|
|
389
|
-
id: "
|
|
305
|
+
id: createStorageErrorId("MSSQL", "SAVE_THREAD", "FAILED"),
|
|
390
306
|
domain: ErrorDomain.STORAGE,
|
|
391
307
|
category: ErrorCategory.THIRD_PARTY,
|
|
392
308
|
details: {
|
|
@@ -397,31 +313,6 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
397
313
|
);
|
|
398
314
|
}
|
|
399
315
|
}
|
|
400
|
-
/**
|
|
401
|
-
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
402
|
-
*/
|
|
403
|
-
async getThreadsByResourceId(args) {
|
|
404
|
-
const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
|
|
405
|
-
try {
|
|
406
|
-
const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
|
|
407
|
-
const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
|
|
408
|
-
const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
|
|
409
|
-
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir}`;
|
|
410
|
-
const request = this.pool.request();
|
|
411
|
-
request.input("resourceId", resourceId);
|
|
412
|
-
const resultSet = await request.query(dataQuery);
|
|
413
|
-
const rows = resultSet.recordset || [];
|
|
414
|
-
return rows.map((thread) => ({
|
|
415
|
-
...thread,
|
|
416
|
-
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
417
|
-
createdAt: thread.createdAt,
|
|
418
|
-
updatedAt: thread.updatedAt
|
|
419
|
-
}));
|
|
420
|
-
} catch (error) {
|
|
421
|
-
this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
|
|
422
|
-
return [];
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
316
|
/**
|
|
426
317
|
* Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
|
|
427
318
|
*/
|
|
@@ -433,7 +324,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
433
324
|
const existingThread = await this.getThreadById({ threadId: id });
|
|
434
325
|
if (!existingThread) {
|
|
435
326
|
throw new MastraError({
|
|
436
|
-
id: "
|
|
327
|
+
id: createStorageErrorId("MSSQL", "UPDATE_THREAD", "NOT_FOUND"),
|
|
437
328
|
domain: ErrorDomain.STORAGE,
|
|
438
329
|
category: ErrorCategory.USER,
|
|
439
330
|
text: `Thread ${id} not found`,
|
|
@@ -449,7 +340,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
449
340
|
};
|
|
450
341
|
try {
|
|
451
342
|
const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
452
|
-
const
|
|
343
|
+
const sql5 = `UPDATE ${table}
|
|
453
344
|
SET title = @title,
|
|
454
345
|
metadata = @metadata,
|
|
455
346
|
[updatedAt] = @updatedAt
|
|
@@ -460,7 +351,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
460
351
|
req.input("title", title);
|
|
461
352
|
req.input("metadata", JSON.stringify(mergedMetadata));
|
|
462
353
|
req.input("updatedAt", /* @__PURE__ */ new Date());
|
|
463
|
-
const result = await req.query(
|
|
354
|
+
const result = await req.query(sql5);
|
|
464
355
|
let thread = result.recordset && result.recordset[0];
|
|
465
356
|
if (thread && "seq_id" in thread) {
|
|
466
357
|
const { seq_id, ...rest } = thread;
|
|
@@ -468,7 +359,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
468
359
|
}
|
|
469
360
|
if (!thread) {
|
|
470
361
|
throw new MastraError({
|
|
471
|
-
id: "
|
|
362
|
+
id: createStorageErrorId("MSSQL", "UPDATE_THREAD", "NOT_FOUND"),
|
|
472
363
|
domain: ErrorDomain.STORAGE,
|
|
473
364
|
category: ErrorCategory.USER,
|
|
474
365
|
text: `Thread ${id} not found after update`,
|
|
@@ -487,7 +378,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
487
378
|
} catch (error) {
|
|
488
379
|
throw new MastraError(
|
|
489
380
|
{
|
|
490
|
-
id: "
|
|
381
|
+
id: createStorageErrorId("MSSQL", "UPDATE_THREAD", "FAILED"),
|
|
491
382
|
domain: ErrorDomain.STORAGE,
|
|
492
383
|
category: ErrorCategory.THIRD_PARTY,
|
|
493
384
|
details: {
|
|
@@ -517,7 +408,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
517
408
|
});
|
|
518
409
|
throw new MastraError(
|
|
519
410
|
{
|
|
520
|
-
id: "
|
|
411
|
+
id: createStorageErrorId("MSSQL", "DELETE_THREAD", "FAILED"),
|
|
521
412
|
domain: ErrorDomain.STORAGE,
|
|
522
413
|
category: ErrorCategory.THIRD_PARTY,
|
|
523
414
|
details: {
|
|
@@ -528,25 +419,18 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
528
419
|
);
|
|
529
420
|
}
|
|
530
421
|
}
|
|
531
|
-
async _getIncludedMessages({
|
|
532
|
-
|
|
533
|
-
selectBy,
|
|
534
|
-
orderByStatement
|
|
535
|
-
}) {
|
|
536
|
-
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
537
|
-
const include = selectBy?.include;
|
|
538
|
-
if (!include) return null;
|
|
422
|
+
async _getIncludedMessages({ include }) {
|
|
423
|
+
if (!include || include.length === 0) return null;
|
|
539
424
|
const unionQueries = [];
|
|
540
425
|
const paramValues = [];
|
|
541
426
|
let paramIdx = 1;
|
|
542
427
|
const paramNames = [];
|
|
428
|
+
const tableName = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
543
429
|
for (const inc of include) {
|
|
544
430
|
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
545
|
-
const
|
|
546
|
-
const
|
|
547
|
-
const
|
|
548
|
-
const pPrev = `@p${paramIdx + 2}`;
|
|
549
|
-
const pNext = `@p${paramIdx + 3}`;
|
|
431
|
+
const pId = `@p${paramIdx}`;
|
|
432
|
+
const pPrev = `@p${paramIdx + 1}`;
|
|
433
|
+
const pNext = `@p${paramIdx + 2}`;
|
|
550
434
|
unionQueries.push(
|
|
551
435
|
`
|
|
552
436
|
SELECT
|
|
@@ -559,30 +443,32 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
559
443
|
m.[resourceId],
|
|
560
444
|
m.seq_id
|
|
561
445
|
FROM (
|
|
562
|
-
SELECT *, ROW_NUMBER() OVER (
|
|
563
|
-
FROM ${
|
|
564
|
-
WHERE [thread_id] = ${
|
|
446
|
+
SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
|
|
447
|
+
FROM ${tableName}
|
|
448
|
+
WHERE [thread_id] = (SELECT thread_id FROM ${tableName} WHERE id = ${pId})
|
|
565
449
|
) AS m
|
|
566
450
|
WHERE m.id = ${pId}
|
|
567
451
|
OR EXISTS (
|
|
568
452
|
SELECT 1
|
|
569
453
|
FROM (
|
|
570
|
-
SELECT *, ROW_NUMBER() OVER (
|
|
571
|
-
FROM ${
|
|
572
|
-
WHERE [thread_id] = ${
|
|
454
|
+
SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
|
|
455
|
+
FROM ${tableName}
|
|
456
|
+
WHERE [thread_id] = (SELECT thread_id FROM ${tableName} WHERE id = ${pId})
|
|
573
457
|
) AS target
|
|
574
458
|
WHERE target.id = ${pId}
|
|
575
459
|
AND (
|
|
576
|
-
|
|
460
|
+
-- Get previous messages (messages that come BEFORE the target)
|
|
461
|
+
(m.row_num < target.row_num AND m.row_num >= target.row_num - ${pPrev})
|
|
577
462
|
OR
|
|
578
|
-
|
|
463
|
+
-- Get next messages (messages that come AFTER the target)
|
|
464
|
+
(m.row_num > target.row_num AND m.row_num <= target.row_num + ${pNext})
|
|
579
465
|
)
|
|
580
466
|
)
|
|
581
467
|
`
|
|
582
468
|
);
|
|
583
|
-
paramValues.push(
|
|
584
|
-
paramNames.push(`p${paramIdx}`, `p${paramIdx + 1}`, `p${paramIdx + 2}
|
|
585
|
-
paramIdx +=
|
|
469
|
+
paramValues.push(id, withPreviousMessages, withNextMessages);
|
|
470
|
+
paramNames.push(`p${paramIdx}`, `p${paramIdx + 1}`, `p${paramIdx + 2}`);
|
|
471
|
+
paramIdx += 3;
|
|
586
472
|
}
|
|
587
473
|
const finalQuery = `
|
|
588
474
|
SELECT * FROM (
|
|
@@ -604,34 +490,16 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
604
490
|
});
|
|
605
491
|
return dedupedRows;
|
|
606
492
|
}
|
|
607
|
-
async
|
|
608
|
-
|
|
493
|
+
async listMessagesById({ messageIds }) {
|
|
494
|
+
if (messageIds.length === 0) return { messages: [] };
|
|
609
495
|
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
|
|
610
496
|
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
611
|
-
const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
612
497
|
try {
|
|
613
|
-
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
614
498
|
let rows = [];
|
|
615
|
-
|
|
616
|
-
if (include?.length) {
|
|
617
|
-
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
618
|
-
if (includeMessages) {
|
|
619
|
-
rows.push(...includeMessages);
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
const excludeIds = rows.map((m) => m.id).filter(Boolean);
|
|
623
|
-
let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
|
|
499
|
+
let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
|
|
624
500
|
const request = this.pool.request();
|
|
625
|
-
request.input(
|
|
626
|
-
|
|
627
|
-
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
628
|
-
query += ` AND id NOT IN (${excludeParams.join(", ")})`;
|
|
629
|
-
excludeIds.forEach((id, idx) => {
|
|
630
|
-
request.input(`id${idx}`, id);
|
|
631
|
-
});
|
|
632
|
-
}
|
|
633
|
-
query += ` ${orderByStatement} OFFSET 0 ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
634
|
-
request.input("limit", limit);
|
|
501
|
+
messageIds.forEach((id, i) => request.input(`id${i}`, id));
|
|
502
|
+
query += ` ${orderByStatement}`;
|
|
635
503
|
const result = await request.query(query);
|
|
636
504
|
const remainingRows = result.recordset || [];
|
|
637
505
|
rows.push(...remainingRows);
|
|
@@ -639,158 +507,177 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
639
507
|
const timeDiff = a.seq_id - b.seq_id;
|
|
640
508
|
return timeDiff;
|
|
641
509
|
});
|
|
642
|
-
|
|
643
|
-
|
|
510
|
+
const messagesWithParsedContent = rows.map((row) => {
|
|
511
|
+
if (typeof row.content === "string") {
|
|
512
|
+
try {
|
|
513
|
+
return { ...row, content: JSON.parse(row.content) };
|
|
514
|
+
} catch {
|
|
515
|
+
return row;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return row;
|
|
519
|
+
});
|
|
520
|
+
const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
|
|
521
|
+
const list = new MessageList().add(cleanMessages, "memory");
|
|
522
|
+
return { messages: list.get.all.db() };
|
|
644
523
|
} catch (error) {
|
|
645
524
|
const mastraError = new MastraError(
|
|
646
525
|
{
|
|
647
|
-
id: "
|
|
526
|
+
id: createStorageErrorId("MSSQL", "LIST_MESSAGES_BY_ID", "FAILED"),
|
|
648
527
|
domain: ErrorDomain.STORAGE,
|
|
649
528
|
category: ErrorCategory.THIRD_PARTY,
|
|
650
529
|
details: {
|
|
651
|
-
|
|
652
|
-
resourceId: resourceId ?? ""
|
|
530
|
+
messageIds: JSON.stringify(messageIds)
|
|
653
531
|
}
|
|
654
532
|
},
|
|
655
533
|
error
|
|
656
534
|
);
|
|
657
535
|
this.logger?.error?.(mastraError.toString());
|
|
658
536
|
this.logger?.trackException?.(mastraError);
|
|
659
|
-
return [];
|
|
537
|
+
return { messages: [] };
|
|
660
538
|
}
|
|
661
539
|
}
|
|
662
|
-
async
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
|
|
668
|
-
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
669
|
-
try {
|
|
670
|
-
let rows = [];
|
|
671
|
-
let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
|
|
672
|
-
const request = this.pool.request();
|
|
673
|
-
messageIds.forEach((id, i) => request.input(`id${i}`, id));
|
|
674
|
-
query += ` ${orderByStatement}`;
|
|
675
|
-
const result = await request.query(query);
|
|
676
|
-
const remainingRows = result.recordset || [];
|
|
677
|
-
rows.push(...remainingRows);
|
|
678
|
-
rows.sort((a, b) => {
|
|
679
|
-
const timeDiff = a.seq_id - b.seq_id;
|
|
680
|
-
return timeDiff;
|
|
681
|
-
});
|
|
682
|
-
rows = rows.map(({ seq_id, ...rest }) => rest);
|
|
683
|
-
if (format === `v1`) return this._parseAndFormatMessages(rows, format);
|
|
684
|
-
return this._parseAndFormatMessages(rows, `v2`);
|
|
685
|
-
} catch (error) {
|
|
686
|
-
const mastraError = new MastraError(
|
|
540
|
+
async listMessages(args) {
|
|
541
|
+
const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
|
|
542
|
+
const threadIds = Array.isArray(threadId) ? threadId : [threadId];
|
|
543
|
+
if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
|
|
544
|
+
throw new MastraError(
|
|
687
545
|
{
|
|
688
|
-
id: "
|
|
546
|
+
id: createStorageErrorId("MSSQL", "LIST_MESSAGES", "INVALID_THREAD_ID"),
|
|
689
547
|
domain: ErrorDomain.STORAGE,
|
|
690
548
|
category: ErrorCategory.THIRD_PARTY,
|
|
691
|
-
details: {
|
|
692
|
-
messageIds: JSON.stringify(messageIds)
|
|
693
|
-
}
|
|
549
|
+
details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
|
|
694
550
|
},
|
|
695
|
-
|
|
551
|
+
new Error("threadId must be a non-empty string or array of non-empty strings")
|
|
696
552
|
);
|
|
697
|
-
this.logger?.error?.(mastraError.toString());
|
|
698
|
-
this.logger?.trackException?.(mastraError);
|
|
699
|
-
return [];
|
|
700
553
|
}
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
554
|
+
if (page < 0) {
|
|
555
|
+
throw new MastraError({
|
|
556
|
+
id: createStorageErrorId("MSSQL", "LIST_MESSAGES", "INVALID_PAGE"),
|
|
557
|
+
domain: ErrorDomain.STORAGE,
|
|
558
|
+
category: ErrorCategory.USER,
|
|
559
|
+
text: "Page number must be non-negative",
|
|
560
|
+
details: {
|
|
561
|
+
threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
|
|
562
|
+
page
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
const perPage = normalizePerPage(perPageInput, 40);
|
|
567
|
+
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
705
568
|
try {
|
|
706
|
-
|
|
707
|
-
const
|
|
708
|
-
const
|
|
709
|
-
const
|
|
710
|
-
const
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
const
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
request
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
request.input("fromDate", fromDate.toISOString());
|
|
724
|
-
}
|
|
725
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
726
|
-
conditions.push("[createdAt] <= @toDate");
|
|
727
|
-
request.input("toDate", toDate.toISOString());
|
|
728
|
-
}
|
|
729
|
-
const whereClause = `WHERE ${conditions.join(" AND ")}`;
|
|
730
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
|
|
731
|
-
const countResult = await request.query(countQuery);
|
|
569
|
+
const { field, direction } = this.parseOrderBy(orderBy, "ASC");
|
|
570
|
+
const orderByStatement = `ORDER BY [${field}] ${direction}, [seq_id] ${direction}`;
|
|
571
|
+
const tableName = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
572
|
+
const baseQuery = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId FROM ${tableName}`;
|
|
573
|
+
const filters = {
|
|
574
|
+
thread_id: threadIds.length === 1 ? threadIds[0] : { $in: threadIds },
|
|
575
|
+
...resourceId ? { resourceId } : {},
|
|
576
|
+
...buildDateRangeFilter(filter?.dateRange, "createdAt")
|
|
577
|
+
};
|
|
578
|
+
const { sql: actualWhereClause = "", params: whereParams } = prepareWhereClause(
|
|
579
|
+
filters);
|
|
580
|
+
const bindWhereParams = (req) => {
|
|
581
|
+
Object.entries(whereParams).forEach(([paramName, paramValue]) => req.input(paramName, paramValue));
|
|
582
|
+
};
|
|
583
|
+
const countRequest = this.pool.request();
|
|
584
|
+
bindWhereParams(countRequest);
|
|
585
|
+
const countResult = await countRequest.query(`SELECT COUNT(*) as total FROM ${tableName}${actualWhereClause}`);
|
|
732
586
|
const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
|
|
733
|
-
|
|
734
|
-
const
|
|
587
|
+
const fetchBaseMessages = async () => {
|
|
588
|
+
const request = this.pool.request();
|
|
589
|
+
bindWhereParams(request);
|
|
590
|
+
if (perPageInput === false) {
|
|
591
|
+
const result2 = await request.query(`${baseQuery}${actualWhereClause} ${orderByStatement}`);
|
|
592
|
+
return result2.recordset || [];
|
|
593
|
+
}
|
|
594
|
+
request.input("offset", offset);
|
|
595
|
+
request.input("limit", perPage > 2147483647 ? sql2.BigInt : sql2.Int, perPage);
|
|
596
|
+
const result = await request.query(
|
|
597
|
+
`${baseQuery}${actualWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`
|
|
598
|
+
);
|
|
599
|
+
return result.recordset || [];
|
|
600
|
+
};
|
|
601
|
+
const baseRows = perPage === 0 ? [] : await fetchBaseMessages();
|
|
602
|
+
const messages = [...baseRows];
|
|
603
|
+
const seqById = /* @__PURE__ */ new Map();
|
|
604
|
+
messages.forEach((msg) => {
|
|
605
|
+
if (typeof msg.seq_id === "number") seqById.set(msg.id, msg.seq_id);
|
|
606
|
+
});
|
|
607
|
+
if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
|
|
735
608
|
return {
|
|
736
|
-
messages:
|
|
737
|
-
total:
|
|
609
|
+
messages: [],
|
|
610
|
+
total: 0,
|
|
738
611
|
page,
|
|
739
|
-
perPage,
|
|
612
|
+
perPage: perPageForResponse,
|
|
740
613
|
hasMore: false
|
|
741
614
|
};
|
|
742
615
|
}
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
const
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
const
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
616
|
+
if (include?.length) {
|
|
617
|
+
const messageIds = new Set(messages.map((m) => m.id));
|
|
618
|
+
const includeMessages = await this._getIncludedMessages({ include });
|
|
619
|
+
includeMessages?.forEach((msg) => {
|
|
620
|
+
if (!messageIds.has(msg.id)) {
|
|
621
|
+
messages.push(msg);
|
|
622
|
+
messageIds.add(msg.id);
|
|
623
|
+
if (typeof msg.seq_id === "number") seqById.set(msg.id, msg.seq_id);
|
|
624
|
+
}
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
const parsed = this._parseAndFormatMessages(messages, "v2");
|
|
628
|
+
const mult = direction === "ASC" ? 1 : -1;
|
|
629
|
+
const finalMessages = parsed.sort((a, b) => {
|
|
630
|
+
const aVal = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
|
|
631
|
+
const bVal = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
|
|
632
|
+
if (aVal == null || bVal == null) {
|
|
633
|
+
return aVal == null && bVal == null ? a.id.localeCompare(b.id) : aVal == null ? 1 : -1;
|
|
634
|
+
}
|
|
635
|
+
const diff = (typeof aVal === "number" && typeof bVal === "number" ? aVal - bVal : String(aVal).localeCompare(String(bVal))) * mult;
|
|
636
|
+
if (diff !== 0) return diff;
|
|
637
|
+
const seqA = seqById.get(a.id);
|
|
638
|
+
const seqB = seqById.get(b.id);
|
|
639
|
+
return seqA != null && seqB != null ? (seqA - seqB) * mult : a.id.localeCompare(b.id);
|
|
640
|
+
});
|
|
641
|
+
const threadIdSet = new Set(threadIds);
|
|
642
|
+
const returnedThreadMessageCount = finalMessages.filter((m) => m.threadId && threadIdSet.has(m.threadId)).length;
|
|
643
|
+
const hasMore = perPageInput !== false && returnedThreadMessageCount < total && offset + perPage < total;
|
|
759
644
|
return {
|
|
760
|
-
messages:
|
|
645
|
+
messages: finalMessages,
|
|
761
646
|
total,
|
|
762
647
|
page,
|
|
763
|
-
perPage,
|
|
764
|
-
hasMore
|
|
648
|
+
perPage: perPageForResponse,
|
|
649
|
+
hasMore
|
|
765
650
|
};
|
|
766
651
|
} catch (error) {
|
|
767
652
|
const mastraError = new MastraError(
|
|
768
653
|
{
|
|
769
|
-
id: "
|
|
654
|
+
id: createStorageErrorId("MSSQL", "LIST_MESSAGES", "FAILED"),
|
|
770
655
|
domain: ErrorDomain.STORAGE,
|
|
771
656
|
category: ErrorCategory.THIRD_PARTY,
|
|
772
657
|
details: {
|
|
773
|
-
threadId,
|
|
774
|
-
resourceId: resourceId ?? ""
|
|
775
|
-
page
|
|
658
|
+
threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
|
|
659
|
+
resourceId: resourceId ?? ""
|
|
776
660
|
}
|
|
777
661
|
},
|
|
778
662
|
error
|
|
779
663
|
);
|
|
780
664
|
this.logger?.error?.(mastraError.toString());
|
|
781
665
|
this.logger?.trackException?.(mastraError);
|
|
782
|
-
return {
|
|
666
|
+
return {
|
|
667
|
+
messages: [],
|
|
668
|
+
total: 0,
|
|
669
|
+
page,
|
|
670
|
+
perPage: perPageForResponse,
|
|
671
|
+
hasMore: false
|
|
672
|
+
};
|
|
783
673
|
}
|
|
784
674
|
}
|
|
785
|
-
async saveMessages({
|
|
786
|
-
messages
|
|
787
|
-
format
|
|
788
|
-
}) {
|
|
789
|
-
if (messages.length === 0) return messages;
|
|
675
|
+
async saveMessages({ messages }) {
|
|
676
|
+
if (messages.length === 0) return { messages: [] };
|
|
790
677
|
const threadId = messages[0]?.threadId;
|
|
791
678
|
if (!threadId) {
|
|
792
679
|
throw new MastraError({
|
|
793
|
-
id: "
|
|
680
|
+
id: createStorageErrorId("MSSQL", "SAVE_MESSAGES", "INVALID_THREAD_ID"),
|
|
794
681
|
domain: ErrorDomain.STORAGE,
|
|
795
682
|
category: ErrorCategory.THIRD_PARTY,
|
|
796
683
|
text: `Thread ID is required`
|
|
@@ -799,7 +686,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
799
686
|
const thread = await this.getThreadById({ threadId });
|
|
800
687
|
if (!thread) {
|
|
801
688
|
throw new MastraError({
|
|
802
|
-
id: "
|
|
689
|
+
id: createStorageErrorId("MSSQL", "SAVE_MESSAGES", "THREAD_NOT_FOUND"),
|
|
803
690
|
domain: ErrorDomain.STORAGE,
|
|
804
691
|
category: ErrorCategory.THIRD_PARTY,
|
|
805
692
|
text: `Thread ${threadId} not found`,
|
|
@@ -830,7 +717,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
830
717
|
"content",
|
|
831
718
|
typeof message.content === "string" ? message.content : JSON.stringify(message.content)
|
|
832
719
|
);
|
|
833
|
-
request.input("createdAt",
|
|
720
|
+
request.input("createdAt", sql2.DateTime2, message.createdAt);
|
|
834
721
|
request.input("role", message.role);
|
|
835
722
|
request.input("type", message.type || "v2");
|
|
836
723
|
request.input("resourceId", message.resourceId);
|
|
@@ -849,7 +736,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
849
736
|
await request.query(mergeSql);
|
|
850
737
|
}
|
|
851
738
|
const threadReq = transaction.request();
|
|
852
|
-
threadReq.input("updatedAt",
|
|
739
|
+
threadReq.input("updatedAt", sql2.DateTime2, /* @__PURE__ */ new Date());
|
|
853
740
|
threadReq.input("id", threadId);
|
|
854
741
|
await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
|
|
855
742
|
await transaction.commit();
|
|
@@ -868,12 +755,11 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
868
755
|
return message;
|
|
869
756
|
});
|
|
870
757
|
const list = new MessageList().add(messagesWithParsedContent, "memory");
|
|
871
|
-
|
|
872
|
-
return list.get.all.v1();
|
|
758
|
+
return { messages: list.get.all.db() };
|
|
873
759
|
} catch (error) {
|
|
874
760
|
throw new MastraError(
|
|
875
761
|
{
|
|
876
|
-
id: "
|
|
762
|
+
id: createStorageErrorId("MSSQL", "SAVE_MESSAGES", "FAILED"),
|
|
877
763
|
domain: ErrorDomain.STORAGE,
|
|
878
764
|
category: ErrorCategory.THIRD_PARTY,
|
|
879
765
|
details: { threadId }
|
|
@@ -964,7 +850,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
964
850
|
await transaction.rollback();
|
|
965
851
|
throw new MastraError(
|
|
966
852
|
{
|
|
967
|
-
id: "
|
|
853
|
+
id: createStorageErrorId("MSSQL", "UPDATE_MESSAGES", "FAILED"),
|
|
968
854
|
domain: ErrorDomain.STORAGE,
|
|
969
855
|
category: ErrorCategory.THIRD_PARTY
|
|
970
856
|
},
|
|
@@ -1026,7 +912,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
1026
912
|
} catch (error) {
|
|
1027
913
|
throw new MastraError(
|
|
1028
914
|
{
|
|
1029
|
-
id: "
|
|
915
|
+
id: createStorageErrorId("MSSQL", "DELETE_MESSAGES", "FAILED"),
|
|
1030
916
|
domain: ErrorDomain.STORAGE,
|
|
1031
917
|
category: ErrorCategory.THIRD_PARTY,
|
|
1032
918
|
details: { messageIds: messageIds.join(", ") }
|
|
@@ -1054,7 +940,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
1054
940
|
} catch (error) {
|
|
1055
941
|
const mastraError = new MastraError(
|
|
1056
942
|
{
|
|
1057
|
-
id: "
|
|
943
|
+
id: createStorageErrorId("MSSQL", "GET_RESOURCE_BY_ID", "FAILED"),
|
|
1058
944
|
domain: ErrorDomain.STORAGE,
|
|
1059
945
|
category: ErrorCategory.THIRD_PARTY,
|
|
1060
946
|
details: { resourceId }
|
|
@@ -1121,7 +1007,7 @@ var MemoryMSSQL = class extends MemoryStorage {
|
|
|
1121
1007
|
} catch (error) {
|
|
1122
1008
|
const mastraError = new MastraError(
|
|
1123
1009
|
{
|
|
1124
|
-
id: "
|
|
1010
|
+
id: createStorageErrorId("MSSQL", "UPDATE_RESOURCE", "FAILED"),
|
|
1125
1011
|
domain: ErrorDomain.STORAGE,
|
|
1126
1012
|
category: ErrorCategory.THIRD_PARTY,
|
|
1127
1013
|
details: { resourceId }
|
|
@@ -1148,13 +1034,13 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1148
1034
|
this.operations = operations;
|
|
1149
1035
|
this.schema = schema;
|
|
1150
1036
|
}
|
|
1151
|
-
get
|
|
1037
|
+
get tracingStrategy() {
|
|
1152
1038
|
return {
|
|
1153
1039
|
preferred: "batch-with-updates",
|
|
1154
1040
|
supported: ["batch-with-updates", "insert-only"]
|
|
1155
1041
|
};
|
|
1156
1042
|
}
|
|
1157
|
-
async
|
|
1043
|
+
async createSpan(span) {
|
|
1158
1044
|
try {
|
|
1159
1045
|
const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
|
|
1160
1046
|
const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
|
|
@@ -1164,11 +1050,11 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1164
1050
|
endedAt
|
|
1165
1051
|
// Note: createdAt/updatedAt will be set by default values
|
|
1166
1052
|
};
|
|
1167
|
-
return this.operations.insert({ tableName:
|
|
1053
|
+
return this.operations.insert({ tableName: TABLE_SPANS, record });
|
|
1168
1054
|
} catch (error) {
|
|
1169
1055
|
throw new MastraError(
|
|
1170
1056
|
{
|
|
1171
|
-
id: "
|
|
1057
|
+
id: createStorageErrorId("MSSQL", "CREATE_SPAN", "FAILED"),
|
|
1172
1058
|
domain: ErrorDomain.STORAGE,
|
|
1173
1059
|
category: ErrorCategory.USER,
|
|
1174
1060
|
details: {
|
|
@@ -1182,10 +1068,10 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1182
1068
|
);
|
|
1183
1069
|
}
|
|
1184
1070
|
}
|
|
1185
|
-
async
|
|
1071
|
+
async getTrace(traceId) {
|
|
1186
1072
|
try {
|
|
1187
1073
|
const tableName = getTableName({
|
|
1188
|
-
indexName:
|
|
1074
|
+
indexName: TABLE_SPANS,
|
|
1189
1075
|
schemaName: getSchemaName(this.schema)
|
|
1190
1076
|
});
|
|
1191
1077
|
const request = this.pool.request();
|
|
@@ -1206,7 +1092,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1206
1092
|
traceId,
|
|
1207
1093
|
spans: result.recordset.map(
|
|
1208
1094
|
(span) => transformFromSqlRow({
|
|
1209
|
-
tableName:
|
|
1095
|
+
tableName: TABLE_SPANS,
|
|
1210
1096
|
sqlRow: span
|
|
1211
1097
|
})
|
|
1212
1098
|
)
|
|
@@ -1214,7 +1100,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1214
1100
|
} catch (error) {
|
|
1215
1101
|
throw new MastraError(
|
|
1216
1102
|
{
|
|
1217
|
-
id: "
|
|
1103
|
+
id: createStorageErrorId("MSSQL", "GET_TRACE", "FAILED"),
|
|
1218
1104
|
domain: ErrorDomain.STORAGE,
|
|
1219
1105
|
category: ErrorCategory.USER,
|
|
1220
1106
|
details: {
|
|
@@ -1225,7 +1111,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1225
1111
|
);
|
|
1226
1112
|
}
|
|
1227
1113
|
}
|
|
1228
|
-
async
|
|
1114
|
+
async updateSpan({
|
|
1229
1115
|
spanId,
|
|
1230
1116
|
traceId,
|
|
1231
1117
|
updates
|
|
@@ -1239,14 +1125,14 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1239
1125
|
data.startedAt = data.startedAt.toISOString();
|
|
1240
1126
|
}
|
|
1241
1127
|
await this.operations.update({
|
|
1242
|
-
tableName:
|
|
1128
|
+
tableName: TABLE_SPANS,
|
|
1243
1129
|
keys: { spanId, traceId },
|
|
1244
1130
|
data
|
|
1245
1131
|
});
|
|
1246
1132
|
} catch (error) {
|
|
1247
1133
|
throw new MastraError(
|
|
1248
1134
|
{
|
|
1249
|
-
id: "
|
|
1135
|
+
id: createStorageErrorId("MSSQL", "UPDATE_SPAN", "FAILED"),
|
|
1250
1136
|
domain: ErrorDomain.STORAGE,
|
|
1251
1137
|
category: ErrorCategory.USER,
|
|
1252
1138
|
details: {
|
|
@@ -1258,7 +1144,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1258
1144
|
);
|
|
1259
1145
|
}
|
|
1260
1146
|
}
|
|
1261
|
-
async
|
|
1147
|
+
async getTracesPaginated({
|
|
1262
1148
|
filters,
|
|
1263
1149
|
pagination
|
|
1264
1150
|
}) {
|
|
@@ -1283,7 +1169,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1283
1169
|
name = `agent run: '${entityId}'`;
|
|
1284
1170
|
} else {
|
|
1285
1171
|
const error = new MastraError({
|
|
1286
|
-
id: "
|
|
1172
|
+
id: createStorageErrorId("MSSQL", "GET_TRACES_PAGINATED", "INVALID_ENTITY_TYPE"),
|
|
1287
1173
|
domain: ErrorDomain.STORAGE,
|
|
1288
1174
|
category: ErrorCategory.USER,
|
|
1289
1175
|
details: {
|
|
@@ -1302,7 +1188,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1302
1188
|
params[entityParam] = name;
|
|
1303
1189
|
}
|
|
1304
1190
|
const tableName = getTableName({
|
|
1305
|
-
indexName:
|
|
1191
|
+
indexName: TABLE_SPANS,
|
|
1306
1192
|
schemaName: getSchemaName(this.schema)
|
|
1307
1193
|
});
|
|
1308
1194
|
try {
|
|
@@ -1336,7 +1222,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1336
1222
|
);
|
|
1337
1223
|
const spans = dataResult.recordset.map(
|
|
1338
1224
|
(row) => transformFromSqlRow({
|
|
1339
|
-
tableName:
|
|
1225
|
+
tableName: TABLE_SPANS,
|
|
1340
1226
|
sqlRow: row
|
|
1341
1227
|
})
|
|
1342
1228
|
);
|
|
@@ -1352,7 +1238,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1352
1238
|
} catch (error) {
|
|
1353
1239
|
throw new MastraError(
|
|
1354
1240
|
{
|
|
1355
|
-
id: "
|
|
1241
|
+
id: createStorageErrorId("MSSQL", "GET_TRACES_PAGINATED", "FAILED"),
|
|
1356
1242
|
domain: ErrorDomain.STORAGE,
|
|
1357
1243
|
category: ErrorCategory.USER
|
|
1358
1244
|
},
|
|
@@ -1360,13 +1246,13 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1360
1246
|
);
|
|
1361
1247
|
}
|
|
1362
1248
|
}
|
|
1363
|
-
async
|
|
1249
|
+
async batchCreateSpans(args) {
|
|
1364
1250
|
if (!args.records || args.records.length === 0) {
|
|
1365
1251
|
return;
|
|
1366
1252
|
}
|
|
1367
1253
|
try {
|
|
1368
1254
|
await this.operations.batchInsert({
|
|
1369
|
-
tableName:
|
|
1255
|
+
tableName: TABLE_SPANS,
|
|
1370
1256
|
records: args.records.map((span) => ({
|
|
1371
1257
|
...span,
|
|
1372
1258
|
startedAt: span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt,
|
|
@@ -1376,7 +1262,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1376
1262
|
} catch (error) {
|
|
1377
1263
|
throw new MastraError(
|
|
1378
1264
|
{
|
|
1379
|
-
id: "
|
|
1265
|
+
id: createStorageErrorId("MSSQL", "BATCH_CREATE_SPANS", "FAILED"),
|
|
1380
1266
|
domain: ErrorDomain.STORAGE,
|
|
1381
1267
|
category: ErrorCategory.USER,
|
|
1382
1268
|
details: {
|
|
@@ -1387,7 +1273,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1387
1273
|
);
|
|
1388
1274
|
}
|
|
1389
1275
|
}
|
|
1390
|
-
async
|
|
1276
|
+
async batchUpdateSpans(args) {
|
|
1391
1277
|
if (!args.records || args.records.length === 0) {
|
|
1392
1278
|
return;
|
|
1393
1279
|
}
|
|
@@ -1406,13 +1292,13 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1406
1292
|
};
|
|
1407
1293
|
});
|
|
1408
1294
|
await this.operations.batchUpdate({
|
|
1409
|
-
tableName:
|
|
1295
|
+
tableName: TABLE_SPANS,
|
|
1410
1296
|
updates
|
|
1411
1297
|
});
|
|
1412
1298
|
} catch (error) {
|
|
1413
1299
|
throw new MastraError(
|
|
1414
1300
|
{
|
|
1415
|
-
id: "
|
|
1301
|
+
id: createStorageErrorId("MSSQL", "BATCH_UPDATE_SPANS", "FAILED"),
|
|
1416
1302
|
domain: ErrorDomain.STORAGE,
|
|
1417
1303
|
category: ErrorCategory.USER,
|
|
1418
1304
|
details: {
|
|
@@ -1423,20 +1309,20 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
|
1423
1309
|
);
|
|
1424
1310
|
}
|
|
1425
1311
|
}
|
|
1426
|
-
async
|
|
1312
|
+
async batchDeleteTraces(args) {
|
|
1427
1313
|
if (!args.traceIds || args.traceIds.length === 0) {
|
|
1428
1314
|
return;
|
|
1429
1315
|
}
|
|
1430
1316
|
try {
|
|
1431
1317
|
const keys = args.traceIds.map((traceId) => ({ traceId }));
|
|
1432
1318
|
await this.operations.batchDelete({
|
|
1433
|
-
tableName:
|
|
1319
|
+
tableName: TABLE_SPANS,
|
|
1434
1320
|
keys
|
|
1435
1321
|
});
|
|
1436
1322
|
} catch (error) {
|
|
1437
1323
|
throw new MastraError(
|
|
1438
1324
|
{
|
|
1439
|
-
id: "
|
|
1325
|
+
id: createStorageErrorId("MSSQL", "BATCH_DELETE_TRACES", "FAILED"),
|
|
1440
1326
|
domain: ErrorDomain.STORAGE,
|
|
1441
1327
|
category: ErrorCategory.USER,
|
|
1442
1328
|
details: {
|
|
@@ -1476,7 +1362,7 @@ var StoreOperationsMSSQL = class extends StoreOperations {
|
|
|
1476
1362
|
return "BIT";
|
|
1477
1363
|
default:
|
|
1478
1364
|
throw new MastraError({
|
|
1479
|
-
id: "
|
|
1365
|
+
id: createStorageErrorId("MSSQL", "TYPE", "NOT_SUPPORTED"),
|
|
1480
1366
|
domain: ErrorDomain.STORAGE,
|
|
1481
1367
|
category: ErrorCategory.THIRD_PARTY
|
|
1482
1368
|
});
|
|
@@ -1551,7 +1437,7 @@ var StoreOperationsMSSQL = class extends StoreOperations {
|
|
|
1551
1437
|
const value = record[col];
|
|
1552
1438
|
const preparedValue = this.prepareValue(value, col, tableName);
|
|
1553
1439
|
if (preparedValue instanceof Date) {
|
|
1554
|
-
request.input(`param${i}`,
|
|
1440
|
+
request.input(`param${i}`, sql2.DateTime2, preparedValue);
|
|
1555
1441
|
} else if (preparedValue === null || preparedValue === void 0) {
|
|
1556
1442
|
request.input(`param${i}`, this.getMssqlType(tableName, col), null);
|
|
1557
1443
|
} else {
|
|
@@ -1562,7 +1448,7 @@ var StoreOperationsMSSQL = class extends StoreOperations {
|
|
|
1562
1448
|
} catch (error) {
|
|
1563
1449
|
throw new MastraError(
|
|
1564
1450
|
{
|
|
1565
|
-
id: "
|
|
1451
|
+
id: createStorageErrorId("MSSQL", "INSERT", "FAILED"),
|
|
1566
1452
|
domain: ErrorDomain.STORAGE,
|
|
1567
1453
|
category: ErrorCategory.THIRD_PARTY,
|
|
1568
1454
|
details: {
|
|
@@ -1588,7 +1474,7 @@ var StoreOperationsMSSQL = class extends StoreOperations {
|
|
|
1588
1474
|
} catch (error) {
|
|
1589
1475
|
throw new MastraError(
|
|
1590
1476
|
{
|
|
1591
|
-
id: "
|
|
1477
|
+
id: createStorageErrorId("MSSQL", "CLEAR_TABLE", "FAILED"),
|
|
1592
1478
|
domain: ErrorDomain.STORAGE,
|
|
1593
1479
|
category: ErrorCategory.THIRD_PARTY,
|
|
1594
1480
|
details: {
|
|
@@ -1691,7 +1577,7 @@ ${columns}
|
|
|
1691
1577
|
} catch (error) {
|
|
1692
1578
|
throw new MastraError(
|
|
1693
1579
|
{
|
|
1694
|
-
id: "
|
|
1580
|
+
id: createStorageErrorId("MSSQL", "CREATE_TABLE", "FAILED"),
|
|
1695
1581
|
domain: ErrorDomain.STORAGE,
|
|
1696
1582
|
category: ErrorCategory.THIRD_PARTY,
|
|
1697
1583
|
details: {
|
|
@@ -1751,7 +1637,7 @@ ${columns}
|
|
|
1751
1637
|
} catch (error) {
|
|
1752
1638
|
throw new MastraError(
|
|
1753
1639
|
{
|
|
1754
|
-
id: "
|
|
1640
|
+
id: createStorageErrorId("MSSQL", "ALTER_TABLE", "FAILED"),
|
|
1755
1641
|
domain: ErrorDomain.STORAGE,
|
|
1756
1642
|
category: ErrorCategory.THIRD_PARTY,
|
|
1757
1643
|
details: {
|
|
@@ -1766,7 +1652,7 @@ ${columns}
|
|
|
1766
1652
|
try {
|
|
1767
1653
|
const keyEntries = Object.entries(keys).map(([key, value]) => [parseSqlIdentifier(key, "column name"), value]);
|
|
1768
1654
|
const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
|
|
1769
|
-
const
|
|
1655
|
+
const sql5 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
|
|
1770
1656
|
const request = this.pool.request();
|
|
1771
1657
|
keyEntries.forEach(([key, value], i) => {
|
|
1772
1658
|
const preparedValue = this.prepareValue(value, key, tableName);
|
|
@@ -1776,7 +1662,7 @@ ${columns}
|
|
|
1776
1662
|
request.input(`param${i}`, preparedValue);
|
|
1777
1663
|
}
|
|
1778
1664
|
});
|
|
1779
|
-
const resultSet = await request.query(
|
|
1665
|
+
const resultSet = await request.query(sql5);
|
|
1780
1666
|
const result = resultSet.recordset[0] || null;
|
|
1781
1667
|
if (!result) {
|
|
1782
1668
|
return null;
|
|
@@ -1792,7 +1678,7 @@ ${columns}
|
|
|
1792
1678
|
} catch (error) {
|
|
1793
1679
|
throw new MastraError(
|
|
1794
1680
|
{
|
|
1795
|
-
id: "
|
|
1681
|
+
id: createStorageErrorId("MSSQL", "LOAD", "FAILED"),
|
|
1796
1682
|
domain: ErrorDomain.STORAGE,
|
|
1797
1683
|
category: ErrorCategory.THIRD_PARTY,
|
|
1798
1684
|
details: {
|
|
@@ -1815,7 +1701,7 @@ ${columns}
|
|
|
1815
1701
|
await transaction.rollback();
|
|
1816
1702
|
throw new MastraError(
|
|
1817
1703
|
{
|
|
1818
|
-
id: "
|
|
1704
|
+
id: createStorageErrorId("MSSQL", "BATCH_INSERT", "FAILED"),
|
|
1819
1705
|
domain: ErrorDomain.STORAGE,
|
|
1820
1706
|
category: ErrorCategory.THIRD_PARTY,
|
|
1821
1707
|
details: {
|
|
@@ -1834,7 +1720,7 @@ ${columns}
|
|
|
1834
1720
|
} catch (error) {
|
|
1835
1721
|
throw new MastraError(
|
|
1836
1722
|
{
|
|
1837
|
-
id: "
|
|
1723
|
+
id: createStorageErrorId("MSSQL", "DROP_TABLE", "FAILED"),
|
|
1838
1724
|
domain: ErrorDomain.STORAGE,
|
|
1839
1725
|
category: ErrorCategory.THIRD_PARTY,
|
|
1840
1726
|
details: {
|
|
@@ -1889,23 +1775,23 @@ ${columns}
|
|
|
1889
1775
|
const col = TABLE_SCHEMAS[tableName]?.[columnName];
|
|
1890
1776
|
switch (col?.type) {
|
|
1891
1777
|
case "text":
|
|
1892
|
-
return
|
|
1778
|
+
return sql2.NVarChar;
|
|
1893
1779
|
case "timestamp":
|
|
1894
|
-
return
|
|
1780
|
+
return sql2.DateTime2;
|
|
1895
1781
|
case "uuid":
|
|
1896
|
-
return
|
|
1782
|
+
return sql2.UniqueIdentifier;
|
|
1897
1783
|
case "jsonb":
|
|
1898
|
-
return
|
|
1784
|
+
return sql2.NVarChar;
|
|
1899
1785
|
case "integer":
|
|
1900
|
-
return
|
|
1786
|
+
return sql2.Int;
|
|
1901
1787
|
case "bigint":
|
|
1902
|
-
return
|
|
1788
|
+
return sql2.BigInt;
|
|
1903
1789
|
case "float":
|
|
1904
|
-
return
|
|
1790
|
+
return sql2.Float;
|
|
1905
1791
|
case "boolean":
|
|
1906
|
-
return
|
|
1792
|
+
return sql2.Bit;
|
|
1907
1793
|
default:
|
|
1908
|
-
return
|
|
1794
|
+
return sql2.NVarChar;
|
|
1909
1795
|
}
|
|
1910
1796
|
}
|
|
1911
1797
|
/**
|
|
@@ -1920,7 +1806,7 @@ ${columns}
|
|
|
1920
1806
|
try {
|
|
1921
1807
|
if (!data || Object.keys(data).length === 0) {
|
|
1922
1808
|
throw new MastraError({
|
|
1923
|
-
id: "
|
|
1809
|
+
id: createStorageErrorId("MSSQL", "UPDATE", "EMPTY_DATA"),
|
|
1924
1810
|
domain: ErrorDomain.STORAGE,
|
|
1925
1811
|
category: ErrorCategory.USER,
|
|
1926
1812
|
text: "Cannot update with empty data payload"
|
|
@@ -1928,7 +1814,7 @@ ${columns}
|
|
|
1928
1814
|
}
|
|
1929
1815
|
if (!keys || Object.keys(keys).length === 0) {
|
|
1930
1816
|
throw new MastraError({
|
|
1931
|
-
id: "
|
|
1817
|
+
id: createStorageErrorId("MSSQL", "UPDATE", "EMPTY_KEYS"),
|
|
1932
1818
|
domain: ErrorDomain.STORAGE,
|
|
1933
1819
|
category: ErrorCategory.USER,
|
|
1934
1820
|
text: "Cannot update without keys to identify records"
|
|
@@ -1969,7 +1855,7 @@ ${columns}
|
|
|
1969
1855
|
} catch (error) {
|
|
1970
1856
|
throw new MastraError(
|
|
1971
1857
|
{
|
|
1972
|
-
id: "
|
|
1858
|
+
id: createStorageErrorId("MSSQL", "UPDATE", "FAILED"),
|
|
1973
1859
|
domain: ErrorDomain.STORAGE,
|
|
1974
1860
|
category: ErrorCategory.THIRD_PARTY,
|
|
1975
1861
|
details: {
|
|
@@ -1998,7 +1884,7 @@ ${columns}
|
|
|
1998
1884
|
await transaction.rollback();
|
|
1999
1885
|
throw new MastraError(
|
|
2000
1886
|
{
|
|
2001
|
-
id: "
|
|
1887
|
+
id: createStorageErrorId("MSSQL", "BATCH_UPDATE", "FAILED"),
|
|
2002
1888
|
domain: ErrorDomain.STORAGE,
|
|
2003
1889
|
category: ErrorCategory.THIRD_PARTY,
|
|
2004
1890
|
details: {
|
|
@@ -2047,7 +1933,7 @@ ${columns}
|
|
|
2047
1933
|
await transaction.rollback();
|
|
2048
1934
|
throw new MastraError(
|
|
2049
1935
|
{
|
|
2050
|
-
id: "
|
|
1936
|
+
id: createStorageErrorId("MSSQL", "BATCH_DELETE", "FAILED"),
|
|
2051
1937
|
domain: ErrorDomain.STORAGE,
|
|
2052
1938
|
category: ErrorCategory.THIRD_PARTY,
|
|
2053
1939
|
details: {
|
|
@@ -2104,7 +1990,7 @@ ${columns}
|
|
|
2104
1990
|
} catch (error) {
|
|
2105
1991
|
throw new MastraError(
|
|
2106
1992
|
{
|
|
2107
|
-
id: "
|
|
1993
|
+
id: createStorageErrorId("MSSQL", "INDEX_CREATE", "FAILED"),
|
|
2108
1994
|
domain: ErrorDomain.STORAGE,
|
|
2109
1995
|
category: ErrorCategory.THIRD_PARTY,
|
|
2110
1996
|
details: {
|
|
@@ -2140,7 +2026,7 @@ ${columns}
|
|
|
2140
2026
|
if (result.recordset.length > 1) {
|
|
2141
2027
|
const tables = result.recordset.map((r) => r.table_name).join(", ");
|
|
2142
2028
|
throw new MastraError({
|
|
2143
|
-
id: "
|
|
2029
|
+
id: createStorageErrorId("MSSQL", "INDEX", "AMBIGUOUS"),
|
|
2144
2030
|
domain: ErrorDomain.STORAGE,
|
|
2145
2031
|
category: ErrorCategory.USER,
|
|
2146
2032
|
text: `Index "${indexNameSafe}" exists on multiple tables (${tables}) in schema "${schemaName}". Please drop indexes manually or ensure unique index names.`
|
|
@@ -2156,7 +2042,7 @@ ${columns}
|
|
|
2156
2042
|
} catch (error) {
|
|
2157
2043
|
throw new MastraError(
|
|
2158
2044
|
{
|
|
2159
|
-
id: "
|
|
2045
|
+
id: createStorageErrorId("MSSQL", "INDEX_DROP", "FAILED"),
|
|
2160
2046
|
domain: ErrorDomain.STORAGE,
|
|
2161
2047
|
category: ErrorCategory.THIRD_PARTY,
|
|
2162
2048
|
details: {
|
|
@@ -2240,7 +2126,7 @@ ${columns}
|
|
|
2240
2126
|
} catch (error) {
|
|
2241
2127
|
throw new MastraError(
|
|
2242
2128
|
{
|
|
2243
|
-
id: "
|
|
2129
|
+
id: createStorageErrorId("MSSQL", "INDEX_LIST", "FAILED"),
|
|
2244
2130
|
domain: ErrorDomain.STORAGE,
|
|
2245
2131
|
category: ErrorCategory.THIRD_PARTY,
|
|
2246
2132
|
details: tableName ? {
|
|
@@ -2313,7 +2199,7 @@ ${columns}
|
|
|
2313
2199
|
} catch (error) {
|
|
2314
2200
|
throw new MastraError(
|
|
2315
2201
|
{
|
|
2316
|
-
id: "
|
|
2202
|
+
id: createStorageErrorId("MSSQL", "INDEX_DESCRIBE", "FAILED"),
|
|
2317
2203
|
domain: ErrorDomain.STORAGE,
|
|
2318
2204
|
category: ErrorCategory.THIRD_PARTY,
|
|
2319
2205
|
details: {
|
|
@@ -2349,35 +2235,30 @@ ${columns}
|
|
|
2349
2235
|
table: TABLE_TRACES,
|
|
2350
2236
|
columns: ["name", "seq_id DESC"]
|
|
2351
2237
|
},
|
|
2352
|
-
{
|
|
2353
|
-
name: `${schemaPrefix}mastra_evals_agent_name_seqid_idx`,
|
|
2354
|
-
table: TABLE_EVALS,
|
|
2355
|
-
columns: ["agent_name", "seq_id DESC"]
|
|
2356
|
-
},
|
|
2357
2238
|
{
|
|
2358
2239
|
name: `${schemaPrefix}mastra_scores_trace_id_span_id_seqid_idx`,
|
|
2359
2240
|
table: TABLE_SCORERS,
|
|
2360
2241
|
columns: ["traceId", "spanId", "seq_id DESC"]
|
|
2361
2242
|
},
|
|
2362
|
-
//
|
|
2243
|
+
// Spans indexes for optimal trace querying
|
|
2363
2244
|
{
|
|
2364
2245
|
name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
|
|
2365
|
-
table:
|
|
2246
|
+
table: TABLE_SPANS,
|
|
2366
2247
|
columns: ["traceId", "startedAt DESC"]
|
|
2367
2248
|
},
|
|
2368
2249
|
{
|
|
2369
2250
|
name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
|
|
2370
|
-
table:
|
|
2251
|
+
table: TABLE_SPANS,
|
|
2371
2252
|
columns: ["parentSpanId", "startedAt DESC"]
|
|
2372
2253
|
},
|
|
2373
2254
|
{
|
|
2374
2255
|
name: `${schemaPrefix}mastra_ai_spans_name_idx`,
|
|
2375
|
-
table:
|
|
2256
|
+
table: TABLE_SPANS,
|
|
2376
2257
|
columns: ["name"]
|
|
2377
2258
|
},
|
|
2378
2259
|
{
|
|
2379
2260
|
name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
|
|
2380
|
-
table:
|
|
2261
|
+
table: TABLE_SPANS,
|
|
2381
2262
|
columns: ["spanType", "startedAt DESC"]
|
|
2382
2263
|
}
|
|
2383
2264
|
];
|
|
@@ -2399,7 +2280,7 @@ ${columns}
|
|
|
2399
2280
|
} catch (error) {
|
|
2400
2281
|
throw new MastraError(
|
|
2401
2282
|
{
|
|
2402
|
-
id: "
|
|
2283
|
+
id: createStorageErrorId("MSSQL", "CREATE_PERFORMANCE_INDEXES", "FAILED"),
|
|
2403
2284
|
domain: ErrorDomain.STORAGE,
|
|
2404
2285
|
category: ErrorCategory.THIRD_PARTY
|
|
2405
2286
|
},
|
|
@@ -2409,20 +2290,9 @@ ${columns}
|
|
|
2409
2290
|
}
|
|
2410
2291
|
};
|
|
2411
2292
|
function transformScoreRow(row) {
|
|
2412
|
-
return {
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
scorer: safelyParseJSON(row.scorer),
|
|
2416
|
-
preprocessStepResult: safelyParseJSON(row.preprocessStepResult),
|
|
2417
|
-
analyzeStepResult: safelyParseJSON(row.analyzeStepResult),
|
|
2418
|
-
metadata: safelyParseJSON(row.metadata),
|
|
2419
|
-
output: safelyParseJSON(row.output),
|
|
2420
|
-
additionalContext: safelyParseJSON(row.additionalContext),
|
|
2421
|
-
runtimeContext: safelyParseJSON(row.runtimeContext),
|
|
2422
|
-
entity: safelyParseJSON(row.entity),
|
|
2423
|
-
createdAt: new Date(row.createdAt),
|
|
2424
|
-
updatedAt: new Date(row.updatedAt)
|
|
2425
|
-
};
|
|
2293
|
+
return transformScoreRow$1(row, {
|
|
2294
|
+
convertTimestamps: true
|
|
2295
|
+
});
|
|
2426
2296
|
}
|
|
2427
2297
|
var ScoresMSSQL = class extends ScoresStorage {
|
|
2428
2298
|
pool;
|
|
@@ -2452,7 +2322,7 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2452
2322
|
} catch (error) {
|
|
2453
2323
|
throw new MastraError(
|
|
2454
2324
|
{
|
|
2455
|
-
id: "
|
|
2325
|
+
id: createStorageErrorId("MSSQL", "GET_SCORE_BY_ID", "FAILED"),
|
|
2456
2326
|
domain: ErrorDomain.STORAGE,
|
|
2457
2327
|
category: ErrorCategory.THIRD_PARTY,
|
|
2458
2328
|
details: { id }
|
|
@@ -2468,15 +2338,23 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2468
2338
|
} catch (error) {
|
|
2469
2339
|
throw new MastraError(
|
|
2470
2340
|
{
|
|
2471
|
-
id: "
|
|
2341
|
+
id: createStorageErrorId("MSSQL", "SAVE_SCORE", "VALIDATION_FAILED"),
|
|
2472
2342
|
domain: ErrorDomain.STORAGE,
|
|
2473
|
-
category: ErrorCategory.
|
|
2343
|
+
category: ErrorCategory.USER,
|
|
2344
|
+
details: {
|
|
2345
|
+
scorer: score.scorer?.id ?? "unknown",
|
|
2346
|
+
entityId: score.entityId ?? "unknown",
|
|
2347
|
+
entityType: score.entityType ?? "unknown",
|
|
2348
|
+
traceId: score.traceId ?? "",
|
|
2349
|
+
spanId: score.spanId ?? ""
|
|
2350
|
+
}
|
|
2474
2351
|
},
|
|
2475
2352
|
error
|
|
2476
2353
|
);
|
|
2477
2354
|
}
|
|
2478
2355
|
try {
|
|
2479
2356
|
const scoreId = randomUUID();
|
|
2357
|
+
const now = /* @__PURE__ */ new Date();
|
|
2480
2358
|
const {
|
|
2481
2359
|
scorer,
|
|
2482
2360
|
preprocessStepResult,
|
|
@@ -2485,7 +2363,7 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2485
2363
|
input,
|
|
2486
2364
|
output,
|
|
2487
2365
|
additionalContext,
|
|
2488
|
-
|
|
2366
|
+
requestContext,
|
|
2489
2367
|
entity,
|
|
2490
2368
|
...rest
|
|
2491
2369
|
} = validatedScore;
|
|
@@ -2500,19 +2378,18 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2500
2378
|
analyzeStepResult: analyzeStepResult || null,
|
|
2501
2379
|
metadata: metadata || null,
|
|
2502
2380
|
additionalContext: additionalContext || null,
|
|
2503
|
-
|
|
2381
|
+
requestContext: requestContext || null,
|
|
2504
2382
|
entity: entity || null,
|
|
2505
2383
|
scorer: scorer || null,
|
|
2506
|
-
createdAt:
|
|
2507
|
-
updatedAt:
|
|
2384
|
+
createdAt: now.toISOString(),
|
|
2385
|
+
updatedAt: now.toISOString()
|
|
2508
2386
|
}
|
|
2509
2387
|
});
|
|
2510
|
-
|
|
2511
|
-
return { score: scoreFromDb };
|
|
2388
|
+
return { score: { ...validatedScore, id: scoreId, createdAt: now, updatedAt: now } };
|
|
2512
2389
|
} catch (error) {
|
|
2513
2390
|
throw new MastraError(
|
|
2514
2391
|
{
|
|
2515
|
-
id: "
|
|
2392
|
+
id: createStorageErrorId("MSSQL", "SAVE_SCORE", "FAILED"),
|
|
2516
2393
|
domain: ErrorDomain.STORAGE,
|
|
2517
2394
|
category: ErrorCategory.THIRD_PARTY
|
|
2518
2395
|
},
|
|
@@ -2520,7 +2397,7 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2520
2397
|
);
|
|
2521
2398
|
}
|
|
2522
2399
|
}
|
|
2523
|
-
async
|
|
2400
|
+
async listScoresByScorerId({
|
|
2524
2401
|
scorerId,
|
|
2525
2402
|
pagination,
|
|
2526
2403
|
entityId,
|
|
@@ -2554,38 +2431,43 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2554
2431
|
});
|
|
2555
2432
|
const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
|
|
2556
2433
|
const total = totalResult.recordset[0]?.count || 0;
|
|
2434
|
+
const { page, perPage: perPageInput } = pagination;
|
|
2557
2435
|
if (total === 0) {
|
|
2558
2436
|
return {
|
|
2559
2437
|
pagination: {
|
|
2560
2438
|
total: 0,
|
|
2561
|
-
page
|
|
2562
|
-
perPage:
|
|
2439
|
+
page,
|
|
2440
|
+
perPage: perPageInput,
|
|
2563
2441
|
hasMore: false
|
|
2564
2442
|
},
|
|
2565
2443
|
scores: []
|
|
2566
2444
|
};
|
|
2567
2445
|
}
|
|
2446
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
2447
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
2448
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
2449
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
2568
2450
|
const dataRequest = this.pool.request();
|
|
2569
2451
|
Object.entries(params).forEach(([key, value]) => {
|
|
2570
2452
|
dataRequest.input(key, value);
|
|
2571
2453
|
});
|
|
2572
|
-
dataRequest.input("perPage",
|
|
2573
|
-
dataRequest.input("offset",
|
|
2454
|
+
dataRequest.input("perPage", limitValue);
|
|
2455
|
+
dataRequest.input("offset", start);
|
|
2574
2456
|
const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
2575
2457
|
const result = await dataRequest.query(dataQuery);
|
|
2576
2458
|
return {
|
|
2577
2459
|
pagination: {
|
|
2578
2460
|
total: Number(total),
|
|
2579
|
-
page
|
|
2580
|
-
perPage:
|
|
2581
|
-
hasMore:
|
|
2461
|
+
page,
|
|
2462
|
+
perPage: perPageForResponse,
|
|
2463
|
+
hasMore: end < total
|
|
2582
2464
|
},
|
|
2583
2465
|
scores: result.recordset.map((row) => transformScoreRow(row))
|
|
2584
2466
|
};
|
|
2585
2467
|
} catch (error) {
|
|
2586
2468
|
throw new MastraError(
|
|
2587
2469
|
{
|
|
2588
|
-
id: "
|
|
2470
|
+
id: createStorageErrorId("MSSQL", "LIST_SCORES_BY_SCORER_ID", "FAILED"),
|
|
2589
2471
|
domain: ErrorDomain.STORAGE,
|
|
2590
2472
|
category: ErrorCategory.THIRD_PARTY,
|
|
2591
2473
|
details: { scorerId }
|
|
@@ -2594,7 +2476,7 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2594
2476
|
);
|
|
2595
2477
|
}
|
|
2596
2478
|
}
|
|
2597
|
-
async
|
|
2479
|
+
async listScoresByRunId({
|
|
2598
2480
|
runId,
|
|
2599
2481
|
pagination
|
|
2600
2482
|
}) {
|
|
@@ -2605,37 +2487,42 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2605
2487
|
`SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
|
|
2606
2488
|
);
|
|
2607
2489
|
const total = totalResult.recordset[0]?.count || 0;
|
|
2490
|
+
const { page, perPage: perPageInput } = pagination;
|
|
2608
2491
|
if (total === 0) {
|
|
2609
2492
|
return {
|
|
2610
2493
|
pagination: {
|
|
2611
2494
|
total: 0,
|
|
2612
|
-
page
|
|
2613
|
-
perPage:
|
|
2495
|
+
page,
|
|
2496
|
+
perPage: perPageInput,
|
|
2614
2497
|
hasMore: false
|
|
2615
2498
|
},
|
|
2616
2499
|
scores: []
|
|
2617
2500
|
};
|
|
2618
2501
|
}
|
|
2502
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
2503
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
2504
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
2505
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
2619
2506
|
const dataRequest = this.pool.request();
|
|
2620
2507
|
dataRequest.input("p1", runId);
|
|
2621
|
-
dataRequest.input("p2",
|
|
2622
|
-
dataRequest.input("p3",
|
|
2508
|
+
dataRequest.input("p2", limitValue);
|
|
2509
|
+
dataRequest.input("p3", start);
|
|
2623
2510
|
const result = await dataRequest.query(
|
|
2624
2511
|
`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`
|
|
2625
2512
|
);
|
|
2626
2513
|
return {
|
|
2627
2514
|
pagination: {
|
|
2628
2515
|
total: Number(total),
|
|
2629
|
-
page
|
|
2630
|
-
perPage:
|
|
2631
|
-
hasMore:
|
|
2516
|
+
page,
|
|
2517
|
+
perPage: perPageForResponse,
|
|
2518
|
+
hasMore: end < total
|
|
2632
2519
|
},
|
|
2633
2520
|
scores: result.recordset.map((row) => transformScoreRow(row))
|
|
2634
2521
|
};
|
|
2635
2522
|
} catch (error) {
|
|
2636
2523
|
throw new MastraError(
|
|
2637
2524
|
{
|
|
2638
|
-
id: "
|
|
2525
|
+
id: createStorageErrorId("MSSQL", "LIST_SCORES_BY_RUN_ID", "FAILED"),
|
|
2639
2526
|
domain: ErrorDomain.STORAGE,
|
|
2640
2527
|
category: ErrorCategory.THIRD_PARTY,
|
|
2641
2528
|
details: { runId }
|
|
@@ -2644,7 +2531,7 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2644
2531
|
);
|
|
2645
2532
|
}
|
|
2646
2533
|
}
|
|
2647
|
-
async
|
|
2534
|
+
async listScoresByEntityId({
|
|
2648
2535
|
entityId,
|
|
2649
2536
|
entityType,
|
|
2650
2537
|
pagination
|
|
@@ -2657,38 +2544,43 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2657
2544
|
`SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
|
|
2658
2545
|
);
|
|
2659
2546
|
const total = totalResult.recordset[0]?.count || 0;
|
|
2547
|
+
const { page, perPage: perPageInput } = pagination;
|
|
2548
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
2549
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
2660
2550
|
if (total === 0) {
|
|
2661
2551
|
return {
|
|
2662
2552
|
pagination: {
|
|
2663
2553
|
total: 0,
|
|
2664
|
-
page
|
|
2665
|
-
perPage:
|
|
2554
|
+
page,
|
|
2555
|
+
perPage: perPageForResponse,
|
|
2666
2556
|
hasMore: false
|
|
2667
2557
|
},
|
|
2668
2558
|
scores: []
|
|
2669
2559
|
};
|
|
2670
2560
|
}
|
|
2561
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
2562
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
2671
2563
|
const dataRequest = this.pool.request();
|
|
2672
2564
|
dataRequest.input("p1", entityId);
|
|
2673
2565
|
dataRequest.input("p2", entityType);
|
|
2674
|
-
dataRequest.input("p3",
|
|
2675
|
-
dataRequest.input("p4",
|
|
2566
|
+
dataRequest.input("p3", limitValue);
|
|
2567
|
+
dataRequest.input("p4", start);
|
|
2676
2568
|
const result = await dataRequest.query(
|
|
2677
2569
|
`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`
|
|
2678
2570
|
);
|
|
2679
2571
|
return {
|
|
2680
2572
|
pagination: {
|
|
2681
2573
|
total: Number(total),
|
|
2682
|
-
page
|
|
2683
|
-
perPage:
|
|
2684
|
-
hasMore:
|
|
2574
|
+
page,
|
|
2575
|
+
perPage: perPageForResponse,
|
|
2576
|
+
hasMore: end < total
|
|
2685
2577
|
},
|
|
2686
2578
|
scores: result.recordset.map((row) => transformScoreRow(row))
|
|
2687
2579
|
};
|
|
2688
2580
|
} catch (error) {
|
|
2689
2581
|
throw new MastraError(
|
|
2690
2582
|
{
|
|
2691
|
-
id: "
|
|
2583
|
+
id: createStorageErrorId("MSSQL", "LIST_SCORES_BY_ENTITY_ID", "FAILED"),
|
|
2692
2584
|
domain: ErrorDomain.STORAGE,
|
|
2693
2585
|
category: ErrorCategory.THIRD_PARTY,
|
|
2694
2586
|
details: { entityId, entityType }
|
|
@@ -2697,7 +2589,7 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2697
2589
|
);
|
|
2698
2590
|
}
|
|
2699
2591
|
}
|
|
2700
|
-
async
|
|
2592
|
+
async listScoresBySpan({
|
|
2701
2593
|
traceId,
|
|
2702
2594
|
spanId,
|
|
2703
2595
|
pagination
|
|
@@ -2710,39 +2602,43 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2710
2602
|
`SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
|
|
2711
2603
|
);
|
|
2712
2604
|
const total = totalResult.recordset[0]?.count || 0;
|
|
2605
|
+
const { page, perPage: perPageInput } = pagination;
|
|
2606
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
2607
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
2713
2608
|
if (total === 0) {
|
|
2714
2609
|
return {
|
|
2715
2610
|
pagination: {
|
|
2716
2611
|
total: 0,
|
|
2717
|
-
page
|
|
2718
|
-
perPage:
|
|
2612
|
+
page,
|
|
2613
|
+
perPage: perPageForResponse,
|
|
2719
2614
|
hasMore: false
|
|
2720
2615
|
},
|
|
2721
2616
|
scores: []
|
|
2722
2617
|
};
|
|
2723
2618
|
}
|
|
2724
|
-
const
|
|
2619
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
2620
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
2725
2621
|
const dataRequest = this.pool.request();
|
|
2726
2622
|
dataRequest.input("p1", traceId);
|
|
2727
2623
|
dataRequest.input("p2", spanId);
|
|
2728
|
-
dataRequest.input("p3",
|
|
2729
|
-
dataRequest.input("p4",
|
|
2624
|
+
dataRequest.input("p3", limitValue);
|
|
2625
|
+
dataRequest.input("p4", start);
|
|
2730
2626
|
const result = await dataRequest.query(
|
|
2731
2627
|
`SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
|
|
2732
2628
|
);
|
|
2733
2629
|
return {
|
|
2734
2630
|
pagination: {
|
|
2735
2631
|
total: Number(total),
|
|
2736
|
-
page
|
|
2737
|
-
perPage:
|
|
2738
|
-
hasMore:
|
|
2632
|
+
page,
|
|
2633
|
+
perPage: perPageForResponse,
|
|
2634
|
+
hasMore: end < total
|
|
2739
2635
|
},
|
|
2740
|
-
scores: result.recordset.
|
|
2636
|
+
scores: result.recordset.map((row) => transformScoreRow(row))
|
|
2741
2637
|
};
|
|
2742
2638
|
} catch (error) {
|
|
2743
2639
|
throw new MastraError(
|
|
2744
2640
|
{
|
|
2745
|
-
id: "
|
|
2641
|
+
id: createStorageErrorId("MSSQL", "LIST_SCORES_BY_SPAN", "FAILED"),
|
|
2746
2642
|
domain: ErrorDomain.STORAGE,
|
|
2747
2643
|
category: ErrorCategory.THIRD_PARTY,
|
|
2748
2644
|
details: { traceId, spanId }
|
|
@@ -2752,173 +2648,6 @@ var ScoresMSSQL = class extends ScoresStorage {
|
|
|
2752
2648
|
}
|
|
2753
2649
|
}
|
|
2754
2650
|
};
|
|
2755
|
-
var TracesMSSQL = class extends TracesStorage {
|
|
2756
|
-
pool;
|
|
2757
|
-
operations;
|
|
2758
|
-
schema;
|
|
2759
|
-
constructor({
|
|
2760
|
-
pool,
|
|
2761
|
-
operations,
|
|
2762
|
-
schema
|
|
2763
|
-
}) {
|
|
2764
|
-
super();
|
|
2765
|
-
this.pool = pool;
|
|
2766
|
-
this.operations = operations;
|
|
2767
|
-
this.schema = schema;
|
|
2768
|
-
}
|
|
2769
|
-
/** @deprecated use getTracesPaginated instead*/
|
|
2770
|
-
async getTraces(args) {
|
|
2771
|
-
if (args.fromDate || args.toDate) {
|
|
2772
|
-
args.dateRange = {
|
|
2773
|
-
start: args.fromDate,
|
|
2774
|
-
end: args.toDate
|
|
2775
|
-
};
|
|
2776
|
-
}
|
|
2777
|
-
const result = await this.getTracesPaginated(args);
|
|
2778
|
-
return result.traces;
|
|
2779
|
-
}
|
|
2780
|
-
async getTracesPaginated(args) {
|
|
2781
|
-
const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
|
|
2782
|
-
const fromDate = dateRange?.start;
|
|
2783
|
-
const toDate = dateRange?.end;
|
|
2784
|
-
const perPage = perPageInput !== void 0 ? perPageInput : 100;
|
|
2785
|
-
const currentOffset = page * perPage;
|
|
2786
|
-
const paramMap = {};
|
|
2787
|
-
const conditions = [];
|
|
2788
|
-
let paramIndex = 1;
|
|
2789
|
-
if (name) {
|
|
2790
|
-
const paramName = `p${paramIndex++}`;
|
|
2791
|
-
conditions.push(`[name] LIKE @${paramName}`);
|
|
2792
|
-
paramMap[paramName] = `${name}%`;
|
|
2793
|
-
}
|
|
2794
|
-
if (scope) {
|
|
2795
|
-
const paramName = `p${paramIndex++}`;
|
|
2796
|
-
conditions.push(`[scope] = @${paramName}`);
|
|
2797
|
-
paramMap[paramName] = scope;
|
|
2798
|
-
}
|
|
2799
|
-
if (attributes) {
|
|
2800
|
-
Object.entries(attributes).forEach(([key, value]) => {
|
|
2801
|
-
const parsedKey = parseFieldKey(key);
|
|
2802
|
-
const paramName = `p${paramIndex++}`;
|
|
2803
|
-
conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
|
|
2804
|
-
paramMap[paramName] = value;
|
|
2805
|
-
});
|
|
2806
|
-
}
|
|
2807
|
-
if (filters) {
|
|
2808
|
-
Object.entries(filters).forEach(([key, value]) => {
|
|
2809
|
-
const parsedKey = parseFieldKey(key);
|
|
2810
|
-
const paramName = `p${paramIndex++}`;
|
|
2811
|
-
conditions.push(`[${parsedKey}] = @${paramName}`);
|
|
2812
|
-
paramMap[paramName] = value;
|
|
2813
|
-
});
|
|
2814
|
-
}
|
|
2815
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
2816
|
-
const paramName = `p${paramIndex++}`;
|
|
2817
|
-
conditions.push(`[createdAt] >= @${paramName}`);
|
|
2818
|
-
paramMap[paramName] = fromDate.toISOString();
|
|
2819
|
-
}
|
|
2820
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
2821
|
-
const paramName = `p${paramIndex++}`;
|
|
2822
|
-
conditions.push(`[createdAt] <= @${paramName}`);
|
|
2823
|
-
paramMap[paramName] = toDate.toISOString();
|
|
2824
|
-
}
|
|
2825
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
2826
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
|
|
2827
|
-
let total = 0;
|
|
2828
|
-
try {
|
|
2829
|
-
const countRequest = this.pool.request();
|
|
2830
|
-
Object.entries(paramMap).forEach(([key, value]) => {
|
|
2831
|
-
if (value instanceof Date) {
|
|
2832
|
-
countRequest.input(key, sql3.DateTime, value);
|
|
2833
|
-
} else {
|
|
2834
|
-
countRequest.input(key, value);
|
|
2835
|
-
}
|
|
2836
|
-
});
|
|
2837
|
-
const countResult = await countRequest.query(countQuery);
|
|
2838
|
-
total = parseInt(countResult.recordset[0].total, 10);
|
|
2839
|
-
} catch (error) {
|
|
2840
|
-
throw new MastraError(
|
|
2841
|
-
{
|
|
2842
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
|
|
2843
|
-
domain: ErrorDomain.STORAGE,
|
|
2844
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
2845
|
-
details: {
|
|
2846
|
-
name: args.name ?? "",
|
|
2847
|
-
scope: args.scope ?? ""
|
|
2848
|
-
}
|
|
2849
|
-
},
|
|
2850
|
-
error
|
|
2851
|
-
);
|
|
2852
|
-
}
|
|
2853
|
-
if (total === 0) {
|
|
2854
|
-
return {
|
|
2855
|
-
traces: [],
|
|
2856
|
-
total: 0,
|
|
2857
|
-
page,
|
|
2858
|
-
perPage,
|
|
2859
|
-
hasMore: false
|
|
2860
|
-
};
|
|
2861
|
-
}
|
|
2862
|
-
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`;
|
|
2863
|
-
const dataRequest = this.pool.request();
|
|
2864
|
-
Object.entries(paramMap).forEach(([key, value]) => {
|
|
2865
|
-
if (value instanceof Date) {
|
|
2866
|
-
dataRequest.input(key, sql3.DateTime, value);
|
|
2867
|
-
} else {
|
|
2868
|
-
dataRequest.input(key, value);
|
|
2869
|
-
}
|
|
2870
|
-
});
|
|
2871
|
-
dataRequest.input("offset", currentOffset);
|
|
2872
|
-
dataRequest.input("limit", perPage);
|
|
2873
|
-
try {
|
|
2874
|
-
const rowsResult = await dataRequest.query(dataQuery);
|
|
2875
|
-
const rows = rowsResult.recordset;
|
|
2876
|
-
const traces = rows.map((row) => ({
|
|
2877
|
-
id: row.id,
|
|
2878
|
-
parentSpanId: row.parentSpanId,
|
|
2879
|
-
traceId: row.traceId,
|
|
2880
|
-
name: row.name,
|
|
2881
|
-
scope: row.scope,
|
|
2882
|
-
kind: row.kind,
|
|
2883
|
-
status: JSON.parse(row.status),
|
|
2884
|
-
events: JSON.parse(row.events),
|
|
2885
|
-
links: JSON.parse(row.links),
|
|
2886
|
-
attributes: JSON.parse(row.attributes),
|
|
2887
|
-
startTime: row.startTime,
|
|
2888
|
-
endTime: row.endTime,
|
|
2889
|
-
other: row.other,
|
|
2890
|
-
createdAt: row.createdAt
|
|
2891
|
-
}));
|
|
2892
|
-
return {
|
|
2893
|
-
traces,
|
|
2894
|
-
total,
|
|
2895
|
-
page,
|
|
2896
|
-
perPage,
|
|
2897
|
-
hasMore: currentOffset + traces.length < total
|
|
2898
|
-
};
|
|
2899
|
-
} catch (error) {
|
|
2900
|
-
throw new MastraError(
|
|
2901
|
-
{
|
|
2902
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
|
|
2903
|
-
domain: ErrorDomain.STORAGE,
|
|
2904
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
2905
|
-
details: {
|
|
2906
|
-
name: args.name ?? "",
|
|
2907
|
-
scope: args.scope ?? ""
|
|
2908
|
-
}
|
|
2909
|
-
},
|
|
2910
|
-
error
|
|
2911
|
-
);
|
|
2912
|
-
}
|
|
2913
|
-
}
|
|
2914
|
-
async batchTraceInsert({ records }) {
|
|
2915
|
-
this.logger.debug("Batch inserting traces", { count: records.length });
|
|
2916
|
-
await this.operations.batchInsert({
|
|
2917
|
-
tableName: TABLE_TRACES,
|
|
2918
|
-
records
|
|
2919
|
-
});
|
|
2920
|
-
}
|
|
2921
|
-
};
|
|
2922
2651
|
var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
2923
2652
|
pool;
|
|
2924
2653
|
operations;
|
|
@@ -2956,13 +2685,13 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
2956
2685
|
runId,
|
|
2957
2686
|
stepId,
|
|
2958
2687
|
result,
|
|
2959
|
-
|
|
2688
|
+
requestContext
|
|
2960
2689
|
}) {
|
|
2961
2690
|
const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
|
|
2962
2691
|
const transaction = this.pool.transaction();
|
|
2963
2692
|
try {
|
|
2964
2693
|
await transaction.begin();
|
|
2965
|
-
const selectRequest = new
|
|
2694
|
+
const selectRequest = new sql2.Request(transaction);
|
|
2966
2695
|
selectRequest.input("workflow_name", workflowName);
|
|
2967
2696
|
selectRequest.input("run_id", runId);
|
|
2968
2697
|
const existingSnapshotResult = await selectRequest.query(
|
|
@@ -2973,28 +2702,29 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
2973
2702
|
snapshot = {
|
|
2974
2703
|
context: {},
|
|
2975
2704
|
activePaths: [],
|
|
2705
|
+
activeStepsPath: {},
|
|
2976
2706
|
timestamp: Date.now(),
|
|
2977
2707
|
suspendedPaths: {},
|
|
2978
2708
|
resumeLabels: {},
|
|
2979
2709
|
serializedStepGraph: [],
|
|
2710
|
+
status: "pending",
|
|
2980
2711
|
value: {},
|
|
2981
2712
|
waitingPaths: {},
|
|
2982
|
-
status: "pending",
|
|
2983
2713
|
runId,
|
|
2984
|
-
|
|
2714
|
+
requestContext: {}
|
|
2985
2715
|
};
|
|
2986
2716
|
} else {
|
|
2987
2717
|
const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
|
|
2988
2718
|
snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
|
|
2989
2719
|
}
|
|
2990
2720
|
snapshot.context[stepId] = result;
|
|
2991
|
-
snapshot.
|
|
2992
|
-
const upsertReq = new
|
|
2721
|
+
snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
|
|
2722
|
+
const upsertReq = new sql2.Request(transaction);
|
|
2993
2723
|
upsertReq.input("workflow_name", workflowName);
|
|
2994
2724
|
upsertReq.input("run_id", runId);
|
|
2995
2725
|
upsertReq.input("snapshot", JSON.stringify(snapshot));
|
|
2996
|
-
upsertReq.input("createdAt",
|
|
2997
|
-
upsertReq.input("updatedAt",
|
|
2726
|
+
upsertReq.input("createdAt", sql2.DateTime2, /* @__PURE__ */ new Date());
|
|
2727
|
+
upsertReq.input("updatedAt", sql2.DateTime2, /* @__PURE__ */ new Date());
|
|
2998
2728
|
await upsertReq.query(
|
|
2999
2729
|
`MERGE ${table} AS target
|
|
3000
2730
|
USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
|
|
@@ -3012,7 +2742,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3012
2742
|
}
|
|
3013
2743
|
throw new MastraError(
|
|
3014
2744
|
{
|
|
3015
|
-
id: "
|
|
2745
|
+
id: createStorageErrorId("MSSQL", "UPDATE_WORKFLOW_RESULTS", "FAILED"),
|
|
3016
2746
|
domain: ErrorDomain.STORAGE,
|
|
3017
2747
|
category: ErrorCategory.THIRD_PARTY,
|
|
3018
2748
|
details: {
|
|
@@ -3034,7 +2764,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3034
2764
|
const transaction = this.pool.transaction();
|
|
3035
2765
|
try {
|
|
3036
2766
|
await transaction.begin();
|
|
3037
|
-
const selectRequest = new
|
|
2767
|
+
const selectRequest = new sql2.Request(transaction);
|
|
3038
2768
|
selectRequest.input("workflow_name", workflowName);
|
|
3039
2769
|
selectRequest.input("run_id", runId);
|
|
3040
2770
|
const existingSnapshotResult = await selectRequest.query(
|
|
@@ -3050,7 +2780,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3050
2780
|
await transaction.rollback();
|
|
3051
2781
|
throw new MastraError(
|
|
3052
2782
|
{
|
|
3053
|
-
id: "
|
|
2783
|
+
id: createStorageErrorId("MSSQL", "UPDATE_WORKFLOW_STATE", "SNAPSHOT_NOT_FOUND"),
|
|
3054
2784
|
domain: ErrorDomain.STORAGE,
|
|
3055
2785
|
category: ErrorCategory.SYSTEM,
|
|
3056
2786
|
details: {
|
|
@@ -3062,11 +2792,11 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3062
2792
|
);
|
|
3063
2793
|
}
|
|
3064
2794
|
const updatedSnapshot = { ...snapshot, ...opts };
|
|
3065
|
-
const updateRequest = new
|
|
2795
|
+
const updateRequest = new sql2.Request(transaction);
|
|
3066
2796
|
updateRequest.input("snapshot", JSON.stringify(updatedSnapshot));
|
|
3067
2797
|
updateRequest.input("workflow_name", workflowName);
|
|
3068
2798
|
updateRequest.input("run_id", runId);
|
|
3069
|
-
updateRequest.input("updatedAt",
|
|
2799
|
+
updateRequest.input("updatedAt", sql2.DateTime2, /* @__PURE__ */ new Date());
|
|
3070
2800
|
await updateRequest.query(
|
|
3071
2801
|
`UPDATE ${table} SET snapshot = @snapshot, [updatedAt] = @updatedAt WHERE workflow_name = @workflow_name AND run_id = @run_id`
|
|
3072
2802
|
);
|
|
@@ -3077,9 +2807,10 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3077
2807
|
await transaction.rollback();
|
|
3078
2808
|
} catch {
|
|
3079
2809
|
}
|
|
2810
|
+
if (error instanceof MastraError) throw error;
|
|
3080
2811
|
throw new MastraError(
|
|
3081
2812
|
{
|
|
3082
|
-
id: "
|
|
2813
|
+
id: createStorageErrorId("MSSQL", "UPDATE_WORKFLOW_STATE", "FAILED"),
|
|
3083
2814
|
domain: ErrorDomain.STORAGE,
|
|
3084
2815
|
category: ErrorCategory.THIRD_PARTY,
|
|
3085
2816
|
details: {
|
|
@@ -3105,8 +2836,8 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3105
2836
|
request.input("run_id", runId);
|
|
3106
2837
|
request.input("resourceId", resourceId);
|
|
3107
2838
|
request.input("snapshot", JSON.stringify(snapshot));
|
|
3108
|
-
request.input("createdAt",
|
|
3109
|
-
request.input("updatedAt",
|
|
2839
|
+
request.input("createdAt", sql2.DateTime2, new Date(now));
|
|
2840
|
+
request.input("updatedAt", sql2.DateTime2, new Date(now));
|
|
3110
2841
|
const mergeSql = `MERGE INTO ${table} AS target
|
|
3111
2842
|
USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
|
|
3112
2843
|
ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
|
|
@@ -3120,7 +2851,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3120
2851
|
} catch (error) {
|
|
3121
2852
|
throw new MastraError(
|
|
3122
2853
|
{
|
|
3123
|
-
id: "
|
|
2854
|
+
id: createStorageErrorId("MSSQL", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
|
|
3124
2855
|
domain: ErrorDomain.STORAGE,
|
|
3125
2856
|
category: ErrorCategory.THIRD_PARTY,
|
|
3126
2857
|
details: {
|
|
@@ -3151,7 +2882,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3151
2882
|
} catch (error) {
|
|
3152
2883
|
throw new MastraError(
|
|
3153
2884
|
{
|
|
3154
|
-
id: "
|
|
2885
|
+
id: createStorageErrorId("MSSQL", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
|
|
3155
2886
|
domain: ErrorDomain.STORAGE,
|
|
3156
2887
|
category: ErrorCategory.THIRD_PARTY,
|
|
3157
2888
|
details: {
|
|
@@ -3191,7 +2922,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3191
2922
|
} catch (error) {
|
|
3192
2923
|
throw new MastraError(
|
|
3193
2924
|
{
|
|
3194
|
-
id: "
|
|
2925
|
+
id: createStorageErrorId("MSSQL", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
|
|
3195
2926
|
domain: ErrorDomain.STORAGE,
|
|
3196
2927
|
category: ErrorCategory.THIRD_PARTY,
|
|
3197
2928
|
details: {
|
|
@@ -3203,13 +2934,14 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3203
2934
|
);
|
|
3204
2935
|
}
|
|
3205
2936
|
}
|
|
3206
|
-
async
|
|
2937
|
+
async listWorkflowRuns({
|
|
3207
2938
|
workflowName,
|
|
3208
2939
|
fromDate,
|
|
3209
2940
|
toDate,
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
resourceId
|
|
2941
|
+
page,
|
|
2942
|
+
perPage,
|
|
2943
|
+
resourceId,
|
|
2944
|
+
status
|
|
3213
2945
|
} = {}) {
|
|
3214
2946
|
try {
|
|
3215
2947
|
const conditions = [];
|
|
@@ -3218,6 +2950,10 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3218
2950
|
conditions.push(`[workflow_name] = @workflowName`);
|
|
3219
2951
|
paramMap["workflowName"] = workflowName;
|
|
3220
2952
|
}
|
|
2953
|
+
if (status) {
|
|
2954
|
+
conditions.push(`JSON_VALUE([snapshot], '$.status') = @status`);
|
|
2955
|
+
paramMap["status"] = status;
|
|
2956
|
+
}
|
|
3221
2957
|
if (resourceId) {
|
|
3222
2958
|
const hasResourceId = await this.operations.hasColumn(TABLE_WORKFLOW_SNAPSHOT, "resourceId");
|
|
3223
2959
|
if (hasResourceId) {
|
|
@@ -3241,20 +2977,23 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3241
2977
|
const request = this.pool.request();
|
|
3242
2978
|
Object.entries(paramMap).forEach(([key, value]) => {
|
|
3243
2979
|
if (value instanceof Date) {
|
|
3244
|
-
request.input(key,
|
|
2980
|
+
request.input(key, sql2.DateTime, value);
|
|
3245
2981
|
} else {
|
|
3246
2982
|
request.input(key, value);
|
|
3247
2983
|
}
|
|
3248
2984
|
});
|
|
3249
|
-
|
|
2985
|
+
const usePagination = typeof perPage === "number" && typeof page === "number";
|
|
2986
|
+
if (usePagination) {
|
|
3250
2987
|
const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
|
|
3251
2988
|
const countResult = await request.query(countQuery);
|
|
3252
2989
|
total = Number(countResult.recordset[0]?.count || 0);
|
|
3253
2990
|
}
|
|
3254
2991
|
let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
|
|
3255
|
-
if (
|
|
3256
|
-
|
|
3257
|
-
|
|
2992
|
+
if (usePagination) {
|
|
2993
|
+
const normalizedPerPage = normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
|
|
2994
|
+
const offset = page * normalizedPerPage;
|
|
2995
|
+
query += ` OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
2996
|
+
request.input("perPage", normalizedPerPage);
|
|
3258
2997
|
request.input("offset", offset);
|
|
3259
2998
|
}
|
|
3260
2999
|
const result = await request.query(query);
|
|
@@ -3263,7 +3002,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
|
3263
3002
|
} catch (error) {
|
|
3264
3003
|
throw new MastraError(
|
|
3265
3004
|
{
|
|
3266
|
-
id: "
|
|
3005
|
+
id: createStorageErrorId("MSSQL", "LIST_WORKFLOW_RUNS", "FAILED"),
|
|
3267
3006
|
domain: ErrorDomain.STORAGE,
|
|
3268
3007
|
category: ErrorCategory.THIRD_PARTY,
|
|
3269
3008
|
details: {
|
|
@@ -3283,7 +3022,10 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3283
3022
|
isConnected = null;
|
|
3284
3023
|
stores;
|
|
3285
3024
|
constructor(config) {
|
|
3286
|
-
|
|
3025
|
+
if (!config.id || typeof config.id !== "string" || config.id.trim() === "") {
|
|
3026
|
+
throw new Error("MSSQLStore: id must be provided and cannot be empty.");
|
|
3027
|
+
}
|
|
3028
|
+
super({ id: config.id, name: "MSSQLStore", disableInit: config.disableInit });
|
|
3287
3029
|
try {
|
|
3288
3030
|
if ("connectionString" in config) {
|
|
3289
3031
|
if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
|
|
@@ -3298,7 +3040,7 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3298
3040
|
}
|
|
3299
3041
|
}
|
|
3300
3042
|
this.schema = config.schemaName || "dbo";
|
|
3301
|
-
this.pool = "connectionString" in config ? new
|
|
3043
|
+
this.pool = "connectionString" in config ? new sql2.ConnectionPool(config.connectionString) : new sql2.ConnectionPool({
|
|
3302
3044
|
server: config.server,
|
|
3303
3045
|
database: config.database,
|
|
3304
3046
|
user: config.user,
|
|
@@ -3306,26 +3048,22 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3306
3048
|
port: config.port,
|
|
3307
3049
|
options: config.options || { encrypt: true, trustServerCertificate: true }
|
|
3308
3050
|
});
|
|
3309
|
-
const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
|
|
3310
3051
|
const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
|
|
3311
3052
|
const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
3312
|
-
const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
3313
3053
|
const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
3314
3054
|
const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
|
|
3315
3055
|
const observability = new ObservabilityMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
3316
3056
|
this.stores = {
|
|
3317
3057
|
operations,
|
|
3318
3058
|
scores,
|
|
3319
|
-
traces,
|
|
3320
3059
|
workflows,
|
|
3321
|
-
legacyEvals,
|
|
3322
3060
|
memory,
|
|
3323
3061
|
observability
|
|
3324
3062
|
};
|
|
3325
3063
|
} catch (e) {
|
|
3326
3064
|
throw new MastraError(
|
|
3327
3065
|
{
|
|
3328
|
-
id: "
|
|
3066
|
+
id: createStorageErrorId("MSSQL", "INITIALIZATION", "FAILED"),
|
|
3329
3067
|
domain: ErrorDomain.STORAGE,
|
|
3330
3068
|
category: ErrorCategory.USER
|
|
3331
3069
|
},
|
|
@@ -3349,7 +3087,7 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3349
3087
|
this.isConnected = null;
|
|
3350
3088
|
throw new MastraError(
|
|
3351
3089
|
{
|
|
3352
|
-
id: "
|
|
3090
|
+
id: createStorageErrorId("MSSQL", "INIT", "FAILED"),
|
|
3353
3091
|
domain: ErrorDomain.STORAGE,
|
|
3354
3092
|
category: ErrorCategory.THIRD_PARTY
|
|
3355
3093
|
},
|
|
@@ -3372,30 +3110,11 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3372
3110
|
hasColumn: true,
|
|
3373
3111
|
createTable: true,
|
|
3374
3112
|
deleteMessages: true,
|
|
3375
|
-
|
|
3376
|
-
|
|
3113
|
+
listScoresBySpan: true,
|
|
3114
|
+
observabilityInstance: true,
|
|
3377
3115
|
indexManagement: true
|
|
3378
3116
|
};
|
|
3379
3117
|
}
|
|
3380
|
-
/** @deprecated use getEvals instead */
|
|
3381
|
-
async getEvalsByAgentName(agentName, type) {
|
|
3382
|
-
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
3383
|
-
}
|
|
3384
|
-
async getEvals(options = {}) {
|
|
3385
|
-
return this.stores.legacyEvals.getEvals(options);
|
|
3386
|
-
}
|
|
3387
|
-
/**
|
|
3388
|
-
* @deprecated use getTracesPaginated instead
|
|
3389
|
-
*/
|
|
3390
|
-
async getTraces(args) {
|
|
3391
|
-
return this.stores.traces.getTraces(args);
|
|
3392
|
-
}
|
|
3393
|
-
async getTracesPaginated(args) {
|
|
3394
|
-
return this.stores.traces.getTracesPaginated(args);
|
|
3395
|
-
}
|
|
3396
|
-
async batchTraceInsert({ records }) {
|
|
3397
|
-
return this.stores.traces.batchTraceInsert({ records });
|
|
3398
|
-
}
|
|
3399
3118
|
async createTable({
|
|
3400
3119
|
tableName,
|
|
3401
3120
|
schema
|
|
@@ -3430,15 +3149,6 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3430
3149
|
async getThreadById({ threadId }) {
|
|
3431
3150
|
return this.stores.memory.getThreadById({ threadId });
|
|
3432
3151
|
}
|
|
3433
|
-
/**
|
|
3434
|
-
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
3435
|
-
*/
|
|
3436
|
-
async getThreadsByResourceId(args) {
|
|
3437
|
-
return this.stores.memory.getThreadsByResourceId(args);
|
|
3438
|
-
}
|
|
3439
|
-
async getThreadsByResourceIdPaginated(args) {
|
|
3440
|
-
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
3441
|
-
}
|
|
3442
3152
|
async saveThread({ thread }) {
|
|
3443
3153
|
return this.stores.memory.saveThread({ thread });
|
|
3444
3154
|
}
|
|
@@ -3452,17 +3162,8 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3452
3162
|
async deleteThread({ threadId }) {
|
|
3453
3163
|
return this.stores.memory.deleteThread({ threadId });
|
|
3454
3164
|
}
|
|
3455
|
-
async
|
|
3456
|
-
return this.stores.memory.
|
|
3457
|
-
}
|
|
3458
|
-
async getMessagesById({
|
|
3459
|
-
messageIds,
|
|
3460
|
-
format
|
|
3461
|
-
}) {
|
|
3462
|
-
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
3463
|
-
}
|
|
3464
|
-
async getMessagesPaginated(args) {
|
|
3465
|
-
return this.stores.memory.getMessagesPaginated(args);
|
|
3165
|
+
async listMessagesById({ messageIds }) {
|
|
3166
|
+
return this.stores.memory.listMessagesById({ messageIds });
|
|
3466
3167
|
}
|
|
3467
3168
|
async saveMessages(args) {
|
|
3468
3169
|
return this.stores.memory.saveMessages(args);
|
|
@@ -3496,9 +3197,9 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3496
3197
|
runId,
|
|
3497
3198
|
stepId,
|
|
3498
3199
|
result,
|
|
3499
|
-
|
|
3200
|
+
requestContext
|
|
3500
3201
|
}) {
|
|
3501
|
-
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result,
|
|
3202
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
|
|
3502
3203
|
}
|
|
3503
3204
|
async updateWorkflowState({
|
|
3504
3205
|
workflowName,
|
|
@@ -3521,15 +3222,8 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3521
3222
|
}) {
|
|
3522
3223
|
return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
|
|
3523
3224
|
}
|
|
3524
|
-
async
|
|
3525
|
-
|
|
3526
|
-
fromDate,
|
|
3527
|
-
toDate,
|
|
3528
|
-
limit,
|
|
3529
|
-
offset,
|
|
3530
|
-
resourceId
|
|
3531
|
-
} = {}) {
|
|
3532
|
-
return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
|
|
3225
|
+
async listWorkflowRuns(args = {}) {
|
|
3226
|
+
return this.stores.workflows.listWorkflowRuns(args);
|
|
3533
3227
|
}
|
|
3534
3228
|
async getWorkflowRunById({
|
|
3535
3229
|
runId,
|
|
@@ -3556,12 +3250,12 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3556
3250
|
return this.stores.operations.dropIndex(indexName);
|
|
3557
3251
|
}
|
|
3558
3252
|
/**
|
|
3559
|
-
*
|
|
3253
|
+
* Tracing / Observability
|
|
3560
3254
|
*/
|
|
3561
3255
|
getObservabilityStore() {
|
|
3562
3256
|
if (!this.stores.observability) {
|
|
3563
3257
|
throw new MastraError({
|
|
3564
|
-
id: "
|
|
3258
|
+
id: createStorageErrorId("MSSQL", "OBSERVABILITY", "NOT_INITIALIZED"),
|
|
3565
3259
|
domain: ErrorDomain.STORAGE,
|
|
3566
3260
|
category: ErrorCategory.SYSTEM,
|
|
3567
3261
|
text: "Observability storage is not initialized"
|
|
@@ -3569,30 +3263,30 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3569
3263
|
}
|
|
3570
3264
|
return this.stores.observability;
|
|
3571
3265
|
}
|
|
3572
|
-
async
|
|
3573
|
-
return this.getObservabilityStore().
|
|
3266
|
+
async createSpan(span) {
|
|
3267
|
+
return this.getObservabilityStore().createSpan(span);
|
|
3574
3268
|
}
|
|
3575
|
-
async
|
|
3269
|
+
async updateSpan({
|
|
3576
3270
|
spanId,
|
|
3577
3271
|
traceId,
|
|
3578
3272
|
updates
|
|
3579
3273
|
}) {
|
|
3580
|
-
return this.getObservabilityStore().
|
|
3274
|
+
return this.getObservabilityStore().updateSpan({ spanId, traceId, updates });
|
|
3581
3275
|
}
|
|
3582
|
-
async
|
|
3583
|
-
return this.getObservabilityStore().
|
|
3276
|
+
async getTrace(traceId) {
|
|
3277
|
+
return this.getObservabilityStore().getTrace(traceId);
|
|
3584
3278
|
}
|
|
3585
|
-
async
|
|
3586
|
-
return this.getObservabilityStore().
|
|
3279
|
+
async getTracesPaginated(args) {
|
|
3280
|
+
return this.getObservabilityStore().getTracesPaginated(args);
|
|
3587
3281
|
}
|
|
3588
|
-
async
|
|
3589
|
-
return this.getObservabilityStore().
|
|
3282
|
+
async batchCreateSpans(args) {
|
|
3283
|
+
return this.getObservabilityStore().batchCreateSpans(args);
|
|
3590
3284
|
}
|
|
3591
|
-
async
|
|
3592
|
-
return this.getObservabilityStore().
|
|
3285
|
+
async batchUpdateSpans(args) {
|
|
3286
|
+
return this.getObservabilityStore().batchUpdateSpans(args);
|
|
3593
3287
|
}
|
|
3594
|
-
async
|
|
3595
|
-
return this.getObservabilityStore().
|
|
3288
|
+
async batchDeleteTraces(args) {
|
|
3289
|
+
return this.getObservabilityStore().batchDeleteTraces(args);
|
|
3596
3290
|
}
|
|
3597
3291
|
/**
|
|
3598
3292
|
* Scorers
|
|
@@ -3600,14 +3294,14 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3600
3294
|
async getScoreById({ id: _id }) {
|
|
3601
3295
|
return this.stores.scores.getScoreById({ id: _id });
|
|
3602
3296
|
}
|
|
3603
|
-
async
|
|
3297
|
+
async listScoresByScorerId({
|
|
3604
3298
|
scorerId: _scorerId,
|
|
3605
3299
|
pagination: _pagination,
|
|
3606
3300
|
entityId: _entityId,
|
|
3607
3301
|
entityType: _entityType,
|
|
3608
3302
|
source: _source
|
|
3609
3303
|
}) {
|
|
3610
|
-
return this.stores.scores.
|
|
3304
|
+
return this.stores.scores.listScoresByScorerId({
|
|
3611
3305
|
scorerId: _scorerId,
|
|
3612
3306
|
pagination: _pagination,
|
|
3613
3307
|
entityId: _entityId,
|
|
@@ -3615,32 +3309,32 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3615
3309
|
source: _source
|
|
3616
3310
|
});
|
|
3617
3311
|
}
|
|
3618
|
-
async saveScore(
|
|
3619
|
-
return this.stores.scores.saveScore(
|
|
3312
|
+
async saveScore(score) {
|
|
3313
|
+
return this.stores.scores.saveScore(score);
|
|
3620
3314
|
}
|
|
3621
|
-
async
|
|
3315
|
+
async listScoresByRunId({
|
|
3622
3316
|
runId: _runId,
|
|
3623
3317
|
pagination: _pagination
|
|
3624
3318
|
}) {
|
|
3625
|
-
return this.stores.scores.
|
|
3319
|
+
return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
|
|
3626
3320
|
}
|
|
3627
|
-
async
|
|
3321
|
+
async listScoresByEntityId({
|
|
3628
3322
|
entityId: _entityId,
|
|
3629
3323
|
entityType: _entityType,
|
|
3630
3324
|
pagination: _pagination
|
|
3631
3325
|
}) {
|
|
3632
|
-
return this.stores.scores.
|
|
3326
|
+
return this.stores.scores.listScoresByEntityId({
|
|
3633
3327
|
entityId: _entityId,
|
|
3634
3328
|
entityType: _entityType,
|
|
3635
3329
|
pagination: _pagination
|
|
3636
3330
|
});
|
|
3637
3331
|
}
|
|
3638
|
-
async
|
|
3332
|
+
async listScoresBySpan({
|
|
3639
3333
|
traceId,
|
|
3640
3334
|
spanId,
|
|
3641
3335
|
pagination: _pagination
|
|
3642
3336
|
}) {
|
|
3643
|
-
return this.stores.scores.
|
|
3337
|
+
return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination: _pagination });
|
|
3644
3338
|
}
|
|
3645
3339
|
};
|
|
3646
3340
|
|