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