@mastra/mssql 0.0.0-share-agent-metadata-with-cloud-20250718110128 → 0.0.0-sidebar-window-undefined-fix-20251029233656
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 +560 -3
- package/README.md +315 -36
- package/dist/index.cjs +2701 -994
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +3 -4
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2702 -995
- package/dist/index.js.map +1 -0
- package/dist/storage/domains/legacy-evals/index.d.ts +20 -0
- package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +98 -0
- package/dist/storage/domains/memory/index.d.ts.map +1 -0
- package/dist/storage/domains/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 +280 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/package.json +26 -12
- package/dist/_tsup-dts-rollup.d.cts +0 -213
- package/dist/_tsup-dts-rollup.d.ts +0 -213
- package/dist/index.d.cts +0 -4
- package/docker-compose.yaml +0 -14
- package/eslint.config.js +0 -6
- package/src/index.ts +0 -2
- package/src/storage/index.test.ts +0 -2239
- package/src/storage/index.ts +0 -2044
- package/tsconfig.json +0 -5
- package/vitest.config.ts +0 -12
package/dist/index.cjs
CHANGED
|
@@ -1,130 +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
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
transformEvalRow(row) {
|
|
98
|
-
let testInfoValue = null, resultValue = null;
|
|
99
|
-
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") {
|
|
100
71
|
try {
|
|
101
|
-
|
|
72
|
+
result[key] = JSON.parse(value);
|
|
102
73
|
} catch {
|
|
74
|
+
result[key] = value;
|
|
103
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;
|
|
104
84
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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 {
|
|
110
96
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
97
|
+
}
|
|
98
|
+
if (row.result) {
|
|
99
|
+
try {
|
|
100
|
+
resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
|
|
101
|
+
} catch {
|
|
102
|
+
}
|
|
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;
|
|
123
124
|
}
|
|
124
125
|
/** @deprecated use getEvals instead */
|
|
125
126
|
async getEvalsByAgentName(agentName, type) {
|
|
126
127
|
try {
|
|
127
|
-
let query = `SELECT * FROM ${
|
|
128
|
+
let query = `SELECT * FROM ${getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
|
|
128
129
|
if (type === "test") {
|
|
129
130
|
query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
|
|
130
131
|
} else if (type === "live") {
|
|
@@ -135,495 +136,164 @@ var MSSQLStore = class extends storage.MastraStorage {
|
|
|
135
136
|
request.input("p1", agentName);
|
|
136
137
|
const result = await request.query(query);
|
|
137
138
|
const rows = result.recordset;
|
|
138
|
-
return typeof
|
|
139
|
+
return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
|
|
139
140
|
} catch (error) {
|
|
140
141
|
if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
|
|
141
142
|
return [];
|
|
142
143
|
}
|
|
143
|
-
|
|
144
|
+
this.logger?.error?.("Failed to get evals for the specified agent:", error);
|
|
144
145
|
throw error;
|
|
145
146
|
}
|
|
146
147
|
}
|
|
147
|
-
async
|
|
148
|
-
const
|
|
149
|
-
try {
|
|
150
|
-
await transaction.begin();
|
|
151
|
-
for (const record of records) {
|
|
152
|
-
await this.insert({ tableName, record });
|
|
153
|
-
}
|
|
154
|
-
await transaction.commit();
|
|
155
|
-
} catch (error$1) {
|
|
156
|
-
await transaction.rollback();
|
|
157
|
-
throw new error.MastraError(
|
|
158
|
-
{
|
|
159
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
|
|
160
|
-
domain: error.ErrorDomain.STORAGE,
|
|
161
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
162
|
-
details: {
|
|
163
|
-
tableName,
|
|
164
|
-
numberOfRecords: records.length
|
|
165
|
-
}
|
|
166
|
-
},
|
|
167
|
-
error$1
|
|
168
|
-
);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
/** @deprecated use getTracesPaginated instead*/
|
|
172
|
-
async getTraces(args) {
|
|
173
|
-
if (args.fromDate || args.toDate) {
|
|
174
|
-
args.dateRange = {
|
|
175
|
-
start: args.fromDate,
|
|
176
|
-
end: args.toDate
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
const result = await this.getTracesPaginated(args);
|
|
180
|
-
return result.traces;
|
|
181
|
-
}
|
|
182
|
-
async getTracesPaginated(args) {
|
|
183
|
-
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;
|
|
184
150
|
const fromDate = dateRange?.start;
|
|
185
151
|
const toDate = dateRange?.end;
|
|
186
|
-
const
|
|
187
|
-
const
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
if (name) {
|
|
192
|
-
const paramName = `p${paramIndex++}`;
|
|
193
|
-
conditions.push(`[name] LIKE @${paramName}`);
|
|
194
|
-
paramMap[paramName] = `${name}%`;
|
|
195
|
-
}
|
|
196
|
-
if (scope) {
|
|
197
|
-
const paramName = `p${paramIndex++}`;
|
|
198
|
-
conditions.push(`[scope] = @${paramName}`);
|
|
199
|
-
paramMap[paramName] = scope;
|
|
200
|
-
}
|
|
201
|
-
if (attributes) {
|
|
202
|
-
Object.entries(attributes).forEach(([key, value]) => {
|
|
203
|
-
const parsedKey = utils.parseFieldKey(key);
|
|
204
|
-
const paramName = `p${paramIndex++}`;
|
|
205
|
-
conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
|
|
206
|
-
paramMap[paramName] = value;
|
|
207
|
-
});
|
|
152
|
+
const where = [];
|
|
153
|
+
const params = {};
|
|
154
|
+
if (agentName) {
|
|
155
|
+
where.push("agent_name = @agentName");
|
|
156
|
+
params["agentName"] = agentName;
|
|
208
157
|
}
|
|
209
|
-
if (
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
conditions.push(`[${parsedKey}] = @${paramName}`);
|
|
214
|
-
paramMap[paramName] = value;
|
|
215
|
-
});
|
|
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)");
|
|
216
162
|
}
|
|
217
163
|
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
paramMap[paramName] = fromDate.toISOString();
|
|
164
|
+
where.push(`[created_at] >= @fromDate`);
|
|
165
|
+
params[`fromDate`] = fromDate.toISOString();
|
|
221
166
|
}
|
|
222
167
|
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
paramMap[paramName] = toDate.toISOString();
|
|
168
|
+
where.push(`[created_at] <= @toDate`);
|
|
169
|
+
params[`toDate`] = toDate.toISOString();
|
|
226
170
|
}
|
|
227
|
-
const whereClause =
|
|
228
|
-
const
|
|
229
|
-
|
|
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`;
|
|
230
176
|
try {
|
|
231
|
-
const
|
|
232
|
-
Object.entries(
|
|
177
|
+
const countReq = this.pool.request();
|
|
178
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
233
179
|
if (value instanceof Date) {
|
|
234
|
-
|
|
180
|
+
countReq.input(key, sql3__default.default.DateTime, value);
|
|
235
181
|
} else {
|
|
236
|
-
|
|
182
|
+
countReq.input(key, value);
|
|
237
183
|
}
|
|
238
184
|
});
|
|
239
|
-
const countResult = await
|
|
240
|
-
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
|
+
};
|
|
241
215
|
} catch (error$1) {
|
|
242
|
-
|
|
216
|
+
const mastraError = new error.MastraError(
|
|
243
217
|
{
|
|
244
|
-
id: "
|
|
218
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
|
|
245
219
|
domain: error.ErrorDomain.STORAGE,
|
|
246
220
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
247
221
|
details: {
|
|
248
|
-
|
|
249
|
-
|
|
222
|
+
agentName: agentName || "all",
|
|
223
|
+
type: type || "all",
|
|
224
|
+
page,
|
|
225
|
+
perPage
|
|
250
226
|
}
|
|
251
227
|
},
|
|
252
228
|
error$1
|
|
253
229
|
);
|
|
230
|
+
this.logger?.error?.(mastraError.toString());
|
|
231
|
+
this.logger?.trackException?.(mastraError);
|
|
232
|
+
throw mastraError;
|
|
254
233
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
} else {
|
|
270
|
-
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
|
+
}
|
|
271
248
|
}
|
|
249
|
+
return message;
|
|
272
250
|
});
|
|
273
|
-
|
|
274
|
-
|
|
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 }) {
|
|
275
266
|
try {
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
createdAt: row.createdAt
|
|
293
|
-
}));
|
|
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
|
+
}
|
|
294
283
|
return {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
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
|
|
300
288
|
};
|
|
301
289
|
} catch (error$1) {
|
|
302
290
|
throw new error.MastraError(
|
|
303
291
|
{
|
|
304
|
-
id: "
|
|
292
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
|
|
305
293
|
domain: error.ErrorDomain.STORAGE,
|
|
306
294
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
307
295
|
details: {
|
|
308
|
-
|
|
309
|
-
scope: args.scope ?? ""
|
|
310
|
-
}
|
|
311
|
-
},
|
|
312
|
-
error$1
|
|
313
|
-
);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
async setupSchema() {
|
|
317
|
-
if (!this.schema || this.schemaSetupComplete) {
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
if (!this.setupSchemaPromise) {
|
|
321
|
-
this.setupSchemaPromise = (async () => {
|
|
322
|
-
try {
|
|
323
|
-
const checkRequest = this.pool.request();
|
|
324
|
-
checkRequest.input("schemaName", this.schema);
|
|
325
|
-
const checkResult = await checkRequest.query(`
|
|
326
|
-
SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
|
|
327
|
-
`);
|
|
328
|
-
const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
|
|
329
|
-
if (!schemaExists) {
|
|
330
|
-
try {
|
|
331
|
-
await this.pool.request().query(`CREATE SCHEMA [${this.schema}]`);
|
|
332
|
-
this.logger?.info?.(`Schema "${this.schema}" created successfully`);
|
|
333
|
-
} catch (error) {
|
|
334
|
-
this.logger?.error?.(`Failed to create schema "${this.schema}"`, { error });
|
|
335
|
-
throw new Error(
|
|
336
|
-
`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.`
|
|
337
|
-
);
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
this.schemaSetupComplete = true;
|
|
341
|
-
this.logger?.debug?.(`Schema "${this.schema}" is ready for use`);
|
|
342
|
-
} catch (error) {
|
|
343
|
-
this.schemaSetupComplete = void 0;
|
|
344
|
-
this.setupSchemaPromise = null;
|
|
345
|
-
throw error;
|
|
346
|
-
} finally {
|
|
347
|
-
this.setupSchemaPromise = null;
|
|
348
|
-
}
|
|
349
|
-
})();
|
|
350
|
-
}
|
|
351
|
-
await this.setupSchemaPromise;
|
|
352
|
-
}
|
|
353
|
-
getSqlType(type, isPrimaryKey = false) {
|
|
354
|
-
switch (type) {
|
|
355
|
-
case "text":
|
|
356
|
-
return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(MAX)";
|
|
357
|
-
case "timestamp":
|
|
358
|
-
return "DATETIME2(7)";
|
|
359
|
-
case "uuid":
|
|
360
|
-
return "UNIQUEIDENTIFIER";
|
|
361
|
-
case "jsonb":
|
|
362
|
-
return "NVARCHAR(MAX)";
|
|
363
|
-
case "integer":
|
|
364
|
-
return "INT";
|
|
365
|
-
case "bigint":
|
|
366
|
-
return "BIGINT";
|
|
367
|
-
default:
|
|
368
|
-
throw new error.MastraError({
|
|
369
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
|
|
370
|
-
domain: error.ErrorDomain.STORAGE,
|
|
371
|
-
category: error.ErrorCategory.THIRD_PARTY
|
|
372
|
-
});
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
async createTable({
|
|
376
|
-
tableName,
|
|
377
|
-
schema
|
|
378
|
-
}) {
|
|
379
|
-
try {
|
|
380
|
-
const uniqueConstraintColumns = tableName === storage.TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
|
|
381
|
-
const columns = Object.entries(schema).map(([name, def]) => {
|
|
382
|
-
const parsedName = utils.parseSqlIdentifier(name, "column name");
|
|
383
|
-
const constraints = [];
|
|
384
|
-
if (def.primaryKey) constraints.push("PRIMARY KEY");
|
|
385
|
-
if (!def.nullable) constraints.push("NOT NULL");
|
|
386
|
-
const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
|
|
387
|
-
return `[${parsedName}] ${this.getSqlType(def.type, isIndexed)} ${constraints.join(" ")}`.trim();
|
|
388
|
-
}).join(",\n");
|
|
389
|
-
if (this.schema) {
|
|
390
|
-
await this.setupSchema();
|
|
391
|
-
}
|
|
392
|
-
const checkTableRequest = this.pool.request();
|
|
393
|
-
checkTableRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
|
|
394
|
-
const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
|
|
395
|
-
checkTableRequest.input("schema", this.schema || "dbo");
|
|
396
|
-
const checkTableResult = await checkTableRequest.query(checkTableSql);
|
|
397
|
-
const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
|
|
398
|
-
if (!tableExists) {
|
|
399
|
-
const createSql = `CREATE TABLE ${this.getTableName(tableName)} (
|
|
400
|
-
${columns}
|
|
401
|
-
)`;
|
|
402
|
-
await this.pool.request().query(createSql);
|
|
403
|
-
}
|
|
404
|
-
const columnCheckSql = `
|
|
405
|
-
SELECT 1 AS found
|
|
406
|
-
FROM INFORMATION_SCHEMA.COLUMNS
|
|
407
|
-
WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
|
|
408
|
-
`;
|
|
409
|
-
const checkColumnRequest = this.pool.request();
|
|
410
|
-
checkColumnRequest.input("schema", this.schema || "dbo");
|
|
411
|
-
checkColumnRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
|
|
412
|
-
const columnResult = await checkColumnRequest.query(columnCheckSql);
|
|
413
|
-
const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
|
|
414
|
-
if (!columnExists) {
|
|
415
|
-
const alterSql = `ALTER TABLE ${this.getTableName(tableName)} ADD seq_id BIGINT IDENTITY(1,1)`;
|
|
416
|
-
await this.pool.request().query(alterSql);
|
|
417
|
-
}
|
|
418
|
-
if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
|
|
419
|
-
const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
|
|
420
|
-
const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
|
|
421
|
-
const checkConstraintRequest = this.pool.request();
|
|
422
|
-
checkConstraintRequest.input("constraintName", constraintName);
|
|
423
|
-
const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
|
|
424
|
-
const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
|
|
425
|
-
if (!constraintExists) {
|
|
426
|
-
const addConstraintSql = `ALTER TABLE ${this.getTableName(tableName)} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
|
|
427
|
-
await this.pool.request().query(addConstraintSql);
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
} catch (error$1) {
|
|
431
|
-
throw new error.MastraError(
|
|
432
|
-
{
|
|
433
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
|
|
434
|
-
domain: error.ErrorDomain.STORAGE,
|
|
435
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
436
|
-
details: {
|
|
437
|
-
tableName
|
|
438
|
-
}
|
|
439
|
-
},
|
|
440
|
-
error$1
|
|
441
|
-
);
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
getDefaultValue(type) {
|
|
445
|
-
switch (type) {
|
|
446
|
-
case "timestamp":
|
|
447
|
-
return "DEFAULT SYSDATETIMEOFFSET()";
|
|
448
|
-
case "jsonb":
|
|
449
|
-
return "DEFAULT N'{}'";
|
|
450
|
-
default:
|
|
451
|
-
return super.getDefaultValue(type);
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
async alterTable({
|
|
455
|
-
tableName,
|
|
456
|
-
schema,
|
|
457
|
-
ifNotExists
|
|
458
|
-
}) {
|
|
459
|
-
const fullTableName = this.getTableName(tableName);
|
|
460
|
-
try {
|
|
461
|
-
for (const columnName of ifNotExists) {
|
|
462
|
-
if (schema[columnName]) {
|
|
463
|
-
const columnCheckRequest = this.pool.request();
|
|
464
|
-
columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
|
|
465
|
-
columnCheckRequest.input("columnName", columnName);
|
|
466
|
-
columnCheckRequest.input("schema", this.schema || "dbo");
|
|
467
|
-
const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
|
|
468
|
-
const checkResult = await columnCheckRequest.query(checkSql);
|
|
469
|
-
const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
|
|
470
|
-
if (!columnExists) {
|
|
471
|
-
const columnDef = schema[columnName];
|
|
472
|
-
const sqlType = this.getSqlType(columnDef.type);
|
|
473
|
-
const nullable = columnDef.nullable === false ? "NOT NULL" : "";
|
|
474
|
-
const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
|
|
475
|
-
const parsedColumnName = utils.parseSqlIdentifier(columnName, "column name");
|
|
476
|
-
const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
|
|
477
|
-
await this.pool.request().query(alterSql);
|
|
478
|
-
this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
} catch (error$1) {
|
|
483
|
-
throw new error.MastraError(
|
|
484
|
-
{
|
|
485
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
|
|
486
|
-
domain: error.ErrorDomain.STORAGE,
|
|
487
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
488
|
-
details: {
|
|
489
|
-
tableName
|
|
490
|
-
}
|
|
491
|
-
},
|
|
492
|
-
error$1
|
|
493
|
-
);
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
async clearTable({ tableName }) {
|
|
497
|
-
const fullTableName = this.getTableName(tableName);
|
|
498
|
-
try {
|
|
499
|
-
const fkQuery = `
|
|
500
|
-
SELECT
|
|
501
|
-
OBJECT_SCHEMA_NAME(fk.parent_object_id) AS schema_name,
|
|
502
|
-
OBJECT_NAME(fk.parent_object_id) AS table_name
|
|
503
|
-
FROM sys.foreign_keys fk
|
|
504
|
-
WHERE fk.referenced_object_id = OBJECT_ID(@fullTableName)
|
|
505
|
-
`;
|
|
506
|
-
const fkResult = await this.pool.request().input("fullTableName", fullTableName).query(fkQuery);
|
|
507
|
-
const childTables = fkResult.recordset || [];
|
|
508
|
-
for (const child of childTables) {
|
|
509
|
-
const childTableName = this.schema ? `[${child.schema_name}].[${child.table_name}]` : `[${child.table_name}]`;
|
|
510
|
-
await this.clearTable({ tableName: childTableName });
|
|
511
|
-
}
|
|
512
|
-
await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
|
|
513
|
-
} catch (error$1) {
|
|
514
|
-
throw new error.MastraError(
|
|
515
|
-
{
|
|
516
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
|
|
517
|
-
domain: error.ErrorDomain.STORAGE,
|
|
518
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
519
|
-
details: {
|
|
520
|
-
tableName
|
|
521
|
-
}
|
|
522
|
-
},
|
|
523
|
-
error$1
|
|
524
|
-
);
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
async insert({ tableName, record }) {
|
|
528
|
-
try {
|
|
529
|
-
const columns = Object.keys(record).map((col) => utils.parseSqlIdentifier(col, "column name"));
|
|
530
|
-
const values = Object.values(record);
|
|
531
|
-
const paramNames = values.map((_, i) => `@param${i}`);
|
|
532
|
-
const insertSql = `INSERT INTO ${this.getTableName(tableName)} (${columns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
|
|
533
|
-
const request = this.pool.request();
|
|
534
|
-
values.forEach((value, i) => {
|
|
535
|
-
if (value instanceof Date) {
|
|
536
|
-
request.input(`param${i}`, sql__default.default.DateTime2, value);
|
|
537
|
-
} else if (typeof value === "object" && value !== null) {
|
|
538
|
-
request.input(`param${i}`, JSON.stringify(value));
|
|
539
|
-
} else {
|
|
540
|
-
request.input(`param${i}`, value);
|
|
541
|
-
}
|
|
542
|
-
});
|
|
543
|
-
await request.query(insertSql);
|
|
544
|
-
} catch (error$1) {
|
|
545
|
-
throw new error.MastraError(
|
|
546
|
-
{
|
|
547
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
|
|
548
|
-
domain: error.ErrorDomain.STORAGE,
|
|
549
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
550
|
-
details: {
|
|
551
|
-
tableName
|
|
552
|
-
}
|
|
553
|
-
},
|
|
554
|
-
error$1
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
async load({ tableName, keys }) {
|
|
559
|
-
try {
|
|
560
|
-
const keyEntries = Object.entries(keys).map(([key, value]) => [utils.parseSqlIdentifier(key, "column name"), value]);
|
|
561
|
-
const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
|
|
562
|
-
const values = keyEntries.map(([_, value]) => value);
|
|
563
|
-
const sql2 = `SELECT * FROM ${this.getTableName(tableName)} WHERE ${conditions}`;
|
|
564
|
-
const request = this.pool.request();
|
|
565
|
-
values.forEach((value, i) => {
|
|
566
|
-
request.input(`param${i}`, value);
|
|
567
|
-
});
|
|
568
|
-
const resultSet = await request.query(sql2);
|
|
569
|
-
const result = resultSet.recordset[0] || null;
|
|
570
|
-
if (!result) {
|
|
571
|
-
return null;
|
|
572
|
-
}
|
|
573
|
-
if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
|
|
574
|
-
const snapshot = result;
|
|
575
|
-
if (typeof snapshot.snapshot === "string") {
|
|
576
|
-
snapshot.snapshot = JSON.parse(snapshot.snapshot);
|
|
577
|
-
}
|
|
578
|
-
return snapshot;
|
|
579
|
-
}
|
|
580
|
-
return result;
|
|
581
|
-
} catch (error$1) {
|
|
582
|
-
throw new error.MastraError(
|
|
583
|
-
{
|
|
584
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
|
|
585
|
-
domain: error.ErrorDomain.STORAGE,
|
|
586
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
587
|
-
details: {
|
|
588
|
-
tableName
|
|
589
|
-
}
|
|
590
|
-
},
|
|
591
|
-
error$1
|
|
592
|
-
);
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
async getThreadById({ threadId }) {
|
|
596
|
-
try {
|
|
597
|
-
const sql2 = `SELECT
|
|
598
|
-
id,
|
|
599
|
-
[resourceId],
|
|
600
|
-
title,
|
|
601
|
-
metadata,
|
|
602
|
-
[createdAt],
|
|
603
|
-
[updatedAt]
|
|
604
|
-
FROM ${this.getTableName(storage.TABLE_THREADS)}
|
|
605
|
-
WHERE id = @threadId`;
|
|
606
|
-
const request = this.pool.request();
|
|
607
|
-
request.input("threadId", threadId);
|
|
608
|
-
const resultSet = await request.query(sql2);
|
|
609
|
-
const thread = resultSet.recordset[0] || null;
|
|
610
|
-
if (!thread) {
|
|
611
|
-
return null;
|
|
612
|
-
}
|
|
613
|
-
return {
|
|
614
|
-
...thread,
|
|
615
|
-
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
616
|
-
createdAt: thread.createdAt,
|
|
617
|
-
updatedAt: thread.updatedAt
|
|
618
|
-
};
|
|
619
|
-
} catch (error$1) {
|
|
620
|
-
throw new error.MastraError(
|
|
621
|
-
{
|
|
622
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
|
|
623
|
-
domain: error.ErrorDomain.STORAGE,
|
|
624
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
625
|
-
details: {
|
|
626
|
-
threadId
|
|
296
|
+
threadId
|
|
627
297
|
}
|
|
628
298
|
},
|
|
629
299
|
error$1
|
|
@@ -631,11 +301,11 @@ ${columns}
|
|
|
631
301
|
}
|
|
632
302
|
}
|
|
633
303
|
async getThreadsByResourceIdPaginated(args) {
|
|
634
|
-
const { resourceId, page = 0, perPage: perPageInput } = args;
|
|
304
|
+
const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
|
|
635
305
|
try {
|
|
636
306
|
const perPage = perPageInput !== void 0 ? perPageInput : 100;
|
|
637
307
|
const currentOffset = page * perPage;
|
|
638
|
-
const baseQuery = `FROM ${
|
|
308
|
+
const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
|
|
639
309
|
const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
|
|
640
310
|
const countRequest = this.pool.request();
|
|
641
311
|
countRequest.input("resourceId", resourceId);
|
|
@@ -650,7 +320,9 @@ ${columns}
|
|
|
650
320
|
hasMore: false
|
|
651
321
|
};
|
|
652
322
|
}
|
|
653
|
-
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`;
|
|
654
326
|
const dataRequest = this.pool.request();
|
|
655
327
|
dataRequest.input("resourceId", resourceId);
|
|
656
328
|
dataRequest.input("perPage", perPage);
|
|
@@ -690,7 +362,7 @@ ${columns}
|
|
|
690
362
|
}
|
|
691
363
|
async saveThread({ thread }) {
|
|
692
364
|
try {
|
|
693
|
-
const table =
|
|
365
|
+
const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
694
366
|
const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
|
|
695
367
|
USING (SELECT @id AS id) AS source
|
|
696
368
|
ON (target.id = source.id)
|
|
@@ -699,7 +371,6 @@ ${columns}
|
|
|
699
371
|
[resourceId] = @resourceId,
|
|
700
372
|
title = @title,
|
|
701
373
|
metadata = @metadata,
|
|
702
|
-
[createdAt] = @createdAt,
|
|
703
374
|
[updatedAt] = @updatedAt
|
|
704
375
|
WHEN NOT MATCHED THEN
|
|
705
376
|
INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
|
|
@@ -708,9 +379,14 @@ ${columns}
|
|
|
708
379
|
req.input("id", thread.id);
|
|
709
380
|
req.input("resourceId", thread.resourceId);
|
|
710
381
|
req.input("title", thread.title);
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
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);
|
|
714
390
|
await req.query(mergeSql);
|
|
715
391
|
return thread;
|
|
716
392
|
} catch (error$1) {
|
|
@@ -731,10 +407,12 @@ ${columns}
|
|
|
731
407
|
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
732
408
|
*/
|
|
733
409
|
async getThreadsByResourceId(args) {
|
|
734
|
-
const { resourceId } = args;
|
|
410
|
+
const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
|
|
735
411
|
try {
|
|
736
|
-
const baseQuery = `FROM ${
|
|
737
|
-
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}`;
|
|
738
416
|
const request = this.pool.request();
|
|
739
417
|
request.input("resourceId", resourceId);
|
|
740
418
|
const resultSet = await request.query(dataQuery);
|
|
@@ -776,8 +454,8 @@ ${columns}
|
|
|
776
454
|
...metadata
|
|
777
455
|
};
|
|
778
456
|
try {
|
|
779
|
-
const table =
|
|
780
|
-
const
|
|
457
|
+
const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
458
|
+
const sql6 = `UPDATE ${table}
|
|
781
459
|
SET title = @title,
|
|
782
460
|
metadata = @metadata,
|
|
783
461
|
[updatedAt] = @updatedAt
|
|
@@ -787,8 +465,8 @@ ${columns}
|
|
|
787
465
|
req.input("id", id);
|
|
788
466
|
req.input("title", title);
|
|
789
467
|
req.input("metadata", JSON.stringify(mergedMetadata));
|
|
790
|
-
req.input("updatedAt",
|
|
791
|
-
const result = await req.query(
|
|
468
|
+
req.input("updatedAt", /* @__PURE__ */ new Date());
|
|
469
|
+
const result = await req.query(sql6);
|
|
792
470
|
let thread = result.recordset && result.recordset[0];
|
|
793
471
|
if (thread && "seq_id" in thread) {
|
|
794
472
|
const { seq_id, ...rest } = thread;
|
|
@@ -828,8 +506,8 @@ ${columns}
|
|
|
828
506
|
}
|
|
829
507
|
}
|
|
830
508
|
async deleteThread({ threadId }) {
|
|
831
|
-
const messagesTable =
|
|
832
|
-
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) });
|
|
833
511
|
const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
|
|
834
512
|
const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
|
|
835
513
|
const tx = this.pool.transaction();
|
|
@@ -861,6 +539,7 @@ ${columns}
|
|
|
861
539
|
selectBy,
|
|
862
540
|
orderByStatement
|
|
863
541
|
}) {
|
|
542
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
864
543
|
const include = selectBy?.include;
|
|
865
544
|
if (!include) return null;
|
|
866
545
|
const unionQueries = [];
|
|
@@ -887,7 +566,7 @@ ${columns}
|
|
|
887
566
|
m.seq_id
|
|
888
567
|
FROM (
|
|
889
568
|
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
890
|
-
FROM ${
|
|
569
|
+
FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
|
|
891
570
|
WHERE [thread_id] = ${pThreadId}
|
|
892
571
|
) AS m
|
|
893
572
|
WHERE m.id = ${pId}
|
|
@@ -895,7 +574,7 @@ ${columns}
|
|
|
895
574
|
SELECT 1
|
|
896
575
|
FROM (
|
|
897
576
|
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
898
|
-
FROM ${
|
|
577
|
+
FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
|
|
899
578
|
WHERE [thread_id] = ${pThreadId}
|
|
900
579
|
) AS target
|
|
901
580
|
WHERE target.id = ${pId}
|
|
@@ -932,11 +611,12 @@ ${columns}
|
|
|
932
611
|
return dedupedRows;
|
|
933
612
|
}
|
|
934
613
|
async getMessages(args) {
|
|
935
|
-
const { threadId, format, selectBy } = args;
|
|
936
|
-
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`;
|
|
937
616
|
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
938
|
-
const limit =
|
|
617
|
+
const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
939
618
|
try {
|
|
619
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
940
620
|
let rows = [];
|
|
941
621
|
const include = selectBy?.include || [];
|
|
942
622
|
if (include?.length) {
|
|
@@ -946,7 +626,7 @@ ${columns}
|
|
|
946
626
|
}
|
|
947
627
|
}
|
|
948
628
|
const excludeIds = rows.map((m) => m.id).filter(Boolean);
|
|
949
|
-
let query = `${selectStatement} FROM ${
|
|
629
|
+
let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
|
|
950
630
|
const request = this.pool.request();
|
|
951
631
|
request.input("threadId", threadId);
|
|
952
632
|
if (excludeIds.length > 0) {
|
|
@@ -966,30 +646,7 @@ ${columns}
|
|
|
966
646
|
return timeDiff;
|
|
967
647
|
});
|
|
968
648
|
rows = rows.map(({ seq_id, ...rest }) => rest);
|
|
969
|
-
|
|
970
|
-
if (typeof message.content === "string") {
|
|
971
|
-
try {
|
|
972
|
-
message.content = JSON.parse(message.content);
|
|
973
|
-
} catch {
|
|
974
|
-
}
|
|
975
|
-
}
|
|
976
|
-
if (format === "v1") {
|
|
977
|
-
if (Array.isArray(message.content)) ; else if (typeof message.content === "object" && message.content && Array.isArray(message.content.parts)) {
|
|
978
|
-
message.content = message.content.parts;
|
|
979
|
-
} else {
|
|
980
|
-
message.content = [{ type: "text", text: "" }];
|
|
981
|
-
}
|
|
982
|
-
} else {
|
|
983
|
-
if (typeof message.content !== "object" || !message.content || !("parts" in message.content)) {
|
|
984
|
-
message.content = { format: 2, parts: [{ type: "text", text: "" }] };
|
|
985
|
-
}
|
|
986
|
-
}
|
|
987
|
-
if (message.type === "v2") delete message.type;
|
|
988
|
-
return message;
|
|
989
|
-
});
|
|
990
|
-
return format === "v2" ? fetchedMessages.map(
|
|
991
|
-
(m) => ({ ...m, content: m.content || { format: 2, parts: [{ type: "text", text: "" }] } })
|
|
992
|
-
) : fetchedMessages;
|
|
649
|
+
return this._parseAndFormatMessages(rows, format);
|
|
993
650
|
} catch (error$1) {
|
|
994
651
|
const mastraError = new error.MastraError(
|
|
995
652
|
{
|
|
@@ -997,40 +654,76 @@ ${columns}
|
|
|
997
654
|
domain: error.ErrorDomain.STORAGE,
|
|
998
655
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
999
656
|
details: {
|
|
1000
|
-
threadId
|
|
657
|
+
threadId,
|
|
658
|
+
resourceId: resourceId ?? ""
|
|
1001
659
|
}
|
|
1002
660
|
},
|
|
1003
661
|
error$1
|
|
1004
662
|
);
|
|
1005
663
|
this.logger?.error?.(mastraError.toString());
|
|
1006
|
-
this.logger?.trackException(mastraError);
|
|
664
|
+
this.logger?.trackException?.(mastraError);
|
|
1007
665
|
return [];
|
|
1008
666
|
}
|
|
1009
667
|
}
|
|
1010
|
-
async
|
|
1011
|
-
|
|
1012
|
-
|
|
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`;
|
|
1013
674
|
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
1014
|
-
|
|
1015
|
-
|
|
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 [];
|
|
1016
706
|
}
|
|
707
|
+
}
|
|
708
|
+
async getMessagesPaginated(args) {
|
|
709
|
+
const { threadId, resourceId, format, selectBy } = args;
|
|
710
|
+
const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
|
|
1017
711
|
try {
|
|
1018
|
-
|
|
1019
|
-
const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
|
|
712
|
+
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
1020
713
|
const fromDate = dateRange?.start;
|
|
1021
714
|
const toDate = dateRange?.end;
|
|
1022
|
-
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
|
|
1023
|
-
const
|
|
1024
|
-
let
|
|
1025
|
-
if (
|
|
1026
|
-
const includeMessages = await this._getIncludedMessages({ threadId
|
|
1027
|
-
if (includeMessages)
|
|
1028
|
-
}
|
|
1029
|
-
const perPage =
|
|
1030
|
-
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;
|
|
1031
724
|
const conditions = ["[thread_id] = @threadId"];
|
|
1032
725
|
const request = this.pool.request();
|
|
1033
|
-
request.input("threadId",
|
|
726
|
+
request.input("threadId", threadId);
|
|
1034
727
|
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1035
728
|
conditions.push("[createdAt] >= @fromDate");
|
|
1036
729
|
request.input("fromDate", fromDate.toISOString());
|
|
@@ -1040,38 +733,38 @@ ${columns}
|
|
|
1040
733
|
request.input("toDate", toDate.toISOString());
|
|
1041
734
|
}
|
|
1042
735
|
const whereClause = `WHERE ${conditions.join(" AND ")}`;
|
|
1043
|
-
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}`;
|
|
1044
737
|
const countResult = await request.query(countQuery);
|
|
1045
738
|
const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
|
|
1046
|
-
if (total === 0 &&
|
|
1047
|
-
const parsedIncluded = this._parseAndFormatMessages(
|
|
739
|
+
if (total === 0 && messages.length > 0) {
|
|
740
|
+
const parsedIncluded = this._parseAndFormatMessages(messages, format);
|
|
1048
741
|
return {
|
|
1049
742
|
messages: parsedIncluded,
|
|
1050
743
|
total: parsedIncluded.length,
|
|
1051
|
-
page
|
|
744
|
+
page,
|
|
1052
745
|
perPage,
|
|
1053
746
|
hasMore: false
|
|
1054
747
|
};
|
|
1055
748
|
}
|
|
1056
|
-
const excludeIds =
|
|
749
|
+
const excludeIds = messages.map((m) => m.id);
|
|
1057
750
|
if (excludeIds.length > 0) {
|
|
1058
751
|
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
1059
752
|
conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
|
|
1060
753
|
excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
|
|
1061
754
|
}
|
|
1062
755
|
const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
|
|
1063
|
-
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`;
|
|
1064
757
|
request.input("offset", currentOffset);
|
|
1065
758
|
request.input("limit", perPage);
|
|
1066
759
|
const rowsResult = await request.query(dataQuery);
|
|
1067
760
|
const rows = rowsResult.recordset || [];
|
|
1068
761
|
rows.sort((a, b) => a.seq_id - b.seq_id);
|
|
1069
|
-
|
|
1070
|
-
const parsed = this._parseAndFormatMessages(
|
|
762
|
+
messages.push(...rows);
|
|
763
|
+
const parsed = this._parseAndFormatMessages(messages, format);
|
|
1071
764
|
return {
|
|
1072
765
|
messages: parsed,
|
|
1073
|
-
total
|
|
1074
|
-
page
|
|
766
|
+
total,
|
|
767
|
+
page,
|
|
1075
768
|
perPage,
|
|
1076
769
|
hasMore: currentOffset + rows.length < total
|
|
1077
770
|
};
|
|
@@ -1083,41 +776,17 @@ ${columns}
|
|
|
1083
776
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1084
777
|
details: {
|
|
1085
778
|
threadId,
|
|
779
|
+
resourceId: resourceId ?? "",
|
|
1086
780
|
page
|
|
1087
781
|
}
|
|
1088
782
|
},
|
|
1089
783
|
error$1
|
|
1090
784
|
);
|
|
1091
785
|
this.logger?.error?.(mastraError.toString());
|
|
1092
|
-
this.logger?.trackException(mastraError);
|
|
786
|
+
this.logger?.trackException?.(mastraError);
|
|
1093
787
|
return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
|
|
1094
788
|
}
|
|
1095
789
|
}
|
|
1096
|
-
_parseAndFormatMessages(messages, format) {
|
|
1097
|
-
const parsedMessages = messages.map((message) => {
|
|
1098
|
-
let parsed = message;
|
|
1099
|
-
if (typeof parsed.content === "string") {
|
|
1100
|
-
try {
|
|
1101
|
-
parsed = { ...parsed, content: JSON.parse(parsed.content) };
|
|
1102
|
-
} catch {
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
if (format === "v1") {
|
|
1106
|
-
if (Array.isArray(parsed.content)) ; else if (parsed.content?.parts) {
|
|
1107
|
-
parsed.content = parsed.content.parts;
|
|
1108
|
-
} else {
|
|
1109
|
-
parsed.content = [{ type: "text", text: "" }];
|
|
1110
|
-
}
|
|
1111
|
-
} else {
|
|
1112
|
-
if (!parsed.content?.parts) {
|
|
1113
|
-
parsed = { ...parsed, content: { format: 2, parts: [{ type: "text", text: "" }] } };
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
return parsed;
|
|
1117
|
-
});
|
|
1118
|
-
const list = new agent.MessageList().add(parsedMessages, "memory");
|
|
1119
|
-
return format === "v2" ? list.get.all.v2() : list.get.all.v1();
|
|
1120
|
-
}
|
|
1121
790
|
async saveMessages({
|
|
1122
791
|
messages,
|
|
1123
792
|
format
|
|
@@ -1142,8 +811,8 @@ ${columns}
|
|
|
1142
811
|
details: { threadId }
|
|
1143
812
|
});
|
|
1144
813
|
}
|
|
1145
|
-
const tableMessages =
|
|
1146
|
-
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) });
|
|
1147
816
|
try {
|
|
1148
817
|
const transaction = this.pool.transaction();
|
|
1149
818
|
await transaction.begin();
|
|
@@ -1166,7 +835,7 @@ ${columns}
|
|
|
1166
835
|
"content",
|
|
1167
836
|
typeof message.content === "string" ? message.content : JSON.stringify(message.content)
|
|
1168
837
|
);
|
|
1169
|
-
request.input("createdAt",
|
|
838
|
+
request.input("createdAt", sql3__default.default.DateTime2, message.createdAt);
|
|
1170
839
|
request.input("role", message.role);
|
|
1171
840
|
request.input("type", message.type || "v2");
|
|
1172
841
|
request.input("resourceId", message.resourceId);
|
|
@@ -1185,7 +854,7 @@ ${columns}
|
|
|
1185
854
|
await request.query(mergeSql);
|
|
1186
855
|
}
|
|
1187
856
|
const threadReq = transaction.request();
|
|
1188
|
-
threadReq.input("updatedAt",
|
|
857
|
+
threadReq.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
|
|
1189
858
|
threadReq.input("id", threadId);
|
|
1190
859
|
await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
|
|
1191
860
|
await transaction.commit();
|
|
@@ -1218,216 +887,6 @@ ${columns}
|
|
|
1218
887
|
);
|
|
1219
888
|
}
|
|
1220
889
|
}
|
|
1221
|
-
async persistWorkflowSnapshot({
|
|
1222
|
-
workflowName,
|
|
1223
|
-
runId,
|
|
1224
|
-
snapshot
|
|
1225
|
-
}) {
|
|
1226
|
-
const table = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
1227
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1228
|
-
try {
|
|
1229
|
-
const request = this.pool.request();
|
|
1230
|
-
request.input("workflow_name", workflowName);
|
|
1231
|
-
request.input("run_id", runId);
|
|
1232
|
-
request.input("snapshot", JSON.stringify(snapshot));
|
|
1233
|
-
request.input("createdAt", now);
|
|
1234
|
-
request.input("updatedAt", now);
|
|
1235
|
-
const mergeSql = `MERGE INTO ${table} AS target
|
|
1236
|
-
USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
|
|
1237
|
-
ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
|
|
1238
|
-
WHEN MATCHED THEN UPDATE SET
|
|
1239
|
-
snapshot = @snapshot,
|
|
1240
|
-
[updatedAt] = @updatedAt
|
|
1241
|
-
WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
|
|
1242
|
-
VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
|
|
1243
|
-
await request.query(mergeSql);
|
|
1244
|
-
} catch (error$1) {
|
|
1245
|
-
throw new error.MastraError(
|
|
1246
|
-
{
|
|
1247
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
|
|
1248
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1249
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1250
|
-
details: {
|
|
1251
|
-
workflowName,
|
|
1252
|
-
runId
|
|
1253
|
-
}
|
|
1254
|
-
},
|
|
1255
|
-
error$1
|
|
1256
|
-
);
|
|
1257
|
-
}
|
|
1258
|
-
}
|
|
1259
|
-
async loadWorkflowSnapshot({
|
|
1260
|
-
workflowName,
|
|
1261
|
-
runId
|
|
1262
|
-
}) {
|
|
1263
|
-
try {
|
|
1264
|
-
const result = await this.load({
|
|
1265
|
-
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
1266
|
-
keys: {
|
|
1267
|
-
workflow_name: workflowName,
|
|
1268
|
-
run_id: runId
|
|
1269
|
-
}
|
|
1270
|
-
});
|
|
1271
|
-
if (!result) {
|
|
1272
|
-
return null;
|
|
1273
|
-
}
|
|
1274
|
-
return result.snapshot;
|
|
1275
|
-
} catch (error$1) {
|
|
1276
|
-
throw new error.MastraError(
|
|
1277
|
-
{
|
|
1278
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
|
|
1279
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1280
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1281
|
-
details: {
|
|
1282
|
-
workflowName,
|
|
1283
|
-
runId
|
|
1284
|
-
}
|
|
1285
|
-
},
|
|
1286
|
-
error$1
|
|
1287
|
-
);
|
|
1288
|
-
}
|
|
1289
|
-
}
|
|
1290
|
-
async hasColumn(table, column) {
|
|
1291
|
-
const schema = this.schema || "dbo";
|
|
1292
|
-
const request = this.pool.request();
|
|
1293
|
-
request.input("schema", schema);
|
|
1294
|
-
request.input("table", table);
|
|
1295
|
-
request.input("column", column);
|
|
1296
|
-
request.input("columnLower", column.toLowerCase());
|
|
1297
|
-
const result = await request.query(
|
|
1298
|
-
`SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
|
|
1299
|
-
);
|
|
1300
|
-
return result.recordset.length > 0;
|
|
1301
|
-
}
|
|
1302
|
-
parseWorkflowRun(row) {
|
|
1303
|
-
let parsedSnapshot = row.snapshot;
|
|
1304
|
-
if (typeof parsedSnapshot === "string") {
|
|
1305
|
-
try {
|
|
1306
|
-
parsedSnapshot = JSON.parse(row.snapshot);
|
|
1307
|
-
} catch (e) {
|
|
1308
|
-
console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
return {
|
|
1312
|
-
workflowName: row.workflow_name,
|
|
1313
|
-
runId: row.run_id,
|
|
1314
|
-
snapshot: parsedSnapshot,
|
|
1315
|
-
createdAt: row.createdAt,
|
|
1316
|
-
updatedAt: row.updatedAt,
|
|
1317
|
-
resourceId: row.resourceId
|
|
1318
|
-
};
|
|
1319
|
-
}
|
|
1320
|
-
async getWorkflowRuns({
|
|
1321
|
-
workflowName,
|
|
1322
|
-
fromDate,
|
|
1323
|
-
toDate,
|
|
1324
|
-
limit,
|
|
1325
|
-
offset,
|
|
1326
|
-
resourceId
|
|
1327
|
-
} = {}) {
|
|
1328
|
-
try {
|
|
1329
|
-
const conditions = [];
|
|
1330
|
-
const paramMap = {};
|
|
1331
|
-
if (workflowName) {
|
|
1332
|
-
conditions.push(`[workflow_name] = @workflowName`);
|
|
1333
|
-
paramMap["workflowName"] = workflowName;
|
|
1334
|
-
}
|
|
1335
|
-
if (resourceId) {
|
|
1336
|
-
const hasResourceId = await this.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
|
|
1337
|
-
if (hasResourceId) {
|
|
1338
|
-
conditions.push(`[resourceId] = @resourceId`);
|
|
1339
|
-
paramMap["resourceId"] = resourceId;
|
|
1340
|
-
} else {
|
|
1341
|
-
console.warn(`[${storage.TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
|
|
1342
|
-
}
|
|
1343
|
-
}
|
|
1344
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1345
|
-
conditions.push(`[createdAt] >= @fromDate`);
|
|
1346
|
-
paramMap[`fromDate`] = fromDate.toISOString();
|
|
1347
|
-
}
|
|
1348
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1349
|
-
conditions.push(`[createdAt] <= @toDate`);
|
|
1350
|
-
paramMap[`toDate`] = toDate.toISOString();
|
|
1351
|
-
}
|
|
1352
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1353
|
-
let total = 0;
|
|
1354
|
-
const tableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
1355
|
-
const request = this.pool.request();
|
|
1356
|
-
Object.entries(paramMap).forEach(([key, value]) => {
|
|
1357
|
-
if (value instanceof Date) {
|
|
1358
|
-
request.input(key, sql__default.default.DateTime, value);
|
|
1359
|
-
} else {
|
|
1360
|
-
request.input(key, value);
|
|
1361
|
-
}
|
|
1362
|
-
});
|
|
1363
|
-
if (limit !== void 0 && offset !== void 0) {
|
|
1364
|
-
const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
|
|
1365
|
-
const countResult = await request.query(countQuery);
|
|
1366
|
-
total = Number(countResult.recordset[0]?.count || 0);
|
|
1367
|
-
}
|
|
1368
|
-
let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
|
|
1369
|
-
if (limit !== void 0 && offset !== void 0) {
|
|
1370
|
-
query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
1371
|
-
request.input("limit", limit);
|
|
1372
|
-
request.input("offset", offset);
|
|
1373
|
-
}
|
|
1374
|
-
const result = await request.query(query);
|
|
1375
|
-
const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
|
|
1376
|
-
return { runs, total: total || runs.length };
|
|
1377
|
-
} catch (error$1) {
|
|
1378
|
-
throw new error.MastraError(
|
|
1379
|
-
{
|
|
1380
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
|
|
1381
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1382
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1383
|
-
details: {
|
|
1384
|
-
workflowName: workflowName || "all"
|
|
1385
|
-
}
|
|
1386
|
-
},
|
|
1387
|
-
error$1
|
|
1388
|
-
);
|
|
1389
|
-
}
|
|
1390
|
-
}
|
|
1391
|
-
async getWorkflowRunById({
|
|
1392
|
-
runId,
|
|
1393
|
-
workflowName
|
|
1394
|
-
}) {
|
|
1395
|
-
try {
|
|
1396
|
-
const conditions = [];
|
|
1397
|
-
const paramMap = {};
|
|
1398
|
-
if (runId) {
|
|
1399
|
-
conditions.push(`[run_id] = @runId`);
|
|
1400
|
-
paramMap["runId"] = runId;
|
|
1401
|
-
}
|
|
1402
|
-
if (workflowName) {
|
|
1403
|
-
conditions.push(`[workflow_name] = @workflowName`);
|
|
1404
|
-
paramMap["workflowName"] = workflowName;
|
|
1405
|
-
}
|
|
1406
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1407
|
-
const tableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
1408
|
-
const query = `SELECT * FROM ${tableName} ${whereClause}`;
|
|
1409
|
-
const request = this.pool.request();
|
|
1410
|
-
Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
|
|
1411
|
-
const result = await request.query(query);
|
|
1412
|
-
if (!result.recordset || result.recordset.length === 0) {
|
|
1413
|
-
return null;
|
|
1414
|
-
}
|
|
1415
|
-
return this.parseWorkflowRun(result.recordset[0]);
|
|
1416
|
-
} catch (error$1) {
|
|
1417
|
-
throw new error.MastraError(
|
|
1418
|
-
{
|
|
1419
|
-
id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
|
|
1420
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1421
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1422
|
-
details: {
|
|
1423
|
-
runId,
|
|
1424
|
-
workflowName: workflowName || ""
|
|
1425
|
-
}
|
|
1426
|
-
},
|
|
1427
|
-
error$1
|
|
1428
|
-
);
|
|
1429
|
-
}
|
|
1430
|
-
}
|
|
1431
890
|
async updateMessages({
|
|
1432
891
|
messages
|
|
1433
892
|
}) {
|
|
@@ -1436,7 +895,7 @@ ${columns}
|
|
|
1436
895
|
}
|
|
1437
896
|
const messageIds = messages.map((m) => m.id);
|
|
1438
897
|
const idParams = messageIds.map((_, i) => `@id${i}`).join(", ");
|
|
1439
|
-
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) })}`;
|
|
1440
899
|
if (idParams.length > 0) {
|
|
1441
900
|
selectQuery += ` WHERE id IN (${idParams})`;
|
|
1442
901
|
} else {
|
|
@@ -1493,7 +952,7 @@ ${columns}
|
|
|
1493
952
|
}
|
|
1494
953
|
}
|
|
1495
954
|
if (setClauses.length > 0) {
|
|
1496
|
-
const updateSql = `UPDATE ${
|
|
955
|
+
const updateSql = `UPDATE ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} SET ${setClauses.join(", ")} WHERE id = @id`;
|
|
1497
956
|
await req.query(updateSql);
|
|
1498
957
|
}
|
|
1499
958
|
}
|
|
@@ -1502,7 +961,7 @@ ${columns}
|
|
|
1502
961
|
const threadReq = transaction.request();
|
|
1503
962
|
Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
|
|
1504
963
|
threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
|
|
1505
|
-
const threadSql = `UPDATE ${
|
|
964
|
+
const threadSql = `UPDATE ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
|
|
1506
965
|
await threadReq.query(threadSql);
|
|
1507
966
|
}
|
|
1508
967
|
await transaction.commit();
|
|
@@ -1530,137 +989,98 @@ ${columns}
|
|
|
1530
989
|
return message;
|
|
1531
990
|
});
|
|
1532
991
|
}
|
|
1533
|
-
async
|
|
1534
|
-
if (
|
|
992
|
+
async deleteMessages(messageIds) {
|
|
993
|
+
if (!messageIds || messageIds.length === 0) {
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
try {
|
|
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);
|
|
1003
|
+
});
|
|
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();
|
|
1535
1010
|
try {
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
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
|
+
}
|
|
1541
1022
|
}
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
}
|
|
1548
|
-
}
|
|
1549
|
-
async getEvals(options = {}) {
|
|
1550
|
-
const { agentName, type, page = 0, perPage = 100, dateRange } = options;
|
|
1551
|
-
const fromDate = dateRange?.start;
|
|
1552
|
-
const toDate = dateRange?.end;
|
|
1553
|
-
const where = [];
|
|
1554
|
-
const params = {};
|
|
1555
|
-
if (agentName) {
|
|
1556
|
-
where.push("agent_name = @agentName");
|
|
1557
|
-
params["agentName"] = agentName;
|
|
1558
|
-
}
|
|
1559
|
-
if (type === "test") {
|
|
1560
|
-
where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
|
|
1561
|
-
} else if (type === "live") {
|
|
1562
|
-
where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
|
|
1563
|
-
}
|
|
1564
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1565
|
-
where.push(`[created_at] >= @fromDate`);
|
|
1566
|
-
params[`fromDate`] = fromDate.toISOString();
|
|
1567
|
-
}
|
|
1568
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1569
|
-
where.push(`[created_at] <= @toDate`);
|
|
1570
|
-
params[`toDate`] = toDate.toISOString();
|
|
1571
|
-
}
|
|
1572
|
-
const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
|
|
1573
|
-
const tableName = this.getTableName(storage.TABLE_EVALS);
|
|
1574
|
-
const offset = page * perPage;
|
|
1575
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
|
|
1576
|
-
const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
1577
|
-
try {
|
|
1578
|
-
const countReq = this.pool.request();
|
|
1579
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
1580
|
-
if (value instanceof Date) {
|
|
1581
|
-
countReq.input(key, sql__default.default.DateTime, value);
|
|
1582
|
-
} else {
|
|
1583
|
-
countReq.input(key, value);
|
|
1023
|
+
await transaction.commit();
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
try {
|
|
1026
|
+
await transaction.rollback();
|
|
1027
|
+
} catch {
|
|
1584
1028
|
}
|
|
1585
|
-
|
|
1586
|
-
const countResult = await countReq.query(countQuery);
|
|
1587
|
-
const total = countResult.recordset[0]?.total || 0;
|
|
1588
|
-
if (total === 0) {
|
|
1589
|
-
return {
|
|
1590
|
-
evals: [],
|
|
1591
|
-
total: 0,
|
|
1592
|
-
page,
|
|
1593
|
-
perPage,
|
|
1594
|
-
hasMore: false
|
|
1595
|
-
};
|
|
1029
|
+
throw error;
|
|
1596
1030
|
}
|
|
1597
|
-
const req = this.pool.request();
|
|
1598
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
1599
|
-
if (value instanceof Date) {
|
|
1600
|
-
req.input(key, sql__default.default.DateTime, value);
|
|
1601
|
-
} else {
|
|
1602
|
-
req.input(key, value);
|
|
1603
|
-
}
|
|
1604
|
-
});
|
|
1605
|
-
req.input("offset", offset);
|
|
1606
|
-
req.input("perPage", perPage);
|
|
1607
|
-
const result = await req.query(dataQuery);
|
|
1608
|
-
const rows = result.recordset;
|
|
1609
|
-
return {
|
|
1610
|
-
evals: rows?.map((row) => this.transformEvalRow(row)) ?? [],
|
|
1611
|
-
total,
|
|
1612
|
-
page,
|
|
1613
|
-
perPage,
|
|
1614
|
-
hasMore: offset + (rows?.length ?? 0) < total
|
|
1615
|
-
};
|
|
1616
1031
|
} catch (error$1) {
|
|
1617
|
-
|
|
1032
|
+
throw new error.MastraError(
|
|
1618
1033
|
{
|
|
1619
|
-
id: "
|
|
1034
|
+
id: "MASTRA_STORAGE_MSSQL_STORE_DELETE_MESSAGES_FAILED",
|
|
1620
1035
|
domain: error.ErrorDomain.STORAGE,
|
|
1621
1036
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1622
|
-
details: {
|
|
1623
|
-
agentName: agentName || "all",
|
|
1624
|
-
type: type || "all",
|
|
1625
|
-
page,
|
|
1626
|
-
perPage
|
|
1627
|
-
}
|
|
1037
|
+
details: { messageIds: messageIds.join(", ") }
|
|
1628
1038
|
},
|
|
1629
1039
|
error$1
|
|
1630
1040
|
);
|
|
1631
|
-
this.logger?.error?.(mastraError.toString());
|
|
1632
|
-
this.logger?.trackException(mastraError);
|
|
1633
|
-
throw mastraError;
|
|
1634
1041
|
}
|
|
1635
1042
|
}
|
|
1636
|
-
async
|
|
1637
|
-
const tableName =
|
|
1043
|
+
async getResourceById({ resourceId }) {
|
|
1044
|
+
const tableName = getTableName({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
|
|
1638
1045
|
try {
|
|
1639
1046
|
const req = this.pool.request();
|
|
1640
|
-
req.input("
|
|
1641
|
-
req.
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
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
|
+
};
|
|
1649
1059
|
} catch (error$1) {
|
|
1650
1060
|
const mastraError = new error.MastraError(
|
|
1651
1061
|
{
|
|
1652
|
-
id: "
|
|
1062
|
+
id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
|
|
1653
1063
|
domain: error.ErrorDomain.STORAGE,
|
|
1654
1064
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1655
|
-
details: { resourceId
|
|
1065
|
+
details: { resourceId }
|
|
1656
1066
|
},
|
|
1657
1067
|
error$1
|
|
1658
1068
|
);
|
|
1659
1069
|
this.logger?.error?.(mastraError.toString());
|
|
1660
|
-
this.logger?.trackException(mastraError);
|
|
1070
|
+
this.logger?.trackException?.(mastraError);
|
|
1661
1071
|
throw mastraError;
|
|
1662
1072
|
}
|
|
1663
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
|
+
}
|
|
1664
1084
|
async updateResource({
|
|
1665
1085
|
resourceId,
|
|
1666
1086
|
workingMemory,
|
|
@@ -1687,7 +1107,7 @@ ${columns}
|
|
|
1687
1107
|
},
|
|
1688
1108
|
updatedAt: /* @__PURE__ */ new Date()
|
|
1689
1109
|
};
|
|
1690
|
-
const tableName =
|
|
1110
|
+
const tableName = getTableName({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
|
|
1691
1111
|
const updates = [];
|
|
1692
1112
|
const req = this.pool.request();
|
|
1693
1113
|
if (workingMemory !== void 0) {
|
|
@@ -1714,39 +1134,2326 @@ ${columns}
|
|
|
1714
1134
|
error$1
|
|
1715
1135
|
);
|
|
1716
1136
|
this.logger?.error?.(mastraError.toString());
|
|
1717
|
-
this.logger?.trackException(mastraError);
|
|
1137
|
+
this.logger?.trackException?.(mastraError);
|
|
1718
1138
|
throw mastraError;
|
|
1719
1139
|
}
|
|
1720
1140
|
}
|
|
1721
|
-
|
|
1722
|
-
|
|
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) {
|
|
1723
1163
|
try {
|
|
1724
|
-
const
|
|
1725
|
-
|
|
1726
|
-
const
|
|
1727
|
-
|
|
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) {
|
|
1728
1208
|
return null;
|
|
1729
1209
|
}
|
|
1730
1210
|
return {
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1211
|
+
traceId,
|
|
1212
|
+
spans: result.recordset.map(
|
|
1213
|
+
(span) => transformFromSqlRow({
|
|
1214
|
+
tableName: storage.TABLE_AI_SPANS,
|
|
1215
|
+
sqlRow: span
|
|
1216
|
+
})
|
|
1217
|
+
)
|
|
1734
1218
|
};
|
|
1735
1219
|
} catch (error$1) {
|
|
1736
|
-
|
|
1220
|
+
throw new error.MastraError(
|
|
1737
1221
|
{
|
|
1738
|
-
id: "
|
|
1222
|
+
id: "MSSQL_STORE_GET_AI_TRACE_FAILED",
|
|
1739
1223
|
domain: error.ErrorDomain.STORAGE,
|
|
1740
|
-
category: error.ErrorCategory.
|
|
1741
|
-
details: {
|
|
1224
|
+
category: error.ErrorCategory.USER,
|
|
1225
|
+
details: {
|
|
1226
|
+
traceId
|
|
1227
|
+
}
|
|
1228
|
+
},
|
|
1229
|
+
error$1
|
|
1230
|
+
);
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
async updateAISpan({
|
|
1234
|
+
spanId,
|
|
1235
|
+
traceId,
|
|
1236
|
+
updates
|
|
1237
|
+
}) {
|
|
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
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
async getAITracesPaginated({
|
|
1267
|
+
filters,
|
|
1268
|
+
pagination
|
|
1269
|
+
}) {
|
|
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)
|
|
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
|
+
}
|
|
1367
|
+
}
|
|
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
|
+
}
|
|
1394
|
+
}
|
|
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
|
+
}
|
|
1742
1450
|
},
|
|
1743
1451
|
error$1
|
|
1744
1452
|
);
|
|
1745
|
-
this.logger?.error?.(mastraError.toString());
|
|
1746
|
-
this.logger?.trackException(mastraError);
|
|
1747
|
-
throw mastraError;
|
|
1748
1453
|
}
|
|
1749
1454
|
}
|
|
1750
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 });
|
|
3454
|
+
}
|
|
3455
|
+
};
|
|
1751
3456
|
|
|
1752
3457
|
exports.MSSQLStore = MSSQLStore;
|
|
3458
|
+
//# sourceMappingURL=index.cjs.map
|
|
3459
|
+
//# sourceMappingURL=index.cjs.map
|