@mastra/mssql 0.0.0-new-scorer-api-20250801075530 → 0.0.0-partial-response-backport-20251204204441
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 +548 -4
- package/README.md +315 -36
- package/dist/index.cjs +2956 -1125
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2956 -1125
- package/dist/index.js.map +1 -1
- package/dist/storage/domains/legacy-evals/index.d.ts +20 -0
- package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +98 -0
- package/dist/storage/domains/memory/index.d.ts.map +1 -0
- package/dist/storage/domains/observability/index.d.ts +44 -0
- package/dist/storage/domains/observability/index.d.ts.map +1 -0
- package/dist/storage/domains/operations/index.d.ts +114 -0
- package/dist/storage/domains/operations/index.d.ts.map +1 -0
- package/dist/storage/domains/scores/index.d.ts +55 -0
- package/dist/storage/domains/scores/index.d.ts.map +1 -0
- package/dist/storage/domains/traces/index.d.ts +37 -0
- package/dist/storage/domains/traces/index.d.ts.map +1 -0
- package/dist/storage/domains/utils.d.ts +25 -0
- package/dist/storage/domains/utils.d.ts.map +1 -0
- package/dist/storage/domains/workflows/index.d.ts +49 -0
- package/dist/storage/domains/workflows/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +144 -87
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +31 -10
- package/docker-compose.yaml +0 -14
- package/eslint.config.js +0 -6
- package/src/index.ts +0 -2
- package/src/storage/index.test.ts +0 -2228
- package/src/storage/index.ts +0 -2136
- package/tsconfig.build.json +0 -9
- package/tsconfig.json +0 -5
- package/tsup.config.ts +0 -22
- package/vitest.config.ts +0 -12
package/dist/index.js
CHANGED
|
@@ -1,127 +1,125 @@
|
|
|
1
|
-
import { MessageList } from '@mastra/core/agent';
|
|
2
1
|
import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
|
|
3
|
-
import { MastraStorage,
|
|
2
|
+
import { MastraStorage, LegacyEvalsStorage, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_TRACES, TABLE_EVALS, TABLE_SCORERS, TABLE_AI_SPANS, ScoresStorage, TracesStorage, WorkflowsStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ObservabilityStorage, safelyParseJSON } from '@mastra/core/storage';
|
|
3
|
+
import sql3 from 'mssql';
|
|
4
4
|
import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
|
|
5
|
-
import
|
|
5
|
+
import { MessageList } from '@mastra/core/agent';
|
|
6
|
+
import { randomUUID } from 'crypto';
|
|
7
|
+
import { saveScorePayloadSchema } from '@mastra/core/scores';
|
|
6
8
|
|
|
7
9
|
// src/storage/index.ts
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
} else {
|
|
22
|
-
const required = ["server", "database", "user", "password"];
|
|
23
|
-
for (const key of required) {
|
|
24
|
-
if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
|
|
25
|
-
throw new Error(`MSSQLStore: ${key} must be provided and cannot be empty.`);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
this.schema = config.schemaName;
|
|
30
|
-
this.pool = "connectionString" in config ? new sql.ConnectionPool(config.connectionString) : new sql.ConnectionPool({
|
|
31
|
-
server: config.server,
|
|
32
|
-
database: config.database,
|
|
33
|
-
user: config.user,
|
|
34
|
-
password: config.password,
|
|
35
|
-
port: config.port,
|
|
36
|
-
options: config.options || { encrypt: true, trustServerCertificate: true }
|
|
37
|
-
});
|
|
38
|
-
} catch (e) {
|
|
39
|
-
throw new MastraError(
|
|
40
|
-
{
|
|
41
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_INITIALIZATION_FAILED",
|
|
42
|
-
domain: ErrorDomain.STORAGE,
|
|
43
|
-
category: ErrorCategory.USER
|
|
44
|
-
},
|
|
45
|
-
e
|
|
46
|
-
);
|
|
47
|
-
}
|
|
10
|
+
function getSchemaName(schema) {
|
|
11
|
+
return schema ? `[${parseSqlIdentifier(schema, "schema name")}]` : void 0;
|
|
12
|
+
}
|
|
13
|
+
function getTableName({ indexName, schemaName }) {
|
|
14
|
+
const parsedIndexName = parseSqlIdentifier(indexName, "index name");
|
|
15
|
+
const quotedIndexName = `[${parsedIndexName}]`;
|
|
16
|
+
const quotedSchemaName = schemaName;
|
|
17
|
+
return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
|
|
18
|
+
}
|
|
19
|
+
function buildDateRangeFilter(dateRange, fieldName) {
|
|
20
|
+
const filters = {};
|
|
21
|
+
if (dateRange?.start) {
|
|
22
|
+
filters[`${fieldName}_gte`] = dateRange.start;
|
|
48
23
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
this.isConnected = this._performInitializationAndStore();
|
|
52
|
-
}
|
|
53
|
-
try {
|
|
54
|
-
await this.isConnected;
|
|
55
|
-
await super.init();
|
|
56
|
-
} catch (error) {
|
|
57
|
-
this.isConnected = null;
|
|
58
|
-
throw new MastraError(
|
|
59
|
-
{
|
|
60
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_INIT_FAILED",
|
|
61
|
-
domain: ErrorDomain.STORAGE,
|
|
62
|
-
category: ErrorCategory.THIRD_PARTY
|
|
63
|
-
},
|
|
64
|
-
error
|
|
65
|
-
);
|
|
66
|
-
}
|
|
24
|
+
if (dateRange?.end) {
|
|
25
|
+
filters[`${fieldName}_lte`] = dateRange.end;
|
|
67
26
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
27
|
+
return filters;
|
|
28
|
+
}
|
|
29
|
+
function prepareWhereClause(filters, _schema) {
|
|
30
|
+
const conditions = [];
|
|
31
|
+
const params = {};
|
|
32
|
+
let paramIndex = 1;
|
|
33
|
+
Object.entries(filters).forEach(([key, value]) => {
|
|
34
|
+
if (value === void 0) return;
|
|
35
|
+
const paramName = `p${paramIndex++}`;
|
|
36
|
+
if (key.endsWith("_gte")) {
|
|
37
|
+
const fieldName = key.slice(0, -4);
|
|
38
|
+
conditions.push(`[${parseSqlIdentifier(fieldName, "field name")}] >= @${paramName}`);
|
|
39
|
+
params[paramName] = value instanceof Date ? value.toISOString() : value;
|
|
40
|
+
} else if (key.endsWith("_lte")) {
|
|
41
|
+
const fieldName = key.slice(0, -4);
|
|
42
|
+
conditions.push(`[${parseSqlIdentifier(fieldName, "field name")}] <= @${paramName}`);
|
|
43
|
+
params[paramName] = value instanceof Date ? value.toISOString() : value;
|
|
44
|
+
} else if (value === null) {
|
|
45
|
+
conditions.push(`[${parseSqlIdentifier(key, "field name")}] IS NULL`);
|
|
46
|
+
} else {
|
|
47
|
+
conditions.push(`[${parseSqlIdentifier(key, "field name")}] = @${paramName}`);
|
|
48
|
+
params[paramName] = value instanceof Date ? value.toISOString() : value;
|
|
74
49
|
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
}
|
|
91
|
-
getSchemaName() {
|
|
92
|
-
return this.schema ? `[${parseSqlIdentifier(this.schema, "schema name")}]` : void 0;
|
|
93
|
-
}
|
|
94
|
-
transformEvalRow(row) {
|
|
95
|
-
let testInfoValue = null, resultValue = null;
|
|
96
|
-
if (row.test_info) {
|
|
50
|
+
});
|
|
51
|
+
return {
|
|
52
|
+
sql: conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "",
|
|
53
|
+
params
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function transformFromSqlRow({
|
|
57
|
+
tableName,
|
|
58
|
+
sqlRow
|
|
59
|
+
}) {
|
|
60
|
+
const schema = TABLE_SCHEMAS[tableName];
|
|
61
|
+
const result = {};
|
|
62
|
+
Object.entries(sqlRow).forEach(([key, value]) => {
|
|
63
|
+
const columnSchema = schema?.[key];
|
|
64
|
+
if (columnSchema?.type === "jsonb" && typeof value === "string") {
|
|
97
65
|
try {
|
|
98
|
-
|
|
66
|
+
result[key] = JSON.parse(value);
|
|
99
67
|
} catch {
|
|
68
|
+
result[key] = value;
|
|
100
69
|
}
|
|
70
|
+
} else if (columnSchema?.type === "timestamp" && value && typeof value === "string") {
|
|
71
|
+
result[key] = new Date(value);
|
|
72
|
+
} else if (columnSchema?.type === "timestamp" && value instanceof Date) {
|
|
73
|
+
result[key] = value;
|
|
74
|
+
} else if (columnSchema?.type === "boolean") {
|
|
75
|
+
result[key] = Boolean(value);
|
|
76
|
+
} else {
|
|
77
|
+
result[key] = value;
|
|
101
78
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
79
|
+
});
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/storage/domains/legacy-evals/index.ts
|
|
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 {
|
|
107
96
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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;
|
|
120
118
|
}
|
|
121
119
|
/** @deprecated use getEvals instead */
|
|
122
120
|
async getEvalsByAgentName(agentName, type) {
|
|
123
121
|
try {
|
|
124
|
-
let query = `SELECT * FROM ${
|
|
122
|
+
let query = `SELECT * FROM ${getTableName({ indexName: TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
|
|
125
123
|
if (type === "test") {
|
|
126
124
|
query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
|
|
127
125
|
} else if (type === "live") {
|
|
@@ -132,606 +130,283 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
132
130
|
request.input("p1", agentName);
|
|
133
131
|
const result = await request.query(query);
|
|
134
132
|
const rows = result.recordset;
|
|
135
|
-
return typeof
|
|
133
|
+
return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
|
|
136
134
|
} catch (error) {
|
|
137
135
|
if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
|
|
138
136
|
return [];
|
|
139
137
|
}
|
|
140
|
-
|
|
138
|
+
this.logger?.error?.("Failed to get evals for the specified agent:", error);
|
|
141
139
|
throw error;
|
|
142
140
|
}
|
|
143
141
|
}
|
|
144
|
-
async
|
|
145
|
-
const
|
|
146
|
-
try {
|
|
147
|
-
await transaction.begin();
|
|
148
|
-
for (const record of records) {
|
|
149
|
-
await this.insert({ tableName, record });
|
|
150
|
-
}
|
|
151
|
-
await transaction.commit();
|
|
152
|
-
} catch (error) {
|
|
153
|
-
await transaction.rollback();
|
|
154
|
-
throw new MastraError(
|
|
155
|
-
{
|
|
156
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
|
|
157
|
-
domain: ErrorDomain.STORAGE,
|
|
158
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
159
|
-
details: {
|
|
160
|
-
tableName,
|
|
161
|
-
numberOfRecords: records.length
|
|
162
|
-
}
|
|
163
|
-
},
|
|
164
|
-
error
|
|
165
|
-
);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
/** @deprecated use getTracesPaginated instead*/
|
|
169
|
-
async getTraces(args) {
|
|
170
|
-
if (args.fromDate || args.toDate) {
|
|
171
|
-
args.dateRange = {
|
|
172
|
-
start: args.fromDate,
|
|
173
|
-
end: args.toDate
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
const result = await this.getTracesPaginated(args);
|
|
177
|
-
return result.traces;
|
|
178
|
-
}
|
|
179
|
-
async getTracesPaginated(args) {
|
|
180
|
-
const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
|
|
142
|
+
async getEvals(options = {}) {
|
|
143
|
+
const { agentName, type, page = 0, perPage = 100, dateRange } = options;
|
|
181
144
|
const fromDate = dateRange?.start;
|
|
182
145
|
const toDate = dateRange?.end;
|
|
183
|
-
const
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
if (name) {
|
|
189
|
-
const paramName = `p${paramIndex++}`;
|
|
190
|
-
conditions.push(`[name] LIKE @${paramName}`);
|
|
191
|
-
paramMap[paramName] = `${name}%`;
|
|
192
|
-
}
|
|
193
|
-
if (scope) {
|
|
194
|
-
const paramName = `p${paramIndex++}`;
|
|
195
|
-
conditions.push(`[scope] = @${paramName}`);
|
|
196
|
-
paramMap[paramName] = scope;
|
|
197
|
-
}
|
|
198
|
-
if (attributes) {
|
|
199
|
-
Object.entries(attributes).forEach(([key, value]) => {
|
|
200
|
-
const parsedKey = parseFieldKey(key);
|
|
201
|
-
const paramName = `p${paramIndex++}`;
|
|
202
|
-
conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
|
|
203
|
-
paramMap[paramName] = value;
|
|
204
|
-
});
|
|
146
|
+
const where = [];
|
|
147
|
+
const params = {};
|
|
148
|
+
if (agentName) {
|
|
149
|
+
where.push("agent_name = @agentName");
|
|
150
|
+
params["agentName"] = agentName;
|
|
205
151
|
}
|
|
206
|
-
if (
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
conditions.push(`[${parsedKey}] = @${paramName}`);
|
|
211
|
-
paramMap[paramName] = value;
|
|
212
|
-
});
|
|
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)");
|
|
213
156
|
}
|
|
214
157
|
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
paramMap[paramName] = fromDate.toISOString();
|
|
158
|
+
where.push(`[created_at] >= @fromDate`);
|
|
159
|
+
params[`fromDate`] = fromDate.toISOString();
|
|
218
160
|
}
|
|
219
161
|
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
paramMap[paramName] = toDate.toISOString();
|
|
162
|
+
where.push(`[created_at] <= @toDate`);
|
|
163
|
+
params[`toDate`] = toDate.toISOString();
|
|
223
164
|
}
|
|
224
|
-
const whereClause =
|
|
225
|
-
const
|
|
226
|
-
|
|
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`;
|
|
227
170
|
try {
|
|
228
|
-
const
|
|
229
|
-
Object.entries(
|
|
171
|
+
const countReq = this.pool.request();
|
|
172
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
230
173
|
if (value instanceof Date) {
|
|
231
|
-
|
|
174
|
+
countReq.input(key, sql3.DateTime, value);
|
|
232
175
|
} else {
|
|
233
|
-
|
|
176
|
+
countReq.input(key, value);
|
|
234
177
|
}
|
|
235
178
|
});
|
|
236
|
-
const countResult = await
|
|
237
|
-
total =
|
|
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
|
+
};
|
|
238
209
|
} catch (error) {
|
|
239
|
-
|
|
210
|
+
const mastraError = new MastraError(
|
|
240
211
|
{
|
|
241
|
-
id: "
|
|
212
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
|
|
242
213
|
domain: ErrorDomain.STORAGE,
|
|
243
214
|
category: ErrorCategory.THIRD_PARTY,
|
|
244
215
|
details: {
|
|
245
|
-
|
|
246
|
-
|
|
216
|
+
agentName: agentName || "all",
|
|
217
|
+
type: type || "all",
|
|
218
|
+
page,
|
|
219
|
+
perPage
|
|
247
220
|
}
|
|
248
221
|
},
|
|
249
222
|
error
|
|
250
223
|
);
|
|
224
|
+
this.logger?.error?.(mastraError.toString());
|
|
225
|
+
this.logger?.trackException?.(mastraError);
|
|
226
|
+
throw mastraError;
|
|
251
227
|
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
} else {
|
|
267
|
-
dataRequest.input(key, value);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
var MemoryMSSQL = class extends MemoryStorage {
|
|
231
|
+
pool;
|
|
232
|
+
schema;
|
|
233
|
+
operations;
|
|
234
|
+
_parseAndFormatMessages(messages, format) {
|
|
235
|
+
const messagesWithParsedContent = messages.map((message) => {
|
|
236
|
+
if (typeof message.content === "string") {
|
|
237
|
+
try {
|
|
238
|
+
return { ...message, content: JSON.parse(message.content) };
|
|
239
|
+
} catch {
|
|
240
|
+
return message;
|
|
241
|
+
}
|
|
268
242
|
}
|
|
243
|
+
return message;
|
|
269
244
|
});
|
|
270
|
-
|
|
271
|
-
|
|
245
|
+
const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
|
|
246
|
+
const list = new MessageList().add(cleanMessages, "memory");
|
|
247
|
+
return format === "v2" ? list.get.all.v2() : list.get.all.v1();
|
|
248
|
+
}
|
|
249
|
+
constructor({
|
|
250
|
+
pool,
|
|
251
|
+
schema,
|
|
252
|
+
operations
|
|
253
|
+
}) {
|
|
254
|
+
super();
|
|
255
|
+
this.pool = pool;
|
|
256
|
+
this.schema = schema;
|
|
257
|
+
this.operations = operations;
|
|
258
|
+
}
|
|
259
|
+
async getThreadById({ threadId }) {
|
|
272
260
|
try {
|
|
273
|
-
const
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
createdAt: row.createdAt
|
|
290
|
-
}));
|
|
261
|
+
const sql7 = `SELECT
|
|
262
|
+
id,
|
|
263
|
+
[resourceId],
|
|
264
|
+
title,
|
|
265
|
+
metadata,
|
|
266
|
+
[createdAt],
|
|
267
|
+
[updatedAt]
|
|
268
|
+
FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })}
|
|
269
|
+
WHERE id = @threadId`;
|
|
270
|
+
const request = this.pool.request();
|
|
271
|
+
request.input("threadId", threadId);
|
|
272
|
+
const resultSet = await request.query(sql7);
|
|
273
|
+
const thread = resultSet.recordset[0] || null;
|
|
274
|
+
if (!thread) {
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
291
277
|
return {
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
hasMore: currentOffset + traces.length < total
|
|
278
|
+
...thread,
|
|
279
|
+
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
280
|
+
createdAt: thread.createdAt,
|
|
281
|
+
updatedAt: thread.updatedAt
|
|
297
282
|
};
|
|
298
283
|
} catch (error) {
|
|
299
284
|
throw new MastraError(
|
|
300
285
|
{
|
|
301
|
-
id: "
|
|
286
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
|
|
302
287
|
domain: ErrorDomain.STORAGE,
|
|
303
288
|
category: ErrorCategory.THIRD_PARTY,
|
|
304
289
|
details: {
|
|
305
|
-
|
|
306
|
-
scope: args.scope ?? ""
|
|
290
|
+
threadId
|
|
307
291
|
}
|
|
308
292
|
},
|
|
309
293
|
error
|
|
310
294
|
);
|
|
311
295
|
}
|
|
312
296
|
}
|
|
313
|
-
async
|
|
314
|
-
|
|
315
|
-
return;
|
|
316
|
-
}
|
|
317
|
-
if (!this.setupSchemaPromise) {
|
|
318
|
-
this.setupSchemaPromise = (async () => {
|
|
319
|
-
try {
|
|
320
|
-
const checkRequest = this.pool.request();
|
|
321
|
-
checkRequest.input("schemaName", this.schema);
|
|
322
|
-
const checkResult = await checkRequest.query(`
|
|
323
|
-
SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
|
|
324
|
-
`);
|
|
325
|
-
const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
|
|
326
|
-
if (!schemaExists) {
|
|
327
|
-
try {
|
|
328
|
-
await this.pool.request().query(`CREATE SCHEMA [${this.schema}]`);
|
|
329
|
-
this.logger?.info?.(`Schema "${this.schema}" created successfully`);
|
|
330
|
-
} catch (error) {
|
|
331
|
-
this.logger?.error?.(`Failed to create schema "${this.schema}"`, { error });
|
|
332
|
-
throw new Error(
|
|
333
|
-
`Unable to create schema "${this.schema}". This requires CREATE privilege on the database. Either create the schema manually or grant CREATE privilege to the user.`
|
|
334
|
-
);
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
this.schemaSetupComplete = true;
|
|
338
|
-
this.logger?.debug?.(`Schema "${this.schema}" is ready for use`);
|
|
339
|
-
} catch (error) {
|
|
340
|
-
this.schemaSetupComplete = void 0;
|
|
341
|
-
this.setupSchemaPromise = null;
|
|
342
|
-
throw error;
|
|
343
|
-
} finally {
|
|
344
|
-
this.setupSchemaPromise = null;
|
|
345
|
-
}
|
|
346
|
-
})();
|
|
347
|
-
}
|
|
348
|
-
await this.setupSchemaPromise;
|
|
349
|
-
}
|
|
350
|
-
getSqlType(type, isPrimaryKey = false) {
|
|
351
|
-
switch (type) {
|
|
352
|
-
case "text":
|
|
353
|
-
return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(MAX)";
|
|
354
|
-
case "timestamp":
|
|
355
|
-
return "DATETIME2(7)";
|
|
356
|
-
case "uuid":
|
|
357
|
-
return "UNIQUEIDENTIFIER";
|
|
358
|
-
case "jsonb":
|
|
359
|
-
return "NVARCHAR(MAX)";
|
|
360
|
-
case "integer":
|
|
361
|
-
return "INT";
|
|
362
|
-
case "bigint":
|
|
363
|
-
return "BIGINT";
|
|
364
|
-
default:
|
|
365
|
-
throw new MastraError({
|
|
366
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
|
|
367
|
-
domain: ErrorDomain.STORAGE,
|
|
368
|
-
category: ErrorCategory.THIRD_PARTY
|
|
369
|
-
});
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
async createTable({
|
|
373
|
-
tableName,
|
|
374
|
-
schema
|
|
375
|
-
}) {
|
|
297
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
298
|
+
const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
|
|
376
299
|
try {
|
|
377
|
-
const
|
|
378
|
-
const
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
const checkTableResult = await checkTableRequest.query(checkTableSql);
|
|
394
|
-
const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
|
|
395
|
-
if (!tableExists) {
|
|
396
|
-
const createSql = `CREATE TABLE ${this.getTableName(tableName)} (
|
|
397
|
-
${columns}
|
|
398
|
-
)`;
|
|
399
|
-
await this.pool.request().query(createSql);
|
|
400
|
-
}
|
|
401
|
-
const columnCheckSql = `
|
|
402
|
-
SELECT 1 AS found
|
|
403
|
-
FROM INFORMATION_SCHEMA.COLUMNS
|
|
404
|
-
WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
|
|
405
|
-
`;
|
|
406
|
-
const checkColumnRequest = this.pool.request();
|
|
407
|
-
checkColumnRequest.input("schema", this.schema || "dbo");
|
|
408
|
-
checkColumnRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
|
|
409
|
-
const columnResult = await checkColumnRequest.query(columnCheckSql);
|
|
410
|
-
const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
|
|
411
|
-
if (!columnExists) {
|
|
412
|
-
const alterSql = `ALTER TABLE ${this.getTableName(tableName)} ADD seq_id BIGINT IDENTITY(1,1)`;
|
|
413
|
-
await this.pool.request().query(alterSql);
|
|
414
|
-
}
|
|
415
|
-
if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
|
|
416
|
-
const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
|
|
417
|
-
const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
|
|
418
|
-
const checkConstraintRequest = this.pool.request();
|
|
419
|
-
checkConstraintRequest.input("constraintName", constraintName);
|
|
420
|
-
const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
|
|
421
|
-
const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
|
|
422
|
-
if (!constraintExists) {
|
|
423
|
-
const addConstraintSql = `ALTER TABLE ${this.getTableName(tableName)} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
|
|
424
|
-
await this.pool.request().query(addConstraintSql);
|
|
425
|
-
}
|
|
300
|
+
const perPage = perPageInput !== void 0 ? perPageInput : 100;
|
|
301
|
+
const currentOffset = page * perPage;
|
|
302
|
+
const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
|
|
303
|
+
const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
|
|
304
|
+
const countRequest = this.pool.request();
|
|
305
|
+
countRequest.input("resourceId", resourceId);
|
|
306
|
+
const countResult = await countRequest.query(countQuery);
|
|
307
|
+
const total = parseInt(countResult.recordset[0]?.count ?? "0", 10);
|
|
308
|
+
if (total === 0) {
|
|
309
|
+
return {
|
|
310
|
+
threads: [],
|
|
311
|
+
total: 0,
|
|
312
|
+
page,
|
|
313
|
+
perPage,
|
|
314
|
+
hasMore: false
|
|
315
|
+
};
|
|
426
316
|
}
|
|
317
|
+
const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
|
|
318
|
+
const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
|
|
319
|
+
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
320
|
+
const dataRequest = this.pool.request();
|
|
321
|
+
dataRequest.input("resourceId", resourceId);
|
|
322
|
+
dataRequest.input("perPage", perPage);
|
|
323
|
+
dataRequest.input("offset", currentOffset);
|
|
324
|
+
const rowsResult = await dataRequest.query(dataQuery);
|
|
325
|
+
const rows = rowsResult.recordset || [];
|
|
326
|
+
const threads = rows.map((thread) => ({
|
|
327
|
+
...thread,
|
|
328
|
+
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
329
|
+
createdAt: thread.createdAt,
|
|
330
|
+
updatedAt: thread.updatedAt
|
|
331
|
+
}));
|
|
332
|
+
return {
|
|
333
|
+
threads,
|
|
334
|
+
total,
|
|
335
|
+
page,
|
|
336
|
+
perPage,
|
|
337
|
+
hasMore: currentOffset + threads.length < total
|
|
338
|
+
};
|
|
427
339
|
} catch (error) {
|
|
428
|
-
|
|
340
|
+
const mastraError = new MastraError(
|
|
429
341
|
{
|
|
430
|
-
id: "
|
|
342
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
|
|
431
343
|
domain: ErrorDomain.STORAGE,
|
|
432
344
|
category: ErrorCategory.THIRD_PARTY,
|
|
433
345
|
details: {
|
|
434
|
-
|
|
346
|
+
resourceId,
|
|
347
|
+
page
|
|
435
348
|
}
|
|
436
349
|
},
|
|
437
350
|
error
|
|
438
351
|
);
|
|
352
|
+
this.logger?.error?.(mastraError.toString());
|
|
353
|
+
this.logger?.trackException?.(mastraError);
|
|
354
|
+
return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
|
|
439
355
|
}
|
|
440
356
|
}
|
|
441
|
-
|
|
442
|
-
switch (type) {
|
|
443
|
-
case "timestamp":
|
|
444
|
-
return "DEFAULT SYSDATETIMEOFFSET()";
|
|
445
|
-
case "jsonb":
|
|
446
|
-
return "DEFAULT N'{}'";
|
|
447
|
-
default:
|
|
448
|
-
return super.getDefaultValue(type);
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
async alterTable({
|
|
452
|
-
tableName,
|
|
453
|
-
schema,
|
|
454
|
-
ifNotExists
|
|
455
|
-
}) {
|
|
456
|
-
const fullTableName = this.getTableName(tableName);
|
|
357
|
+
async saveThread({ thread }) {
|
|
457
358
|
try {
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
359
|
+
const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
360
|
+
const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
|
|
361
|
+
USING (SELECT @id AS id) AS source
|
|
362
|
+
ON (target.id = source.id)
|
|
363
|
+
WHEN MATCHED THEN
|
|
364
|
+
UPDATE SET
|
|
365
|
+
[resourceId] = @resourceId,
|
|
366
|
+
title = @title,
|
|
367
|
+
metadata = @metadata,
|
|
368
|
+
[updatedAt] = @updatedAt
|
|
369
|
+
WHEN NOT MATCHED THEN
|
|
370
|
+
INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
|
|
371
|
+
VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
|
|
372
|
+
const req = this.pool.request();
|
|
373
|
+
req.input("id", thread.id);
|
|
374
|
+
req.input("resourceId", thread.resourceId);
|
|
375
|
+
req.input("title", thread.title);
|
|
376
|
+
const metadata = thread.metadata ? JSON.stringify(thread.metadata) : null;
|
|
377
|
+
if (metadata === null) {
|
|
378
|
+
req.input("metadata", sql3.NVarChar, null);
|
|
379
|
+
} else {
|
|
380
|
+
req.input("metadata", metadata);
|
|
478
381
|
}
|
|
382
|
+
req.input("createdAt", sql3.DateTime2, thread.createdAt);
|
|
383
|
+
req.input("updatedAt", sql3.DateTime2, thread.updatedAt);
|
|
384
|
+
await req.query(mergeSql);
|
|
385
|
+
return thread;
|
|
479
386
|
} catch (error) {
|
|
480
387
|
throw new MastraError(
|
|
481
388
|
{
|
|
482
|
-
id: "
|
|
389
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
|
|
483
390
|
domain: ErrorDomain.STORAGE,
|
|
484
391
|
category: ErrorCategory.THIRD_PARTY,
|
|
485
392
|
details: {
|
|
486
|
-
|
|
393
|
+
threadId: thread.id
|
|
487
394
|
}
|
|
488
395
|
},
|
|
489
396
|
error
|
|
490
397
|
);
|
|
491
398
|
}
|
|
492
399
|
}
|
|
493
|
-
|
|
494
|
-
|
|
400
|
+
/**
|
|
401
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
402
|
+
*/
|
|
403
|
+
async getThreadsByResourceId(args) {
|
|
404
|
+
const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
|
|
495
405
|
try {
|
|
496
|
-
const
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
FROM sys.foreign_keys fk
|
|
501
|
-
WHERE fk.referenced_object_id = OBJECT_ID(@fullTableName)
|
|
502
|
-
`;
|
|
503
|
-
const fkResult = await this.pool.request().input("fullTableName", fullTableName).query(fkQuery);
|
|
504
|
-
const childTables = fkResult.recordset || [];
|
|
505
|
-
for (const child of childTables) {
|
|
506
|
-
const childTableName = this.schema ? `[${child.schema_name}].[${child.table_name}]` : `[${child.table_name}]`;
|
|
507
|
-
await this.clearTable({ tableName: childTableName });
|
|
508
|
-
}
|
|
509
|
-
await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
|
|
510
|
-
} catch (error) {
|
|
511
|
-
throw new MastraError(
|
|
512
|
-
{
|
|
513
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
|
|
514
|
-
domain: ErrorDomain.STORAGE,
|
|
515
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
516
|
-
details: {
|
|
517
|
-
tableName
|
|
518
|
-
}
|
|
519
|
-
},
|
|
520
|
-
error
|
|
521
|
-
);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
async insert({ tableName, record }) {
|
|
525
|
-
try {
|
|
526
|
-
const columns = Object.keys(record).map((col) => parseSqlIdentifier(col, "column name"));
|
|
527
|
-
const values = Object.values(record);
|
|
528
|
-
const paramNames = values.map((_, i) => `@param${i}`);
|
|
529
|
-
const insertSql = `INSERT INTO ${this.getTableName(tableName)} (${columns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
|
|
530
|
-
const request = this.pool.request();
|
|
531
|
-
values.forEach((value, i) => {
|
|
532
|
-
if (value instanceof Date) {
|
|
533
|
-
request.input(`param${i}`, sql.DateTime2, value);
|
|
534
|
-
} else if (typeof value === "object" && value !== null) {
|
|
535
|
-
request.input(`param${i}`, JSON.stringify(value));
|
|
536
|
-
} else {
|
|
537
|
-
request.input(`param${i}`, value);
|
|
538
|
-
}
|
|
539
|
-
});
|
|
540
|
-
await request.query(insertSql);
|
|
541
|
-
} catch (error) {
|
|
542
|
-
throw new MastraError(
|
|
543
|
-
{
|
|
544
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
|
|
545
|
-
domain: ErrorDomain.STORAGE,
|
|
546
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
547
|
-
details: {
|
|
548
|
-
tableName
|
|
549
|
-
}
|
|
550
|
-
},
|
|
551
|
-
error
|
|
552
|
-
);
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
async load({ tableName, keys }) {
|
|
556
|
-
try {
|
|
557
|
-
const keyEntries = Object.entries(keys).map(([key, value]) => [parseSqlIdentifier(key, "column name"), value]);
|
|
558
|
-
const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
|
|
559
|
-
const values = keyEntries.map(([_, value]) => value);
|
|
560
|
-
const sql2 = `SELECT * FROM ${this.getTableName(tableName)} WHERE ${conditions}`;
|
|
561
|
-
const request = this.pool.request();
|
|
562
|
-
values.forEach((value, i) => {
|
|
563
|
-
request.input(`param${i}`, value);
|
|
564
|
-
});
|
|
565
|
-
const resultSet = await request.query(sql2);
|
|
566
|
-
const result = resultSet.recordset[0] || null;
|
|
567
|
-
if (!result) {
|
|
568
|
-
return null;
|
|
569
|
-
}
|
|
570
|
-
if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
|
|
571
|
-
const snapshot = result;
|
|
572
|
-
if (typeof snapshot.snapshot === "string") {
|
|
573
|
-
snapshot.snapshot = JSON.parse(snapshot.snapshot);
|
|
574
|
-
}
|
|
575
|
-
return snapshot;
|
|
576
|
-
}
|
|
577
|
-
return result;
|
|
578
|
-
} catch (error) {
|
|
579
|
-
throw new MastraError(
|
|
580
|
-
{
|
|
581
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
|
|
582
|
-
domain: ErrorDomain.STORAGE,
|
|
583
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
584
|
-
details: {
|
|
585
|
-
tableName
|
|
586
|
-
}
|
|
587
|
-
},
|
|
588
|
-
error
|
|
589
|
-
);
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
async getThreadById({ threadId }) {
|
|
593
|
-
try {
|
|
594
|
-
const sql2 = `SELECT
|
|
595
|
-
id,
|
|
596
|
-
[resourceId],
|
|
597
|
-
title,
|
|
598
|
-
metadata,
|
|
599
|
-
[createdAt],
|
|
600
|
-
[updatedAt]
|
|
601
|
-
FROM ${this.getTableName(TABLE_THREADS)}
|
|
602
|
-
WHERE id = @threadId`;
|
|
603
|
-
const request = this.pool.request();
|
|
604
|
-
request.input("threadId", threadId);
|
|
605
|
-
const resultSet = await request.query(sql2);
|
|
606
|
-
const thread = resultSet.recordset[0] || null;
|
|
607
|
-
if (!thread) {
|
|
608
|
-
return null;
|
|
609
|
-
}
|
|
610
|
-
return {
|
|
611
|
-
...thread,
|
|
612
|
-
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
613
|
-
createdAt: thread.createdAt,
|
|
614
|
-
updatedAt: thread.updatedAt
|
|
615
|
-
};
|
|
616
|
-
} catch (error) {
|
|
617
|
-
throw new MastraError(
|
|
618
|
-
{
|
|
619
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
|
|
620
|
-
domain: ErrorDomain.STORAGE,
|
|
621
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
622
|
-
details: {
|
|
623
|
-
threadId
|
|
624
|
-
}
|
|
625
|
-
},
|
|
626
|
-
error
|
|
627
|
-
);
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
async getThreadsByResourceIdPaginated(args) {
|
|
631
|
-
const { resourceId, page = 0, perPage: perPageInput } = args;
|
|
632
|
-
try {
|
|
633
|
-
const perPage = perPageInput !== void 0 ? perPageInput : 100;
|
|
634
|
-
const currentOffset = page * perPage;
|
|
635
|
-
const baseQuery = `FROM ${this.getTableName(TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
|
|
636
|
-
const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
|
|
637
|
-
const countRequest = this.pool.request();
|
|
638
|
-
countRequest.input("resourceId", resourceId);
|
|
639
|
-
const countResult = await countRequest.query(countQuery);
|
|
640
|
-
const total = parseInt(countResult.recordset[0]?.count ?? "0", 10);
|
|
641
|
-
if (total === 0) {
|
|
642
|
-
return {
|
|
643
|
-
threads: [],
|
|
644
|
-
total: 0,
|
|
645
|
-
page,
|
|
646
|
-
perPage,
|
|
647
|
-
hasMore: false
|
|
648
|
-
};
|
|
649
|
-
}
|
|
650
|
-
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
651
|
-
const dataRequest = this.pool.request();
|
|
652
|
-
dataRequest.input("resourceId", resourceId);
|
|
653
|
-
dataRequest.input("perPage", perPage);
|
|
654
|
-
dataRequest.input("offset", currentOffset);
|
|
655
|
-
const rowsResult = await dataRequest.query(dataQuery);
|
|
656
|
-
const rows = rowsResult.recordset || [];
|
|
657
|
-
const threads = rows.map((thread) => ({
|
|
658
|
-
...thread,
|
|
659
|
-
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
660
|
-
createdAt: thread.createdAt,
|
|
661
|
-
updatedAt: thread.updatedAt
|
|
662
|
-
}));
|
|
663
|
-
return {
|
|
664
|
-
threads,
|
|
665
|
-
total,
|
|
666
|
-
page,
|
|
667
|
-
perPage,
|
|
668
|
-
hasMore: currentOffset + threads.length < total
|
|
669
|
-
};
|
|
670
|
-
} catch (error) {
|
|
671
|
-
const mastraError = new MastraError(
|
|
672
|
-
{
|
|
673
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
|
|
674
|
-
domain: ErrorDomain.STORAGE,
|
|
675
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
676
|
-
details: {
|
|
677
|
-
resourceId,
|
|
678
|
-
page
|
|
679
|
-
}
|
|
680
|
-
},
|
|
681
|
-
error
|
|
682
|
-
);
|
|
683
|
-
this.logger?.error?.(mastraError.toString());
|
|
684
|
-
this.logger?.trackException?.(mastraError);
|
|
685
|
-
return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
async saveThread({ thread }) {
|
|
689
|
-
try {
|
|
690
|
-
const table = this.getTableName(TABLE_THREADS);
|
|
691
|
-
const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
|
|
692
|
-
USING (SELECT @id AS id) AS source
|
|
693
|
-
ON (target.id = source.id)
|
|
694
|
-
WHEN MATCHED THEN
|
|
695
|
-
UPDATE SET
|
|
696
|
-
[resourceId] = @resourceId,
|
|
697
|
-
title = @title,
|
|
698
|
-
metadata = @metadata,
|
|
699
|
-
[createdAt] = @createdAt,
|
|
700
|
-
[updatedAt] = @updatedAt
|
|
701
|
-
WHEN NOT MATCHED THEN
|
|
702
|
-
INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
|
|
703
|
-
VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
|
|
704
|
-
const req = this.pool.request();
|
|
705
|
-
req.input("id", thread.id);
|
|
706
|
-
req.input("resourceId", thread.resourceId);
|
|
707
|
-
req.input("title", thread.title);
|
|
708
|
-
req.input("metadata", thread.metadata ? JSON.stringify(thread.metadata) : null);
|
|
709
|
-
req.input("createdAt", thread.createdAt);
|
|
710
|
-
req.input("updatedAt", thread.updatedAt);
|
|
711
|
-
await req.query(mergeSql);
|
|
712
|
-
return thread;
|
|
713
|
-
} catch (error) {
|
|
714
|
-
throw new MastraError(
|
|
715
|
-
{
|
|
716
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
|
|
717
|
-
domain: ErrorDomain.STORAGE,
|
|
718
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
719
|
-
details: {
|
|
720
|
-
threadId: thread.id
|
|
721
|
-
}
|
|
722
|
-
},
|
|
723
|
-
error
|
|
724
|
-
);
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
/**
|
|
728
|
-
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
729
|
-
*/
|
|
730
|
-
async getThreadsByResourceId(args) {
|
|
731
|
-
const { resourceId } = args;
|
|
732
|
-
try {
|
|
733
|
-
const baseQuery = `FROM ${this.getTableName(TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
|
|
734
|
-
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC`;
|
|
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}`;
|
|
735
410
|
const request = this.pool.request();
|
|
736
411
|
request.input("resourceId", resourceId);
|
|
737
412
|
const resultSet = await request.query(dataQuery);
|
|
@@ -773,8 +448,8 @@ ${columns}
|
|
|
773
448
|
...metadata
|
|
774
449
|
};
|
|
775
450
|
try {
|
|
776
|
-
const table =
|
|
777
|
-
const
|
|
451
|
+
const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
452
|
+
const sql7 = `UPDATE ${table}
|
|
778
453
|
SET title = @title,
|
|
779
454
|
metadata = @metadata,
|
|
780
455
|
[updatedAt] = @updatedAt
|
|
@@ -784,8 +459,8 @@ ${columns}
|
|
|
784
459
|
req.input("id", id);
|
|
785
460
|
req.input("title", title);
|
|
786
461
|
req.input("metadata", JSON.stringify(mergedMetadata));
|
|
787
|
-
req.input("updatedAt",
|
|
788
|
-
const result = await req.query(
|
|
462
|
+
req.input("updatedAt", /* @__PURE__ */ new Date());
|
|
463
|
+
const result = await req.query(sql7);
|
|
789
464
|
let thread = result.recordset && result.recordset[0];
|
|
790
465
|
if (thread && "seq_id" in thread) {
|
|
791
466
|
const { seq_id, ...rest } = thread;
|
|
@@ -825,8 +500,8 @@ ${columns}
|
|
|
825
500
|
}
|
|
826
501
|
}
|
|
827
502
|
async deleteThread({ threadId }) {
|
|
828
|
-
const messagesTable =
|
|
829
|
-
const threadsTable =
|
|
503
|
+
const messagesTable = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
504
|
+
const threadsTable = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
830
505
|
const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
|
|
831
506
|
const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
|
|
832
507
|
const tx = this.pool.transaction();
|
|
@@ -858,6 +533,7 @@ ${columns}
|
|
|
858
533
|
selectBy,
|
|
859
534
|
orderByStatement
|
|
860
535
|
}) {
|
|
536
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
861
537
|
const include = selectBy?.include;
|
|
862
538
|
if (!include) return null;
|
|
863
539
|
const unionQueries = [];
|
|
@@ -884,7 +560,7 @@ ${columns}
|
|
|
884
560
|
m.seq_id
|
|
885
561
|
FROM (
|
|
886
562
|
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
887
|
-
FROM ${
|
|
563
|
+
FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
|
|
888
564
|
WHERE [thread_id] = ${pThreadId}
|
|
889
565
|
) AS m
|
|
890
566
|
WHERE m.id = ${pId}
|
|
@@ -892,7 +568,7 @@ ${columns}
|
|
|
892
568
|
SELECT 1
|
|
893
569
|
FROM (
|
|
894
570
|
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
895
|
-
FROM ${
|
|
571
|
+
FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
|
|
896
572
|
WHERE [thread_id] = ${pThreadId}
|
|
897
573
|
) AS target
|
|
898
574
|
WHERE target.id = ${pId}
|
|
@@ -929,11 +605,12 @@ ${columns}
|
|
|
929
605
|
return dedupedRows;
|
|
930
606
|
}
|
|
931
607
|
async getMessages(args) {
|
|
932
|
-
const { threadId, format, selectBy } = args;
|
|
933
|
-
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
|
|
608
|
+
const { threadId, resourceId, format, selectBy } = args;
|
|
609
|
+
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
|
|
934
610
|
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
935
|
-
const limit =
|
|
611
|
+
const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
936
612
|
try {
|
|
613
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
937
614
|
let rows = [];
|
|
938
615
|
const include = selectBy?.include || [];
|
|
939
616
|
if (include?.length) {
|
|
@@ -943,7 +620,7 @@ ${columns}
|
|
|
943
620
|
}
|
|
944
621
|
}
|
|
945
622
|
const excludeIds = rows.map((m) => m.id).filter(Boolean);
|
|
946
|
-
let query = `${selectStatement} FROM ${
|
|
623
|
+
let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
|
|
947
624
|
const request = this.pool.request();
|
|
948
625
|
request.input("threadId", threadId);
|
|
949
626
|
if (excludeIds.length > 0) {
|
|
@@ -963,30 +640,7 @@ ${columns}
|
|
|
963
640
|
return timeDiff;
|
|
964
641
|
});
|
|
965
642
|
rows = rows.map(({ seq_id, ...rest }) => rest);
|
|
966
|
-
|
|
967
|
-
if (typeof message.content === "string") {
|
|
968
|
-
try {
|
|
969
|
-
message.content = JSON.parse(message.content);
|
|
970
|
-
} catch {
|
|
971
|
-
}
|
|
972
|
-
}
|
|
973
|
-
if (format === "v1") {
|
|
974
|
-
if (Array.isArray(message.content)) ; else if (typeof message.content === "object" && message.content && Array.isArray(message.content.parts)) {
|
|
975
|
-
message.content = message.content.parts;
|
|
976
|
-
} else {
|
|
977
|
-
message.content = [{ type: "text", text: "" }];
|
|
978
|
-
}
|
|
979
|
-
} else {
|
|
980
|
-
if (typeof message.content !== "object" || !message.content || !("parts" in message.content)) {
|
|
981
|
-
message.content = { format: 2, parts: [{ type: "text", text: "" }] };
|
|
982
|
-
}
|
|
983
|
-
}
|
|
984
|
-
if (message.type === "v2") delete message.type;
|
|
985
|
-
return message;
|
|
986
|
-
});
|
|
987
|
-
return format === "v2" ? fetchedMessages.map(
|
|
988
|
-
(m) => ({ ...m, content: m.content || { format: 2, parts: [{ type: "text", text: "" }] } })
|
|
989
|
-
) : fetchedMessages;
|
|
643
|
+
return this._parseAndFormatMessages(rows, format);
|
|
990
644
|
} catch (error) {
|
|
991
645
|
const mastraError = new MastraError(
|
|
992
646
|
{
|
|
@@ -994,40 +648,76 @@ ${columns}
|
|
|
994
648
|
domain: ErrorDomain.STORAGE,
|
|
995
649
|
category: ErrorCategory.THIRD_PARTY,
|
|
996
650
|
details: {
|
|
997
|
-
threadId
|
|
651
|
+
threadId,
|
|
652
|
+
resourceId: resourceId ?? ""
|
|
998
653
|
}
|
|
999
654
|
},
|
|
1000
655
|
error
|
|
1001
656
|
);
|
|
1002
657
|
this.logger?.error?.(mastraError.toString());
|
|
1003
|
-
this.logger?.trackException(mastraError);
|
|
658
|
+
this.logger?.trackException?.(mastraError);
|
|
1004
659
|
return [];
|
|
1005
660
|
}
|
|
1006
661
|
}
|
|
1007
|
-
async
|
|
1008
|
-
|
|
1009
|
-
|
|
662
|
+
async getMessagesById({
|
|
663
|
+
messageIds,
|
|
664
|
+
format
|
|
665
|
+
}) {
|
|
666
|
+
if (messageIds.length === 0) return [];
|
|
667
|
+
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
|
|
1010
668
|
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
1011
|
-
|
|
1012
|
-
|
|
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(
|
|
687
|
+
{
|
|
688
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
|
|
689
|
+
domain: ErrorDomain.STORAGE,
|
|
690
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
691
|
+
details: {
|
|
692
|
+
messageIds: JSON.stringify(messageIds)
|
|
693
|
+
}
|
|
694
|
+
},
|
|
695
|
+
error
|
|
696
|
+
);
|
|
697
|
+
this.logger?.error?.(mastraError.toString());
|
|
698
|
+
this.logger?.trackException?.(mastraError);
|
|
699
|
+
return [];
|
|
1013
700
|
}
|
|
701
|
+
}
|
|
702
|
+
async getMessagesPaginated(args) {
|
|
703
|
+
const { threadId, resourceId, format, selectBy } = args;
|
|
704
|
+
const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
|
|
1014
705
|
try {
|
|
1015
|
-
|
|
1016
|
-
const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
|
|
706
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
1017
707
|
const fromDate = dateRange?.start;
|
|
1018
708
|
const toDate = dateRange?.end;
|
|
1019
|
-
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
|
|
1020
|
-
const
|
|
1021
|
-
let
|
|
1022
|
-
if (
|
|
1023
|
-
const includeMessages = await this._getIncludedMessages({ threadId
|
|
1024
|
-
if (includeMessages)
|
|
1025
|
-
}
|
|
1026
|
-
const perPage =
|
|
1027
|
-
const currentOffset =
|
|
709
|
+
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
|
|
710
|
+
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
711
|
+
let messages = [];
|
|
712
|
+
if (selectBy?.include?.length) {
|
|
713
|
+
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
714
|
+
if (includeMessages) messages.push(...includeMessages);
|
|
715
|
+
}
|
|
716
|
+
const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
717
|
+
const currentOffset = page * perPage;
|
|
1028
718
|
const conditions = ["[thread_id] = @threadId"];
|
|
1029
719
|
const request = this.pool.request();
|
|
1030
|
-
request.input("threadId",
|
|
720
|
+
request.input("threadId", threadId);
|
|
1031
721
|
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1032
722
|
conditions.push("[createdAt] >= @fromDate");
|
|
1033
723
|
request.input("fromDate", fromDate.toISOString());
|
|
@@ -1037,38 +727,39 @@ ${columns}
|
|
|
1037
727
|
request.input("toDate", toDate.toISOString());
|
|
1038
728
|
}
|
|
1039
729
|
const whereClause = `WHERE ${conditions.join(" AND ")}`;
|
|
1040
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${
|
|
730
|
+
const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
|
|
1041
731
|
const countResult = await request.query(countQuery);
|
|
1042
732
|
const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
|
|
1043
|
-
if (total === 0 &&
|
|
1044
|
-
const parsedIncluded = this._parseAndFormatMessages(
|
|
733
|
+
if (total === 0 && messages.length > 0) {
|
|
734
|
+
const parsedIncluded = this._parseAndFormatMessages(messages, format);
|
|
1045
735
|
return {
|
|
1046
736
|
messages: parsedIncluded,
|
|
1047
737
|
total: parsedIncluded.length,
|
|
1048
|
-
page
|
|
738
|
+
page,
|
|
1049
739
|
perPage,
|
|
1050
740
|
hasMore: false
|
|
1051
741
|
};
|
|
1052
742
|
}
|
|
1053
|
-
const excludeIds =
|
|
743
|
+
const excludeIds = messages.map((m) => m.id);
|
|
1054
744
|
if (excludeIds.length > 0) {
|
|
1055
745
|
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
1056
746
|
conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
|
|
1057
747
|
excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
|
|
1058
748
|
}
|
|
1059
749
|
const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
|
|
1060
|
-
const dataQuery = `${selectStatement} FROM ${
|
|
750
|
+
const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
1061
751
|
request.input("offset", currentOffset);
|
|
1062
752
|
request.input("limit", perPage);
|
|
1063
753
|
const rowsResult = await request.query(dataQuery);
|
|
1064
754
|
const rows = rowsResult.recordset || [];
|
|
1065
755
|
rows.sort((a, b) => a.seq_id - b.seq_id);
|
|
1066
|
-
|
|
1067
|
-
|
|
756
|
+
messages.push(...rows);
|
|
757
|
+
let parsed = this._parseAndFormatMessages(messages, format);
|
|
758
|
+
parsed = parsed.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
1068
759
|
return {
|
|
1069
760
|
messages: parsed,
|
|
1070
|
-
total
|
|
1071
|
-
page
|
|
761
|
+
total,
|
|
762
|
+
page,
|
|
1072
763
|
perPage,
|
|
1073
764
|
hasMore: currentOffset + rows.length < total
|
|
1074
765
|
};
|
|
@@ -1080,41 +771,17 @@ ${columns}
|
|
|
1080
771
|
category: ErrorCategory.THIRD_PARTY,
|
|
1081
772
|
details: {
|
|
1082
773
|
threadId,
|
|
774
|
+
resourceId: resourceId ?? "",
|
|
1083
775
|
page
|
|
1084
776
|
}
|
|
1085
777
|
},
|
|
1086
778
|
error
|
|
1087
779
|
);
|
|
1088
780
|
this.logger?.error?.(mastraError.toString());
|
|
1089
|
-
this.logger?.trackException(mastraError);
|
|
781
|
+
this.logger?.trackException?.(mastraError);
|
|
1090
782
|
return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
|
|
1091
783
|
}
|
|
1092
784
|
}
|
|
1093
|
-
_parseAndFormatMessages(messages, format) {
|
|
1094
|
-
const parsedMessages = messages.map((message) => {
|
|
1095
|
-
let parsed = message;
|
|
1096
|
-
if (typeof parsed.content === "string") {
|
|
1097
|
-
try {
|
|
1098
|
-
parsed = { ...parsed, content: JSON.parse(parsed.content) };
|
|
1099
|
-
} catch {
|
|
1100
|
-
}
|
|
1101
|
-
}
|
|
1102
|
-
if (format === "v1") {
|
|
1103
|
-
if (Array.isArray(parsed.content)) ; else if (parsed.content?.parts) {
|
|
1104
|
-
parsed.content = parsed.content.parts;
|
|
1105
|
-
} else {
|
|
1106
|
-
parsed.content = [{ type: "text", text: "" }];
|
|
1107
|
-
}
|
|
1108
|
-
} else {
|
|
1109
|
-
if (!parsed.content?.parts) {
|
|
1110
|
-
parsed = { ...parsed, content: { format: 2, parts: [{ type: "text", text: "" }] } };
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
return parsed;
|
|
1114
|
-
});
|
|
1115
|
-
const list = new MessageList().add(parsedMessages, "memory");
|
|
1116
|
-
return format === "v2" ? list.get.all.v2() : list.get.all.v1();
|
|
1117
|
-
}
|
|
1118
785
|
async saveMessages({
|
|
1119
786
|
messages,
|
|
1120
787
|
format
|
|
@@ -1139,8 +806,8 @@ ${columns}
|
|
|
1139
806
|
details: { threadId }
|
|
1140
807
|
});
|
|
1141
808
|
}
|
|
1142
|
-
const tableMessages =
|
|
1143
|
-
const tableThreads =
|
|
809
|
+
const tableMessages = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
810
|
+
const tableThreads = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
1144
811
|
try {
|
|
1145
812
|
const transaction = this.pool.transaction();
|
|
1146
813
|
await transaction.begin();
|
|
@@ -1163,7 +830,7 @@ ${columns}
|
|
|
1163
830
|
"content",
|
|
1164
831
|
typeof message.content === "string" ? message.content : JSON.stringify(message.content)
|
|
1165
832
|
);
|
|
1166
|
-
request.input("createdAt", message.createdAt
|
|
833
|
+
request.input("createdAt", sql3.DateTime2, message.createdAt);
|
|
1167
834
|
request.input("role", message.role);
|
|
1168
835
|
request.input("type", message.type || "v2");
|
|
1169
836
|
request.input("resourceId", message.resourceId);
|
|
@@ -1182,7 +849,7 @@ ${columns}
|
|
|
1182
849
|
await request.query(mergeSql);
|
|
1183
850
|
}
|
|
1184
851
|
const threadReq = transaction.request();
|
|
1185
|
-
threadReq.input("updatedAt",
|
|
852
|
+
threadReq.input("updatedAt", sql3.DateTime2, /* @__PURE__ */ new Date());
|
|
1186
853
|
threadReq.input("id", threadId);
|
|
1187
854
|
await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
|
|
1188
855
|
await transaction.commit();
|
|
@@ -1215,216 +882,6 @@ ${columns}
|
|
|
1215
882
|
);
|
|
1216
883
|
}
|
|
1217
884
|
}
|
|
1218
|
-
async persistWorkflowSnapshot({
|
|
1219
|
-
workflowName,
|
|
1220
|
-
runId,
|
|
1221
|
-
snapshot
|
|
1222
|
-
}) {
|
|
1223
|
-
const table = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
1224
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1225
|
-
try {
|
|
1226
|
-
const request = this.pool.request();
|
|
1227
|
-
request.input("workflow_name", workflowName);
|
|
1228
|
-
request.input("run_id", runId);
|
|
1229
|
-
request.input("snapshot", JSON.stringify(snapshot));
|
|
1230
|
-
request.input("createdAt", now);
|
|
1231
|
-
request.input("updatedAt", now);
|
|
1232
|
-
const mergeSql = `MERGE INTO ${table} AS target
|
|
1233
|
-
USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
|
|
1234
|
-
ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
|
|
1235
|
-
WHEN MATCHED THEN UPDATE SET
|
|
1236
|
-
snapshot = @snapshot,
|
|
1237
|
-
[updatedAt] = @updatedAt
|
|
1238
|
-
WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
|
|
1239
|
-
VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
|
|
1240
|
-
await request.query(mergeSql);
|
|
1241
|
-
} catch (error) {
|
|
1242
|
-
throw new MastraError(
|
|
1243
|
-
{
|
|
1244
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
|
|
1245
|
-
domain: ErrorDomain.STORAGE,
|
|
1246
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1247
|
-
details: {
|
|
1248
|
-
workflowName,
|
|
1249
|
-
runId
|
|
1250
|
-
}
|
|
1251
|
-
},
|
|
1252
|
-
error
|
|
1253
|
-
);
|
|
1254
|
-
}
|
|
1255
|
-
}
|
|
1256
|
-
async loadWorkflowSnapshot({
|
|
1257
|
-
workflowName,
|
|
1258
|
-
runId
|
|
1259
|
-
}) {
|
|
1260
|
-
try {
|
|
1261
|
-
const result = await this.load({
|
|
1262
|
-
tableName: TABLE_WORKFLOW_SNAPSHOT,
|
|
1263
|
-
keys: {
|
|
1264
|
-
workflow_name: workflowName,
|
|
1265
|
-
run_id: runId
|
|
1266
|
-
}
|
|
1267
|
-
});
|
|
1268
|
-
if (!result) {
|
|
1269
|
-
return null;
|
|
1270
|
-
}
|
|
1271
|
-
return result.snapshot;
|
|
1272
|
-
} catch (error) {
|
|
1273
|
-
throw new MastraError(
|
|
1274
|
-
{
|
|
1275
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
|
|
1276
|
-
domain: ErrorDomain.STORAGE,
|
|
1277
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1278
|
-
details: {
|
|
1279
|
-
workflowName,
|
|
1280
|
-
runId
|
|
1281
|
-
}
|
|
1282
|
-
},
|
|
1283
|
-
error
|
|
1284
|
-
);
|
|
1285
|
-
}
|
|
1286
|
-
}
|
|
1287
|
-
async hasColumn(table, column) {
|
|
1288
|
-
const schema = this.schema || "dbo";
|
|
1289
|
-
const request = this.pool.request();
|
|
1290
|
-
request.input("schema", schema);
|
|
1291
|
-
request.input("table", table);
|
|
1292
|
-
request.input("column", column);
|
|
1293
|
-
request.input("columnLower", column.toLowerCase());
|
|
1294
|
-
const result = await request.query(
|
|
1295
|
-
`SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
|
|
1296
|
-
);
|
|
1297
|
-
return result.recordset.length > 0;
|
|
1298
|
-
}
|
|
1299
|
-
parseWorkflowRun(row) {
|
|
1300
|
-
let parsedSnapshot = row.snapshot;
|
|
1301
|
-
if (typeof parsedSnapshot === "string") {
|
|
1302
|
-
try {
|
|
1303
|
-
parsedSnapshot = JSON.parse(row.snapshot);
|
|
1304
|
-
} catch (e) {
|
|
1305
|
-
console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
return {
|
|
1309
|
-
workflowName: row.workflow_name,
|
|
1310
|
-
runId: row.run_id,
|
|
1311
|
-
snapshot: parsedSnapshot,
|
|
1312
|
-
createdAt: row.createdAt,
|
|
1313
|
-
updatedAt: row.updatedAt,
|
|
1314
|
-
resourceId: row.resourceId
|
|
1315
|
-
};
|
|
1316
|
-
}
|
|
1317
|
-
async getWorkflowRuns({
|
|
1318
|
-
workflowName,
|
|
1319
|
-
fromDate,
|
|
1320
|
-
toDate,
|
|
1321
|
-
limit,
|
|
1322
|
-
offset,
|
|
1323
|
-
resourceId
|
|
1324
|
-
} = {}) {
|
|
1325
|
-
try {
|
|
1326
|
-
const conditions = [];
|
|
1327
|
-
const paramMap = {};
|
|
1328
|
-
if (workflowName) {
|
|
1329
|
-
conditions.push(`[workflow_name] = @workflowName`);
|
|
1330
|
-
paramMap["workflowName"] = workflowName;
|
|
1331
|
-
}
|
|
1332
|
-
if (resourceId) {
|
|
1333
|
-
const hasResourceId = await this.hasColumn(TABLE_WORKFLOW_SNAPSHOT, "resourceId");
|
|
1334
|
-
if (hasResourceId) {
|
|
1335
|
-
conditions.push(`[resourceId] = @resourceId`);
|
|
1336
|
-
paramMap["resourceId"] = resourceId;
|
|
1337
|
-
} else {
|
|
1338
|
-
console.warn(`[${TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
|
|
1339
|
-
}
|
|
1340
|
-
}
|
|
1341
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1342
|
-
conditions.push(`[createdAt] >= @fromDate`);
|
|
1343
|
-
paramMap[`fromDate`] = fromDate.toISOString();
|
|
1344
|
-
}
|
|
1345
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1346
|
-
conditions.push(`[createdAt] <= @toDate`);
|
|
1347
|
-
paramMap[`toDate`] = toDate.toISOString();
|
|
1348
|
-
}
|
|
1349
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1350
|
-
let total = 0;
|
|
1351
|
-
const tableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
1352
|
-
const request = this.pool.request();
|
|
1353
|
-
Object.entries(paramMap).forEach(([key, value]) => {
|
|
1354
|
-
if (value instanceof Date) {
|
|
1355
|
-
request.input(key, sql.DateTime, value);
|
|
1356
|
-
} else {
|
|
1357
|
-
request.input(key, value);
|
|
1358
|
-
}
|
|
1359
|
-
});
|
|
1360
|
-
if (limit !== void 0 && offset !== void 0) {
|
|
1361
|
-
const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
|
|
1362
|
-
const countResult = await request.query(countQuery);
|
|
1363
|
-
total = Number(countResult.recordset[0]?.count || 0);
|
|
1364
|
-
}
|
|
1365
|
-
let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
|
|
1366
|
-
if (limit !== void 0 && offset !== void 0) {
|
|
1367
|
-
query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
1368
|
-
request.input("limit", limit);
|
|
1369
|
-
request.input("offset", offset);
|
|
1370
|
-
}
|
|
1371
|
-
const result = await request.query(query);
|
|
1372
|
-
const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
|
|
1373
|
-
return { runs, total: total || runs.length };
|
|
1374
|
-
} catch (error) {
|
|
1375
|
-
throw new MastraError(
|
|
1376
|
-
{
|
|
1377
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
|
|
1378
|
-
domain: ErrorDomain.STORAGE,
|
|
1379
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1380
|
-
details: {
|
|
1381
|
-
workflowName: workflowName || "all"
|
|
1382
|
-
}
|
|
1383
|
-
},
|
|
1384
|
-
error
|
|
1385
|
-
);
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
async getWorkflowRunById({
|
|
1389
|
-
runId,
|
|
1390
|
-
workflowName
|
|
1391
|
-
}) {
|
|
1392
|
-
try {
|
|
1393
|
-
const conditions = [];
|
|
1394
|
-
const paramMap = {};
|
|
1395
|
-
if (runId) {
|
|
1396
|
-
conditions.push(`[run_id] = @runId`);
|
|
1397
|
-
paramMap["runId"] = runId;
|
|
1398
|
-
}
|
|
1399
|
-
if (workflowName) {
|
|
1400
|
-
conditions.push(`[workflow_name] = @workflowName`);
|
|
1401
|
-
paramMap["workflowName"] = workflowName;
|
|
1402
|
-
}
|
|
1403
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1404
|
-
const tableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
1405
|
-
const query = `SELECT * FROM ${tableName} ${whereClause}`;
|
|
1406
|
-
const request = this.pool.request();
|
|
1407
|
-
Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
|
|
1408
|
-
const result = await request.query(query);
|
|
1409
|
-
if (!result.recordset || result.recordset.length === 0) {
|
|
1410
|
-
return null;
|
|
1411
|
-
}
|
|
1412
|
-
return this.parseWorkflowRun(result.recordset[0]);
|
|
1413
|
-
} catch (error) {
|
|
1414
|
-
throw new MastraError(
|
|
1415
|
-
{
|
|
1416
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
|
|
1417
|
-
domain: ErrorDomain.STORAGE,
|
|
1418
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1419
|
-
details: {
|
|
1420
|
-
runId,
|
|
1421
|
-
workflowName: workflowName || ""
|
|
1422
|
-
}
|
|
1423
|
-
},
|
|
1424
|
-
error
|
|
1425
|
-
);
|
|
1426
|
-
}
|
|
1427
|
-
}
|
|
1428
885
|
async updateMessages({
|
|
1429
886
|
messages
|
|
1430
887
|
}) {
|
|
@@ -1433,7 +890,7 @@ ${columns}
|
|
|
1433
890
|
}
|
|
1434
891
|
const messageIds = messages.map((m) => m.id);
|
|
1435
892
|
const idParams = messageIds.map((_, i) => `@id${i}`).join(", ");
|
|
1436
|
-
let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${
|
|
893
|
+
let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}`;
|
|
1437
894
|
if (idParams.length > 0) {
|
|
1438
895
|
selectQuery += ` WHERE id IN (${idParams})`;
|
|
1439
896
|
} else {
|
|
@@ -1490,7 +947,7 @@ ${columns}
|
|
|
1490
947
|
}
|
|
1491
948
|
}
|
|
1492
949
|
if (setClauses.length > 0) {
|
|
1493
|
-
const updateSql = `UPDATE ${
|
|
950
|
+
const updateSql = `UPDATE ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} SET ${setClauses.join(", ")} WHERE id = @id`;
|
|
1494
951
|
await req.query(updateSql);
|
|
1495
952
|
}
|
|
1496
953
|
}
|
|
@@ -1499,7 +956,7 @@ ${columns}
|
|
|
1499
956
|
const threadReq = transaction.request();
|
|
1500
957
|
Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
|
|
1501
958
|
threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
|
|
1502
|
-
const threadSql = `UPDATE ${
|
|
959
|
+
const threadSql = `UPDATE ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
|
|
1503
960
|
await threadReq.query(threadSql);
|
|
1504
961
|
}
|
|
1505
962
|
await transaction.commit();
|
|
@@ -1527,136 +984,97 @@ ${columns}
|
|
|
1527
984
|
return message;
|
|
1528
985
|
});
|
|
1529
986
|
}
|
|
1530
|
-
async
|
|
1531
|
-
if (
|
|
987
|
+
async deleteMessages(messageIds) {
|
|
988
|
+
if (!messageIds || messageIds.length === 0) {
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
try {
|
|
992
|
+
const messageTableName = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
993
|
+
const threadTableName = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
994
|
+
const placeholders = messageIds.map((_, idx) => `@p${idx + 1}`).join(",");
|
|
995
|
+
const request = this.pool.request();
|
|
996
|
+
messageIds.forEach((id, idx) => {
|
|
997
|
+
request.input(`p${idx + 1}`, id);
|
|
998
|
+
});
|
|
999
|
+
const messages = await request.query(
|
|
1000
|
+
`SELECT DISTINCT [thread_id] FROM ${messageTableName} WHERE [id] IN (${placeholders})`
|
|
1001
|
+
);
|
|
1002
|
+
const threadIds = messages.recordset?.map((msg) => msg.thread_id).filter(Boolean) || [];
|
|
1003
|
+
const transaction = this.pool.transaction();
|
|
1004
|
+
await transaction.begin();
|
|
1532
1005
|
try {
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1006
|
+
const deleteRequest = transaction.request();
|
|
1007
|
+
messageIds.forEach((id, idx) => {
|
|
1008
|
+
deleteRequest.input(`p${idx + 1}`, id);
|
|
1009
|
+
});
|
|
1010
|
+
await deleteRequest.query(`DELETE FROM ${messageTableName} WHERE [id] IN (${placeholders})`);
|
|
1011
|
+
if (threadIds.length > 0) {
|
|
1012
|
+
for (const threadId of threadIds) {
|
|
1013
|
+
const updateRequest = transaction.request();
|
|
1014
|
+
updateRequest.input("p1", threadId);
|
|
1015
|
+
await updateRequest.query(`UPDATE ${threadTableName} SET [updatedAt] = GETDATE() WHERE [id] = @p1`);
|
|
1016
|
+
}
|
|
1538
1017
|
}
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1018
|
+
await transaction.commit();
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
try {
|
|
1021
|
+
await transaction.rollback();
|
|
1022
|
+
} catch {
|
|
1542
1023
|
}
|
|
1024
|
+
throw error;
|
|
1543
1025
|
}
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
throw new MastraError(
|
|
1028
|
+
{
|
|
1029
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_DELETE_MESSAGES_FAILED",
|
|
1030
|
+
domain: ErrorDomain.STORAGE,
|
|
1031
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1032
|
+
details: { messageIds: messageIds.join(", ") }
|
|
1033
|
+
},
|
|
1034
|
+
error
|
|
1035
|
+
);
|
|
1544
1036
|
}
|
|
1545
1037
|
}
|
|
1546
|
-
async
|
|
1547
|
-
const
|
|
1548
|
-
const fromDate = dateRange?.start;
|
|
1549
|
-
const toDate = dateRange?.end;
|
|
1550
|
-
const where = [];
|
|
1551
|
-
const params = {};
|
|
1552
|
-
if (agentName) {
|
|
1553
|
-
where.push("agent_name = @agentName");
|
|
1554
|
-
params["agentName"] = agentName;
|
|
1555
|
-
}
|
|
1556
|
-
if (type === "test") {
|
|
1557
|
-
where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
|
|
1558
|
-
} else if (type === "live") {
|
|
1559
|
-
where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
|
|
1560
|
-
}
|
|
1561
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1562
|
-
where.push(`[created_at] >= @fromDate`);
|
|
1563
|
-
params[`fromDate`] = fromDate.toISOString();
|
|
1564
|
-
}
|
|
1565
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1566
|
-
where.push(`[created_at] <= @toDate`);
|
|
1567
|
-
params[`toDate`] = toDate.toISOString();
|
|
1568
|
-
}
|
|
1569
|
-
const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
|
|
1570
|
-
const tableName = this.getTableName(TABLE_EVALS);
|
|
1571
|
-
const offset = page * perPage;
|
|
1572
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
|
|
1573
|
-
const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
1038
|
+
async getResourceById({ resourceId }) {
|
|
1039
|
+
const tableName = getTableName({ indexName: TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
|
|
1574
1040
|
try {
|
|
1575
|
-
const countReq = this.pool.request();
|
|
1576
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
1577
|
-
if (value instanceof Date) {
|
|
1578
|
-
countReq.input(key, sql.DateTime, value);
|
|
1579
|
-
} else {
|
|
1580
|
-
countReq.input(key, value);
|
|
1581
|
-
}
|
|
1582
|
-
});
|
|
1583
|
-
const countResult = await countReq.query(countQuery);
|
|
1584
|
-
const total = countResult.recordset[0]?.total || 0;
|
|
1585
|
-
if (total === 0) {
|
|
1586
|
-
return {
|
|
1587
|
-
evals: [],
|
|
1588
|
-
total: 0,
|
|
1589
|
-
page,
|
|
1590
|
-
perPage,
|
|
1591
|
-
hasMore: false
|
|
1592
|
-
};
|
|
1593
|
-
}
|
|
1594
1041
|
const req = this.pool.request();
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
}
|
|
1601
|
-
});
|
|
1602
|
-
req.input("offset", offset);
|
|
1603
|
-
req.input("perPage", perPage);
|
|
1604
|
-
const result = await req.query(dataQuery);
|
|
1605
|
-
const rows = result.recordset;
|
|
1042
|
+
req.input("resourceId", resourceId);
|
|
1043
|
+
const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
|
|
1044
|
+
if (!result) {
|
|
1045
|
+
return null;
|
|
1046
|
+
}
|
|
1606
1047
|
return {
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1048
|
+
id: result.id,
|
|
1049
|
+
createdAt: result.createdAt,
|
|
1050
|
+
updatedAt: result.updatedAt,
|
|
1051
|
+
workingMemory: result.workingMemory,
|
|
1052
|
+
metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
|
|
1612
1053
|
};
|
|
1613
1054
|
} catch (error) {
|
|
1614
1055
|
const mastraError = new MastraError(
|
|
1615
1056
|
{
|
|
1616
|
-
id: "
|
|
1057
|
+
id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
|
|
1617
1058
|
domain: ErrorDomain.STORAGE,
|
|
1618
1059
|
category: ErrorCategory.THIRD_PARTY,
|
|
1619
|
-
details: {
|
|
1620
|
-
agentName: agentName || "all",
|
|
1621
|
-
type: type || "all",
|
|
1622
|
-
page,
|
|
1623
|
-
perPage
|
|
1624
|
-
}
|
|
1060
|
+
details: { resourceId }
|
|
1625
1061
|
},
|
|
1626
1062
|
error
|
|
1627
1063
|
);
|
|
1628
1064
|
this.logger?.error?.(mastraError.toString());
|
|
1629
|
-
this.logger?.trackException(mastraError);
|
|
1065
|
+
this.logger?.trackException?.(mastraError);
|
|
1630
1066
|
throw mastraError;
|
|
1631
1067
|
}
|
|
1632
1068
|
}
|
|
1633
1069
|
async saveResource({ resource }) {
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
await req.query(
|
|
1643
|
-
`INSERT INTO ${tableName} (id, workingMemory, metadata, createdAt, updatedAt) VALUES (@id, @workingMemory, @metadata, @createdAt, @updatedAt)`
|
|
1644
|
-
);
|
|
1645
|
-
return resource;
|
|
1646
|
-
} catch (error) {
|
|
1647
|
-
const mastraError = new MastraError(
|
|
1648
|
-
{
|
|
1649
|
-
id: "MASTRA_STORAGE_MSSQL_SAVE_RESOURCE_FAILED",
|
|
1650
|
-
domain: ErrorDomain.STORAGE,
|
|
1651
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1652
|
-
details: { resourceId: resource.id }
|
|
1653
|
-
},
|
|
1654
|
-
error
|
|
1655
|
-
);
|
|
1656
|
-
this.logger?.error?.(mastraError.toString());
|
|
1657
|
-
this.logger?.trackException(mastraError);
|
|
1658
|
-
throw mastraError;
|
|
1659
|
-
}
|
|
1070
|
+
await this.operations.insert({
|
|
1071
|
+
tableName: TABLE_RESOURCES,
|
|
1072
|
+
record: {
|
|
1073
|
+
...resource,
|
|
1074
|
+
metadata: resource.metadata
|
|
1075
|
+
}
|
|
1076
|
+
});
|
|
1077
|
+
return resource;
|
|
1660
1078
|
}
|
|
1661
1079
|
async updateResource({
|
|
1662
1080
|
resourceId,
|
|
@@ -1684,7 +1102,7 @@ ${columns}
|
|
|
1684
1102
|
},
|
|
1685
1103
|
updatedAt: /* @__PURE__ */ new Date()
|
|
1686
1104
|
};
|
|
1687
|
-
const tableName =
|
|
1105
|
+
const tableName = getTableName({ indexName: TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
|
|
1688
1106
|
const updates = [];
|
|
1689
1107
|
const req = this.pool.request();
|
|
1690
1108
|
if (workingMemory !== void 0) {
|
|
@@ -1711,104 +1129,2517 @@ ${columns}
|
|
|
1711
1129
|
error
|
|
1712
1130
|
);
|
|
1713
1131
|
this.logger?.error?.(mastraError.toString());
|
|
1714
|
-
this.logger?.trackException(mastraError);
|
|
1132
|
+
this.logger?.trackException?.(mastraError);
|
|
1715
1133
|
throw mastraError;
|
|
1716
1134
|
}
|
|
1717
1135
|
}
|
|
1718
|
-
|
|
1719
|
-
|
|
1136
|
+
};
|
|
1137
|
+
var ObservabilityMSSQL = class extends ObservabilityStorage {
|
|
1138
|
+
pool;
|
|
1139
|
+
operations;
|
|
1140
|
+
schema;
|
|
1141
|
+
constructor({
|
|
1142
|
+
pool,
|
|
1143
|
+
operations,
|
|
1144
|
+
schema
|
|
1145
|
+
}) {
|
|
1146
|
+
super();
|
|
1147
|
+
this.pool = pool;
|
|
1148
|
+
this.operations = operations;
|
|
1149
|
+
this.schema = schema;
|
|
1150
|
+
}
|
|
1151
|
+
get aiTracingStrategy() {
|
|
1152
|
+
return {
|
|
1153
|
+
preferred: "batch-with-updates",
|
|
1154
|
+
supported: ["batch-with-updates", "insert-only"]
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
async createAISpan(span) {
|
|
1720
1158
|
try {
|
|
1721
|
-
const
|
|
1722
|
-
|
|
1723
|
-
const
|
|
1724
|
-
|
|
1159
|
+
const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
|
|
1160
|
+
const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
|
|
1161
|
+
const record = {
|
|
1162
|
+
...span,
|
|
1163
|
+
startedAt,
|
|
1164
|
+
endedAt
|
|
1165
|
+
// Note: createdAt/updatedAt will be set by default values
|
|
1166
|
+
};
|
|
1167
|
+
return this.operations.insert({ tableName: TABLE_AI_SPANS, record });
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
throw new MastraError(
|
|
1170
|
+
{
|
|
1171
|
+
id: "MSSQL_STORE_CREATE_AI_SPAN_FAILED",
|
|
1172
|
+
domain: ErrorDomain.STORAGE,
|
|
1173
|
+
category: ErrorCategory.USER,
|
|
1174
|
+
details: {
|
|
1175
|
+
spanId: span.spanId,
|
|
1176
|
+
traceId: span.traceId,
|
|
1177
|
+
spanType: span.spanType,
|
|
1178
|
+
spanName: span.name
|
|
1179
|
+
}
|
|
1180
|
+
},
|
|
1181
|
+
error
|
|
1182
|
+
);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
async getAITrace(traceId) {
|
|
1186
|
+
try {
|
|
1187
|
+
const tableName = getTableName({
|
|
1188
|
+
indexName: TABLE_AI_SPANS,
|
|
1189
|
+
schemaName: getSchemaName(this.schema)
|
|
1190
|
+
});
|
|
1191
|
+
const request = this.pool.request();
|
|
1192
|
+
request.input("traceId", traceId);
|
|
1193
|
+
const result = await request.query(
|
|
1194
|
+
`SELECT
|
|
1195
|
+
[traceId], [spanId], [parentSpanId], [name], [scope], [spanType],
|
|
1196
|
+
[attributes], [metadata], [links], [input], [output], [error], [isEvent],
|
|
1197
|
+
[startedAt], [endedAt], [createdAt], [updatedAt]
|
|
1198
|
+
FROM ${tableName}
|
|
1199
|
+
WHERE [traceId] = @traceId
|
|
1200
|
+
ORDER BY [startedAt] DESC`
|
|
1201
|
+
);
|
|
1202
|
+
if (!result.recordset || result.recordset.length === 0) {
|
|
1725
1203
|
return null;
|
|
1726
1204
|
}
|
|
1727
1205
|
return {
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1206
|
+
traceId,
|
|
1207
|
+
spans: result.recordset.map(
|
|
1208
|
+
(span) => transformFromSqlRow({
|
|
1209
|
+
tableName: TABLE_AI_SPANS,
|
|
1210
|
+
sqlRow: span
|
|
1211
|
+
})
|
|
1212
|
+
)
|
|
1731
1213
|
};
|
|
1732
1214
|
} catch (error) {
|
|
1733
|
-
|
|
1215
|
+
throw new MastraError(
|
|
1734
1216
|
{
|
|
1735
|
-
id: "
|
|
1217
|
+
id: "MSSQL_STORE_GET_AI_TRACE_FAILED",
|
|
1736
1218
|
domain: ErrorDomain.STORAGE,
|
|
1737
|
-
category: ErrorCategory.
|
|
1738
|
-
details: {
|
|
1219
|
+
category: ErrorCategory.USER,
|
|
1220
|
+
details: {
|
|
1221
|
+
traceId
|
|
1222
|
+
}
|
|
1739
1223
|
},
|
|
1740
1224
|
error
|
|
1741
1225
|
);
|
|
1742
|
-
this.logger?.error?.(mastraError.toString());
|
|
1743
|
-
this.logger?.trackException(mastraError);
|
|
1744
|
-
throw mastraError;
|
|
1745
1226
|
}
|
|
1746
1227
|
}
|
|
1747
|
-
async
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1752
|
-
details: { id },
|
|
1753
|
-
text: "getScoreById is not implemented yet in MongoDBStore"
|
|
1754
|
-
});
|
|
1755
|
-
}
|
|
1756
|
-
async saveScore(_score) {
|
|
1757
|
-
throw new MastraError({
|
|
1758
|
-
id: "STORAGE_MONGODB_STORE_SAVE_SCORE_FAILED",
|
|
1759
|
-
domain: ErrorDomain.STORAGE,
|
|
1760
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1761
|
-
details: {},
|
|
1762
|
-
text: "saveScore is not implemented yet in MongoDBStore"
|
|
1763
|
-
});
|
|
1764
|
-
}
|
|
1765
|
-
async getScoresByScorerId({
|
|
1766
|
-
scorerId,
|
|
1767
|
-
pagination: _pagination,
|
|
1768
|
-
entityId,
|
|
1769
|
-
entityType
|
|
1228
|
+
async updateAISpan({
|
|
1229
|
+
spanId,
|
|
1230
|
+
traceId,
|
|
1231
|
+
updates
|
|
1770
1232
|
}) {
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1233
|
+
try {
|
|
1234
|
+
const data = { ...updates };
|
|
1235
|
+
if (data.endedAt instanceof Date) {
|
|
1236
|
+
data.endedAt = data.endedAt.toISOString();
|
|
1237
|
+
}
|
|
1238
|
+
if (data.startedAt instanceof Date) {
|
|
1239
|
+
data.startedAt = data.startedAt.toISOString();
|
|
1240
|
+
}
|
|
1241
|
+
await this.operations.update({
|
|
1242
|
+
tableName: TABLE_AI_SPANS,
|
|
1243
|
+
keys: { spanId, traceId },
|
|
1244
|
+
data
|
|
1245
|
+
});
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
throw new MastraError(
|
|
1248
|
+
{
|
|
1249
|
+
id: "MSSQL_STORE_UPDATE_AI_SPAN_FAILED",
|
|
1250
|
+
domain: ErrorDomain.STORAGE,
|
|
1251
|
+
category: ErrorCategory.USER,
|
|
1252
|
+
details: {
|
|
1253
|
+
spanId,
|
|
1254
|
+
traceId
|
|
1255
|
+
}
|
|
1256
|
+
},
|
|
1257
|
+
error
|
|
1258
|
+
);
|
|
1259
|
+
}
|
|
1778
1260
|
}
|
|
1779
|
-
async
|
|
1780
|
-
|
|
1781
|
-
pagination
|
|
1261
|
+
async getAITracesPaginated({
|
|
1262
|
+
filters,
|
|
1263
|
+
pagination
|
|
1782
1264
|
}) {
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1265
|
+
const page = pagination?.page ?? 0;
|
|
1266
|
+
const perPage = pagination?.perPage ?? 10;
|
|
1267
|
+
const { entityId, entityType, ...actualFilters } = filters || {};
|
|
1268
|
+
const filtersWithDateRange = {
|
|
1269
|
+
...actualFilters,
|
|
1270
|
+
...buildDateRangeFilter(pagination?.dateRange, "startedAt"),
|
|
1271
|
+
parentSpanId: null
|
|
1272
|
+
// Only get root spans for traces
|
|
1273
|
+
};
|
|
1274
|
+
const whereClause = prepareWhereClause(filtersWithDateRange);
|
|
1275
|
+
let actualWhereClause = whereClause.sql;
|
|
1276
|
+
const params = { ...whereClause.params };
|
|
1277
|
+
let currentParamIndex = Object.keys(params).length + 1;
|
|
1278
|
+
if (entityId && entityType) {
|
|
1279
|
+
let name = "";
|
|
1280
|
+
if (entityType === "workflow") {
|
|
1281
|
+
name = `workflow run: '${entityId}'`;
|
|
1282
|
+
} else if (entityType === "agent") {
|
|
1283
|
+
name = `agent run: '${entityId}'`;
|
|
1284
|
+
} else {
|
|
1285
|
+
const error = new MastraError({
|
|
1286
|
+
id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
|
|
1287
|
+
domain: ErrorDomain.STORAGE,
|
|
1288
|
+
category: ErrorCategory.USER,
|
|
1289
|
+
details: {
|
|
1290
|
+
entityType
|
|
1291
|
+
},
|
|
1292
|
+
text: `Cannot filter by entity type: ${entityType}`
|
|
1293
|
+
});
|
|
1294
|
+
throw error;
|
|
1295
|
+
}
|
|
1296
|
+
const entityParam = `p${currentParamIndex++}`;
|
|
1297
|
+
if (actualWhereClause) {
|
|
1298
|
+
actualWhereClause += ` AND [name] = @${entityParam}`;
|
|
1299
|
+
} else {
|
|
1300
|
+
actualWhereClause = ` WHERE [name] = @${entityParam}`;
|
|
1301
|
+
}
|
|
1302
|
+
params[entityParam] = name;
|
|
1303
|
+
}
|
|
1304
|
+
const tableName = getTableName({
|
|
1305
|
+
indexName: TABLE_AI_SPANS,
|
|
1306
|
+
schemaName: getSchemaName(this.schema)
|
|
1789
1307
|
});
|
|
1308
|
+
try {
|
|
1309
|
+
const countRequest = this.pool.request();
|
|
1310
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
1311
|
+
countRequest.input(key, value);
|
|
1312
|
+
});
|
|
1313
|
+
const countResult = await countRequest.query(
|
|
1314
|
+
`SELECT COUNT(*) as count FROM ${tableName}${actualWhereClause}`
|
|
1315
|
+
);
|
|
1316
|
+
const total = countResult.recordset[0]?.count ?? 0;
|
|
1317
|
+
if (total === 0) {
|
|
1318
|
+
return {
|
|
1319
|
+
pagination: {
|
|
1320
|
+
total: 0,
|
|
1321
|
+
page,
|
|
1322
|
+
perPage,
|
|
1323
|
+
hasMore: false
|
|
1324
|
+
},
|
|
1325
|
+
spans: []
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
const dataRequest = this.pool.request();
|
|
1329
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
1330
|
+
dataRequest.input(key, value);
|
|
1331
|
+
});
|
|
1332
|
+
dataRequest.input("offset", page * perPage);
|
|
1333
|
+
dataRequest.input("limit", perPage);
|
|
1334
|
+
const dataResult = await dataRequest.query(
|
|
1335
|
+
`SELECT * FROM ${tableName}${actualWhereClause} ORDER BY [startedAt] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`
|
|
1336
|
+
);
|
|
1337
|
+
const spans = dataResult.recordset.map(
|
|
1338
|
+
(row) => transformFromSqlRow({
|
|
1339
|
+
tableName: TABLE_AI_SPANS,
|
|
1340
|
+
sqlRow: row
|
|
1341
|
+
})
|
|
1342
|
+
);
|
|
1343
|
+
return {
|
|
1344
|
+
pagination: {
|
|
1345
|
+
total,
|
|
1346
|
+
page,
|
|
1347
|
+
perPage,
|
|
1348
|
+
hasMore: (page + 1) * perPage < total
|
|
1349
|
+
},
|
|
1350
|
+
spans
|
|
1351
|
+
};
|
|
1352
|
+
} catch (error) {
|
|
1353
|
+
throw new MastraError(
|
|
1354
|
+
{
|
|
1355
|
+
id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
|
|
1356
|
+
domain: ErrorDomain.STORAGE,
|
|
1357
|
+
category: ErrorCategory.USER
|
|
1358
|
+
},
|
|
1359
|
+
error
|
|
1360
|
+
);
|
|
1361
|
+
}
|
|
1790
1362
|
}
|
|
1791
|
-
async
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1363
|
+
async batchCreateAISpans(args) {
|
|
1364
|
+
if (!args.records || args.records.length === 0) {
|
|
1365
|
+
return;
|
|
1366
|
+
}
|
|
1367
|
+
try {
|
|
1368
|
+
await this.operations.batchInsert({
|
|
1369
|
+
tableName: TABLE_AI_SPANS,
|
|
1370
|
+
records: args.records.map((span) => ({
|
|
1371
|
+
...span,
|
|
1372
|
+
startedAt: span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt,
|
|
1373
|
+
endedAt: span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt
|
|
1374
|
+
}))
|
|
1375
|
+
});
|
|
1376
|
+
} catch (error) {
|
|
1377
|
+
throw new MastraError(
|
|
1378
|
+
{
|
|
1379
|
+
id: "MSSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
|
|
1380
|
+
domain: ErrorDomain.STORAGE,
|
|
1381
|
+
category: ErrorCategory.USER,
|
|
1382
|
+
details: {
|
|
1383
|
+
count: args.records.length
|
|
1384
|
+
}
|
|
1385
|
+
},
|
|
1386
|
+
error
|
|
1387
|
+
);
|
|
1388
|
+
}
|
|
1803
1389
|
}
|
|
1804
|
-
async
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1390
|
+
async batchUpdateAISpans(args) {
|
|
1391
|
+
if (!args.records || args.records.length === 0) {
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
try {
|
|
1395
|
+
const updates = args.records.map(({ traceId, spanId, updates: data }) => {
|
|
1396
|
+
const processedData = { ...data };
|
|
1397
|
+
if (processedData.endedAt instanceof Date) {
|
|
1398
|
+
processedData.endedAt = processedData.endedAt.toISOString();
|
|
1399
|
+
}
|
|
1400
|
+
if (processedData.startedAt instanceof Date) {
|
|
1401
|
+
processedData.startedAt = processedData.startedAt.toISOString();
|
|
1402
|
+
}
|
|
1403
|
+
return {
|
|
1404
|
+
keys: { spanId, traceId },
|
|
1405
|
+
data: processedData
|
|
1406
|
+
};
|
|
1407
|
+
});
|
|
1408
|
+
await this.operations.batchUpdate({
|
|
1409
|
+
tableName: TABLE_AI_SPANS,
|
|
1410
|
+
updates
|
|
1411
|
+
});
|
|
1412
|
+
} catch (error) {
|
|
1413
|
+
throw new MastraError(
|
|
1414
|
+
{
|
|
1415
|
+
id: "MSSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
|
|
1416
|
+
domain: ErrorDomain.STORAGE,
|
|
1417
|
+
category: ErrorCategory.USER,
|
|
1418
|
+
details: {
|
|
1419
|
+
count: args.records.length
|
|
1420
|
+
}
|
|
1421
|
+
},
|
|
1422
|
+
error
|
|
1423
|
+
);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
async batchDeleteAITraces(args) {
|
|
1427
|
+
if (!args.traceIds || args.traceIds.length === 0) {
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
try {
|
|
1431
|
+
const keys = args.traceIds.map((traceId) => ({ traceId }));
|
|
1432
|
+
await this.operations.batchDelete({
|
|
1433
|
+
tableName: TABLE_AI_SPANS,
|
|
1434
|
+
keys
|
|
1435
|
+
});
|
|
1436
|
+
} catch (error) {
|
|
1437
|
+
throw new MastraError(
|
|
1438
|
+
{
|
|
1439
|
+
id: "MSSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
|
|
1440
|
+
domain: ErrorDomain.STORAGE,
|
|
1441
|
+
category: ErrorCategory.USER,
|
|
1442
|
+
details: {
|
|
1443
|
+
count: args.traceIds.length
|
|
1444
|
+
}
|
|
1445
|
+
},
|
|
1446
|
+
error
|
|
1447
|
+
);
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
};
|
|
1451
|
+
var StoreOperationsMSSQL = class extends StoreOperations {
|
|
1452
|
+
pool;
|
|
1453
|
+
schemaName;
|
|
1454
|
+
setupSchemaPromise = null;
|
|
1455
|
+
schemaSetupComplete = void 0;
|
|
1456
|
+
getSqlType(type, isPrimaryKey = false, useLargeStorage = false) {
|
|
1457
|
+
switch (type) {
|
|
1458
|
+
case "text":
|
|
1459
|
+
if (useLargeStorage) {
|
|
1460
|
+
return "NVARCHAR(MAX)";
|
|
1461
|
+
}
|
|
1462
|
+
return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(400)";
|
|
1463
|
+
case "timestamp":
|
|
1464
|
+
return "DATETIME2(7)";
|
|
1465
|
+
case "uuid":
|
|
1466
|
+
return "UNIQUEIDENTIFIER";
|
|
1467
|
+
case "jsonb":
|
|
1468
|
+
return "NVARCHAR(MAX)";
|
|
1469
|
+
case "integer":
|
|
1470
|
+
return "INT";
|
|
1471
|
+
case "bigint":
|
|
1472
|
+
return "BIGINT";
|
|
1473
|
+
case "float":
|
|
1474
|
+
return "FLOAT";
|
|
1475
|
+
case "boolean":
|
|
1476
|
+
return "BIT";
|
|
1477
|
+
default:
|
|
1478
|
+
throw new MastraError({
|
|
1479
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
|
|
1480
|
+
domain: ErrorDomain.STORAGE,
|
|
1481
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1482
|
+
});
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
constructor({ pool, schemaName }) {
|
|
1486
|
+
super();
|
|
1487
|
+
this.pool = pool;
|
|
1488
|
+
this.schemaName = schemaName;
|
|
1489
|
+
}
|
|
1490
|
+
async hasColumn(table, column) {
|
|
1491
|
+
const schema = this.schemaName || "dbo";
|
|
1492
|
+
const request = this.pool.request();
|
|
1493
|
+
request.input("schema", schema);
|
|
1494
|
+
request.input("table", table);
|
|
1495
|
+
request.input("column", column);
|
|
1496
|
+
request.input("columnLower", column.toLowerCase());
|
|
1497
|
+
const result = await request.query(
|
|
1498
|
+
`SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
|
|
1499
|
+
);
|
|
1500
|
+
return result.recordset.length > 0;
|
|
1501
|
+
}
|
|
1502
|
+
async setupSchema() {
|
|
1503
|
+
if (!this.schemaName || this.schemaSetupComplete) {
|
|
1504
|
+
return;
|
|
1505
|
+
}
|
|
1506
|
+
if (!this.setupSchemaPromise) {
|
|
1507
|
+
this.setupSchemaPromise = (async () => {
|
|
1508
|
+
try {
|
|
1509
|
+
const checkRequest = this.pool.request();
|
|
1510
|
+
checkRequest.input("schemaName", this.schemaName);
|
|
1511
|
+
const checkResult = await checkRequest.query(`
|
|
1512
|
+
SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
|
|
1513
|
+
`);
|
|
1514
|
+
const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
|
|
1515
|
+
if (!schemaExists) {
|
|
1516
|
+
try {
|
|
1517
|
+
await this.pool.request().query(`CREATE SCHEMA [${this.schemaName}]`);
|
|
1518
|
+
this.logger?.info?.(`Schema "${this.schemaName}" created successfully`);
|
|
1519
|
+
} catch (error) {
|
|
1520
|
+
this.logger?.error?.(`Failed to create schema "${this.schemaName}"`, { error });
|
|
1521
|
+
throw new Error(
|
|
1522
|
+
`Unable to create schema "${this.schemaName}". This requires CREATE privilege on the database. Either create the schema manually or grant CREATE privilege to the user.`
|
|
1523
|
+
);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
this.schemaSetupComplete = true;
|
|
1527
|
+
this.logger?.debug?.(`Schema "${this.schemaName}" is ready for use`);
|
|
1528
|
+
} catch (error) {
|
|
1529
|
+
this.schemaSetupComplete = void 0;
|
|
1530
|
+
this.setupSchemaPromise = null;
|
|
1531
|
+
throw error;
|
|
1532
|
+
} finally {
|
|
1533
|
+
this.setupSchemaPromise = null;
|
|
1534
|
+
}
|
|
1535
|
+
})();
|
|
1536
|
+
}
|
|
1537
|
+
await this.setupSchemaPromise;
|
|
1538
|
+
}
|
|
1539
|
+
async insert({
|
|
1540
|
+
tableName,
|
|
1541
|
+
record,
|
|
1542
|
+
transaction
|
|
1543
|
+
}) {
|
|
1544
|
+
try {
|
|
1545
|
+
const columns = Object.keys(record);
|
|
1546
|
+
const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
|
|
1547
|
+
const paramNames = columns.map((_, i) => `@param${i}`);
|
|
1548
|
+
const insertSql = `INSERT INTO ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (${parsedColumns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
|
|
1549
|
+
const request = transaction ? transaction.request() : this.pool.request();
|
|
1550
|
+
columns.forEach((col, i) => {
|
|
1551
|
+
const value = record[col];
|
|
1552
|
+
const preparedValue = this.prepareValue(value, col, tableName);
|
|
1553
|
+
if (preparedValue instanceof Date) {
|
|
1554
|
+
request.input(`param${i}`, sql3.DateTime2, preparedValue);
|
|
1555
|
+
} else if (preparedValue === null || preparedValue === void 0) {
|
|
1556
|
+
request.input(`param${i}`, this.getMssqlType(tableName, col), null);
|
|
1557
|
+
} else {
|
|
1558
|
+
request.input(`param${i}`, preparedValue);
|
|
1559
|
+
}
|
|
1560
|
+
});
|
|
1561
|
+
await request.query(insertSql);
|
|
1562
|
+
} catch (error) {
|
|
1563
|
+
throw new MastraError(
|
|
1564
|
+
{
|
|
1565
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
|
|
1566
|
+
domain: ErrorDomain.STORAGE,
|
|
1567
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1568
|
+
details: {
|
|
1569
|
+
tableName
|
|
1570
|
+
}
|
|
1571
|
+
},
|
|
1572
|
+
error
|
|
1573
|
+
);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
async clearTable({ tableName }) {
|
|
1577
|
+
const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
|
|
1578
|
+
try {
|
|
1579
|
+
try {
|
|
1580
|
+
await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
|
|
1581
|
+
} catch (truncateError) {
|
|
1582
|
+
if (truncateError?.number === 4712) {
|
|
1583
|
+
await this.pool.request().query(`DELETE FROM ${fullTableName}`);
|
|
1584
|
+
} else {
|
|
1585
|
+
throw truncateError;
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
} catch (error) {
|
|
1589
|
+
throw new MastraError(
|
|
1590
|
+
{
|
|
1591
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
|
|
1592
|
+
domain: ErrorDomain.STORAGE,
|
|
1593
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1594
|
+
details: {
|
|
1595
|
+
tableName
|
|
1596
|
+
}
|
|
1597
|
+
},
|
|
1598
|
+
error
|
|
1599
|
+
);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
getDefaultValue(type) {
|
|
1603
|
+
switch (type) {
|
|
1604
|
+
case "timestamp":
|
|
1605
|
+
return "DEFAULT SYSUTCDATETIME()";
|
|
1606
|
+
case "jsonb":
|
|
1607
|
+
return "DEFAULT N'{}'";
|
|
1608
|
+
case "boolean":
|
|
1609
|
+
return "DEFAULT 0";
|
|
1610
|
+
default:
|
|
1611
|
+
return super.getDefaultValue(type);
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
async createTable({
|
|
1615
|
+
tableName,
|
|
1616
|
+
schema
|
|
1617
|
+
}) {
|
|
1618
|
+
try {
|
|
1619
|
+
const uniqueConstraintColumns = tableName === TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
|
|
1620
|
+
const largeDataColumns = [
|
|
1621
|
+
"workingMemory",
|
|
1622
|
+
"snapshot",
|
|
1623
|
+
"metadata",
|
|
1624
|
+
"content",
|
|
1625
|
+
// messages.content - can be very long conversation content
|
|
1626
|
+
"input",
|
|
1627
|
+
// evals.input - test input data
|
|
1628
|
+
"output",
|
|
1629
|
+
// evals.output - test output data
|
|
1630
|
+
"instructions",
|
|
1631
|
+
// evals.instructions - evaluation instructions
|
|
1632
|
+
"other"
|
|
1633
|
+
// traces.other - additional trace data
|
|
1634
|
+
];
|
|
1635
|
+
const columns = Object.entries(schema).map(([name, def]) => {
|
|
1636
|
+
const parsedName = parseSqlIdentifier(name, "column name");
|
|
1637
|
+
const constraints = [];
|
|
1638
|
+
if (def.primaryKey) constraints.push("PRIMARY KEY");
|
|
1639
|
+
if (!def.nullable) constraints.push("NOT NULL");
|
|
1640
|
+
const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
|
|
1641
|
+
const useLargeStorage = largeDataColumns.includes(name);
|
|
1642
|
+
return `[${parsedName}] ${this.getSqlType(def.type, isIndexed, useLargeStorage)} ${constraints.join(" ")}`.trim();
|
|
1643
|
+
}).join(",\n");
|
|
1644
|
+
if (this.schemaName) {
|
|
1645
|
+
await this.setupSchema();
|
|
1646
|
+
}
|
|
1647
|
+
const checkTableRequest = this.pool.request();
|
|
1648
|
+
checkTableRequest.input(
|
|
1649
|
+
"tableName",
|
|
1650
|
+
getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
|
|
1651
|
+
);
|
|
1652
|
+
const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
|
|
1653
|
+
checkTableRequest.input("schema", this.schemaName || "dbo");
|
|
1654
|
+
const checkTableResult = await checkTableRequest.query(checkTableSql);
|
|
1655
|
+
const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
|
|
1656
|
+
if (!tableExists) {
|
|
1657
|
+
const createSql = `CREATE TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (
|
|
1658
|
+
${columns}
|
|
1659
|
+
)`;
|
|
1660
|
+
await this.pool.request().query(createSql);
|
|
1661
|
+
}
|
|
1662
|
+
const columnCheckSql = `
|
|
1663
|
+
SELECT 1 AS found
|
|
1664
|
+
FROM INFORMATION_SCHEMA.COLUMNS
|
|
1665
|
+
WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
|
|
1666
|
+
`;
|
|
1667
|
+
const checkColumnRequest = this.pool.request();
|
|
1668
|
+
checkColumnRequest.input("schema", this.schemaName || "dbo");
|
|
1669
|
+
checkColumnRequest.input(
|
|
1670
|
+
"tableName",
|
|
1671
|
+
getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
|
|
1672
|
+
);
|
|
1673
|
+
const columnResult = await checkColumnRequest.query(columnCheckSql);
|
|
1674
|
+
const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
|
|
1675
|
+
if (!columnExists) {
|
|
1676
|
+
const alterSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD seq_id BIGINT IDENTITY(1,1)`;
|
|
1677
|
+
await this.pool.request().query(alterSql);
|
|
1678
|
+
}
|
|
1679
|
+
if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
|
|
1680
|
+
const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
|
|
1681
|
+
const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
|
|
1682
|
+
const checkConstraintRequest = this.pool.request();
|
|
1683
|
+
checkConstraintRequest.input("constraintName", constraintName);
|
|
1684
|
+
const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
|
|
1685
|
+
const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
|
|
1686
|
+
if (!constraintExists) {
|
|
1687
|
+
const addConstraintSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
|
|
1688
|
+
await this.pool.request().query(addConstraintSql);
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
} catch (error) {
|
|
1692
|
+
throw new MastraError(
|
|
1693
|
+
{
|
|
1694
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
|
|
1695
|
+
domain: ErrorDomain.STORAGE,
|
|
1696
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1697
|
+
details: {
|
|
1698
|
+
tableName
|
|
1699
|
+
}
|
|
1700
|
+
},
|
|
1701
|
+
error
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
/**
|
|
1706
|
+
* Alters table schema to add columns if they don't exist
|
|
1707
|
+
* @param tableName Name of the table
|
|
1708
|
+
* @param schema Schema of the table
|
|
1709
|
+
* @param ifNotExists Array of column names to add if they don't exist
|
|
1710
|
+
*/
|
|
1711
|
+
async alterTable({
|
|
1712
|
+
tableName,
|
|
1713
|
+
schema,
|
|
1714
|
+
ifNotExists
|
|
1715
|
+
}) {
|
|
1716
|
+
const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
|
|
1717
|
+
try {
|
|
1718
|
+
for (const columnName of ifNotExists) {
|
|
1719
|
+
if (schema[columnName]) {
|
|
1720
|
+
const columnCheckRequest = this.pool.request();
|
|
1721
|
+
columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
|
|
1722
|
+
columnCheckRequest.input("columnName", columnName);
|
|
1723
|
+
columnCheckRequest.input("schema", this.schemaName || "dbo");
|
|
1724
|
+
const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
|
|
1725
|
+
const checkResult = await columnCheckRequest.query(checkSql);
|
|
1726
|
+
const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
|
|
1727
|
+
if (!columnExists) {
|
|
1728
|
+
const columnDef = schema[columnName];
|
|
1729
|
+
const largeDataColumns = [
|
|
1730
|
+
"workingMemory",
|
|
1731
|
+
"snapshot",
|
|
1732
|
+
"metadata",
|
|
1733
|
+
"content",
|
|
1734
|
+
"input",
|
|
1735
|
+
"output",
|
|
1736
|
+
"instructions",
|
|
1737
|
+
"other"
|
|
1738
|
+
];
|
|
1739
|
+
const useLargeStorage = largeDataColumns.includes(columnName);
|
|
1740
|
+
const isIndexed = !!columnDef.primaryKey;
|
|
1741
|
+
const sqlType = this.getSqlType(columnDef.type, isIndexed, useLargeStorage);
|
|
1742
|
+
const nullable = columnDef.nullable === false ? "NOT NULL" : "";
|
|
1743
|
+
const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
|
|
1744
|
+
const parsedColumnName = parseSqlIdentifier(columnName, "column name");
|
|
1745
|
+
const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
|
|
1746
|
+
await this.pool.request().query(alterSql);
|
|
1747
|
+
this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
} catch (error) {
|
|
1752
|
+
throw new MastraError(
|
|
1753
|
+
{
|
|
1754
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
|
|
1755
|
+
domain: ErrorDomain.STORAGE,
|
|
1756
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1757
|
+
details: {
|
|
1758
|
+
tableName
|
|
1759
|
+
}
|
|
1760
|
+
},
|
|
1761
|
+
error
|
|
1762
|
+
);
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
async load({ tableName, keys }) {
|
|
1766
|
+
try {
|
|
1767
|
+
const keyEntries = Object.entries(keys).map(([key, value]) => [parseSqlIdentifier(key, "column name"), value]);
|
|
1768
|
+
const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
|
|
1769
|
+
const sql7 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
|
|
1770
|
+
const request = this.pool.request();
|
|
1771
|
+
keyEntries.forEach(([key, value], i) => {
|
|
1772
|
+
const preparedValue = this.prepareValue(value, key, tableName);
|
|
1773
|
+
if (preparedValue === null || preparedValue === void 0) {
|
|
1774
|
+
request.input(`param${i}`, this.getMssqlType(tableName, key), null);
|
|
1775
|
+
} else {
|
|
1776
|
+
request.input(`param${i}`, preparedValue);
|
|
1777
|
+
}
|
|
1778
|
+
});
|
|
1779
|
+
const resultSet = await request.query(sql7);
|
|
1780
|
+
const result = resultSet.recordset[0] || null;
|
|
1781
|
+
if (!result) {
|
|
1782
|
+
return null;
|
|
1783
|
+
}
|
|
1784
|
+
if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
|
|
1785
|
+
const snapshot = result;
|
|
1786
|
+
if (typeof snapshot.snapshot === "string") {
|
|
1787
|
+
snapshot.snapshot = JSON.parse(snapshot.snapshot);
|
|
1788
|
+
}
|
|
1789
|
+
return snapshot;
|
|
1790
|
+
}
|
|
1791
|
+
return result;
|
|
1792
|
+
} catch (error) {
|
|
1793
|
+
throw new MastraError(
|
|
1794
|
+
{
|
|
1795
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
|
|
1796
|
+
domain: ErrorDomain.STORAGE,
|
|
1797
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1798
|
+
details: {
|
|
1799
|
+
tableName
|
|
1800
|
+
}
|
|
1801
|
+
},
|
|
1802
|
+
error
|
|
1803
|
+
);
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
async batchInsert({ tableName, records }) {
|
|
1807
|
+
const transaction = this.pool.transaction();
|
|
1808
|
+
try {
|
|
1809
|
+
await transaction.begin();
|
|
1810
|
+
for (const record of records) {
|
|
1811
|
+
await this.insert({ tableName, record, transaction });
|
|
1812
|
+
}
|
|
1813
|
+
await transaction.commit();
|
|
1814
|
+
} catch (error) {
|
|
1815
|
+
await transaction.rollback();
|
|
1816
|
+
throw new MastraError(
|
|
1817
|
+
{
|
|
1818
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
|
|
1819
|
+
domain: ErrorDomain.STORAGE,
|
|
1820
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1821
|
+
details: {
|
|
1822
|
+
tableName,
|
|
1823
|
+
numberOfRecords: records.length
|
|
1824
|
+
}
|
|
1825
|
+
},
|
|
1826
|
+
error
|
|
1827
|
+
);
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
async dropTable({ tableName }) {
|
|
1831
|
+
try {
|
|
1832
|
+
const tableNameWithSchema = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
|
|
1833
|
+
await this.pool.request().query(`DROP TABLE IF EXISTS ${tableNameWithSchema}`);
|
|
1834
|
+
} catch (error) {
|
|
1835
|
+
throw new MastraError(
|
|
1836
|
+
{
|
|
1837
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_DROP_TABLE_FAILED",
|
|
1838
|
+
domain: ErrorDomain.STORAGE,
|
|
1839
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1840
|
+
details: {
|
|
1841
|
+
tableName
|
|
1842
|
+
}
|
|
1843
|
+
},
|
|
1844
|
+
error
|
|
1845
|
+
);
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
/**
|
|
1849
|
+
* Prepares a value for database operations, handling Date objects and JSON serialization
|
|
1850
|
+
*/
|
|
1851
|
+
prepareValue(value, columnName, tableName) {
|
|
1852
|
+
if (value === null || value === void 0) {
|
|
1853
|
+
return value;
|
|
1854
|
+
}
|
|
1855
|
+
if (value instanceof Date) {
|
|
1856
|
+
return value;
|
|
1857
|
+
}
|
|
1858
|
+
const schema = TABLE_SCHEMAS[tableName];
|
|
1859
|
+
const columnSchema = schema?.[columnName];
|
|
1860
|
+
if (columnSchema?.type === "boolean") {
|
|
1861
|
+
return value ? 1 : 0;
|
|
1862
|
+
}
|
|
1863
|
+
if (columnSchema?.type === "jsonb") {
|
|
1864
|
+
if (typeof value === "string") {
|
|
1865
|
+
const trimmed = value.trim();
|
|
1866
|
+
if (trimmed.length > 0) {
|
|
1867
|
+
try {
|
|
1868
|
+
JSON.parse(trimmed);
|
|
1869
|
+
return trimmed;
|
|
1870
|
+
} catch {
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
return JSON.stringify(value);
|
|
1874
|
+
}
|
|
1875
|
+
if (typeof value === "bigint") {
|
|
1876
|
+
return value.toString();
|
|
1877
|
+
}
|
|
1878
|
+
return JSON.stringify(value);
|
|
1879
|
+
}
|
|
1880
|
+
if (typeof value === "object") {
|
|
1881
|
+
return JSON.stringify(value);
|
|
1882
|
+
}
|
|
1883
|
+
return value;
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* Maps TABLE_SCHEMAS types to mssql param types (used when value is null)
|
|
1887
|
+
*/
|
|
1888
|
+
getMssqlType(tableName, columnName) {
|
|
1889
|
+
const col = TABLE_SCHEMAS[tableName]?.[columnName];
|
|
1890
|
+
switch (col?.type) {
|
|
1891
|
+
case "text":
|
|
1892
|
+
return sql3.NVarChar;
|
|
1893
|
+
case "timestamp":
|
|
1894
|
+
return sql3.DateTime2;
|
|
1895
|
+
case "uuid":
|
|
1896
|
+
return sql3.UniqueIdentifier;
|
|
1897
|
+
case "jsonb":
|
|
1898
|
+
return sql3.NVarChar;
|
|
1899
|
+
case "integer":
|
|
1900
|
+
return sql3.Int;
|
|
1901
|
+
case "bigint":
|
|
1902
|
+
return sql3.BigInt;
|
|
1903
|
+
case "float":
|
|
1904
|
+
return sql3.Float;
|
|
1905
|
+
case "boolean":
|
|
1906
|
+
return sql3.Bit;
|
|
1907
|
+
default:
|
|
1908
|
+
return sql3.NVarChar;
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
/**
|
|
1912
|
+
* Update a single record in the database
|
|
1913
|
+
*/
|
|
1914
|
+
async update({
|
|
1915
|
+
tableName,
|
|
1916
|
+
keys,
|
|
1917
|
+
data,
|
|
1918
|
+
transaction
|
|
1919
|
+
}) {
|
|
1920
|
+
try {
|
|
1921
|
+
if (!data || Object.keys(data).length === 0) {
|
|
1922
|
+
throw new MastraError({
|
|
1923
|
+
id: "MASTRA_STORAGE_MSSQL_UPDATE_EMPTY_DATA",
|
|
1924
|
+
domain: ErrorDomain.STORAGE,
|
|
1925
|
+
category: ErrorCategory.USER,
|
|
1926
|
+
text: "Cannot update with empty data payload"
|
|
1927
|
+
});
|
|
1928
|
+
}
|
|
1929
|
+
if (!keys || Object.keys(keys).length === 0) {
|
|
1930
|
+
throw new MastraError({
|
|
1931
|
+
id: "MASTRA_STORAGE_MSSQL_UPDATE_EMPTY_KEYS",
|
|
1932
|
+
domain: ErrorDomain.STORAGE,
|
|
1933
|
+
category: ErrorCategory.USER,
|
|
1934
|
+
text: "Cannot update without keys to identify records"
|
|
1935
|
+
});
|
|
1936
|
+
}
|
|
1937
|
+
const setClauses = [];
|
|
1938
|
+
const request = transaction ? transaction.request() : this.pool.request();
|
|
1939
|
+
let paramIndex = 0;
|
|
1940
|
+
Object.entries(data).forEach(([key, value]) => {
|
|
1941
|
+
const parsedKey = parseSqlIdentifier(key, "column name");
|
|
1942
|
+
const paramName = `set${paramIndex++}`;
|
|
1943
|
+
setClauses.push(`[${parsedKey}] = @${paramName}`);
|
|
1944
|
+
const preparedValue = this.prepareValue(value, key, tableName);
|
|
1945
|
+
if (preparedValue === null || preparedValue === void 0) {
|
|
1946
|
+
request.input(paramName, this.getMssqlType(tableName, key), null);
|
|
1947
|
+
} else {
|
|
1948
|
+
request.input(paramName, preparedValue);
|
|
1949
|
+
}
|
|
1950
|
+
});
|
|
1951
|
+
const whereConditions = [];
|
|
1952
|
+
Object.entries(keys).forEach(([key, value]) => {
|
|
1953
|
+
const parsedKey = parseSqlIdentifier(key, "column name");
|
|
1954
|
+
const paramName = `where${paramIndex++}`;
|
|
1955
|
+
whereConditions.push(`[${parsedKey}] = @${paramName}`);
|
|
1956
|
+
const preparedValue = this.prepareValue(value, key, tableName);
|
|
1957
|
+
if (preparedValue === null || preparedValue === void 0) {
|
|
1958
|
+
request.input(paramName, this.getMssqlType(tableName, key), null);
|
|
1959
|
+
} else {
|
|
1960
|
+
request.input(paramName, preparedValue);
|
|
1961
|
+
}
|
|
1962
|
+
});
|
|
1963
|
+
const tableName_ = getTableName({
|
|
1964
|
+
indexName: tableName,
|
|
1965
|
+
schemaName: getSchemaName(this.schemaName)
|
|
1966
|
+
});
|
|
1967
|
+
const updateSql = `UPDATE ${tableName_} SET ${setClauses.join(", ")} WHERE ${whereConditions.join(" AND ")}`;
|
|
1968
|
+
await request.query(updateSql);
|
|
1969
|
+
} catch (error) {
|
|
1970
|
+
throw new MastraError(
|
|
1971
|
+
{
|
|
1972
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_FAILED",
|
|
1973
|
+
domain: ErrorDomain.STORAGE,
|
|
1974
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1975
|
+
details: {
|
|
1976
|
+
tableName
|
|
1977
|
+
}
|
|
1978
|
+
},
|
|
1979
|
+
error
|
|
1980
|
+
);
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
/**
|
|
1984
|
+
* Update multiple records in a single batch transaction
|
|
1985
|
+
*/
|
|
1986
|
+
async batchUpdate({
|
|
1987
|
+
tableName,
|
|
1988
|
+
updates
|
|
1989
|
+
}) {
|
|
1990
|
+
const transaction = this.pool.transaction();
|
|
1991
|
+
try {
|
|
1992
|
+
await transaction.begin();
|
|
1993
|
+
for (const { keys, data } of updates) {
|
|
1994
|
+
await this.update({ tableName, keys, data, transaction });
|
|
1995
|
+
}
|
|
1996
|
+
await transaction.commit();
|
|
1997
|
+
} catch (error) {
|
|
1998
|
+
await transaction.rollback();
|
|
1999
|
+
throw new MastraError(
|
|
2000
|
+
{
|
|
2001
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_UPDATE_FAILED",
|
|
2002
|
+
domain: ErrorDomain.STORAGE,
|
|
2003
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2004
|
+
details: {
|
|
2005
|
+
tableName,
|
|
2006
|
+
numberOfRecords: updates.length
|
|
2007
|
+
}
|
|
2008
|
+
},
|
|
2009
|
+
error
|
|
2010
|
+
);
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
/**
|
|
2014
|
+
* Delete multiple records by keys
|
|
2015
|
+
*/
|
|
2016
|
+
async batchDelete({ tableName, keys }) {
|
|
2017
|
+
if (keys.length === 0) {
|
|
2018
|
+
return;
|
|
2019
|
+
}
|
|
2020
|
+
const tableName_ = getTableName({
|
|
2021
|
+
indexName: tableName,
|
|
2022
|
+
schemaName: getSchemaName(this.schemaName)
|
|
2023
|
+
});
|
|
2024
|
+
const transaction = this.pool.transaction();
|
|
2025
|
+
try {
|
|
2026
|
+
await transaction.begin();
|
|
2027
|
+
for (const keySet of keys) {
|
|
2028
|
+
const conditions = [];
|
|
2029
|
+
const request = transaction.request();
|
|
2030
|
+
let paramIndex = 0;
|
|
2031
|
+
Object.entries(keySet).forEach(([key, value]) => {
|
|
2032
|
+
const parsedKey = parseSqlIdentifier(key, "column name");
|
|
2033
|
+
const paramName = `p${paramIndex++}`;
|
|
2034
|
+
conditions.push(`[${parsedKey}] = @${paramName}`);
|
|
2035
|
+
const preparedValue = this.prepareValue(value, key, tableName);
|
|
2036
|
+
if (preparedValue === null || preparedValue === void 0) {
|
|
2037
|
+
request.input(paramName, this.getMssqlType(tableName, key), null);
|
|
2038
|
+
} else {
|
|
2039
|
+
request.input(paramName, preparedValue);
|
|
2040
|
+
}
|
|
2041
|
+
});
|
|
2042
|
+
const deleteSql = `DELETE FROM ${tableName_} WHERE ${conditions.join(" AND ")}`;
|
|
2043
|
+
await request.query(deleteSql);
|
|
2044
|
+
}
|
|
2045
|
+
await transaction.commit();
|
|
2046
|
+
} catch (error) {
|
|
2047
|
+
await transaction.rollback();
|
|
2048
|
+
throw new MastraError(
|
|
2049
|
+
{
|
|
2050
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_DELETE_FAILED",
|
|
2051
|
+
domain: ErrorDomain.STORAGE,
|
|
2052
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2053
|
+
details: {
|
|
2054
|
+
tableName,
|
|
2055
|
+
numberOfRecords: keys.length
|
|
2056
|
+
}
|
|
2057
|
+
},
|
|
2058
|
+
error
|
|
2059
|
+
);
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
/**
|
|
2063
|
+
* Create a new index on a table
|
|
2064
|
+
*/
|
|
2065
|
+
async createIndex(options) {
|
|
2066
|
+
try {
|
|
2067
|
+
const { name, table, columns, unique = false, where } = options;
|
|
2068
|
+
const schemaName = this.schemaName || "dbo";
|
|
2069
|
+
const fullTableName = getTableName({
|
|
2070
|
+
indexName: table,
|
|
2071
|
+
schemaName: getSchemaName(this.schemaName)
|
|
2072
|
+
});
|
|
2073
|
+
const indexNameSafe = parseSqlIdentifier(name, "index name");
|
|
2074
|
+
const checkRequest = this.pool.request();
|
|
2075
|
+
checkRequest.input("indexName", indexNameSafe);
|
|
2076
|
+
checkRequest.input("schemaName", schemaName);
|
|
2077
|
+
checkRequest.input("tableName", table);
|
|
2078
|
+
const indexExists = await checkRequest.query(`
|
|
2079
|
+
SELECT 1 as found
|
|
2080
|
+
FROM sys.indexes i
|
|
2081
|
+
INNER JOIN sys.tables t ON i.object_id = t.object_id
|
|
2082
|
+
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
|
|
2083
|
+
WHERE i.name = @indexName
|
|
2084
|
+
AND s.name = @schemaName
|
|
2085
|
+
AND t.name = @tableName
|
|
2086
|
+
`);
|
|
2087
|
+
if (indexExists.recordset && indexExists.recordset.length > 0) {
|
|
2088
|
+
return;
|
|
2089
|
+
}
|
|
2090
|
+
const uniqueStr = unique ? "UNIQUE " : "";
|
|
2091
|
+
const columnsStr = columns.map((col) => {
|
|
2092
|
+
if (col.includes(" DESC") || col.includes(" ASC")) {
|
|
2093
|
+
const [colName, ...modifiers] = col.split(" ");
|
|
2094
|
+
if (!colName) {
|
|
2095
|
+
throw new Error(`Invalid column specification: ${col}`);
|
|
2096
|
+
}
|
|
2097
|
+
return `[${parseSqlIdentifier(colName, "column name")}] ${modifiers.join(" ")}`;
|
|
2098
|
+
}
|
|
2099
|
+
return `[${parseSqlIdentifier(col, "column name")}]`;
|
|
2100
|
+
}).join(", ");
|
|
2101
|
+
const whereStr = where ? ` WHERE ${where}` : "";
|
|
2102
|
+
const createIndexSql = `CREATE ${uniqueStr}INDEX [${indexNameSafe}] ON ${fullTableName} (${columnsStr})${whereStr}`;
|
|
2103
|
+
await this.pool.request().query(createIndexSql);
|
|
2104
|
+
} catch (error) {
|
|
2105
|
+
throw new MastraError(
|
|
2106
|
+
{
|
|
2107
|
+
id: "MASTRA_STORAGE_MSSQL_INDEX_CREATE_FAILED",
|
|
2108
|
+
domain: ErrorDomain.STORAGE,
|
|
2109
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2110
|
+
details: {
|
|
2111
|
+
indexName: options.name,
|
|
2112
|
+
tableName: options.table
|
|
2113
|
+
}
|
|
2114
|
+
},
|
|
2115
|
+
error
|
|
2116
|
+
);
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
/**
|
|
2120
|
+
* Drop an existing index
|
|
2121
|
+
*/
|
|
2122
|
+
async dropIndex(indexName) {
|
|
2123
|
+
try {
|
|
2124
|
+
const schemaName = this.schemaName || "dbo";
|
|
2125
|
+
const indexNameSafe = parseSqlIdentifier(indexName, "index name");
|
|
2126
|
+
const checkRequest = this.pool.request();
|
|
2127
|
+
checkRequest.input("indexName", indexNameSafe);
|
|
2128
|
+
checkRequest.input("schemaName", schemaName);
|
|
2129
|
+
const result = await checkRequest.query(`
|
|
2130
|
+
SELECT t.name as table_name
|
|
2131
|
+
FROM sys.indexes i
|
|
2132
|
+
INNER JOIN sys.tables t ON i.object_id = t.object_id
|
|
2133
|
+
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
|
|
2134
|
+
WHERE i.name = @indexName
|
|
2135
|
+
AND s.name = @schemaName
|
|
2136
|
+
`);
|
|
2137
|
+
if (!result.recordset || result.recordset.length === 0) {
|
|
2138
|
+
return;
|
|
2139
|
+
}
|
|
2140
|
+
if (result.recordset.length > 1) {
|
|
2141
|
+
const tables = result.recordset.map((r) => r.table_name).join(", ");
|
|
2142
|
+
throw new MastraError({
|
|
2143
|
+
id: "MASTRA_STORAGE_MSSQL_INDEX_AMBIGUOUS",
|
|
2144
|
+
domain: ErrorDomain.STORAGE,
|
|
2145
|
+
category: ErrorCategory.USER,
|
|
2146
|
+
text: `Index "${indexNameSafe}" exists on multiple tables (${tables}) in schema "${schemaName}". Please drop indexes manually or ensure unique index names.`
|
|
2147
|
+
});
|
|
2148
|
+
}
|
|
2149
|
+
const tableName = result.recordset[0].table_name;
|
|
2150
|
+
const fullTableName = getTableName({
|
|
2151
|
+
indexName: tableName,
|
|
2152
|
+
schemaName: getSchemaName(this.schemaName)
|
|
2153
|
+
});
|
|
2154
|
+
const dropSql = `DROP INDEX [${indexNameSafe}] ON ${fullTableName}`;
|
|
2155
|
+
await this.pool.request().query(dropSql);
|
|
2156
|
+
} catch (error) {
|
|
2157
|
+
throw new MastraError(
|
|
2158
|
+
{
|
|
2159
|
+
id: "MASTRA_STORAGE_MSSQL_INDEX_DROP_FAILED",
|
|
2160
|
+
domain: ErrorDomain.STORAGE,
|
|
2161
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2162
|
+
details: {
|
|
2163
|
+
indexName
|
|
2164
|
+
}
|
|
2165
|
+
},
|
|
2166
|
+
error
|
|
2167
|
+
);
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
/**
|
|
2171
|
+
* List indexes for a specific table or all tables
|
|
2172
|
+
*/
|
|
2173
|
+
async listIndexes(tableName) {
|
|
2174
|
+
try {
|
|
2175
|
+
const schemaName = this.schemaName || "dbo";
|
|
2176
|
+
let query;
|
|
2177
|
+
const request = this.pool.request();
|
|
2178
|
+
request.input("schemaName", schemaName);
|
|
2179
|
+
if (tableName) {
|
|
2180
|
+
query = `
|
|
2181
|
+
SELECT
|
|
2182
|
+
i.name as name,
|
|
2183
|
+
o.name as [table],
|
|
2184
|
+
i.is_unique as is_unique,
|
|
2185
|
+
CAST(SUM(s.used_page_count) * 8 / 1024.0 AS VARCHAR(50)) + ' MB' as size
|
|
2186
|
+
FROM sys.indexes i
|
|
2187
|
+
INNER JOIN sys.objects o ON i.object_id = o.object_id
|
|
2188
|
+
INNER JOIN sys.schemas sch ON o.schema_id = sch.schema_id
|
|
2189
|
+
LEFT JOIN sys.dm_db_partition_stats s ON i.object_id = s.object_id AND i.index_id = s.index_id
|
|
2190
|
+
WHERE sch.name = @schemaName
|
|
2191
|
+
AND o.name = @tableName
|
|
2192
|
+
AND i.name IS NOT NULL
|
|
2193
|
+
GROUP BY i.name, o.name, i.is_unique
|
|
2194
|
+
`;
|
|
2195
|
+
request.input("tableName", tableName);
|
|
2196
|
+
} else {
|
|
2197
|
+
query = `
|
|
2198
|
+
SELECT
|
|
2199
|
+
i.name as name,
|
|
2200
|
+
o.name as [table],
|
|
2201
|
+
i.is_unique as is_unique,
|
|
2202
|
+
CAST(SUM(s.used_page_count) * 8 / 1024.0 AS VARCHAR(50)) + ' MB' as size
|
|
2203
|
+
FROM sys.indexes i
|
|
2204
|
+
INNER JOIN sys.objects o ON i.object_id = o.object_id
|
|
2205
|
+
INNER JOIN sys.schemas sch ON o.schema_id = sch.schema_id
|
|
2206
|
+
LEFT JOIN sys.dm_db_partition_stats s ON i.object_id = s.object_id AND i.index_id = s.index_id
|
|
2207
|
+
WHERE sch.name = @schemaName
|
|
2208
|
+
AND i.name IS NOT NULL
|
|
2209
|
+
GROUP BY i.name, o.name, i.is_unique
|
|
2210
|
+
`;
|
|
2211
|
+
}
|
|
2212
|
+
const result = await request.query(query);
|
|
2213
|
+
const indexes = [];
|
|
2214
|
+
for (const row of result.recordset) {
|
|
2215
|
+
const colRequest = this.pool.request();
|
|
2216
|
+
colRequest.input("indexName", row.name);
|
|
2217
|
+
colRequest.input("schemaName", schemaName);
|
|
2218
|
+
const colResult = await colRequest.query(`
|
|
2219
|
+
SELECT c.name as column_name
|
|
2220
|
+
FROM sys.indexes i
|
|
2221
|
+
INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
|
|
2222
|
+
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
|
|
2223
|
+
INNER JOIN sys.objects o ON i.object_id = o.object_id
|
|
2224
|
+
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
|
|
2225
|
+
WHERE i.name = @indexName
|
|
2226
|
+
AND s.name = @schemaName
|
|
2227
|
+
ORDER BY ic.key_ordinal
|
|
2228
|
+
`);
|
|
2229
|
+
indexes.push({
|
|
2230
|
+
name: row.name,
|
|
2231
|
+
table: row.table,
|
|
2232
|
+
columns: colResult.recordset.map((c) => c.column_name),
|
|
2233
|
+
unique: row.is_unique || false,
|
|
2234
|
+
size: row.size || "0 MB",
|
|
2235
|
+
definition: ""
|
|
2236
|
+
// MSSQL doesn't store definition like PG
|
|
2237
|
+
});
|
|
2238
|
+
}
|
|
2239
|
+
return indexes;
|
|
2240
|
+
} catch (error) {
|
|
2241
|
+
throw new MastraError(
|
|
2242
|
+
{
|
|
2243
|
+
id: "MASTRA_STORAGE_MSSQL_INDEX_LIST_FAILED",
|
|
2244
|
+
domain: ErrorDomain.STORAGE,
|
|
2245
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2246
|
+
details: tableName ? {
|
|
2247
|
+
tableName
|
|
2248
|
+
} : {}
|
|
2249
|
+
},
|
|
2250
|
+
error
|
|
2251
|
+
);
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
/**
|
|
2255
|
+
* Get detailed statistics for a specific index
|
|
2256
|
+
*/
|
|
2257
|
+
async describeIndex(indexName) {
|
|
2258
|
+
try {
|
|
2259
|
+
const schemaName = this.schemaName || "dbo";
|
|
2260
|
+
const request = this.pool.request();
|
|
2261
|
+
request.input("indexName", indexName);
|
|
2262
|
+
request.input("schemaName", schemaName);
|
|
2263
|
+
const query = `
|
|
2264
|
+
SELECT
|
|
2265
|
+
i.name as name,
|
|
2266
|
+
o.name as [table],
|
|
2267
|
+
i.is_unique as is_unique,
|
|
2268
|
+
CAST(SUM(s.used_page_count) * 8 / 1024.0 AS VARCHAR(50)) + ' MB' as size,
|
|
2269
|
+
i.type_desc as method,
|
|
2270
|
+
ISNULL(us.user_scans, 0) as scans,
|
|
2271
|
+
ISNULL(us.user_seeks + us.user_scans, 0) as tuples_read,
|
|
2272
|
+
ISNULL(us.user_lookups, 0) as tuples_fetched
|
|
2273
|
+
FROM sys.indexes i
|
|
2274
|
+
INNER JOIN sys.objects o ON i.object_id = o.object_id
|
|
2275
|
+
INNER JOIN sys.schemas sch ON o.schema_id = sch.schema_id
|
|
2276
|
+
LEFT JOIN sys.dm_db_partition_stats s ON i.object_id = s.object_id AND i.index_id = s.index_id
|
|
2277
|
+
LEFT JOIN sys.dm_db_index_usage_stats us ON i.object_id = us.object_id AND i.index_id = us.index_id
|
|
2278
|
+
WHERE i.name = @indexName
|
|
2279
|
+
AND sch.name = @schemaName
|
|
2280
|
+
GROUP BY i.name, o.name, i.is_unique, i.type_desc, us.user_seeks, us.user_scans, us.user_lookups
|
|
2281
|
+
`;
|
|
2282
|
+
const result = await request.query(query);
|
|
2283
|
+
if (!result.recordset || result.recordset.length === 0) {
|
|
2284
|
+
throw new Error(`Index "${indexName}" not found in schema "${schemaName}"`);
|
|
2285
|
+
}
|
|
2286
|
+
const row = result.recordset[0];
|
|
2287
|
+
const colRequest = this.pool.request();
|
|
2288
|
+
colRequest.input("indexName", indexName);
|
|
2289
|
+
colRequest.input("schemaName", schemaName);
|
|
2290
|
+
const colResult = await colRequest.query(`
|
|
2291
|
+
SELECT c.name as column_name
|
|
2292
|
+
FROM sys.indexes i
|
|
2293
|
+
INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
|
|
2294
|
+
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
|
|
2295
|
+
INNER JOIN sys.objects o ON i.object_id = o.object_id
|
|
2296
|
+
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
|
|
2297
|
+
WHERE i.name = @indexName
|
|
2298
|
+
AND s.name = @schemaName
|
|
2299
|
+
ORDER BY ic.key_ordinal
|
|
2300
|
+
`);
|
|
2301
|
+
return {
|
|
2302
|
+
name: row.name,
|
|
2303
|
+
table: row.table,
|
|
2304
|
+
columns: colResult.recordset.map((c) => c.column_name),
|
|
2305
|
+
unique: row.is_unique || false,
|
|
2306
|
+
size: row.size || "0 MB",
|
|
2307
|
+
definition: "",
|
|
2308
|
+
method: row.method?.toLowerCase() || "nonclustered",
|
|
2309
|
+
scans: Number(row.scans) || 0,
|
|
2310
|
+
tuples_read: Number(row.tuples_read) || 0,
|
|
2311
|
+
tuples_fetched: Number(row.tuples_fetched) || 0
|
|
2312
|
+
};
|
|
2313
|
+
} catch (error) {
|
|
2314
|
+
throw new MastraError(
|
|
2315
|
+
{
|
|
2316
|
+
id: "MASTRA_STORAGE_MSSQL_INDEX_DESCRIBE_FAILED",
|
|
2317
|
+
domain: ErrorDomain.STORAGE,
|
|
2318
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2319
|
+
details: {
|
|
2320
|
+
indexName
|
|
2321
|
+
}
|
|
2322
|
+
},
|
|
2323
|
+
error
|
|
2324
|
+
);
|
|
2325
|
+
}
|
|
2326
|
+
}
|
|
2327
|
+
/**
|
|
2328
|
+
* Returns definitions for automatic performance indexes
|
|
2329
|
+
* IMPORTANT: Uses seq_id DESC instead of createdAt DESC for MSSQL due to millisecond accuracy limitations
|
|
2330
|
+
* NOTE: Using NVARCHAR(400) for text columns (800 bytes) leaves room for composite indexes
|
|
2331
|
+
*/
|
|
2332
|
+
getAutomaticIndexDefinitions() {
|
|
2333
|
+
const schemaPrefix = this.schemaName ? `${this.schemaName}_` : "";
|
|
2334
|
+
return [
|
|
2335
|
+
// Composite indexes for optimal filtering + sorting performance
|
|
2336
|
+
// NVARCHAR(400) = 800 bytes, plus BIGINT (8 bytes) = 808 bytes total (under 900-byte limit)
|
|
2337
|
+
{
|
|
2338
|
+
name: `${schemaPrefix}mastra_threads_resourceid_seqid_idx`,
|
|
2339
|
+
table: TABLE_THREADS,
|
|
2340
|
+
columns: ["resourceId", "seq_id DESC"]
|
|
2341
|
+
},
|
|
2342
|
+
{
|
|
2343
|
+
name: `${schemaPrefix}mastra_messages_thread_id_seqid_idx`,
|
|
2344
|
+
table: TABLE_MESSAGES,
|
|
2345
|
+
columns: ["thread_id", "seq_id DESC"]
|
|
2346
|
+
},
|
|
2347
|
+
{
|
|
2348
|
+
name: `${schemaPrefix}mastra_traces_name_seqid_idx`,
|
|
2349
|
+
table: TABLE_TRACES,
|
|
2350
|
+
columns: ["name", "seq_id DESC"]
|
|
2351
|
+
},
|
|
2352
|
+
{
|
|
2353
|
+
name: `${schemaPrefix}mastra_evals_agent_name_seqid_idx`,
|
|
2354
|
+
table: TABLE_EVALS,
|
|
2355
|
+
columns: ["agent_name", "seq_id DESC"]
|
|
2356
|
+
},
|
|
2357
|
+
{
|
|
2358
|
+
name: `${schemaPrefix}mastra_scores_trace_id_span_id_seqid_idx`,
|
|
2359
|
+
table: TABLE_SCORERS,
|
|
2360
|
+
columns: ["traceId", "spanId", "seq_id DESC"]
|
|
2361
|
+
},
|
|
2362
|
+
// AI Spans indexes for optimal trace querying
|
|
2363
|
+
{
|
|
2364
|
+
name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
|
|
2365
|
+
table: TABLE_AI_SPANS,
|
|
2366
|
+
columns: ["traceId", "startedAt DESC"]
|
|
2367
|
+
},
|
|
2368
|
+
{
|
|
2369
|
+
name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
|
|
2370
|
+
table: TABLE_AI_SPANS,
|
|
2371
|
+
columns: ["parentSpanId", "startedAt DESC"]
|
|
2372
|
+
},
|
|
2373
|
+
{
|
|
2374
|
+
name: `${schemaPrefix}mastra_ai_spans_name_idx`,
|
|
2375
|
+
table: TABLE_AI_SPANS,
|
|
2376
|
+
columns: ["name"]
|
|
2377
|
+
},
|
|
2378
|
+
{
|
|
2379
|
+
name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
|
|
2380
|
+
table: TABLE_AI_SPANS,
|
|
2381
|
+
columns: ["spanType", "startedAt DESC"]
|
|
2382
|
+
}
|
|
2383
|
+
];
|
|
2384
|
+
}
|
|
2385
|
+
/**
|
|
2386
|
+
* Creates automatic indexes for optimal query performance
|
|
2387
|
+
* Uses getAutomaticIndexDefinitions() to determine which indexes to create
|
|
2388
|
+
*/
|
|
2389
|
+
async createAutomaticIndexes() {
|
|
2390
|
+
try {
|
|
2391
|
+
const indexes = this.getAutomaticIndexDefinitions();
|
|
2392
|
+
for (const indexOptions of indexes) {
|
|
2393
|
+
try {
|
|
2394
|
+
await this.createIndex(indexOptions);
|
|
2395
|
+
} catch (error) {
|
|
2396
|
+
this.logger?.warn?.(`Failed to create index ${indexOptions.name}:`, error);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
} catch (error) {
|
|
2400
|
+
throw new MastraError(
|
|
2401
|
+
{
|
|
2402
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_PERFORMANCE_INDEXES_FAILED",
|
|
2403
|
+
domain: ErrorDomain.STORAGE,
|
|
2404
|
+
category: ErrorCategory.THIRD_PARTY
|
|
2405
|
+
},
|
|
2406
|
+
error
|
|
2407
|
+
);
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
};
|
|
2411
|
+
function transformScoreRow(row) {
|
|
2412
|
+
return {
|
|
2413
|
+
...row,
|
|
2414
|
+
input: safelyParseJSON(row.input),
|
|
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
|
+
};
|
|
2426
|
+
}
|
|
2427
|
+
var ScoresMSSQL = class extends ScoresStorage {
|
|
2428
|
+
pool;
|
|
2429
|
+
operations;
|
|
2430
|
+
schema;
|
|
2431
|
+
constructor({
|
|
2432
|
+
pool,
|
|
2433
|
+
operations,
|
|
2434
|
+
schema
|
|
2435
|
+
}) {
|
|
2436
|
+
super();
|
|
2437
|
+
this.pool = pool;
|
|
2438
|
+
this.operations = operations;
|
|
2439
|
+
this.schema = schema;
|
|
2440
|
+
}
|
|
2441
|
+
async getScoreById({ id }) {
|
|
2442
|
+
try {
|
|
2443
|
+
const request = this.pool.request();
|
|
2444
|
+
request.input("p1", id);
|
|
2445
|
+
const result = await request.query(
|
|
2446
|
+
`SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE id = @p1`
|
|
2447
|
+
);
|
|
2448
|
+
if (result.recordset.length === 0) {
|
|
2449
|
+
return null;
|
|
2450
|
+
}
|
|
2451
|
+
return transformScoreRow(result.recordset[0]);
|
|
2452
|
+
} catch (error) {
|
|
2453
|
+
throw new MastraError(
|
|
2454
|
+
{
|
|
2455
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORE_BY_ID_FAILED",
|
|
2456
|
+
domain: ErrorDomain.STORAGE,
|
|
2457
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2458
|
+
details: { id }
|
|
2459
|
+
},
|
|
2460
|
+
error
|
|
2461
|
+
);
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
async saveScore(score) {
|
|
2465
|
+
let validatedScore;
|
|
2466
|
+
try {
|
|
2467
|
+
validatedScore = saveScorePayloadSchema.parse(score);
|
|
2468
|
+
} catch (error) {
|
|
2469
|
+
throw new MastraError(
|
|
2470
|
+
{
|
|
2471
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_VALIDATION_FAILED",
|
|
2472
|
+
domain: ErrorDomain.STORAGE,
|
|
2473
|
+
category: ErrorCategory.THIRD_PARTY
|
|
2474
|
+
},
|
|
2475
|
+
error
|
|
2476
|
+
);
|
|
2477
|
+
}
|
|
2478
|
+
try {
|
|
2479
|
+
const scoreId = randomUUID();
|
|
2480
|
+
const {
|
|
2481
|
+
scorer,
|
|
2482
|
+
preprocessStepResult,
|
|
2483
|
+
analyzeStepResult,
|
|
2484
|
+
metadata,
|
|
2485
|
+
input,
|
|
2486
|
+
output,
|
|
2487
|
+
additionalContext,
|
|
2488
|
+
runtimeContext,
|
|
2489
|
+
entity,
|
|
2490
|
+
...rest
|
|
2491
|
+
} = validatedScore;
|
|
2492
|
+
await this.operations.insert({
|
|
2493
|
+
tableName: TABLE_SCORERS,
|
|
2494
|
+
record: {
|
|
2495
|
+
id: scoreId,
|
|
2496
|
+
...rest,
|
|
2497
|
+
input: input || "",
|
|
2498
|
+
output: output || "",
|
|
2499
|
+
preprocessStepResult: preprocessStepResult || null,
|
|
2500
|
+
analyzeStepResult: analyzeStepResult || null,
|
|
2501
|
+
metadata: metadata || null,
|
|
2502
|
+
additionalContext: additionalContext || null,
|
|
2503
|
+
runtimeContext: runtimeContext || null,
|
|
2504
|
+
entity: entity || null,
|
|
2505
|
+
scorer: scorer || null,
|
|
2506
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2507
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2508
|
+
}
|
|
2509
|
+
});
|
|
2510
|
+
const scoreFromDb = await this.getScoreById({ id: scoreId });
|
|
2511
|
+
return { score: scoreFromDb };
|
|
2512
|
+
} catch (error) {
|
|
2513
|
+
throw new MastraError(
|
|
2514
|
+
{
|
|
2515
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_FAILED",
|
|
2516
|
+
domain: ErrorDomain.STORAGE,
|
|
2517
|
+
category: ErrorCategory.THIRD_PARTY
|
|
2518
|
+
},
|
|
2519
|
+
error
|
|
2520
|
+
);
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
async getScoresByScorerId({
|
|
2524
|
+
scorerId,
|
|
2525
|
+
pagination,
|
|
2526
|
+
entityId,
|
|
2527
|
+
entityType,
|
|
2528
|
+
source
|
|
2529
|
+
}) {
|
|
2530
|
+
try {
|
|
2531
|
+
const conditions = ["[scorerId] = @p1"];
|
|
2532
|
+
const params = { p1: scorerId };
|
|
2533
|
+
let paramIndex = 2;
|
|
2534
|
+
if (entityId) {
|
|
2535
|
+
conditions.push(`[entityId] = @p${paramIndex}`);
|
|
2536
|
+
params[`p${paramIndex}`] = entityId;
|
|
2537
|
+
paramIndex++;
|
|
2538
|
+
}
|
|
2539
|
+
if (entityType) {
|
|
2540
|
+
conditions.push(`[entityType] = @p${paramIndex}`);
|
|
2541
|
+
params[`p${paramIndex}`] = entityType;
|
|
2542
|
+
paramIndex++;
|
|
2543
|
+
}
|
|
2544
|
+
if (source) {
|
|
2545
|
+
conditions.push(`[source] = @p${paramIndex}`);
|
|
2546
|
+
params[`p${paramIndex}`] = source;
|
|
2547
|
+
paramIndex++;
|
|
2548
|
+
}
|
|
2549
|
+
const whereClause = conditions.join(" AND ");
|
|
2550
|
+
const tableName = getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) });
|
|
2551
|
+
const countRequest = this.pool.request();
|
|
2552
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
2553
|
+
countRequest.input(key, value);
|
|
2554
|
+
});
|
|
2555
|
+
const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
|
|
2556
|
+
const total = totalResult.recordset[0]?.count || 0;
|
|
2557
|
+
if (total === 0) {
|
|
2558
|
+
return {
|
|
2559
|
+
pagination: {
|
|
2560
|
+
total: 0,
|
|
2561
|
+
page: pagination.page,
|
|
2562
|
+
perPage: pagination.perPage,
|
|
2563
|
+
hasMore: false
|
|
2564
|
+
},
|
|
2565
|
+
scores: []
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
const dataRequest = this.pool.request();
|
|
2569
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
2570
|
+
dataRequest.input(key, value);
|
|
2571
|
+
});
|
|
2572
|
+
dataRequest.input("perPage", pagination.perPage);
|
|
2573
|
+
dataRequest.input("offset", pagination.page * pagination.perPage);
|
|
2574
|
+
const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
2575
|
+
const result = await dataRequest.query(dataQuery);
|
|
2576
|
+
return {
|
|
2577
|
+
pagination: {
|
|
2578
|
+
total: Number(total),
|
|
2579
|
+
page: pagination.page,
|
|
2580
|
+
perPage: pagination.perPage,
|
|
2581
|
+
hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
|
|
2582
|
+
},
|
|
2583
|
+
scores: result.recordset.map((row) => transformScoreRow(row))
|
|
2584
|
+
};
|
|
2585
|
+
} catch (error) {
|
|
2586
|
+
throw new MastraError(
|
|
2587
|
+
{
|
|
2588
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
|
|
2589
|
+
domain: ErrorDomain.STORAGE,
|
|
2590
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2591
|
+
details: { scorerId }
|
|
2592
|
+
},
|
|
2593
|
+
error
|
|
2594
|
+
);
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
async getScoresByRunId({
|
|
2598
|
+
runId,
|
|
2599
|
+
pagination
|
|
2600
|
+
}) {
|
|
2601
|
+
try {
|
|
2602
|
+
const request = this.pool.request();
|
|
2603
|
+
request.input("p1", runId);
|
|
2604
|
+
const totalResult = await request.query(
|
|
2605
|
+
`SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
|
|
2606
|
+
);
|
|
2607
|
+
const total = totalResult.recordset[0]?.count || 0;
|
|
2608
|
+
if (total === 0) {
|
|
2609
|
+
return {
|
|
2610
|
+
pagination: {
|
|
2611
|
+
total: 0,
|
|
2612
|
+
page: pagination.page,
|
|
2613
|
+
perPage: pagination.perPage,
|
|
2614
|
+
hasMore: false
|
|
2615
|
+
},
|
|
2616
|
+
scores: []
|
|
2617
|
+
};
|
|
2618
|
+
}
|
|
2619
|
+
const dataRequest = this.pool.request();
|
|
2620
|
+
dataRequest.input("p1", runId);
|
|
2621
|
+
dataRequest.input("p2", pagination.perPage);
|
|
2622
|
+
dataRequest.input("p3", pagination.page * pagination.perPage);
|
|
2623
|
+
const result = await dataRequest.query(
|
|
2624
|
+
`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
|
+
);
|
|
2626
|
+
return {
|
|
2627
|
+
pagination: {
|
|
2628
|
+
total: Number(total),
|
|
2629
|
+
page: pagination.page,
|
|
2630
|
+
perPage: pagination.perPage,
|
|
2631
|
+
hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
|
|
2632
|
+
},
|
|
2633
|
+
scores: result.recordset.map((row) => transformScoreRow(row))
|
|
2634
|
+
};
|
|
2635
|
+
} catch (error) {
|
|
2636
|
+
throw new MastraError(
|
|
2637
|
+
{
|
|
2638
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_RUN_ID_FAILED",
|
|
2639
|
+
domain: ErrorDomain.STORAGE,
|
|
2640
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2641
|
+
details: { runId }
|
|
2642
|
+
},
|
|
2643
|
+
error
|
|
2644
|
+
);
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
async getScoresByEntityId({
|
|
2648
|
+
entityId,
|
|
2649
|
+
entityType,
|
|
2650
|
+
pagination
|
|
2651
|
+
}) {
|
|
2652
|
+
try {
|
|
2653
|
+
const request = this.pool.request();
|
|
2654
|
+
request.input("p1", entityId);
|
|
2655
|
+
request.input("p2", entityType);
|
|
2656
|
+
const totalResult = await request.query(
|
|
2657
|
+
`SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
|
|
2658
|
+
);
|
|
2659
|
+
const total = totalResult.recordset[0]?.count || 0;
|
|
2660
|
+
if (total === 0) {
|
|
2661
|
+
return {
|
|
2662
|
+
pagination: {
|
|
2663
|
+
total: 0,
|
|
2664
|
+
page: pagination.page,
|
|
2665
|
+
perPage: pagination.perPage,
|
|
2666
|
+
hasMore: false
|
|
2667
|
+
},
|
|
2668
|
+
scores: []
|
|
2669
|
+
};
|
|
2670
|
+
}
|
|
2671
|
+
const dataRequest = this.pool.request();
|
|
2672
|
+
dataRequest.input("p1", entityId);
|
|
2673
|
+
dataRequest.input("p2", entityType);
|
|
2674
|
+
dataRequest.input("p3", pagination.perPage);
|
|
2675
|
+
dataRequest.input("p4", pagination.page * pagination.perPage);
|
|
2676
|
+
const result = await dataRequest.query(
|
|
2677
|
+
`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
|
+
);
|
|
2679
|
+
return {
|
|
2680
|
+
pagination: {
|
|
2681
|
+
total: Number(total),
|
|
2682
|
+
page: pagination.page,
|
|
2683
|
+
perPage: pagination.perPage,
|
|
2684
|
+
hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
|
|
2685
|
+
},
|
|
2686
|
+
scores: result.recordset.map((row) => transformScoreRow(row))
|
|
2687
|
+
};
|
|
2688
|
+
} catch (error) {
|
|
2689
|
+
throw new MastraError(
|
|
2690
|
+
{
|
|
2691
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
|
|
2692
|
+
domain: ErrorDomain.STORAGE,
|
|
2693
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2694
|
+
details: { entityId, entityType }
|
|
2695
|
+
},
|
|
2696
|
+
error
|
|
2697
|
+
);
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
async getScoresBySpan({
|
|
2701
|
+
traceId,
|
|
2702
|
+
spanId,
|
|
2703
|
+
pagination
|
|
2704
|
+
}) {
|
|
2705
|
+
try {
|
|
2706
|
+
const request = this.pool.request();
|
|
2707
|
+
request.input("p1", traceId);
|
|
2708
|
+
request.input("p2", spanId);
|
|
2709
|
+
const totalResult = await request.query(
|
|
2710
|
+
`SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
|
|
2711
|
+
);
|
|
2712
|
+
const total = totalResult.recordset[0]?.count || 0;
|
|
2713
|
+
if (total === 0) {
|
|
2714
|
+
return {
|
|
2715
|
+
pagination: {
|
|
2716
|
+
total: 0,
|
|
2717
|
+
page: pagination.page,
|
|
2718
|
+
perPage: pagination.perPage,
|
|
2719
|
+
hasMore: false
|
|
2720
|
+
},
|
|
2721
|
+
scores: []
|
|
2722
|
+
};
|
|
2723
|
+
}
|
|
2724
|
+
const limit = pagination.perPage + 1;
|
|
2725
|
+
const dataRequest = this.pool.request();
|
|
2726
|
+
dataRequest.input("p1", traceId);
|
|
2727
|
+
dataRequest.input("p2", spanId);
|
|
2728
|
+
dataRequest.input("p3", limit);
|
|
2729
|
+
dataRequest.input("p4", pagination.page * pagination.perPage);
|
|
2730
|
+
const result = await dataRequest.query(
|
|
2731
|
+
`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
|
+
);
|
|
2733
|
+
return {
|
|
2734
|
+
pagination: {
|
|
2735
|
+
total: Number(total),
|
|
2736
|
+
page: pagination.page,
|
|
2737
|
+
perPage: pagination.perPage,
|
|
2738
|
+
hasMore: result.recordset.length > pagination.perPage
|
|
2739
|
+
},
|
|
2740
|
+
scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
|
|
2741
|
+
};
|
|
2742
|
+
} catch (error) {
|
|
2743
|
+
throw new MastraError(
|
|
2744
|
+
{
|
|
2745
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SPAN_FAILED",
|
|
2746
|
+
domain: ErrorDomain.STORAGE,
|
|
2747
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2748
|
+
details: { traceId, spanId }
|
|
2749
|
+
},
|
|
2750
|
+
error
|
|
2751
|
+
);
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
};
|
|
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
|
+
var WorkflowsMSSQL = class extends WorkflowsStorage {
|
|
2923
|
+
pool;
|
|
2924
|
+
operations;
|
|
2925
|
+
schema;
|
|
2926
|
+
constructor({
|
|
2927
|
+
pool,
|
|
2928
|
+
operations,
|
|
2929
|
+
schema
|
|
2930
|
+
}) {
|
|
2931
|
+
super();
|
|
2932
|
+
this.pool = pool;
|
|
2933
|
+
this.operations = operations;
|
|
2934
|
+
this.schema = schema;
|
|
2935
|
+
}
|
|
2936
|
+
parseWorkflowRun(row) {
|
|
2937
|
+
let parsedSnapshot = row.snapshot;
|
|
2938
|
+
if (typeof parsedSnapshot === "string") {
|
|
2939
|
+
try {
|
|
2940
|
+
parsedSnapshot = JSON.parse(row.snapshot);
|
|
2941
|
+
} catch (e) {
|
|
2942
|
+
this.logger?.warn?.(`Failed to parse snapshot for workflow ${row.workflow_name}:`, e);
|
|
2943
|
+
}
|
|
2944
|
+
}
|
|
2945
|
+
return {
|
|
2946
|
+
workflowName: row.workflow_name,
|
|
2947
|
+
runId: row.run_id,
|
|
2948
|
+
snapshot: parsedSnapshot,
|
|
2949
|
+
createdAt: row.createdAt,
|
|
2950
|
+
updatedAt: row.updatedAt,
|
|
2951
|
+
resourceId: row.resourceId
|
|
2952
|
+
};
|
|
2953
|
+
}
|
|
2954
|
+
async updateWorkflowResults({
|
|
2955
|
+
workflowName,
|
|
2956
|
+
runId,
|
|
2957
|
+
stepId,
|
|
2958
|
+
result,
|
|
2959
|
+
runtimeContext
|
|
2960
|
+
}) {
|
|
2961
|
+
const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
|
|
2962
|
+
const transaction = this.pool.transaction();
|
|
2963
|
+
try {
|
|
2964
|
+
await transaction.begin();
|
|
2965
|
+
const selectRequest = new sql3.Request(transaction);
|
|
2966
|
+
selectRequest.input("workflow_name", workflowName);
|
|
2967
|
+
selectRequest.input("run_id", runId);
|
|
2968
|
+
const existingSnapshotResult = await selectRequest.query(
|
|
2969
|
+
`SELECT snapshot FROM ${table} WITH (UPDLOCK, HOLDLOCK) WHERE workflow_name = @workflow_name AND run_id = @run_id`
|
|
2970
|
+
);
|
|
2971
|
+
let snapshot;
|
|
2972
|
+
if (!existingSnapshotResult.recordset || existingSnapshotResult.recordset.length === 0) {
|
|
2973
|
+
snapshot = {
|
|
2974
|
+
context: {},
|
|
2975
|
+
activePaths: [],
|
|
2976
|
+
activeStepsPath: {},
|
|
2977
|
+
timestamp: Date.now(),
|
|
2978
|
+
suspendedPaths: {},
|
|
2979
|
+
resumeLabels: {},
|
|
2980
|
+
serializedStepGraph: [],
|
|
2981
|
+
status: "pending",
|
|
2982
|
+
value: {},
|
|
2983
|
+
waitingPaths: {},
|
|
2984
|
+
runId,
|
|
2985
|
+
runtimeContext: {}
|
|
2986
|
+
};
|
|
2987
|
+
} else {
|
|
2988
|
+
const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
|
|
2989
|
+
snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
|
|
2990
|
+
}
|
|
2991
|
+
snapshot.context[stepId] = result;
|
|
2992
|
+
snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
|
|
2993
|
+
const upsertReq = new sql3.Request(transaction);
|
|
2994
|
+
upsertReq.input("workflow_name", workflowName);
|
|
2995
|
+
upsertReq.input("run_id", runId);
|
|
2996
|
+
upsertReq.input("snapshot", JSON.stringify(snapshot));
|
|
2997
|
+
upsertReq.input("createdAt", sql3.DateTime2, /* @__PURE__ */ new Date());
|
|
2998
|
+
upsertReq.input("updatedAt", sql3.DateTime2, /* @__PURE__ */ new Date());
|
|
2999
|
+
await upsertReq.query(
|
|
3000
|
+
`MERGE ${table} AS target
|
|
3001
|
+
USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
|
|
3002
|
+
ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
|
|
3003
|
+
WHEN MATCHED THEN UPDATE SET snapshot = @snapshot, [updatedAt] = @updatedAt
|
|
3004
|
+
WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
|
|
3005
|
+
VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`
|
|
3006
|
+
);
|
|
3007
|
+
await transaction.commit();
|
|
3008
|
+
return snapshot.context;
|
|
3009
|
+
} catch (error) {
|
|
3010
|
+
try {
|
|
3011
|
+
await transaction.rollback();
|
|
3012
|
+
} catch {
|
|
3013
|
+
}
|
|
3014
|
+
throw new MastraError(
|
|
3015
|
+
{
|
|
3016
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_WORKFLOW_RESULTS_FAILED",
|
|
3017
|
+
domain: ErrorDomain.STORAGE,
|
|
3018
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
3019
|
+
details: {
|
|
3020
|
+
workflowName,
|
|
3021
|
+
runId,
|
|
3022
|
+
stepId
|
|
3023
|
+
}
|
|
3024
|
+
},
|
|
3025
|
+
error
|
|
3026
|
+
);
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
async updateWorkflowState({
|
|
3030
|
+
workflowName,
|
|
3031
|
+
runId,
|
|
3032
|
+
opts
|
|
3033
|
+
}) {
|
|
3034
|
+
const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
|
|
3035
|
+
const transaction = this.pool.transaction();
|
|
3036
|
+
try {
|
|
3037
|
+
await transaction.begin();
|
|
3038
|
+
const selectRequest = new sql3.Request(transaction);
|
|
3039
|
+
selectRequest.input("workflow_name", workflowName);
|
|
3040
|
+
selectRequest.input("run_id", runId);
|
|
3041
|
+
const existingSnapshotResult = await selectRequest.query(
|
|
3042
|
+
`SELECT snapshot FROM ${table} WITH (UPDLOCK, HOLDLOCK) WHERE workflow_name = @workflow_name AND run_id = @run_id`
|
|
3043
|
+
);
|
|
3044
|
+
if (!existingSnapshotResult.recordset || existingSnapshotResult.recordset.length === 0) {
|
|
3045
|
+
await transaction.rollback();
|
|
3046
|
+
return void 0;
|
|
3047
|
+
}
|
|
3048
|
+
const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
|
|
3049
|
+
const snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
|
|
3050
|
+
if (!snapshot || !snapshot?.context) {
|
|
3051
|
+
await transaction.rollback();
|
|
3052
|
+
throw new MastraError(
|
|
3053
|
+
{
|
|
3054
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_WORKFLOW_STATE_SNAPSHOT_NOT_FOUND",
|
|
3055
|
+
domain: ErrorDomain.STORAGE,
|
|
3056
|
+
category: ErrorCategory.SYSTEM,
|
|
3057
|
+
details: {
|
|
3058
|
+
workflowName,
|
|
3059
|
+
runId
|
|
3060
|
+
}
|
|
3061
|
+
},
|
|
3062
|
+
new Error(`Snapshot not found for runId ${runId}`)
|
|
3063
|
+
);
|
|
3064
|
+
}
|
|
3065
|
+
const updatedSnapshot = { ...snapshot, ...opts };
|
|
3066
|
+
const updateRequest = new sql3.Request(transaction);
|
|
3067
|
+
updateRequest.input("snapshot", JSON.stringify(updatedSnapshot));
|
|
3068
|
+
updateRequest.input("workflow_name", workflowName);
|
|
3069
|
+
updateRequest.input("run_id", runId);
|
|
3070
|
+
updateRequest.input("updatedAt", sql3.DateTime2, /* @__PURE__ */ new Date());
|
|
3071
|
+
await updateRequest.query(
|
|
3072
|
+
`UPDATE ${table} SET snapshot = @snapshot, [updatedAt] = @updatedAt WHERE workflow_name = @workflow_name AND run_id = @run_id`
|
|
3073
|
+
);
|
|
3074
|
+
await transaction.commit();
|
|
3075
|
+
return updatedSnapshot;
|
|
3076
|
+
} catch (error) {
|
|
3077
|
+
try {
|
|
3078
|
+
await transaction.rollback();
|
|
3079
|
+
} catch {
|
|
3080
|
+
}
|
|
3081
|
+
throw new MastraError(
|
|
3082
|
+
{
|
|
3083
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_WORKFLOW_STATE_FAILED",
|
|
3084
|
+
domain: ErrorDomain.STORAGE,
|
|
3085
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
3086
|
+
details: {
|
|
3087
|
+
workflowName,
|
|
3088
|
+
runId
|
|
3089
|
+
}
|
|
3090
|
+
},
|
|
3091
|
+
error
|
|
3092
|
+
);
|
|
3093
|
+
}
|
|
3094
|
+
}
|
|
3095
|
+
async persistWorkflowSnapshot({
|
|
3096
|
+
workflowName,
|
|
3097
|
+
runId,
|
|
3098
|
+
resourceId,
|
|
3099
|
+
snapshot
|
|
3100
|
+
}) {
|
|
3101
|
+
const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
|
|
3102
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3103
|
+
try {
|
|
3104
|
+
const request = this.pool.request();
|
|
3105
|
+
request.input("workflow_name", workflowName);
|
|
3106
|
+
request.input("run_id", runId);
|
|
3107
|
+
request.input("resourceId", resourceId);
|
|
3108
|
+
request.input("snapshot", JSON.stringify(snapshot));
|
|
3109
|
+
request.input("createdAt", sql3.DateTime2, new Date(now));
|
|
3110
|
+
request.input("updatedAt", sql3.DateTime2, new Date(now));
|
|
3111
|
+
const mergeSql = `MERGE INTO ${table} AS target
|
|
3112
|
+
USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
|
|
3113
|
+
ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
|
|
3114
|
+
WHEN MATCHED THEN UPDATE SET
|
|
3115
|
+
resourceId = @resourceId,
|
|
3116
|
+
snapshot = @snapshot,
|
|
3117
|
+
[updatedAt] = @updatedAt
|
|
3118
|
+
WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, resourceId, snapshot, [createdAt], [updatedAt])
|
|
3119
|
+
VALUES (@workflow_name, @run_id, @resourceId, @snapshot, @createdAt, @updatedAt);`;
|
|
3120
|
+
await request.query(mergeSql);
|
|
3121
|
+
} catch (error) {
|
|
3122
|
+
throw new MastraError(
|
|
3123
|
+
{
|
|
3124
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
|
|
3125
|
+
domain: ErrorDomain.STORAGE,
|
|
3126
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
3127
|
+
details: {
|
|
3128
|
+
workflowName,
|
|
3129
|
+
runId
|
|
3130
|
+
}
|
|
3131
|
+
},
|
|
3132
|
+
error
|
|
3133
|
+
);
|
|
3134
|
+
}
|
|
3135
|
+
}
|
|
3136
|
+
async loadWorkflowSnapshot({
|
|
3137
|
+
workflowName,
|
|
3138
|
+
runId
|
|
3139
|
+
}) {
|
|
3140
|
+
try {
|
|
3141
|
+
const result = await this.operations.load({
|
|
3142
|
+
tableName: TABLE_WORKFLOW_SNAPSHOT,
|
|
3143
|
+
keys: {
|
|
3144
|
+
workflow_name: workflowName,
|
|
3145
|
+
run_id: runId
|
|
3146
|
+
}
|
|
3147
|
+
});
|
|
3148
|
+
if (!result) {
|
|
3149
|
+
return null;
|
|
3150
|
+
}
|
|
3151
|
+
return result.snapshot;
|
|
3152
|
+
} catch (error) {
|
|
3153
|
+
throw new MastraError(
|
|
3154
|
+
{
|
|
3155
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
|
|
3156
|
+
domain: ErrorDomain.STORAGE,
|
|
3157
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
3158
|
+
details: {
|
|
3159
|
+
workflowName,
|
|
3160
|
+
runId
|
|
3161
|
+
}
|
|
3162
|
+
},
|
|
3163
|
+
error
|
|
3164
|
+
);
|
|
3165
|
+
}
|
|
3166
|
+
}
|
|
3167
|
+
async getWorkflowRunById({
|
|
3168
|
+
runId,
|
|
3169
|
+
workflowName
|
|
3170
|
+
}) {
|
|
3171
|
+
try {
|
|
3172
|
+
const conditions = [];
|
|
3173
|
+
const paramMap = {};
|
|
3174
|
+
if (runId) {
|
|
3175
|
+
conditions.push(`[run_id] = @runId`);
|
|
3176
|
+
paramMap["runId"] = runId;
|
|
3177
|
+
}
|
|
3178
|
+
if (workflowName) {
|
|
3179
|
+
conditions.push(`[workflow_name] = @workflowName`);
|
|
3180
|
+
paramMap["workflowName"] = workflowName;
|
|
3181
|
+
}
|
|
3182
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
3183
|
+
const tableName = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
|
|
3184
|
+
const query = `SELECT * FROM ${tableName} ${whereClause}`;
|
|
3185
|
+
const request = this.pool.request();
|
|
3186
|
+
Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
|
|
3187
|
+
const result = await request.query(query);
|
|
3188
|
+
if (!result.recordset || result.recordset.length === 0) {
|
|
3189
|
+
return null;
|
|
3190
|
+
}
|
|
3191
|
+
return this.parseWorkflowRun(result.recordset[0]);
|
|
3192
|
+
} catch (error) {
|
|
3193
|
+
throw new MastraError(
|
|
3194
|
+
{
|
|
3195
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
|
|
3196
|
+
domain: ErrorDomain.STORAGE,
|
|
3197
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
3198
|
+
details: {
|
|
3199
|
+
runId,
|
|
3200
|
+
workflowName: workflowName || ""
|
|
3201
|
+
}
|
|
3202
|
+
},
|
|
3203
|
+
error
|
|
3204
|
+
);
|
|
3205
|
+
}
|
|
3206
|
+
}
|
|
3207
|
+
async getWorkflowRuns({
|
|
3208
|
+
workflowName,
|
|
3209
|
+
fromDate,
|
|
3210
|
+
toDate,
|
|
3211
|
+
limit,
|
|
3212
|
+
offset,
|
|
3213
|
+
resourceId,
|
|
3214
|
+
status
|
|
3215
|
+
} = {}) {
|
|
3216
|
+
try {
|
|
3217
|
+
const conditions = [];
|
|
3218
|
+
const paramMap = {};
|
|
3219
|
+
if (workflowName) {
|
|
3220
|
+
conditions.push(`[workflow_name] = @workflowName`);
|
|
3221
|
+
paramMap["workflowName"] = workflowName;
|
|
3222
|
+
}
|
|
3223
|
+
if (status) {
|
|
3224
|
+
conditions.push(`JSON_VALUE([snapshot], '$.status') = @status`);
|
|
3225
|
+
paramMap["status"] = status;
|
|
3226
|
+
}
|
|
3227
|
+
if (resourceId) {
|
|
3228
|
+
const hasResourceId = await this.operations.hasColumn(TABLE_WORKFLOW_SNAPSHOT, "resourceId");
|
|
3229
|
+
if (hasResourceId) {
|
|
3230
|
+
conditions.push(`[resourceId] = @resourceId`);
|
|
3231
|
+
paramMap["resourceId"] = resourceId;
|
|
3232
|
+
} else {
|
|
3233
|
+
this.logger?.warn?.(`[${TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
|
|
3234
|
+
}
|
|
3235
|
+
}
|
|
3236
|
+
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
3237
|
+
conditions.push(`[createdAt] >= @fromDate`);
|
|
3238
|
+
paramMap[`fromDate`] = fromDate.toISOString();
|
|
3239
|
+
}
|
|
3240
|
+
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
3241
|
+
conditions.push(`[createdAt] <= @toDate`);
|
|
3242
|
+
paramMap[`toDate`] = toDate.toISOString();
|
|
3243
|
+
}
|
|
3244
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
3245
|
+
let total = 0;
|
|
3246
|
+
const tableName = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
|
|
3247
|
+
const request = this.pool.request();
|
|
3248
|
+
Object.entries(paramMap).forEach(([key, value]) => {
|
|
3249
|
+
if (value instanceof Date) {
|
|
3250
|
+
request.input(key, sql3.DateTime, value);
|
|
3251
|
+
} else {
|
|
3252
|
+
request.input(key, value);
|
|
3253
|
+
}
|
|
3254
|
+
});
|
|
3255
|
+
if (limit !== void 0 && offset !== void 0) {
|
|
3256
|
+
const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
|
|
3257
|
+
const countResult = await request.query(countQuery);
|
|
3258
|
+
total = Number(countResult.recordset[0]?.count || 0);
|
|
3259
|
+
}
|
|
3260
|
+
let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
|
|
3261
|
+
if (limit !== void 0 && offset !== void 0) {
|
|
3262
|
+
query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
3263
|
+
request.input("limit", limit);
|
|
3264
|
+
request.input("offset", offset);
|
|
3265
|
+
}
|
|
3266
|
+
const result = await request.query(query);
|
|
3267
|
+
const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
|
|
3268
|
+
return { runs, total: total || runs.length };
|
|
3269
|
+
} catch (error) {
|
|
3270
|
+
throw new MastraError(
|
|
3271
|
+
{
|
|
3272
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
|
|
3273
|
+
domain: ErrorDomain.STORAGE,
|
|
3274
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
3275
|
+
details: {
|
|
3276
|
+
workflowName: workflowName || "all"
|
|
3277
|
+
}
|
|
3278
|
+
},
|
|
3279
|
+
error
|
|
3280
|
+
);
|
|
3281
|
+
}
|
|
3282
|
+
}
|
|
3283
|
+
};
|
|
3284
|
+
|
|
3285
|
+
// src/storage/index.ts
|
|
3286
|
+
var MSSQLStore = class extends MastraStorage {
|
|
3287
|
+
pool;
|
|
3288
|
+
schema;
|
|
3289
|
+
isConnected = null;
|
|
3290
|
+
stores;
|
|
3291
|
+
constructor(config) {
|
|
3292
|
+
super({ name: "MSSQLStore" });
|
|
3293
|
+
try {
|
|
3294
|
+
if ("connectionString" in config) {
|
|
3295
|
+
if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
|
|
3296
|
+
throw new Error("MSSQLStore: connectionString must be provided and cannot be empty.");
|
|
3297
|
+
}
|
|
3298
|
+
} else {
|
|
3299
|
+
const required = ["server", "database", "user", "password"];
|
|
3300
|
+
for (const key of required) {
|
|
3301
|
+
if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
|
|
3302
|
+
throw new Error(`MSSQLStore: ${key} must be provided and cannot be empty.`);
|
|
3303
|
+
}
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
this.schema = config.schemaName || "dbo";
|
|
3307
|
+
this.pool = "connectionString" in config ? new sql3.ConnectionPool(config.connectionString) : new sql3.ConnectionPool({
|
|
3308
|
+
server: config.server,
|
|
3309
|
+
database: config.database,
|
|
3310
|
+
user: config.user,
|
|
3311
|
+
password: config.password,
|
|
3312
|
+
port: config.port,
|
|
3313
|
+
options: config.options || { encrypt: true, trustServerCertificate: true }
|
|
3314
|
+
});
|
|
3315
|
+
const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
|
|
3316
|
+
const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
|
|
3317
|
+
const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
3318
|
+
const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
3319
|
+
const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
3320
|
+
const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
|
|
3321
|
+
const observability = new ObservabilityMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
3322
|
+
this.stores = {
|
|
3323
|
+
operations,
|
|
3324
|
+
scores,
|
|
3325
|
+
traces,
|
|
3326
|
+
workflows,
|
|
3327
|
+
legacyEvals,
|
|
3328
|
+
memory,
|
|
3329
|
+
observability
|
|
3330
|
+
};
|
|
3331
|
+
} catch (e) {
|
|
3332
|
+
throw new MastraError(
|
|
3333
|
+
{
|
|
3334
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_INITIALIZATION_FAILED",
|
|
3335
|
+
domain: ErrorDomain.STORAGE,
|
|
3336
|
+
category: ErrorCategory.USER
|
|
3337
|
+
},
|
|
3338
|
+
e
|
|
3339
|
+
);
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
async init() {
|
|
3343
|
+
if (this.isConnected === null) {
|
|
3344
|
+
this.isConnected = this._performInitializationAndStore();
|
|
3345
|
+
}
|
|
3346
|
+
try {
|
|
3347
|
+
await this.isConnected;
|
|
3348
|
+
await super.init();
|
|
3349
|
+
try {
|
|
3350
|
+
await this.stores.operations.createAutomaticIndexes();
|
|
3351
|
+
} catch (indexError) {
|
|
3352
|
+
this.logger?.warn?.("Failed to create indexes:", indexError);
|
|
3353
|
+
}
|
|
3354
|
+
} catch (error) {
|
|
3355
|
+
this.isConnected = null;
|
|
3356
|
+
throw new MastraError(
|
|
3357
|
+
{
|
|
3358
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_INIT_FAILED",
|
|
3359
|
+
domain: ErrorDomain.STORAGE,
|
|
3360
|
+
category: ErrorCategory.THIRD_PARTY
|
|
3361
|
+
},
|
|
3362
|
+
error
|
|
3363
|
+
);
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
async _performInitializationAndStore() {
|
|
3367
|
+
try {
|
|
3368
|
+
await this.pool.connect();
|
|
3369
|
+
return true;
|
|
3370
|
+
} catch (err) {
|
|
3371
|
+
throw err;
|
|
3372
|
+
}
|
|
3373
|
+
}
|
|
3374
|
+
get supports() {
|
|
3375
|
+
return {
|
|
3376
|
+
selectByIncludeResourceScope: true,
|
|
3377
|
+
resourceWorkingMemory: true,
|
|
3378
|
+
hasColumn: true,
|
|
3379
|
+
createTable: true,
|
|
3380
|
+
deleteMessages: true,
|
|
3381
|
+
getScoresBySpan: true,
|
|
3382
|
+
aiTracing: true,
|
|
3383
|
+
indexManagement: true
|
|
3384
|
+
};
|
|
3385
|
+
}
|
|
3386
|
+
/** @deprecated use getEvals instead */
|
|
3387
|
+
async getEvalsByAgentName(agentName, type) {
|
|
3388
|
+
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
3389
|
+
}
|
|
3390
|
+
async getEvals(options = {}) {
|
|
3391
|
+
return this.stores.legacyEvals.getEvals(options);
|
|
3392
|
+
}
|
|
3393
|
+
/**
|
|
3394
|
+
* @deprecated use getTracesPaginated instead
|
|
3395
|
+
*/
|
|
3396
|
+
async getTraces(args) {
|
|
3397
|
+
return this.stores.traces.getTraces(args);
|
|
3398
|
+
}
|
|
3399
|
+
async getTracesPaginated(args) {
|
|
3400
|
+
return this.stores.traces.getTracesPaginated(args);
|
|
3401
|
+
}
|
|
3402
|
+
async batchTraceInsert({ records }) {
|
|
3403
|
+
return this.stores.traces.batchTraceInsert({ records });
|
|
3404
|
+
}
|
|
3405
|
+
async createTable({
|
|
3406
|
+
tableName,
|
|
3407
|
+
schema
|
|
3408
|
+
}) {
|
|
3409
|
+
return this.stores.operations.createTable({ tableName, schema });
|
|
3410
|
+
}
|
|
3411
|
+
async alterTable({
|
|
3412
|
+
tableName,
|
|
3413
|
+
schema,
|
|
3414
|
+
ifNotExists
|
|
3415
|
+
}) {
|
|
3416
|
+
return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
|
|
3417
|
+
}
|
|
3418
|
+
async clearTable({ tableName }) {
|
|
3419
|
+
return this.stores.operations.clearTable({ tableName });
|
|
3420
|
+
}
|
|
3421
|
+
async dropTable({ tableName }) {
|
|
3422
|
+
return this.stores.operations.dropTable({ tableName });
|
|
3423
|
+
}
|
|
3424
|
+
async insert({ tableName, record }) {
|
|
3425
|
+
return this.stores.operations.insert({ tableName, record });
|
|
3426
|
+
}
|
|
3427
|
+
async batchInsert({ tableName, records }) {
|
|
3428
|
+
return this.stores.operations.batchInsert({ tableName, records });
|
|
3429
|
+
}
|
|
3430
|
+
async load({ tableName, keys }) {
|
|
3431
|
+
return this.stores.operations.load({ tableName, keys });
|
|
3432
|
+
}
|
|
3433
|
+
/**
|
|
3434
|
+
* Memory
|
|
3435
|
+
*/
|
|
3436
|
+
async getThreadById({ threadId }) {
|
|
3437
|
+
return this.stores.memory.getThreadById({ threadId });
|
|
3438
|
+
}
|
|
3439
|
+
/**
|
|
3440
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
3441
|
+
*/
|
|
3442
|
+
async getThreadsByResourceId(args) {
|
|
3443
|
+
return this.stores.memory.getThreadsByResourceId(args);
|
|
3444
|
+
}
|
|
3445
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
3446
|
+
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
3447
|
+
}
|
|
3448
|
+
async saveThread({ thread }) {
|
|
3449
|
+
return this.stores.memory.saveThread({ thread });
|
|
3450
|
+
}
|
|
3451
|
+
async updateThread({
|
|
3452
|
+
id,
|
|
3453
|
+
title,
|
|
3454
|
+
metadata
|
|
3455
|
+
}) {
|
|
3456
|
+
return this.stores.memory.updateThread({ id, title, metadata });
|
|
3457
|
+
}
|
|
3458
|
+
async deleteThread({ threadId }) {
|
|
3459
|
+
return this.stores.memory.deleteThread({ threadId });
|
|
3460
|
+
}
|
|
3461
|
+
async getMessages(args) {
|
|
3462
|
+
return this.stores.memory.getMessages(args);
|
|
3463
|
+
}
|
|
3464
|
+
async getMessagesById({
|
|
3465
|
+
messageIds,
|
|
3466
|
+
format
|
|
3467
|
+
}) {
|
|
3468
|
+
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
3469
|
+
}
|
|
3470
|
+
async getMessagesPaginated(args) {
|
|
3471
|
+
return this.stores.memory.getMessagesPaginated(args);
|
|
3472
|
+
}
|
|
3473
|
+
async saveMessages(args) {
|
|
3474
|
+
return this.stores.memory.saveMessages(args);
|
|
3475
|
+
}
|
|
3476
|
+
async updateMessages({
|
|
3477
|
+
messages
|
|
3478
|
+
}) {
|
|
3479
|
+
return this.stores.memory.updateMessages({ messages });
|
|
3480
|
+
}
|
|
3481
|
+
async deleteMessages(messageIds) {
|
|
3482
|
+
return this.stores.memory.deleteMessages(messageIds);
|
|
3483
|
+
}
|
|
3484
|
+
async getResourceById({ resourceId }) {
|
|
3485
|
+
return this.stores.memory.getResourceById({ resourceId });
|
|
3486
|
+
}
|
|
3487
|
+
async saveResource({ resource }) {
|
|
3488
|
+
return this.stores.memory.saveResource({ resource });
|
|
3489
|
+
}
|
|
3490
|
+
async updateResource({
|
|
3491
|
+
resourceId,
|
|
3492
|
+
workingMemory,
|
|
3493
|
+
metadata
|
|
3494
|
+
}) {
|
|
3495
|
+
return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
|
|
3496
|
+
}
|
|
3497
|
+
/**
|
|
3498
|
+
* Workflows
|
|
3499
|
+
*/
|
|
3500
|
+
async updateWorkflowResults({
|
|
3501
|
+
workflowName,
|
|
3502
|
+
runId,
|
|
3503
|
+
stepId,
|
|
3504
|
+
result,
|
|
3505
|
+
runtimeContext
|
|
3506
|
+
}) {
|
|
3507
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
|
|
3508
|
+
}
|
|
3509
|
+
async updateWorkflowState({
|
|
3510
|
+
workflowName,
|
|
3511
|
+
runId,
|
|
3512
|
+
opts
|
|
3513
|
+
}) {
|
|
3514
|
+
return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
|
|
3515
|
+
}
|
|
3516
|
+
async persistWorkflowSnapshot({
|
|
3517
|
+
workflowName,
|
|
3518
|
+
runId,
|
|
3519
|
+
resourceId,
|
|
3520
|
+
snapshot
|
|
3521
|
+
}) {
|
|
3522
|
+
return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
|
|
3523
|
+
}
|
|
3524
|
+
async loadWorkflowSnapshot({
|
|
3525
|
+
workflowName,
|
|
3526
|
+
runId
|
|
3527
|
+
}) {
|
|
3528
|
+
return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
|
|
3529
|
+
}
|
|
3530
|
+
async getWorkflowRuns(args = {}) {
|
|
3531
|
+
return this.stores.workflows.getWorkflowRuns(args);
|
|
3532
|
+
}
|
|
3533
|
+
async getWorkflowRunById({
|
|
3534
|
+
runId,
|
|
3535
|
+
workflowName
|
|
3536
|
+
}) {
|
|
3537
|
+
return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
|
|
3538
|
+
}
|
|
3539
|
+
async close() {
|
|
3540
|
+
await this.pool.close();
|
|
3541
|
+
}
|
|
3542
|
+
/**
|
|
3543
|
+
* Index Management
|
|
3544
|
+
*/
|
|
3545
|
+
async createIndex(options) {
|
|
3546
|
+
return this.stores.operations.createIndex(options);
|
|
3547
|
+
}
|
|
3548
|
+
async listIndexes(tableName) {
|
|
3549
|
+
return this.stores.operations.listIndexes(tableName);
|
|
3550
|
+
}
|
|
3551
|
+
async describeIndex(indexName) {
|
|
3552
|
+
return this.stores.operations.describeIndex(indexName);
|
|
3553
|
+
}
|
|
3554
|
+
async dropIndex(indexName) {
|
|
3555
|
+
return this.stores.operations.dropIndex(indexName);
|
|
3556
|
+
}
|
|
3557
|
+
/**
|
|
3558
|
+
* AI Tracing / Observability
|
|
3559
|
+
*/
|
|
3560
|
+
getObservabilityStore() {
|
|
3561
|
+
if (!this.stores.observability) {
|
|
3562
|
+
throw new MastraError({
|
|
3563
|
+
id: "MSSQL_STORE_OBSERVABILITY_NOT_INITIALIZED",
|
|
3564
|
+
domain: ErrorDomain.STORAGE,
|
|
3565
|
+
category: ErrorCategory.SYSTEM,
|
|
3566
|
+
text: "Observability storage is not initialized"
|
|
3567
|
+
});
|
|
3568
|
+
}
|
|
3569
|
+
return this.stores.observability;
|
|
3570
|
+
}
|
|
3571
|
+
async createAISpan(span) {
|
|
3572
|
+
return this.getObservabilityStore().createAISpan(span);
|
|
3573
|
+
}
|
|
3574
|
+
async updateAISpan({
|
|
3575
|
+
spanId,
|
|
3576
|
+
traceId,
|
|
3577
|
+
updates
|
|
3578
|
+
}) {
|
|
3579
|
+
return this.getObservabilityStore().updateAISpan({ spanId, traceId, updates });
|
|
3580
|
+
}
|
|
3581
|
+
async getAITrace(traceId) {
|
|
3582
|
+
return this.getObservabilityStore().getAITrace(traceId);
|
|
3583
|
+
}
|
|
3584
|
+
async getAITracesPaginated(args) {
|
|
3585
|
+
return this.getObservabilityStore().getAITracesPaginated(args);
|
|
3586
|
+
}
|
|
3587
|
+
async batchCreateAISpans(args) {
|
|
3588
|
+
return this.getObservabilityStore().batchCreateAISpans(args);
|
|
3589
|
+
}
|
|
3590
|
+
async batchUpdateAISpans(args) {
|
|
3591
|
+
return this.getObservabilityStore().batchUpdateAISpans(args);
|
|
3592
|
+
}
|
|
3593
|
+
async batchDeleteAITraces(args) {
|
|
3594
|
+
return this.getObservabilityStore().batchDeleteAITraces(args);
|
|
3595
|
+
}
|
|
3596
|
+
/**
|
|
3597
|
+
* Scorers
|
|
3598
|
+
*/
|
|
3599
|
+
async getScoreById({ id: _id }) {
|
|
3600
|
+
return this.stores.scores.getScoreById({ id: _id });
|
|
3601
|
+
}
|
|
3602
|
+
async getScoresByScorerId({
|
|
3603
|
+
scorerId: _scorerId,
|
|
3604
|
+
pagination: _pagination,
|
|
3605
|
+
entityId: _entityId,
|
|
3606
|
+
entityType: _entityType,
|
|
3607
|
+
source: _source
|
|
3608
|
+
}) {
|
|
3609
|
+
return this.stores.scores.getScoresByScorerId({
|
|
3610
|
+
scorerId: _scorerId,
|
|
3611
|
+
pagination: _pagination,
|
|
3612
|
+
entityId: _entityId,
|
|
3613
|
+
entityType: _entityType,
|
|
3614
|
+
source: _source
|
|
3615
|
+
});
|
|
3616
|
+
}
|
|
3617
|
+
async saveScore(_score) {
|
|
3618
|
+
return this.stores.scores.saveScore(_score);
|
|
3619
|
+
}
|
|
3620
|
+
async getScoresByRunId({
|
|
3621
|
+
runId: _runId,
|
|
3622
|
+
pagination: _pagination
|
|
3623
|
+
}) {
|
|
3624
|
+
return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
|
|
3625
|
+
}
|
|
3626
|
+
async getScoresByEntityId({
|
|
3627
|
+
entityId: _entityId,
|
|
3628
|
+
entityType: _entityType,
|
|
3629
|
+
pagination: _pagination
|
|
3630
|
+
}) {
|
|
3631
|
+
return this.stores.scores.getScoresByEntityId({
|
|
3632
|
+
entityId: _entityId,
|
|
3633
|
+
entityType: _entityType,
|
|
3634
|
+
pagination: _pagination
|
|
3635
|
+
});
|
|
3636
|
+
}
|
|
3637
|
+
async getScoresBySpan({
|
|
3638
|
+
traceId,
|
|
3639
|
+
spanId,
|
|
3640
|
+
pagination: _pagination
|
|
3641
|
+
}) {
|
|
3642
|
+
return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
|
|
1812
3643
|
}
|
|
1813
3644
|
};
|
|
1814
3645
|
|