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