@mastra/mssql 0.0.0-zod-v4-compat-part-2-20250822105954 → 0.0.0-zod-v4-stuff-20250825154219
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 +129 -3
- package/dist/index.cjs +1617 -1104
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1617 -1104
- 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/operations/index.d.ts +51 -0
- package/dist/storage/domains/operations/index.d.ts.map +1 -0
- package/dist/storage/domains/scores/index.d.ts +46 -0
- package/dist/storage/domains/scores/index.d.ts.map +1 -0
- package/dist/storage/domains/traces/index.d.ts +37 -0
- package/dist/storage/domains/traces/index.d.ts.map +1 -0
- package/dist/storage/domains/utils.d.ts +6 -0
- package/dist/storage/domains/utils.d.ts.map +1 -0
- package/dist/storage/domains/workflows/index.d.ts +36 -0
- package/dist/storage/domains/workflows/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +78 -82
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +7 -6
- package/src/storage/domains/legacy-evals/index.ts +175 -0
- package/src/storage/domains/memory/index.ts +1084 -0
- package/src/storage/domains/operations/index.ts +401 -0
- package/src/storage/domains/scores/index.ts +316 -0
- package/src/storage/domains/traces/index.ts +212 -0
- package/src/storage/domains/utils.ts +12 -0
- package/src/storage/domains/workflows/index.ts +259 -0
- package/src/storage/index.ts +158 -1834
- package/tsup.config.ts +2 -7
package/src/storage/index.ts
CHANGED
|
@@ -1,19 +1,9 @@
|
|
|
1
|
-
import { MessageList } from '@mastra/core/agent';
|
|
2
1
|
import type { MastraMessageContentV2, MastraMessageV2 } from '@mastra/core/agent';
|
|
3
2
|
export type MastraMessageV2WithTypedContent = Omit<MastraMessageV2, 'content'> & { content: MastraMessageContentV2 };
|
|
4
3
|
import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
|
|
5
|
-
import type { MetricResult } from '@mastra/core/eval';
|
|
6
4
|
import type { MastraMessageV1, StorageThreadType } from '@mastra/core/memory';
|
|
7
5
|
import type { ScoreRowData } from '@mastra/core/scores';
|
|
8
|
-
import {
|
|
9
|
-
MastraStorage,
|
|
10
|
-
TABLE_MESSAGES,
|
|
11
|
-
TABLE_THREADS,
|
|
12
|
-
TABLE_TRACES,
|
|
13
|
-
TABLE_RESOURCES,
|
|
14
|
-
TABLE_WORKFLOW_SNAPSHOT,
|
|
15
|
-
TABLE_EVALS,
|
|
16
|
-
} from '@mastra/core/storage';
|
|
6
|
+
import { MastraStorage } from '@mastra/core/storage';
|
|
17
7
|
import type {
|
|
18
8
|
EvalRow,
|
|
19
9
|
PaginationInfo,
|
|
@@ -25,10 +15,20 @@ import type {
|
|
|
25
15
|
WorkflowRuns,
|
|
26
16
|
PaginationArgs,
|
|
27
17
|
StoragePagination,
|
|
18
|
+
ThreadSortOptions,
|
|
19
|
+
StorageDomains,
|
|
20
|
+
StorageGetTracesArg,
|
|
21
|
+
StorageGetTracesPaginatedArg,
|
|
28
22
|
} from '@mastra/core/storage';
|
|
29
|
-
import {
|
|
23
|
+
import type { Trace } from '@mastra/core/telemetry';
|
|
30
24
|
import type { WorkflowRunState } from '@mastra/core/workflows';
|
|
31
25
|
import sql from 'mssql';
|
|
26
|
+
import { LegacyEvalsMSSQL } from './domains/legacy-evals';
|
|
27
|
+
import { MemoryMSSQL } from './domains/memory';
|
|
28
|
+
import { StoreOperationsMSSQL } from './domains/operations';
|
|
29
|
+
import { ScoresMSSQL } from './domains/scores';
|
|
30
|
+
import { TracesMSSQL } from './domains/traces';
|
|
31
|
+
import { WorkflowsMSSQL } from './domains/workflows';
|
|
32
32
|
|
|
33
33
|
export type MSSQLConfigType = {
|
|
34
34
|
schemaName?: string;
|
|
@@ -51,9 +51,8 @@ export type MSSQLConfig = MSSQLConfigType;
|
|
|
51
51
|
export class MSSQLStore extends MastraStorage {
|
|
52
52
|
public pool: sql.ConnectionPool;
|
|
53
53
|
private schema?: string;
|
|
54
|
-
private setupSchemaPromise: Promise<void> | null = null;
|
|
55
|
-
private schemaSetupComplete: boolean | undefined = undefined;
|
|
56
54
|
private isConnected: Promise<boolean> | null = null;
|
|
55
|
+
stores: StorageDomains;
|
|
57
56
|
|
|
58
57
|
constructor(config: MSSQLConfigType) {
|
|
59
58
|
super({ name: 'MSSQLStore' });
|
|
@@ -75,7 +74,7 @@ export class MSSQLStore extends MastraStorage {
|
|
|
75
74
|
}
|
|
76
75
|
}
|
|
77
76
|
|
|
78
|
-
this.schema = config.schemaName;
|
|
77
|
+
this.schema = config.schemaName || 'dbo';
|
|
79
78
|
this.pool =
|
|
80
79
|
'connectionString' in config
|
|
81
80
|
? new sql.ConnectionPool(config.connectionString)
|
|
@@ -87,6 +86,22 @@ export class MSSQLStore extends MastraStorage {
|
|
|
87
86
|
port: config.port,
|
|
88
87
|
options: config.options || { encrypt: true, trustServerCertificate: true },
|
|
89
88
|
});
|
|
89
|
+
|
|
90
|
+
const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
|
|
91
|
+
const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
|
|
92
|
+
const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
93
|
+
const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
94
|
+
const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
|
|
95
|
+
const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
|
|
96
|
+
|
|
97
|
+
this.stores = {
|
|
98
|
+
operations,
|
|
99
|
+
scores,
|
|
100
|
+
traces,
|
|
101
|
+
workflows,
|
|
102
|
+
legacyEvals,
|
|
103
|
+
memory,
|
|
104
|
+
};
|
|
90
105
|
} catch (e) {
|
|
91
106
|
throw new MastraError(
|
|
92
107
|
{
|
|
@@ -140,340 +155,37 @@ export class MSSQLStore extends MastraStorage {
|
|
|
140
155
|
resourceWorkingMemory: true,
|
|
141
156
|
hasColumn: true,
|
|
142
157
|
createTable: true,
|
|
143
|
-
deleteMessages:
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
private getTableName(indexName: string) {
|
|
148
|
-
const parsedIndexName = parseSqlIdentifier(indexName, 'index name');
|
|
149
|
-
const quotedIndexName = `[${parsedIndexName}]`;
|
|
150
|
-
const quotedSchemaName = this.getSchemaName();
|
|
151
|
-
return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
private getSchemaName() {
|
|
155
|
-
return this.schema ? `[${parseSqlIdentifier(this.schema, 'schema name')}]` : undefined;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
private transformEvalRow(row: Record<string, any>): EvalRow {
|
|
159
|
-
let testInfoValue = null,
|
|
160
|
-
resultValue = null;
|
|
161
|
-
if (row.test_info) {
|
|
162
|
-
try {
|
|
163
|
-
testInfoValue = typeof row.test_info === 'string' ? JSON.parse(row.test_info) : row.test_info;
|
|
164
|
-
} catch {}
|
|
165
|
-
}
|
|
166
|
-
if (row.test_info) {
|
|
167
|
-
try {
|
|
168
|
-
resultValue = typeof row.result === 'string' ? JSON.parse(row.result) : row.result;
|
|
169
|
-
} catch {}
|
|
170
|
-
}
|
|
171
|
-
return {
|
|
172
|
-
agentName: row.agent_name as string,
|
|
173
|
-
input: row.input as string,
|
|
174
|
-
output: row.output as string,
|
|
175
|
-
result: resultValue as MetricResult,
|
|
176
|
-
metricName: row.metric_name as string,
|
|
177
|
-
instructions: row.instructions as string,
|
|
178
|
-
testInfo: testInfoValue,
|
|
179
|
-
globalRunId: row.global_run_id as string,
|
|
180
|
-
runId: row.run_id as string,
|
|
181
|
-
createdAt: row.created_at as string,
|
|
158
|
+
deleteMessages: true,
|
|
182
159
|
};
|
|
183
160
|
}
|
|
184
161
|
|
|
185
162
|
/** @deprecated use getEvals instead */
|
|
186
163
|
async getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]> {
|
|
187
|
-
|
|
188
|
-
let query = `SELECT * FROM ${this.getTableName(TABLE_EVALS)} WHERE agent_name = @p1`;
|
|
189
|
-
if (type === 'test') {
|
|
190
|
-
query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
|
|
191
|
-
} else if (type === 'live') {
|
|
192
|
-
query += " AND (test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)";
|
|
193
|
-
}
|
|
194
|
-
query += ' ORDER BY created_at DESC';
|
|
195
|
-
|
|
196
|
-
const request = this.pool.request();
|
|
197
|
-
request.input('p1', agentName);
|
|
198
|
-
const result = await request.query(query);
|
|
199
|
-
const rows = result.recordset;
|
|
200
|
-
return typeof this.transformEvalRow === 'function'
|
|
201
|
-
? (rows?.map((row: any) => this.transformEvalRow(row)) ?? [])
|
|
202
|
-
: (rows ?? []);
|
|
203
|
-
} catch (error: any) {
|
|
204
|
-
if (error && error.number === 208 && error.message && error.message.includes('Invalid object name')) {
|
|
205
|
-
return [];
|
|
206
|
-
}
|
|
207
|
-
console.error('Failed to get evals for the specified agent: ' + error?.message);
|
|
208
|
-
throw error;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
async batchInsert({ tableName, records }: { tableName: TABLE_NAMES; records: Record<string, any>[] }): Promise<void> {
|
|
213
|
-
const transaction = this.pool.transaction();
|
|
214
|
-
try {
|
|
215
|
-
await transaction.begin();
|
|
216
|
-
for (const record of records) {
|
|
217
|
-
await this.insert({ tableName, record });
|
|
218
|
-
}
|
|
219
|
-
await transaction.commit();
|
|
220
|
-
} catch (error) {
|
|
221
|
-
await transaction.rollback();
|
|
222
|
-
throw new MastraError(
|
|
223
|
-
{
|
|
224
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED',
|
|
225
|
-
domain: ErrorDomain.STORAGE,
|
|
226
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
227
|
-
details: {
|
|
228
|
-
tableName,
|
|
229
|
-
numberOfRecords: records.length,
|
|
230
|
-
},
|
|
231
|
-
},
|
|
232
|
-
error,
|
|
233
|
-
);
|
|
234
|
-
}
|
|
164
|
+
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
235
165
|
}
|
|
236
166
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
perPage?: number;
|
|
245
|
-
fromDate?: Date;
|
|
246
|
-
toDate?: Date;
|
|
247
|
-
}): Promise<any[]> {
|
|
248
|
-
if (args.fromDate || args.toDate) {
|
|
249
|
-
(args as any).dateRange = {
|
|
250
|
-
start: args.fromDate,
|
|
251
|
-
end: args.toDate,
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
const result = await this.getTracesPaginated(args);
|
|
255
|
-
return result.traces;
|
|
167
|
+
async getEvals(
|
|
168
|
+
options: {
|
|
169
|
+
agentName?: string;
|
|
170
|
+
type?: 'test' | 'live';
|
|
171
|
+
} & PaginationArgs = {},
|
|
172
|
+
): Promise<PaginationInfo & { evals: EvalRow[] }> {
|
|
173
|
+
return this.stores.legacyEvals.getEvals(options);
|
|
256
174
|
}
|
|
257
175
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
filters?: Record<string, any>;
|
|
264
|
-
} & PaginationArgs,
|
|
265
|
-
): Promise<
|
|
266
|
-
PaginationInfo & {
|
|
267
|
-
traces: any[];
|
|
268
|
-
}
|
|
269
|
-
> {
|
|
270
|
-
const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
|
|
271
|
-
const fromDate = dateRange?.start;
|
|
272
|
-
const toDate = dateRange?.end;
|
|
273
|
-
|
|
274
|
-
const perPage = perPageInput !== undefined ? perPageInput : 100;
|
|
275
|
-
const currentOffset = page * perPage;
|
|
276
|
-
|
|
277
|
-
const paramMap: Record<string, any> = {};
|
|
278
|
-
const conditions: string[] = [];
|
|
279
|
-
let paramIndex = 1;
|
|
280
|
-
|
|
281
|
-
if (name) {
|
|
282
|
-
const paramName = `p${paramIndex++}`;
|
|
283
|
-
conditions.push(`[name] LIKE @${paramName}`);
|
|
284
|
-
paramMap[paramName] = `${name}%`;
|
|
285
|
-
}
|
|
286
|
-
if (scope) {
|
|
287
|
-
const paramName = `p${paramIndex++}`;
|
|
288
|
-
conditions.push(`[scope] = @${paramName}`);
|
|
289
|
-
paramMap[paramName] = scope;
|
|
290
|
-
}
|
|
291
|
-
if (attributes) {
|
|
292
|
-
Object.entries(attributes).forEach(([key, value]) => {
|
|
293
|
-
const parsedKey = parseFieldKey(key);
|
|
294
|
-
const paramName = `p${paramIndex++}`;
|
|
295
|
-
conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
|
|
296
|
-
paramMap[paramName] = value;
|
|
297
|
-
});
|
|
298
|
-
}
|
|
299
|
-
if (filters) {
|
|
300
|
-
Object.entries(filters).forEach(([key, value]) => {
|
|
301
|
-
const parsedKey = parseFieldKey(key);
|
|
302
|
-
const paramName = `p${paramIndex++}`;
|
|
303
|
-
conditions.push(`[${parsedKey}] = @${paramName}`);
|
|
304
|
-
paramMap[paramName] = value;
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
308
|
-
const paramName = `p${paramIndex++}`;
|
|
309
|
-
conditions.push(`[createdAt] >= @${paramName}`);
|
|
310
|
-
paramMap[paramName] = fromDate.toISOString();
|
|
311
|
-
}
|
|
312
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
313
|
-
const paramName = `p${paramIndex++}`;
|
|
314
|
-
conditions.push(`[createdAt] <= @${paramName}`);
|
|
315
|
-
paramMap[paramName] = toDate.toISOString();
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
319
|
-
|
|
320
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(TABLE_TRACES)} ${whereClause}`;
|
|
321
|
-
let total = 0;
|
|
322
|
-
try {
|
|
323
|
-
const countRequest = this.pool.request();
|
|
324
|
-
Object.entries(paramMap).forEach(([key, value]) => {
|
|
325
|
-
if (value instanceof Date) {
|
|
326
|
-
countRequest.input(key, sql.DateTime, value);
|
|
327
|
-
} else {
|
|
328
|
-
countRequest.input(key, value);
|
|
329
|
-
}
|
|
330
|
-
});
|
|
331
|
-
const countResult = await countRequest.query(countQuery);
|
|
332
|
-
total = parseInt(countResult.recordset[0].total, 10);
|
|
333
|
-
} catch (error) {
|
|
334
|
-
throw new MastraError(
|
|
335
|
-
{
|
|
336
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT',
|
|
337
|
-
domain: ErrorDomain.STORAGE,
|
|
338
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
339
|
-
details: {
|
|
340
|
-
name: args.name ?? '',
|
|
341
|
-
scope: args.scope ?? '',
|
|
342
|
-
},
|
|
343
|
-
},
|
|
344
|
-
error,
|
|
345
|
-
);
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
if (total === 0) {
|
|
349
|
-
return {
|
|
350
|
-
traces: [],
|
|
351
|
-
total: 0,
|
|
352
|
-
page,
|
|
353
|
-
perPage,
|
|
354
|
-
hasMore: false,
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
const dataQuery = `SELECT * FROM ${this.getTableName(TABLE_TRACES)} ${whereClause} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
359
|
-
const dataRequest = this.pool.request();
|
|
360
|
-
Object.entries(paramMap).forEach(([key, value]) => {
|
|
361
|
-
if (value instanceof Date) {
|
|
362
|
-
dataRequest.input(key, sql.DateTime, value);
|
|
363
|
-
} else {
|
|
364
|
-
dataRequest.input(key, value);
|
|
365
|
-
}
|
|
366
|
-
});
|
|
367
|
-
dataRequest.input('offset', currentOffset);
|
|
368
|
-
dataRequest.input('limit', perPage);
|
|
369
|
-
|
|
370
|
-
try {
|
|
371
|
-
const rowsResult = await dataRequest.query(dataQuery);
|
|
372
|
-
const rows = rowsResult.recordset;
|
|
373
|
-
const traces = rows.map(row => ({
|
|
374
|
-
id: row.id,
|
|
375
|
-
parentSpanId: row.parentSpanId,
|
|
376
|
-
traceId: row.traceId,
|
|
377
|
-
name: row.name,
|
|
378
|
-
scope: row.scope,
|
|
379
|
-
kind: row.kind,
|
|
380
|
-
status: JSON.parse(row.status),
|
|
381
|
-
events: JSON.parse(row.events),
|
|
382
|
-
links: JSON.parse(row.links),
|
|
383
|
-
attributes: JSON.parse(row.attributes),
|
|
384
|
-
startTime: row.startTime,
|
|
385
|
-
endTime: row.endTime,
|
|
386
|
-
other: row.other,
|
|
387
|
-
createdAt: row.createdAt,
|
|
388
|
-
}));
|
|
389
|
-
|
|
390
|
-
return {
|
|
391
|
-
traces,
|
|
392
|
-
total,
|
|
393
|
-
page,
|
|
394
|
-
perPage,
|
|
395
|
-
hasMore: currentOffset + traces.length < total,
|
|
396
|
-
};
|
|
397
|
-
} catch (error) {
|
|
398
|
-
throw new MastraError(
|
|
399
|
-
{
|
|
400
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES',
|
|
401
|
-
domain: ErrorDomain.STORAGE,
|
|
402
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
403
|
-
details: {
|
|
404
|
-
name: args.name ?? '',
|
|
405
|
-
scope: args.scope ?? '',
|
|
406
|
-
},
|
|
407
|
-
},
|
|
408
|
-
error,
|
|
409
|
-
);
|
|
410
|
-
}
|
|
176
|
+
/**
|
|
177
|
+
* @deprecated use getTracesPaginated instead
|
|
178
|
+
*/
|
|
179
|
+
public async getTraces(args: StorageGetTracesArg): Promise<Trace[]> {
|
|
180
|
+
return this.stores.traces.getTraces(args);
|
|
411
181
|
}
|
|
412
182
|
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
return;
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
if (!this.setupSchemaPromise) {
|
|
419
|
-
this.setupSchemaPromise = (async () => {
|
|
420
|
-
try {
|
|
421
|
-
const checkRequest = this.pool.request();
|
|
422
|
-
checkRequest.input('schemaName', this.schema);
|
|
423
|
-
const checkResult = await checkRequest.query(`
|
|
424
|
-
SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
|
|
425
|
-
`);
|
|
426
|
-
const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
|
|
427
|
-
|
|
428
|
-
if (!schemaExists) {
|
|
429
|
-
try {
|
|
430
|
-
await this.pool.request().query(`CREATE SCHEMA [${this.schema}]`);
|
|
431
|
-
this.logger?.info?.(`Schema "${this.schema}" created successfully`);
|
|
432
|
-
} catch (error) {
|
|
433
|
-
this.logger?.error?.(`Failed to create schema "${this.schema}"`, { error });
|
|
434
|
-
throw new Error(
|
|
435
|
-
`Unable to create schema "${this.schema}". This requires CREATE privilege on the database. ` +
|
|
436
|
-
`Either create the schema manually or grant CREATE privilege to the user.`,
|
|
437
|
-
);
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
this.schemaSetupComplete = true;
|
|
442
|
-
this.logger?.debug?.(`Schema "${this.schema}" is ready for use`);
|
|
443
|
-
} catch (error) {
|
|
444
|
-
this.schemaSetupComplete = undefined;
|
|
445
|
-
this.setupSchemaPromise = null;
|
|
446
|
-
throw error;
|
|
447
|
-
} finally {
|
|
448
|
-
this.setupSchemaPromise = null;
|
|
449
|
-
}
|
|
450
|
-
})();
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
await this.setupSchemaPromise;
|
|
183
|
+
public async getTracesPaginated(args: StorageGetTracesPaginatedArg): Promise<PaginationInfo & { traces: Trace[] }> {
|
|
184
|
+
return this.stores.traces.getTracesPaginated(args);
|
|
454
185
|
}
|
|
455
186
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
case 'text':
|
|
459
|
-
return isPrimaryKey ? 'NVARCHAR(255)' : 'NVARCHAR(MAX)';
|
|
460
|
-
case 'timestamp':
|
|
461
|
-
return 'DATETIME2(7)';
|
|
462
|
-
case 'uuid':
|
|
463
|
-
return 'UNIQUEIDENTIFIER';
|
|
464
|
-
case 'jsonb':
|
|
465
|
-
return 'NVARCHAR(MAX)';
|
|
466
|
-
case 'integer':
|
|
467
|
-
return 'INT';
|
|
468
|
-
case 'bigint':
|
|
469
|
-
return 'BIGINT';
|
|
470
|
-
default:
|
|
471
|
-
throw new MastraError({
|
|
472
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED',
|
|
473
|
-
domain: ErrorDomain.STORAGE,
|
|
474
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
475
|
-
});
|
|
476
|
-
}
|
|
187
|
+
async batchTraceInsert({ records }: { records: Record<string, any>[] }): Promise<void> {
|
|
188
|
+
return this.stores.traces.batchTraceInsert({ records });
|
|
477
189
|
}
|
|
478
190
|
|
|
479
191
|
async createTable({
|
|
@@ -483,88 +195,7 @@ export class MSSQLStore extends MastraStorage {
|
|
|
483
195
|
tableName: TABLE_NAMES;
|
|
484
196
|
schema: Record<string, StorageColumn>;
|
|
485
197
|
}): Promise<void> {
|
|
486
|
-
|
|
487
|
-
const uniqueConstraintColumns = tableName === TABLE_WORKFLOW_SNAPSHOT ? ['workflow_name', 'run_id'] : [];
|
|
488
|
-
|
|
489
|
-
const columns = Object.entries(schema)
|
|
490
|
-
.map(([name, def]) => {
|
|
491
|
-
const parsedName = parseSqlIdentifier(name, 'column name');
|
|
492
|
-
const constraints = [];
|
|
493
|
-
if (def.primaryKey) constraints.push('PRIMARY KEY');
|
|
494
|
-
if (!def.nullable) constraints.push('NOT NULL');
|
|
495
|
-
const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
|
|
496
|
-
return `[${parsedName}] ${this.getSqlType(def.type, isIndexed)} ${constraints.join(' ')}`.trim();
|
|
497
|
-
})
|
|
498
|
-
.join(',\n');
|
|
499
|
-
|
|
500
|
-
if (this.schema) {
|
|
501
|
-
await this.setupSchema();
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
const checkTableRequest = this.pool.request();
|
|
505
|
-
checkTableRequest.input('tableName', this.getTableName(tableName).replace(/[[\]]/g, '').split('.').pop());
|
|
506
|
-
const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
|
|
507
|
-
checkTableRequest.input('schema', this.schema || 'dbo');
|
|
508
|
-
const checkTableResult = await checkTableRequest.query(checkTableSql);
|
|
509
|
-
const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
|
|
510
|
-
|
|
511
|
-
if (!tableExists) {
|
|
512
|
-
const createSql = `CREATE TABLE ${this.getTableName(tableName)} (\n${columns}\n)`;
|
|
513
|
-
await this.pool.request().query(createSql);
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
const columnCheckSql = `
|
|
517
|
-
SELECT 1 AS found
|
|
518
|
-
FROM INFORMATION_SCHEMA.COLUMNS
|
|
519
|
-
WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
|
|
520
|
-
`;
|
|
521
|
-
const checkColumnRequest = this.pool.request();
|
|
522
|
-
checkColumnRequest.input('schema', this.schema || 'dbo');
|
|
523
|
-
checkColumnRequest.input('tableName', this.getTableName(tableName).replace(/[[\]]/g, '').split('.').pop());
|
|
524
|
-
const columnResult = await checkColumnRequest.query(columnCheckSql);
|
|
525
|
-
const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
|
|
526
|
-
|
|
527
|
-
if (!columnExists) {
|
|
528
|
-
const alterSql = `ALTER TABLE ${this.getTableName(tableName)} ADD seq_id BIGINT IDENTITY(1,1)`;
|
|
529
|
-
await this.pool.request().query(alterSql);
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
|
|
533
|
-
const constraintName = 'mastra_workflow_snapshot_workflow_name_run_id_key';
|
|
534
|
-
const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
|
|
535
|
-
const checkConstraintRequest = this.pool.request();
|
|
536
|
-
checkConstraintRequest.input('constraintName', constraintName);
|
|
537
|
-
const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
|
|
538
|
-
const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
|
|
539
|
-
if (!constraintExists) {
|
|
540
|
-
const addConstraintSql = `ALTER TABLE ${this.getTableName(tableName)} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
|
|
541
|
-
await this.pool.request().query(addConstraintSql);
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
} catch (error) {
|
|
545
|
-
throw new MastraError(
|
|
546
|
-
{
|
|
547
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED',
|
|
548
|
-
domain: ErrorDomain.STORAGE,
|
|
549
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
550
|
-
details: {
|
|
551
|
-
tableName,
|
|
552
|
-
},
|
|
553
|
-
},
|
|
554
|
-
error,
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
protected getDefaultValue(type: StorageColumn['type']): string {
|
|
560
|
-
switch (type) {
|
|
561
|
-
case 'timestamp':
|
|
562
|
-
return 'DEFAULT SYSDATETIMEOFFSET()';
|
|
563
|
-
case 'jsonb':
|
|
564
|
-
return "DEFAULT N'{}'";
|
|
565
|
-
default:
|
|
566
|
-
return super.getDefaultValue(type);
|
|
567
|
-
}
|
|
198
|
+
return this.stores.operations.createTable({ tableName, schema });
|
|
568
199
|
}
|
|
569
200
|
|
|
570
201
|
async alterTable({
|
|
@@ -576,321 +207,58 @@ export class MSSQLStore extends MastraStorage {
|
|
|
576
207
|
schema: Record<string, StorageColumn>;
|
|
577
208
|
ifNotExists: string[];
|
|
578
209
|
}): Promise<void> {
|
|
579
|
-
|
|
580
|
-
try {
|
|
581
|
-
for (const columnName of ifNotExists) {
|
|
582
|
-
if (schema[columnName]) {
|
|
583
|
-
const columnCheckRequest = this.pool.request();
|
|
584
|
-
columnCheckRequest.input('tableName', fullTableName.replace(/[[\]]/g, '').split('.').pop());
|
|
585
|
-
columnCheckRequest.input('columnName', columnName);
|
|
586
|
-
columnCheckRequest.input('schema', this.schema || 'dbo');
|
|
587
|
-
const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
|
|
588
|
-
const checkResult = await columnCheckRequest.query(checkSql);
|
|
589
|
-
const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
|
|
590
|
-
if (!columnExists) {
|
|
591
|
-
const columnDef = schema[columnName];
|
|
592
|
-
const sqlType = this.getSqlType(columnDef.type);
|
|
593
|
-
const nullable = columnDef.nullable === false ? 'NOT NULL' : '';
|
|
594
|
-
const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : '';
|
|
595
|
-
const parsedColumnName = parseSqlIdentifier(columnName, 'column name');
|
|
596
|
-
const alterSql =
|
|
597
|
-
`ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
|
|
598
|
-
await this.pool.request().query(alterSql);
|
|
599
|
-
this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
} catch (error) {
|
|
604
|
-
throw new MastraError(
|
|
605
|
-
{
|
|
606
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED',
|
|
607
|
-
domain: ErrorDomain.STORAGE,
|
|
608
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
609
|
-
details: {
|
|
610
|
-
tableName,
|
|
611
|
-
},
|
|
612
|
-
},
|
|
613
|
-
error,
|
|
614
|
-
);
|
|
615
|
-
}
|
|
210
|
+
return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
|
|
616
211
|
}
|
|
617
212
|
|
|
618
213
|
async clearTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
OBJECT_NAME(fk.parent_object_id) AS table_name
|
|
625
|
-
FROM sys.foreign_keys fk
|
|
626
|
-
WHERE fk.referenced_object_id = OBJECT_ID(@fullTableName)
|
|
627
|
-
`;
|
|
628
|
-
const fkResult = await this.pool.request().input('fullTableName', fullTableName).query(fkQuery);
|
|
629
|
-
const childTables: { schema_name: string; table_name: string }[] = fkResult.recordset || [];
|
|
630
|
-
for (const child of childTables) {
|
|
631
|
-
const childTableName = this.schema ? `[${child.schema_name}].[${child.table_name}]` : `[${child.table_name}]`;
|
|
632
|
-
await this.clearTable({ tableName: childTableName as TABLE_NAMES });
|
|
633
|
-
}
|
|
634
|
-
await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
|
|
635
|
-
} catch (error) {
|
|
636
|
-
throw new MastraError(
|
|
637
|
-
{
|
|
638
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED',
|
|
639
|
-
domain: ErrorDomain.STORAGE,
|
|
640
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
641
|
-
details: {
|
|
642
|
-
tableName,
|
|
643
|
-
},
|
|
644
|
-
},
|
|
645
|
-
error,
|
|
646
|
-
);
|
|
647
|
-
}
|
|
214
|
+
return this.stores.operations.clearTable({ tableName });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async dropTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {
|
|
218
|
+
return this.stores.operations.dropTable({ tableName });
|
|
648
219
|
}
|
|
649
220
|
|
|
650
221
|
async insert({ tableName, record }: { tableName: TABLE_NAMES; record: Record<string, any> }): Promise<void> {
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
const values = Object.values(record);
|
|
654
|
-
const paramNames = values.map((_, i) => `@param${i}`);
|
|
655
|
-
const insertSql = `INSERT INTO ${this.getTableName(tableName)} (${columns.map(c => `[${c}]`).join(', ')}) VALUES (${paramNames.join(', ')})`;
|
|
656
|
-
const request = this.pool.request();
|
|
657
|
-
values.forEach((value, i) => {
|
|
658
|
-
if (value instanceof Date) {
|
|
659
|
-
request.input(`param${i}`, sql.DateTime2, value);
|
|
660
|
-
} else if (typeof value === 'object' && value !== null) {
|
|
661
|
-
request.input(`param${i}`, JSON.stringify(value));
|
|
662
|
-
} else {
|
|
663
|
-
request.input(`param${i}`, value);
|
|
664
|
-
}
|
|
665
|
-
});
|
|
222
|
+
return this.stores.operations.insert({ tableName, record });
|
|
223
|
+
}
|
|
666
224
|
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
throw new MastraError(
|
|
670
|
-
{
|
|
671
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED',
|
|
672
|
-
domain: ErrorDomain.STORAGE,
|
|
673
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
674
|
-
details: {
|
|
675
|
-
tableName,
|
|
676
|
-
},
|
|
677
|
-
},
|
|
678
|
-
error,
|
|
679
|
-
);
|
|
680
|
-
}
|
|
225
|
+
async batchInsert({ tableName, records }: { tableName: TABLE_NAMES; records: Record<string, any>[] }): Promise<void> {
|
|
226
|
+
return this.stores.operations.batchInsert({ tableName, records });
|
|
681
227
|
}
|
|
682
228
|
|
|
683
229
|
async load<R>({ tableName, keys }: { tableName: TABLE_NAMES; keys: Record<string, string> }): Promise<R | null> {
|
|
684
|
-
|
|
685
|
-
const keyEntries = Object.entries(keys).map(([key, value]) => [parseSqlIdentifier(key, 'column name'), value]);
|
|
686
|
-
const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(' AND ');
|
|
687
|
-
const values = keyEntries.map(([_, value]) => value);
|
|
688
|
-
const sql = `SELECT * FROM ${this.getTableName(tableName)} WHERE ${conditions}`;
|
|
689
|
-
const request = this.pool.request();
|
|
690
|
-
values.forEach((value, i) => {
|
|
691
|
-
request.input(`param${i}`, value);
|
|
692
|
-
});
|
|
693
|
-
const resultSet = await request.query(sql);
|
|
694
|
-
const result = resultSet.recordset[0] || null;
|
|
695
|
-
if (!result) {
|
|
696
|
-
return null;
|
|
697
|
-
}
|
|
698
|
-
if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
|
|
699
|
-
const snapshot = result as any;
|
|
700
|
-
if (typeof snapshot.snapshot === 'string') {
|
|
701
|
-
snapshot.snapshot = JSON.parse(snapshot.snapshot);
|
|
702
|
-
}
|
|
703
|
-
return snapshot;
|
|
704
|
-
}
|
|
705
|
-
return result;
|
|
706
|
-
} catch (error) {
|
|
707
|
-
throw new MastraError(
|
|
708
|
-
{
|
|
709
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED',
|
|
710
|
-
domain: ErrorDomain.STORAGE,
|
|
711
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
712
|
-
details: {
|
|
713
|
-
tableName,
|
|
714
|
-
},
|
|
715
|
-
},
|
|
716
|
-
error,
|
|
717
|
-
);
|
|
718
|
-
}
|
|
230
|
+
return this.stores.operations.load({ tableName, keys });
|
|
719
231
|
}
|
|
720
232
|
|
|
233
|
+
/**
|
|
234
|
+
* Memory
|
|
235
|
+
*/
|
|
236
|
+
|
|
721
237
|
async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
FROM ${this.getTableName(TABLE_THREADS)}
|
|
731
|
-
WHERE id = @threadId`;
|
|
732
|
-
const request = this.pool.request();
|
|
733
|
-
request.input('threadId', threadId);
|
|
734
|
-
const resultSet = await request.query(sql);
|
|
735
|
-
const thread = resultSet.recordset[0] || null;
|
|
736
|
-
if (!thread) {
|
|
737
|
-
return null;
|
|
738
|
-
}
|
|
739
|
-
return {
|
|
740
|
-
...thread,
|
|
741
|
-
metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
|
|
742
|
-
createdAt: thread.createdAt,
|
|
743
|
-
updatedAt: thread.updatedAt,
|
|
744
|
-
};
|
|
745
|
-
} catch (error) {
|
|
746
|
-
throw new MastraError(
|
|
747
|
-
{
|
|
748
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED',
|
|
749
|
-
domain: ErrorDomain.STORAGE,
|
|
750
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
751
|
-
details: {
|
|
752
|
-
threadId,
|
|
753
|
-
},
|
|
754
|
-
},
|
|
755
|
-
error,
|
|
756
|
-
);
|
|
757
|
-
}
|
|
238
|
+
return this.stores.memory.getThreadById({ threadId });
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
243
|
+
*/
|
|
244
|
+
public async getThreadsByResourceId(args: { resourceId: string } & ThreadSortOptions): Promise<StorageThreadType[]> {
|
|
245
|
+
return this.stores.memory.getThreadsByResourceId(args);
|
|
758
246
|
}
|
|
759
247
|
|
|
760
248
|
public async getThreadsByResourceIdPaginated(
|
|
761
249
|
args: {
|
|
762
250
|
resourceId: string;
|
|
763
|
-
|
|
251
|
+
page: number;
|
|
252
|
+
perPage: number;
|
|
253
|
+
} & ThreadSortOptions,
|
|
764
254
|
): Promise<PaginationInfo & { threads: StorageThreadType[] }> {
|
|
765
|
-
|
|
766
|
-
try {
|
|
767
|
-
const perPage = perPageInput !== undefined ? perPageInput : 100;
|
|
768
|
-
const currentOffset = page * perPage;
|
|
769
|
-
const baseQuery = `FROM ${this.getTableName(TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
|
|
770
|
-
|
|
771
|
-
const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
|
|
772
|
-
const countRequest = this.pool.request();
|
|
773
|
-
countRequest.input('resourceId', resourceId);
|
|
774
|
-
const countResult = await countRequest.query(countQuery);
|
|
775
|
-
const total = parseInt(countResult.recordset[0]?.count ?? '0', 10);
|
|
776
|
-
|
|
777
|
-
if (total === 0) {
|
|
778
|
-
return {
|
|
779
|
-
threads: [],
|
|
780
|
-
total: 0,
|
|
781
|
-
page,
|
|
782
|
-
perPage,
|
|
783
|
-
hasMore: false,
|
|
784
|
-
};
|
|
785
|
-
}
|
|
786
|
-
|
|
787
|
-
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
788
|
-
const dataRequest = this.pool.request();
|
|
789
|
-
dataRequest.input('resourceId', resourceId);
|
|
790
|
-
dataRequest.input('perPage', perPage);
|
|
791
|
-
dataRequest.input('offset', currentOffset);
|
|
792
|
-
const rowsResult = await dataRequest.query(dataQuery);
|
|
793
|
-
const rows = rowsResult.recordset || [];
|
|
794
|
-
const threads = rows.map(thread => ({
|
|
795
|
-
...thread,
|
|
796
|
-
metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
|
|
797
|
-
createdAt: thread.createdAt,
|
|
798
|
-
updatedAt: thread.updatedAt,
|
|
799
|
-
}));
|
|
800
|
-
|
|
801
|
-
return {
|
|
802
|
-
threads,
|
|
803
|
-
total,
|
|
804
|
-
page,
|
|
805
|
-
perPage,
|
|
806
|
-
hasMore: currentOffset + threads.length < total,
|
|
807
|
-
};
|
|
808
|
-
} catch (error) {
|
|
809
|
-
const mastraError = new MastraError(
|
|
810
|
-
{
|
|
811
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED',
|
|
812
|
-
domain: ErrorDomain.STORAGE,
|
|
813
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
814
|
-
details: {
|
|
815
|
-
resourceId,
|
|
816
|
-
page,
|
|
817
|
-
},
|
|
818
|
-
},
|
|
819
|
-
error,
|
|
820
|
-
);
|
|
821
|
-
this.logger?.error?.(mastraError.toString());
|
|
822
|
-
this.logger?.trackException?.(mastraError);
|
|
823
|
-
return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
public async saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType> {
|
|
828
|
-
try {
|
|
829
|
-
const table = this.getTableName(TABLE_THREADS);
|
|
830
|
-
const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
|
|
831
|
-
USING (SELECT @id AS id) AS source
|
|
832
|
-
ON (target.id = source.id)
|
|
833
|
-
WHEN MATCHED THEN
|
|
834
|
-
UPDATE SET
|
|
835
|
-
[resourceId] = @resourceId,
|
|
836
|
-
title = @title,
|
|
837
|
-
metadata = @metadata,
|
|
838
|
-
[createdAt] = @createdAt,
|
|
839
|
-
[updatedAt] = @updatedAt
|
|
840
|
-
WHEN NOT MATCHED THEN
|
|
841
|
-
INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
|
|
842
|
-
VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
|
|
843
|
-
const req = this.pool.request();
|
|
844
|
-
req.input('id', thread.id);
|
|
845
|
-
req.input('resourceId', thread.resourceId);
|
|
846
|
-
req.input('title', thread.title);
|
|
847
|
-
req.input('metadata', thread.metadata ? JSON.stringify(thread.metadata) : null);
|
|
848
|
-
req.input('createdAt', thread.createdAt);
|
|
849
|
-
req.input('updatedAt', thread.updatedAt);
|
|
850
|
-
await req.query(mergeSql);
|
|
851
|
-
return thread;
|
|
852
|
-
} catch (error) {
|
|
853
|
-
throw new MastraError(
|
|
854
|
-
{
|
|
855
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED',
|
|
856
|
-
domain: ErrorDomain.STORAGE,
|
|
857
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
858
|
-
details: {
|
|
859
|
-
threadId: thread.id,
|
|
860
|
-
},
|
|
861
|
-
},
|
|
862
|
-
error,
|
|
863
|
-
);
|
|
864
|
-
}
|
|
255
|
+
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
865
256
|
}
|
|
866
257
|
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
*/
|
|
870
|
-
public async getThreadsByResourceId(args: { resourceId: string }): Promise<StorageThreadType[]> {
|
|
871
|
-
const { resourceId } = args;
|
|
872
|
-
try {
|
|
873
|
-
const baseQuery = `FROM ${this.getTableName(TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
|
|
874
|
-
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC`;
|
|
875
|
-
const request = this.pool.request();
|
|
876
|
-
request.input('resourceId', resourceId);
|
|
877
|
-
const resultSet = await request.query(dataQuery);
|
|
878
|
-
const rows = resultSet.recordset || [];
|
|
879
|
-
return rows.map(thread => ({
|
|
880
|
-
...thread,
|
|
881
|
-
metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
|
|
882
|
-
createdAt: thread.createdAt,
|
|
883
|
-
updatedAt: thread.updatedAt,
|
|
884
|
-
}));
|
|
885
|
-
} catch (error) {
|
|
886
|
-
this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
|
|
887
|
-
return [];
|
|
888
|
-
}
|
|
258
|
+
async saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType> {
|
|
259
|
+
return this.stores.memory.saveThread({ thread });
|
|
889
260
|
}
|
|
890
261
|
|
|
891
|
-
/**
|
|
892
|
-
* Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
|
|
893
|
-
*/
|
|
894
262
|
async updateThread({
|
|
895
263
|
id,
|
|
896
264
|
title,
|
|
@@ -900,195 +268,11 @@ export class MSSQLStore extends MastraStorage {
|
|
|
900
268
|
title: string;
|
|
901
269
|
metadata: Record<string, unknown>;
|
|
902
270
|
}): Promise<StorageThreadType> {
|
|
903
|
-
|
|
904
|
-
if (!existingThread) {
|
|
905
|
-
throw new MastraError({
|
|
906
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED',
|
|
907
|
-
domain: ErrorDomain.STORAGE,
|
|
908
|
-
category: ErrorCategory.USER,
|
|
909
|
-
text: `Thread ${id} not found`,
|
|
910
|
-
details: {
|
|
911
|
-
threadId: id,
|
|
912
|
-
title,
|
|
913
|
-
},
|
|
914
|
-
});
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
const mergedMetadata = {
|
|
918
|
-
...existingThread.metadata,
|
|
919
|
-
...metadata,
|
|
920
|
-
};
|
|
921
|
-
|
|
922
|
-
try {
|
|
923
|
-
const table = this.getTableName(TABLE_THREADS);
|
|
924
|
-
const sql = `UPDATE ${table}
|
|
925
|
-
SET title = @title,
|
|
926
|
-
metadata = @metadata,
|
|
927
|
-
[updatedAt] = @updatedAt
|
|
928
|
-
OUTPUT INSERTED.*
|
|
929
|
-
WHERE id = @id`;
|
|
930
|
-
const req = this.pool.request();
|
|
931
|
-
req.input('id', id);
|
|
932
|
-
req.input('title', title);
|
|
933
|
-
req.input('metadata', JSON.stringify(mergedMetadata));
|
|
934
|
-
req.input('updatedAt', new Date().toISOString());
|
|
935
|
-
const result = await req.query(sql);
|
|
936
|
-
let thread = result.recordset && result.recordset[0];
|
|
937
|
-
if (thread && 'seq_id' in thread) {
|
|
938
|
-
const { seq_id, ...rest } = thread;
|
|
939
|
-
thread = rest;
|
|
940
|
-
}
|
|
941
|
-
if (!thread) {
|
|
942
|
-
throw new MastraError({
|
|
943
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED',
|
|
944
|
-
domain: ErrorDomain.STORAGE,
|
|
945
|
-
category: ErrorCategory.USER,
|
|
946
|
-
text: `Thread ${id} not found after update`,
|
|
947
|
-
details: {
|
|
948
|
-
threadId: id,
|
|
949
|
-
title,
|
|
950
|
-
},
|
|
951
|
-
});
|
|
952
|
-
}
|
|
953
|
-
return {
|
|
954
|
-
...thread,
|
|
955
|
-
metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
|
|
956
|
-
createdAt: thread.createdAt,
|
|
957
|
-
updatedAt: thread.updatedAt,
|
|
958
|
-
};
|
|
959
|
-
} catch (error) {
|
|
960
|
-
throw new MastraError(
|
|
961
|
-
{
|
|
962
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED',
|
|
963
|
-
domain: ErrorDomain.STORAGE,
|
|
964
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
965
|
-
details: {
|
|
966
|
-
threadId: id,
|
|
967
|
-
title,
|
|
968
|
-
},
|
|
969
|
-
},
|
|
970
|
-
error,
|
|
971
|
-
);
|
|
972
|
-
}
|
|
271
|
+
return this.stores.memory.updateThread({ id, title, metadata });
|
|
973
272
|
}
|
|
974
273
|
|
|
975
274
|
async deleteThread({ threadId }: { threadId: string }): Promise<void> {
|
|
976
|
-
|
|
977
|
-
const threadsTable = this.getTableName(TABLE_THREADS);
|
|
978
|
-
const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
|
|
979
|
-
const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
|
|
980
|
-
const tx = this.pool.transaction();
|
|
981
|
-
try {
|
|
982
|
-
await tx.begin();
|
|
983
|
-
const req = tx.request();
|
|
984
|
-
req.input('threadId', threadId);
|
|
985
|
-
await req.query(deleteMessagesSql);
|
|
986
|
-
await req.query(deleteThreadSql);
|
|
987
|
-
await tx.commit();
|
|
988
|
-
} catch (error) {
|
|
989
|
-
await tx.rollback().catch(() => {});
|
|
990
|
-
throw new MastraError(
|
|
991
|
-
{
|
|
992
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_DELETE_THREAD_FAILED',
|
|
993
|
-
domain: ErrorDomain.STORAGE,
|
|
994
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
995
|
-
details: {
|
|
996
|
-
threadId,
|
|
997
|
-
},
|
|
998
|
-
},
|
|
999
|
-
error,
|
|
1000
|
-
);
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
private async _getIncludedMessages({
|
|
1005
|
-
threadId,
|
|
1006
|
-
selectBy,
|
|
1007
|
-
orderByStatement,
|
|
1008
|
-
}: {
|
|
1009
|
-
threadId: string;
|
|
1010
|
-
selectBy: StorageGetMessagesArg['selectBy'];
|
|
1011
|
-
orderByStatement: string;
|
|
1012
|
-
}) {
|
|
1013
|
-
const include = selectBy?.include;
|
|
1014
|
-
if (!include) return null;
|
|
1015
|
-
|
|
1016
|
-
const unionQueries: string[] = [];
|
|
1017
|
-
const paramValues: any[] = [];
|
|
1018
|
-
let paramIdx = 1;
|
|
1019
|
-
const paramNames: string[] = [];
|
|
1020
|
-
|
|
1021
|
-
for (const inc of include) {
|
|
1022
|
-
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
1023
|
-
const searchId = inc.threadId || threadId;
|
|
1024
|
-
|
|
1025
|
-
const pThreadId = `@p${paramIdx}`;
|
|
1026
|
-
const pId = `@p${paramIdx + 1}`;
|
|
1027
|
-
const pPrev = `@p${paramIdx + 2}`;
|
|
1028
|
-
const pNext = `@p${paramIdx + 3}`;
|
|
1029
|
-
|
|
1030
|
-
unionQueries.push(
|
|
1031
|
-
`
|
|
1032
|
-
SELECT
|
|
1033
|
-
m.id,
|
|
1034
|
-
m.content,
|
|
1035
|
-
m.role,
|
|
1036
|
-
m.type,
|
|
1037
|
-
m.[createdAt],
|
|
1038
|
-
m.thread_id AS threadId,
|
|
1039
|
-
m.[resourceId],
|
|
1040
|
-
m.seq_id
|
|
1041
|
-
FROM (
|
|
1042
|
-
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
1043
|
-
FROM ${this.getTableName(TABLE_MESSAGES)}
|
|
1044
|
-
WHERE [thread_id] = ${pThreadId}
|
|
1045
|
-
) AS m
|
|
1046
|
-
WHERE m.id = ${pId}
|
|
1047
|
-
OR EXISTS (
|
|
1048
|
-
SELECT 1
|
|
1049
|
-
FROM (
|
|
1050
|
-
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
1051
|
-
FROM ${this.getTableName(TABLE_MESSAGES)}
|
|
1052
|
-
WHERE [thread_id] = ${pThreadId}
|
|
1053
|
-
) AS target
|
|
1054
|
-
WHERE target.id = ${pId}
|
|
1055
|
-
AND (
|
|
1056
|
-
(m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
|
|
1057
|
-
OR
|
|
1058
|
-
(m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
|
|
1059
|
-
)
|
|
1060
|
-
)
|
|
1061
|
-
`,
|
|
1062
|
-
);
|
|
1063
|
-
|
|
1064
|
-
paramValues.push(searchId, id, withPreviousMessages, withNextMessages);
|
|
1065
|
-
paramNames.push(`p${paramIdx}`, `p${paramIdx + 1}`, `p${paramIdx + 2}`, `p${paramIdx + 3}`);
|
|
1066
|
-
paramIdx += 4;
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
const finalQuery = `
|
|
1070
|
-
SELECT * FROM (
|
|
1071
|
-
${unionQueries.join(' UNION ALL ')}
|
|
1072
|
-
) AS union_result
|
|
1073
|
-
ORDER BY [seq_id] ASC
|
|
1074
|
-
`;
|
|
1075
|
-
|
|
1076
|
-
const req = this.pool.request();
|
|
1077
|
-
for (let i = 0; i < paramValues.length; ++i) {
|
|
1078
|
-
req.input(paramNames[i] as string, paramValues[i]);
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
const result = await req.query(finalQuery);
|
|
1082
|
-
const includedRows = result.recordset || [];
|
|
1083
|
-
|
|
1084
|
-
const seen = new Set<string>();
|
|
1085
|
-
const dedupedRows = includedRows.filter((row: any) => {
|
|
1086
|
-
if (seen.has(row.id)) return false;
|
|
1087
|
-
seen.add(row.id);
|
|
1088
|
-
return true;
|
|
1089
|
-
});
|
|
1090
|
-
|
|
1091
|
-
return dedupedRows;
|
|
275
|
+
return this.stores.memory.deleteThread({ threadId });
|
|
1092
276
|
}
|
|
1093
277
|
|
|
1094
278
|
/**
|
|
@@ -1101,87 +285,19 @@ export class MSSQLStore extends MastraStorage {
|
|
|
1101
285
|
format?: 'v1' | 'v2';
|
|
1102
286
|
},
|
|
1103
287
|
): Promise<MastraMessageV1[] | MastraMessageV2[]> {
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
1107
|
-
const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
1108
|
-
try {
|
|
1109
|
-
let rows: any[] = [];
|
|
1110
|
-
const include = selectBy?.include || [];
|
|
1111
|
-
if (include?.length) {
|
|
1112
|
-
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
1113
|
-
if (includeMessages) {
|
|
1114
|
-
rows.push(...includeMessages);
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
const excludeIds = rows.map(m => m.id).filter(Boolean);
|
|
1118
|
-
|
|
1119
|
-
let query = `${selectStatement} FROM ${this.getTableName(TABLE_MESSAGES)} WHERE [thread_id] = @threadId`;
|
|
1120
|
-
const request = this.pool.request();
|
|
1121
|
-
request.input('threadId', threadId);
|
|
1122
|
-
|
|
1123
|
-
if (excludeIds.length > 0) {
|
|
1124
|
-
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
1125
|
-
query += ` AND id NOT IN (${excludeParams.join(', ')})`;
|
|
1126
|
-
excludeIds.forEach((id, idx) => {
|
|
1127
|
-
request.input(`id${idx}`, id);
|
|
1128
|
-
});
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
query += ` ${orderByStatement} OFFSET 0 ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
1132
|
-
request.input('limit', limit);
|
|
1133
|
-
const result = await request.query(query);
|
|
1134
|
-
const remainingRows = result.recordset || [];
|
|
1135
|
-
rows.push(...remainingRows);
|
|
1136
|
-
rows.sort((a, b) => {
|
|
1137
|
-
const timeDiff = a.seq_id - b.seq_id;
|
|
1138
|
-
return timeDiff;
|
|
1139
|
-
});
|
|
1140
|
-
rows = rows.map(({ seq_id, ...rest }) => rest);
|
|
1141
|
-
const fetchedMessages = (rows || []).map(message => {
|
|
1142
|
-
if (typeof message.content === 'string') {
|
|
1143
|
-
try {
|
|
1144
|
-
message.content = JSON.parse(message.content);
|
|
1145
|
-
} catch {}
|
|
1146
|
-
}
|
|
288
|
+
return this.stores.memory.getMessages(args);
|
|
289
|
+
}
|
|
1147
290
|
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
}
|
|
1159
|
-
}
|
|
1160
|
-
if (message.type === 'v2') delete message.type;
|
|
1161
|
-
return message as MastraMessageV1;
|
|
1162
|
-
});
|
|
1163
|
-
return format === 'v2'
|
|
1164
|
-
? fetchedMessages.map(
|
|
1165
|
-
m =>
|
|
1166
|
-
({ ...m, content: m.content || { format: 2, parts: [{ type: 'text', text: '' }] } }) as MastraMessageV2,
|
|
1167
|
-
)
|
|
1168
|
-
: fetchedMessages;
|
|
1169
|
-
} catch (error) {
|
|
1170
|
-
const mastraError = new MastraError(
|
|
1171
|
-
{
|
|
1172
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_FAILED',
|
|
1173
|
-
domain: ErrorDomain.STORAGE,
|
|
1174
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1175
|
-
details: {
|
|
1176
|
-
threadId,
|
|
1177
|
-
},
|
|
1178
|
-
},
|
|
1179
|
-
error,
|
|
1180
|
-
);
|
|
1181
|
-
this.logger?.error?.(mastraError.toString());
|
|
1182
|
-
this.logger?.trackException(mastraError);
|
|
1183
|
-
return [];
|
|
1184
|
-
}
|
|
291
|
+
async getMessagesById({ messageIds, format }: { messageIds: string[]; format: 'v1' }): Promise<MastraMessageV1[]>;
|
|
292
|
+
async getMessagesById({ messageIds, format }: { messageIds: string[]; format?: 'v2' }): Promise<MastraMessageV2[]>;
|
|
293
|
+
async getMessagesById({
|
|
294
|
+
messageIds,
|
|
295
|
+
format,
|
|
296
|
+
}: {
|
|
297
|
+
messageIds: string[];
|
|
298
|
+
format?: 'v1' | 'v2';
|
|
299
|
+
}): Promise<MastraMessageV1[] | MastraMessageV2[]> {
|
|
300
|
+
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
1185
301
|
}
|
|
1186
302
|
|
|
1187
303
|
public async getMessagesPaginated(
|
|
@@ -1189,246 +305,58 @@ export class MSSQLStore extends MastraStorage {
|
|
|
1189
305
|
format?: 'v1' | 'v2';
|
|
1190
306
|
},
|
|
1191
307
|
): Promise<PaginationInfo & { messages: MastraMessageV1[] | MastraMessageV2[] }> {
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
1195
|
-
let messages: any[] = [];
|
|
1196
|
-
if (selectBy?.include?.length) {
|
|
1197
|
-
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
1198
|
-
if (includeMessages) {
|
|
1199
|
-
messages.push(...includeMessages);
|
|
1200
|
-
}
|
|
1201
|
-
}
|
|
1202
|
-
try {
|
|
1203
|
-
const { threadId, format, selectBy } = args;
|
|
1204
|
-
const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
|
|
1205
|
-
const fromDate = dateRange?.start;
|
|
1206
|
-
const toDate = dateRange?.end;
|
|
1207
|
-
|
|
1208
|
-
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
|
|
1209
|
-
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
1210
|
-
|
|
1211
|
-
let messages: any[] = [];
|
|
1212
|
-
|
|
1213
|
-
if (selectBy?.include?.length) {
|
|
1214
|
-
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
1215
|
-
if (includeMessages) messages.push(...includeMessages);
|
|
1216
|
-
}
|
|
1217
|
-
|
|
1218
|
-
const perPage =
|
|
1219
|
-
perPageInput !== undefined
|
|
1220
|
-
? perPageInput
|
|
1221
|
-
: this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
1222
|
-
const currentOffset = page * perPage;
|
|
1223
|
-
|
|
1224
|
-
const conditions: string[] = ['[thread_id] = @threadId'];
|
|
1225
|
-
const request = this.pool.request();
|
|
1226
|
-
request.input('threadId', threadId);
|
|
1227
|
-
|
|
1228
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1229
|
-
conditions.push('[createdAt] >= @fromDate');
|
|
1230
|
-
request.input('fromDate', fromDate.toISOString());
|
|
1231
|
-
}
|
|
1232
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1233
|
-
conditions.push('[createdAt] <= @toDate');
|
|
1234
|
-
request.input('toDate', toDate.toISOString());
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
const whereClause = `WHERE ${conditions.join(' AND ')}`;
|
|
1238
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(TABLE_MESSAGES)} ${whereClause}`;
|
|
1239
|
-
const countResult = await request.query(countQuery);
|
|
1240
|
-
const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
|
|
1241
|
-
|
|
1242
|
-
if (total === 0 && messages.length > 0) {
|
|
1243
|
-
const parsedIncluded = this._parseAndFormatMessages(messages, format);
|
|
1244
|
-
return {
|
|
1245
|
-
messages: parsedIncluded,
|
|
1246
|
-
total: parsedIncluded.length,
|
|
1247
|
-
page,
|
|
1248
|
-
perPage,
|
|
1249
|
-
hasMore: false,
|
|
1250
|
-
};
|
|
1251
|
-
}
|
|
1252
|
-
|
|
1253
|
-
const excludeIds = messages.map(m => m.id);
|
|
1254
|
-
if (excludeIds.length > 0) {
|
|
1255
|
-
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
1256
|
-
conditions.push(`id NOT IN (${excludeParams.join(', ')})`);
|
|
1257
|
-
excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
|
|
1258
|
-
}
|
|
1259
|
-
|
|
1260
|
-
const finalWhereClause = `WHERE ${conditions.join(' AND ')}`;
|
|
1261
|
-
const dataQuery = `${selectStatement} FROM ${this.getTableName(TABLE_MESSAGES)} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
1262
|
-
|
|
1263
|
-
request.input('offset', currentOffset);
|
|
1264
|
-
request.input('limit', perPage);
|
|
308
|
+
return this.stores.memory.getMessagesPaginated(args);
|
|
309
|
+
}
|
|
1265
310
|
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
311
|
+
async saveMessages(args: { messages: MastraMessageV1[]; format?: undefined | 'v1' }): Promise<MastraMessageV1[]>;
|
|
312
|
+
async saveMessages(args: { messages: MastraMessageV2[]; format: 'v2' }): Promise<MastraMessageV2[]>;
|
|
313
|
+
async saveMessages(
|
|
314
|
+
args: { messages: MastraMessageV1[]; format?: undefined | 'v1' } | { messages: MastraMessageV2[]; format: 'v2' },
|
|
315
|
+
): Promise<MastraMessageV2[] | MastraMessageV1[]> {
|
|
316
|
+
return this.stores.memory.saveMessages(args);
|
|
317
|
+
}
|
|
1270
318
|
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
319
|
+
async updateMessages({
|
|
320
|
+
messages,
|
|
321
|
+
}: {
|
|
322
|
+
messages: (Partial<Omit<MastraMessageV2, 'createdAt'>> & {
|
|
323
|
+
id: string;
|
|
324
|
+
content?: {
|
|
325
|
+
metadata?: MastraMessageContentV2['metadata'];
|
|
326
|
+
content?: MastraMessageContentV2['content'];
|
|
1278
327
|
};
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED',
|
|
1283
|
-
domain: ErrorDomain.STORAGE,
|
|
1284
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1285
|
-
details: {
|
|
1286
|
-
threadId,
|
|
1287
|
-
page,
|
|
1288
|
-
},
|
|
1289
|
-
},
|
|
1290
|
-
error,
|
|
1291
|
-
);
|
|
1292
|
-
this.logger?.error?.(mastraError.toString());
|
|
1293
|
-
this.logger?.trackException(mastraError);
|
|
1294
|
-
return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
|
|
1295
|
-
}
|
|
328
|
+
})[];
|
|
329
|
+
}): Promise<MastraMessageV2[]> {
|
|
330
|
+
return this.stores.memory.updateMessages({ messages });
|
|
1296
331
|
}
|
|
1297
332
|
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
if (typeof parsed.content === 'string') {
|
|
1302
|
-
try {
|
|
1303
|
-
parsed = { ...parsed, content: JSON.parse(parsed.content) };
|
|
1304
|
-
} catch {}
|
|
1305
|
-
}
|
|
1306
|
-
|
|
1307
|
-
if (format === 'v1') {
|
|
1308
|
-
if (Array.isArray(parsed.content)) {
|
|
1309
|
-
} else if (parsed.content?.parts) {
|
|
1310
|
-
parsed.content = parsed.content.parts;
|
|
1311
|
-
} else {
|
|
1312
|
-
parsed.content = [{ type: 'text', text: '' }];
|
|
1313
|
-
}
|
|
1314
|
-
} else {
|
|
1315
|
-
if (!parsed.content?.parts) {
|
|
1316
|
-
parsed = { ...parsed, content: { format: 2, parts: [{ type: 'text', text: '' }] } };
|
|
1317
|
-
}
|
|
1318
|
-
}
|
|
333
|
+
async deleteMessages(messageIds: string[]): Promise<void> {
|
|
334
|
+
return this.stores.memory.deleteMessages(messageIds);
|
|
335
|
+
}
|
|
1319
336
|
|
|
1320
|
-
|
|
1321
|
-
});
|
|
337
|
+
async getResourceById({ resourceId }: { resourceId: string }): Promise<StorageResourceType | null> {
|
|
338
|
+
return this.stores.memory.getResourceById({ resourceId });
|
|
339
|
+
}
|
|
1322
340
|
|
|
1323
|
-
|
|
1324
|
-
return
|
|
341
|
+
async saveResource({ resource }: { resource: StorageResourceType }): Promise<StorageResourceType> {
|
|
342
|
+
return this.stores.memory.saveResource({ resource });
|
|
1325
343
|
}
|
|
1326
344
|
|
|
1327
|
-
async
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
if (!threadId) {
|
|
1338
|
-
throw new MastraError({
|
|
1339
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED',
|
|
1340
|
-
domain: ErrorDomain.STORAGE,
|
|
1341
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1342
|
-
text: `Thread ID is required`,
|
|
1343
|
-
});
|
|
1344
|
-
}
|
|
1345
|
-
const thread = await this.getThreadById({ threadId });
|
|
1346
|
-
if (!thread) {
|
|
1347
|
-
throw new MastraError({
|
|
1348
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED',
|
|
1349
|
-
domain: ErrorDomain.STORAGE,
|
|
1350
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1351
|
-
text: `Thread ${threadId} not found`,
|
|
1352
|
-
details: { threadId },
|
|
1353
|
-
});
|
|
1354
|
-
}
|
|
1355
|
-
const tableMessages = this.getTableName(TABLE_MESSAGES);
|
|
1356
|
-
const tableThreads = this.getTableName(TABLE_THREADS);
|
|
1357
|
-
try {
|
|
1358
|
-
const transaction = this.pool.transaction();
|
|
1359
|
-
await transaction.begin();
|
|
1360
|
-
try {
|
|
1361
|
-
for (const message of messages) {
|
|
1362
|
-
if (!message.threadId) {
|
|
1363
|
-
throw new Error(
|
|
1364
|
-
`Expected to find a threadId for message, but couldn't find one. An unexpected error has occurred.`,
|
|
1365
|
-
);
|
|
1366
|
-
}
|
|
1367
|
-
if (!message.resourceId) {
|
|
1368
|
-
throw new Error(
|
|
1369
|
-
`Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred.`,
|
|
1370
|
-
);
|
|
1371
|
-
}
|
|
1372
|
-
const request = transaction.request();
|
|
1373
|
-
request.input('id', message.id);
|
|
1374
|
-
request.input('thread_id', message.threadId);
|
|
1375
|
-
request.input(
|
|
1376
|
-
'content',
|
|
1377
|
-
typeof message.content === 'string' ? message.content : JSON.stringify(message.content),
|
|
1378
|
-
);
|
|
1379
|
-
request.input('createdAt', message.createdAt.toISOString() || new Date().toISOString());
|
|
1380
|
-
request.input('role', message.role);
|
|
1381
|
-
request.input('type', message.type || 'v2');
|
|
1382
|
-
request.input('resourceId', message.resourceId);
|
|
1383
|
-
const mergeSql = `MERGE INTO ${tableMessages} AS target
|
|
1384
|
-
USING (SELECT @id AS id) AS src
|
|
1385
|
-
ON target.id = src.id
|
|
1386
|
-
WHEN MATCHED THEN UPDATE SET
|
|
1387
|
-
thread_id = @thread_id,
|
|
1388
|
-
content = @content,
|
|
1389
|
-
[createdAt] = @createdAt,
|
|
1390
|
-
role = @role,
|
|
1391
|
-
type = @type,
|
|
1392
|
-
resourceId = @resourceId
|
|
1393
|
-
WHEN NOT MATCHED THEN INSERT (id, thread_id, content, [createdAt], role, type, resourceId)
|
|
1394
|
-
VALUES (@id, @thread_id, @content, @createdAt, @role, @type, @resourceId);`;
|
|
1395
|
-
await request.query(mergeSql);
|
|
1396
|
-
}
|
|
1397
|
-
const threadReq = transaction.request();
|
|
1398
|
-
threadReq.input('updatedAt', new Date().toISOString());
|
|
1399
|
-
threadReq.input('id', threadId);
|
|
1400
|
-
await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
|
|
1401
|
-
await transaction.commit();
|
|
1402
|
-
} catch (error) {
|
|
1403
|
-
await transaction.rollback();
|
|
1404
|
-
throw error;
|
|
1405
|
-
}
|
|
1406
|
-
const messagesWithParsedContent = messages.map(message => {
|
|
1407
|
-
if (typeof message.content === 'string') {
|
|
1408
|
-
try {
|
|
1409
|
-
return { ...message, content: JSON.parse(message.content) };
|
|
1410
|
-
} catch {
|
|
1411
|
-
return message;
|
|
1412
|
-
}
|
|
1413
|
-
}
|
|
1414
|
-
return message;
|
|
1415
|
-
});
|
|
1416
|
-
const list = new MessageList().add(messagesWithParsedContent, 'memory');
|
|
1417
|
-
if (format === 'v2') return list.get.all.v2();
|
|
1418
|
-
return list.get.all.v1();
|
|
1419
|
-
} catch (error) {
|
|
1420
|
-
throw new MastraError(
|
|
1421
|
-
{
|
|
1422
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED',
|
|
1423
|
-
domain: ErrorDomain.STORAGE,
|
|
1424
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1425
|
-
details: { threadId },
|
|
1426
|
-
},
|
|
1427
|
-
error,
|
|
1428
|
-
);
|
|
1429
|
-
}
|
|
345
|
+
async updateResource({
|
|
346
|
+
resourceId,
|
|
347
|
+
workingMemory,
|
|
348
|
+
metadata,
|
|
349
|
+
}: {
|
|
350
|
+
resourceId: string;
|
|
351
|
+
workingMemory?: string;
|
|
352
|
+
metadata?: Record<string, unknown>;
|
|
353
|
+
}): Promise<StorageResourceType> {
|
|
354
|
+
return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
|
|
1430
355
|
}
|
|
1431
356
|
|
|
357
|
+
/**
|
|
358
|
+
* Workflows
|
|
359
|
+
*/
|
|
1432
360
|
async persistWorkflowSnapshot({
|
|
1433
361
|
workflowName,
|
|
1434
362
|
runId,
|
|
@@ -1438,38 +366,7 @@ export class MSSQLStore extends MastraStorage {
|
|
|
1438
366
|
runId: string;
|
|
1439
367
|
snapshot: WorkflowRunState;
|
|
1440
368
|
}): Promise<void> {
|
|
1441
|
-
|
|
1442
|
-
const now = new Date().toISOString();
|
|
1443
|
-
try {
|
|
1444
|
-
const request = this.pool.request();
|
|
1445
|
-
request.input('workflow_name', workflowName);
|
|
1446
|
-
request.input('run_id', runId);
|
|
1447
|
-
request.input('snapshot', JSON.stringify(snapshot));
|
|
1448
|
-
request.input('createdAt', now);
|
|
1449
|
-
request.input('updatedAt', now);
|
|
1450
|
-
const mergeSql = `MERGE INTO ${table} AS target
|
|
1451
|
-
USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
|
|
1452
|
-
ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
|
|
1453
|
-
WHEN MATCHED THEN UPDATE SET
|
|
1454
|
-
snapshot = @snapshot,
|
|
1455
|
-
[updatedAt] = @updatedAt
|
|
1456
|
-
WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
|
|
1457
|
-
VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
|
|
1458
|
-
await request.query(mergeSql);
|
|
1459
|
-
} catch (error) {
|
|
1460
|
-
throw new MastraError(
|
|
1461
|
-
{
|
|
1462
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED',
|
|
1463
|
-
domain: ErrorDomain.STORAGE,
|
|
1464
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1465
|
-
details: {
|
|
1466
|
-
workflowName,
|
|
1467
|
-
runId,
|
|
1468
|
-
},
|
|
1469
|
-
},
|
|
1470
|
-
error,
|
|
1471
|
-
);
|
|
1472
|
-
}
|
|
369
|
+
return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
|
|
1473
370
|
}
|
|
1474
371
|
|
|
1475
372
|
async loadWorkflowSnapshot({
|
|
@@ -1479,64 +376,7 @@ export class MSSQLStore extends MastraStorage {
|
|
|
1479
376
|
workflowName: string;
|
|
1480
377
|
runId: string;
|
|
1481
378
|
}): Promise<WorkflowRunState | null> {
|
|
1482
|
-
|
|
1483
|
-
const result = await this.load({
|
|
1484
|
-
tableName: TABLE_WORKFLOW_SNAPSHOT,
|
|
1485
|
-
keys: {
|
|
1486
|
-
workflow_name: workflowName,
|
|
1487
|
-
run_id: runId,
|
|
1488
|
-
},
|
|
1489
|
-
});
|
|
1490
|
-
if (!result) {
|
|
1491
|
-
return null;
|
|
1492
|
-
}
|
|
1493
|
-
return (result as any).snapshot;
|
|
1494
|
-
} catch (error) {
|
|
1495
|
-
throw new MastraError(
|
|
1496
|
-
{
|
|
1497
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED',
|
|
1498
|
-
domain: ErrorDomain.STORAGE,
|
|
1499
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1500
|
-
details: {
|
|
1501
|
-
workflowName,
|
|
1502
|
-
runId,
|
|
1503
|
-
},
|
|
1504
|
-
},
|
|
1505
|
-
error,
|
|
1506
|
-
);
|
|
1507
|
-
}
|
|
1508
|
-
}
|
|
1509
|
-
|
|
1510
|
-
private async hasColumn(table: string, column: string): Promise<boolean> {
|
|
1511
|
-
const schema = this.schema || 'dbo';
|
|
1512
|
-
const request = this.pool.request();
|
|
1513
|
-
request.input('schema', schema);
|
|
1514
|
-
request.input('table', table);
|
|
1515
|
-
request.input('column', column);
|
|
1516
|
-
request.input('columnLower', column.toLowerCase());
|
|
1517
|
-
const result = await request.query(
|
|
1518
|
-
`SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`,
|
|
1519
|
-
);
|
|
1520
|
-
return result.recordset.length > 0;
|
|
1521
|
-
}
|
|
1522
|
-
|
|
1523
|
-
private parseWorkflowRun(row: any): WorkflowRun {
|
|
1524
|
-
let parsedSnapshot: WorkflowRunState | string = row.snapshot as string;
|
|
1525
|
-
if (typeof parsedSnapshot === 'string') {
|
|
1526
|
-
try {
|
|
1527
|
-
parsedSnapshot = JSON.parse(row.snapshot as string) as WorkflowRunState;
|
|
1528
|
-
} catch (e) {
|
|
1529
|
-
console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
|
|
1530
|
-
}
|
|
1531
|
-
}
|
|
1532
|
-
return {
|
|
1533
|
-
workflowName: row.workflow_name,
|
|
1534
|
-
runId: row.run_id,
|
|
1535
|
-
snapshot: parsedSnapshot,
|
|
1536
|
-
createdAt: row.createdAt,
|
|
1537
|
-
updatedAt: row.updatedAt,
|
|
1538
|
-
resourceId: row.resourceId,
|
|
1539
|
-
};
|
|
379
|
+
return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
|
|
1540
380
|
}
|
|
1541
381
|
|
|
1542
382
|
async getWorkflowRuns({
|
|
@@ -1554,75 +394,7 @@ export class MSSQLStore extends MastraStorage {
|
|
|
1554
394
|
offset?: number;
|
|
1555
395
|
resourceId?: string;
|
|
1556
396
|
} = {}): Promise<WorkflowRuns> {
|
|
1557
|
-
|
|
1558
|
-
const conditions: string[] = [];
|
|
1559
|
-
const paramMap: Record<string, any> = {};
|
|
1560
|
-
|
|
1561
|
-
if (workflowName) {
|
|
1562
|
-
conditions.push(`[workflow_name] = @workflowName`);
|
|
1563
|
-
paramMap['workflowName'] = workflowName;
|
|
1564
|
-
}
|
|
1565
|
-
|
|
1566
|
-
if (resourceId) {
|
|
1567
|
-
const hasResourceId = await this.hasColumn(TABLE_WORKFLOW_SNAPSHOT, 'resourceId');
|
|
1568
|
-
if (hasResourceId) {
|
|
1569
|
-
conditions.push(`[resourceId] = @resourceId`);
|
|
1570
|
-
paramMap['resourceId'] = resourceId;
|
|
1571
|
-
} else {
|
|
1572
|
-
console.warn(`[${TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
|
|
1573
|
-
}
|
|
1574
|
-
}
|
|
1575
|
-
|
|
1576
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1577
|
-
conditions.push(`[createdAt] >= @fromDate`);
|
|
1578
|
-
paramMap[`fromDate`] = fromDate.toISOString();
|
|
1579
|
-
}
|
|
1580
|
-
|
|
1581
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1582
|
-
conditions.push(`[createdAt] <= @toDate`);
|
|
1583
|
-
paramMap[`toDate`] = toDate.toISOString();
|
|
1584
|
-
}
|
|
1585
|
-
|
|
1586
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
1587
|
-
let total = 0;
|
|
1588
|
-
const tableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
1589
|
-
const request = this.pool.request();
|
|
1590
|
-
Object.entries(paramMap).forEach(([key, value]) => {
|
|
1591
|
-
if (value instanceof Date) {
|
|
1592
|
-
request.input(key, sql.DateTime, value);
|
|
1593
|
-
} else {
|
|
1594
|
-
request.input(key, value);
|
|
1595
|
-
}
|
|
1596
|
-
});
|
|
1597
|
-
|
|
1598
|
-
if (limit !== undefined && offset !== undefined) {
|
|
1599
|
-
const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
|
|
1600
|
-
const countResult = await request.query(countQuery);
|
|
1601
|
-
total = Number(countResult.recordset[0]?.count || 0);
|
|
1602
|
-
}
|
|
1603
|
-
|
|
1604
|
-
let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
|
|
1605
|
-
if (limit !== undefined && offset !== undefined) {
|
|
1606
|
-
query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
1607
|
-
request.input('limit', limit);
|
|
1608
|
-
request.input('offset', offset);
|
|
1609
|
-
}
|
|
1610
|
-
const result = await request.query(query);
|
|
1611
|
-
const runs = (result.recordset || []).map(row => this.parseWorkflowRun(row));
|
|
1612
|
-
return { runs, total: total || runs.length };
|
|
1613
|
-
} catch (error) {
|
|
1614
|
-
throw new MastraError(
|
|
1615
|
-
{
|
|
1616
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED',
|
|
1617
|
-
domain: ErrorDomain.STORAGE,
|
|
1618
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1619
|
-
details: {
|
|
1620
|
-
workflowName: workflowName || 'all',
|
|
1621
|
-
},
|
|
1622
|
-
},
|
|
1623
|
-
error,
|
|
1624
|
-
);
|
|
1625
|
-
}
|
|
397
|
+
return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
|
|
1626
398
|
}
|
|
1627
399
|
|
|
1628
400
|
async getWorkflowRunById({
|
|
@@ -1632,505 +404,57 @@ export class MSSQLStore extends MastraStorage {
|
|
|
1632
404
|
runId: string;
|
|
1633
405
|
workflowName?: string;
|
|
1634
406
|
}): Promise<WorkflowRun | null> {
|
|
1635
|
-
|
|
1636
|
-
const conditions: string[] = [];
|
|
1637
|
-
const paramMap: Record<string, any> = {};
|
|
1638
|
-
|
|
1639
|
-
if (runId) {
|
|
1640
|
-
conditions.push(`[run_id] = @runId`);
|
|
1641
|
-
paramMap['runId'] = runId;
|
|
1642
|
-
}
|
|
1643
|
-
|
|
1644
|
-
if (workflowName) {
|
|
1645
|
-
conditions.push(`[workflow_name] = @workflowName`);
|
|
1646
|
-
paramMap['workflowName'] = workflowName;
|
|
1647
|
-
}
|
|
1648
|
-
|
|
1649
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
1650
|
-
const tableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
1651
|
-
const query = `SELECT * FROM ${tableName} ${whereClause}`;
|
|
1652
|
-
const request = this.pool.request();
|
|
1653
|
-
Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
|
|
1654
|
-
const result = await request.query(query);
|
|
1655
|
-
|
|
1656
|
-
if (!result.recordset || result.recordset.length === 0) {
|
|
1657
|
-
return null;
|
|
1658
|
-
}
|
|
1659
|
-
|
|
1660
|
-
return this.parseWorkflowRun(result.recordset[0]);
|
|
1661
|
-
} catch (error) {
|
|
1662
|
-
throw new MastraError(
|
|
1663
|
-
{
|
|
1664
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED',
|
|
1665
|
-
domain: ErrorDomain.STORAGE,
|
|
1666
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1667
|
-
details: {
|
|
1668
|
-
runId,
|
|
1669
|
-
workflowName: workflowName || '',
|
|
1670
|
-
},
|
|
1671
|
-
},
|
|
1672
|
-
error,
|
|
1673
|
-
);
|
|
1674
|
-
}
|
|
407
|
+
return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
|
|
1675
408
|
}
|
|
1676
409
|
|
|
1677
|
-
async
|
|
1678
|
-
|
|
1679
|
-
}: {
|
|
1680
|
-
messages: (Partial<Omit<MastraMessageV2, 'createdAt'>> & {
|
|
1681
|
-
id: string;
|
|
1682
|
-
content?: {
|
|
1683
|
-
metadata?: MastraMessageContentV2['metadata'];
|
|
1684
|
-
content?: MastraMessageContentV2['content'];
|
|
1685
|
-
};
|
|
1686
|
-
})[];
|
|
1687
|
-
}): Promise<MastraMessageV2[]> {
|
|
1688
|
-
if (!messages || messages.length === 0) {
|
|
1689
|
-
return [];
|
|
1690
|
-
}
|
|
1691
|
-
|
|
1692
|
-
const messageIds = messages.map(m => m.id);
|
|
1693
|
-
const idParams = messageIds.map((_, i) => `@id${i}`).join(', ');
|
|
1694
|
-
let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${this.getTableName(TABLE_MESSAGES)}`;
|
|
1695
|
-
if (idParams.length > 0) {
|
|
1696
|
-
selectQuery += ` WHERE id IN (${idParams})`;
|
|
1697
|
-
} else {
|
|
1698
|
-
return [];
|
|
1699
|
-
}
|
|
1700
|
-
const selectReq = this.pool.request();
|
|
1701
|
-
messageIds.forEach((id, i) => selectReq.input(`id${i}`, id));
|
|
1702
|
-
const existingMessagesDb = (await selectReq.query(selectQuery)).recordset;
|
|
1703
|
-
if (!existingMessagesDb || existingMessagesDb.length === 0) {
|
|
1704
|
-
return [];
|
|
1705
|
-
}
|
|
1706
|
-
|
|
1707
|
-
const existingMessages: MastraMessageV2[] = existingMessagesDb.map(msg => {
|
|
1708
|
-
if (typeof msg.content === 'string') {
|
|
1709
|
-
try {
|
|
1710
|
-
msg.content = JSON.parse(msg.content);
|
|
1711
|
-
} catch {}
|
|
1712
|
-
}
|
|
1713
|
-
return msg as MastraMessageV2;
|
|
1714
|
-
});
|
|
1715
|
-
|
|
1716
|
-
const threadIdsToUpdate = new Set<string>();
|
|
1717
|
-
const transaction = this.pool.transaction();
|
|
1718
|
-
|
|
1719
|
-
try {
|
|
1720
|
-
await transaction.begin();
|
|
1721
|
-
for (const existingMessage of existingMessages) {
|
|
1722
|
-
const updatePayload = messages.find(m => m.id === existingMessage.id);
|
|
1723
|
-
if (!updatePayload) continue;
|
|
1724
|
-
const { id, ...fieldsToUpdate } = updatePayload;
|
|
1725
|
-
if (Object.keys(fieldsToUpdate).length === 0) continue;
|
|
1726
|
-
threadIdsToUpdate.add(existingMessage.threadId!);
|
|
1727
|
-
if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
|
|
1728
|
-
threadIdsToUpdate.add(updatePayload.threadId);
|
|
1729
|
-
}
|
|
1730
|
-
const setClauses: string[] = [];
|
|
1731
|
-
const req = transaction.request();
|
|
1732
|
-
req.input('id', id);
|
|
1733
|
-
const columnMapping: Record<string, string> = { threadId: 'thread_id' };
|
|
1734
|
-
const updatableFields = { ...fieldsToUpdate };
|
|
1735
|
-
if (updatableFields.content) {
|
|
1736
|
-
const newContent = {
|
|
1737
|
-
...existingMessage.content,
|
|
1738
|
-
...updatableFields.content,
|
|
1739
|
-
...(existingMessage.content?.metadata && updatableFields.content.metadata
|
|
1740
|
-
? { metadata: { ...existingMessage.content.metadata, ...updatableFields.content.metadata } }
|
|
1741
|
-
: {}),
|
|
1742
|
-
};
|
|
1743
|
-
setClauses.push(`content = @content`);
|
|
1744
|
-
req.input('content', JSON.stringify(newContent));
|
|
1745
|
-
delete updatableFields.content;
|
|
1746
|
-
}
|
|
1747
|
-
for (const key in updatableFields) {
|
|
1748
|
-
if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
|
|
1749
|
-
const dbColumn = columnMapping[key] || key;
|
|
1750
|
-
setClauses.push(`[${dbColumn}] = @${dbColumn}`);
|
|
1751
|
-
req.input(dbColumn, updatableFields[key as keyof typeof updatableFields]);
|
|
1752
|
-
}
|
|
1753
|
-
}
|
|
1754
|
-
if (setClauses.length > 0) {
|
|
1755
|
-
const updateSql = `UPDATE ${this.getTableName(TABLE_MESSAGES)} SET ${setClauses.join(', ')} WHERE id = @id`;
|
|
1756
|
-
await req.query(updateSql);
|
|
1757
|
-
}
|
|
1758
|
-
}
|
|
1759
|
-
if (threadIdsToUpdate.size > 0) {
|
|
1760
|
-
const threadIdParams = Array.from(threadIdsToUpdate)
|
|
1761
|
-
.map((_, i) => `@tid${i}`)
|
|
1762
|
-
.join(', ');
|
|
1763
|
-
const threadReq = transaction.request();
|
|
1764
|
-
Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
|
|
1765
|
-
threadReq.input('updatedAt', new Date().toISOString());
|
|
1766
|
-
const threadSql = `UPDATE ${this.getTableName(TABLE_THREADS)} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
|
|
1767
|
-
await threadReq.query(threadSql);
|
|
1768
|
-
}
|
|
1769
|
-
await transaction.commit();
|
|
1770
|
-
} catch (error) {
|
|
1771
|
-
await transaction.rollback();
|
|
1772
|
-
throw new MastraError(
|
|
1773
|
-
{
|
|
1774
|
-
id: 'MASTRA_STORAGE_MSSQL_UPDATE_MESSAGES_FAILED',
|
|
1775
|
-
domain: ErrorDomain.STORAGE,
|
|
1776
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1777
|
-
},
|
|
1778
|
-
error,
|
|
1779
|
-
);
|
|
1780
|
-
}
|
|
1781
|
-
|
|
1782
|
-
const refetchReq = this.pool.request();
|
|
1783
|
-
messageIds.forEach((id, i) => refetchReq.input(`id${i}`, id));
|
|
1784
|
-
const updatedMessages = (await refetchReq.query(selectQuery)).recordset;
|
|
1785
|
-
return (updatedMessages || []).map(message => {
|
|
1786
|
-
if (typeof message.content === 'string') {
|
|
1787
|
-
try {
|
|
1788
|
-
message.content = JSON.parse(message.content);
|
|
1789
|
-
} catch {}
|
|
1790
|
-
}
|
|
1791
|
-
return message;
|
|
1792
|
-
});
|
|
410
|
+
async close(): Promise<void> {
|
|
411
|
+
await this.pool.close();
|
|
1793
412
|
}
|
|
1794
413
|
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
} else if (this.pool.connecting) {
|
|
1801
|
-
await this.pool.connect();
|
|
1802
|
-
await this.pool.close();
|
|
1803
|
-
}
|
|
1804
|
-
} catch (err: any) {
|
|
1805
|
-
if (err.message && err.message.includes('Cannot close a pool while it is connecting')) {
|
|
1806
|
-
} else {
|
|
1807
|
-
throw err;
|
|
1808
|
-
}
|
|
1809
|
-
}
|
|
1810
|
-
}
|
|
1811
|
-
}
|
|
1812
|
-
|
|
1813
|
-
async getEvals(
|
|
1814
|
-
options: {
|
|
1815
|
-
agentName?: string;
|
|
1816
|
-
type?: 'test' | 'live';
|
|
1817
|
-
} & PaginationArgs = {},
|
|
1818
|
-
): Promise<PaginationInfo & { evals: EvalRow[] }> {
|
|
1819
|
-
const { agentName, type, page = 0, perPage = 100, dateRange } = options;
|
|
1820
|
-
const fromDate = dateRange?.start;
|
|
1821
|
-
const toDate = dateRange?.end;
|
|
1822
|
-
|
|
1823
|
-
const where: string[] = [];
|
|
1824
|
-
const params: Record<string, any> = {};
|
|
1825
|
-
|
|
1826
|
-
if (agentName) {
|
|
1827
|
-
where.push('agent_name = @agentName');
|
|
1828
|
-
params['agentName'] = agentName;
|
|
1829
|
-
}
|
|
1830
|
-
|
|
1831
|
-
if (type === 'test') {
|
|
1832
|
-
where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
|
|
1833
|
-
} else if (type === 'live') {
|
|
1834
|
-
where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
|
|
1835
|
-
}
|
|
1836
|
-
|
|
1837
|
-
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
1838
|
-
where.push(`[created_at] >= @fromDate`);
|
|
1839
|
-
params[`fromDate`] = fromDate.toISOString();
|
|
1840
|
-
}
|
|
1841
|
-
|
|
1842
|
-
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
1843
|
-
where.push(`[created_at] <= @toDate`);
|
|
1844
|
-
params[`toDate`] = toDate.toISOString();
|
|
1845
|
-
}
|
|
1846
|
-
|
|
1847
|
-
const whereClause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
|
|
1848
|
-
const tableName = this.getTableName(TABLE_EVALS);
|
|
1849
|
-
const offset = page * perPage;
|
|
1850
|
-
|
|
1851
|
-
const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
|
|
1852
|
-
const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
1853
|
-
|
|
1854
|
-
try {
|
|
1855
|
-
const countReq = this.pool.request();
|
|
1856
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
1857
|
-
if (value instanceof Date) {
|
|
1858
|
-
countReq.input(key, sql.DateTime, value);
|
|
1859
|
-
} else {
|
|
1860
|
-
countReq.input(key, value);
|
|
1861
|
-
}
|
|
1862
|
-
});
|
|
1863
|
-
const countResult = await countReq.query(countQuery);
|
|
1864
|
-
const total = countResult.recordset[0]?.total || 0;
|
|
1865
|
-
|
|
1866
|
-
if (total === 0) {
|
|
1867
|
-
return {
|
|
1868
|
-
evals: [],
|
|
1869
|
-
total: 0,
|
|
1870
|
-
page,
|
|
1871
|
-
perPage,
|
|
1872
|
-
hasMore: false,
|
|
1873
|
-
};
|
|
1874
|
-
}
|
|
1875
|
-
|
|
1876
|
-
const req = this.pool.request();
|
|
1877
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
1878
|
-
if (value instanceof Date) {
|
|
1879
|
-
req.input(key, sql.DateTime, value);
|
|
1880
|
-
} else {
|
|
1881
|
-
req.input(key, value);
|
|
1882
|
-
}
|
|
1883
|
-
});
|
|
1884
|
-
req.input('offset', offset);
|
|
1885
|
-
req.input('perPage', perPage);
|
|
1886
|
-
|
|
1887
|
-
const result = await req.query(dataQuery);
|
|
1888
|
-
const rows = result.recordset;
|
|
1889
|
-
|
|
1890
|
-
return {
|
|
1891
|
-
evals: rows?.map(row => this.transformEvalRow(row)) ?? [],
|
|
1892
|
-
total,
|
|
1893
|
-
page,
|
|
1894
|
-
perPage,
|
|
1895
|
-
hasMore: offset + (rows?.length ?? 0) < total,
|
|
1896
|
-
};
|
|
1897
|
-
} catch (error) {
|
|
1898
|
-
const mastraError = new MastraError(
|
|
1899
|
-
{
|
|
1900
|
-
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED',
|
|
1901
|
-
domain: ErrorDomain.STORAGE,
|
|
1902
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1903
|
-
details: {
|
|
1904
|
-
agentName: agentName || 'all',
|
|
1905
|
-
type: type || 'all',
|
|
1906
|
-
page,
|
|
1907
|
-
perPage,
|
|
1908
|
-
},
|
|
1909
|
-
},
|
|
1910
|
-
error,
|
|
1911
|
-
);
|
|
1912
|
-
this.logger?.error?.(mastraError.toString());
|
|
1913
|
-
this.logger?.trackException(mastraError);
|
|
1914
|
-
throw mastraError;
|
|
1915
|
-
}
|
|
1916
|
-
}
|
|
1917
|
-
|
|
1918
|
-
async saveResource({ resource }: { resource: StorageResourceType }): Promise<StorageResourceType> {
|
|
1919
|
-
const tableName = this.getTableName(TABLE_RESOURCES);
|
|
1920
|
-
try {
|
|
1921
|
-
const req = this.pool.request();
|
|
1922
|
-
req.input('id', resource.id);
|
|
1923
|
-
req.input('workingMemory', resource.workingMemory);
|
|
1924
|
-
req.input('metadata', JSON.stringify(resource.metadata));
|
|
1925
|
-
req.input('createdAt', resource.createdAt.toISOString());
|
|
1926
|
-
req.input('updatedAt', resource.updatedAt.toISOString());
|
|
1927
|
-
|
|
1928
|
-
await req.query(
|
|
1929
|
-
`INSERT INTO ${tableName} (id, workingMemory, metadata, createdAt, updatedAt) VALUES (@id, @workingMemory, @metadata, @createdAt, @updatedAt)`,
|
|
1930
|
-
);
|
|
1931
|
-
|
|
1932
|
-
return resource;
|
|
1933
|
-
} catch (error) {
|
|
1934
|
-
const mastraError = new MastraError(
|
|
1935
|
-
{
|
|
1936
|
-
id: 'MASTRA_STORAGE_MSSQL_SAVE_RESOURCE_FAILED',
|
|
1937
|
-
domain: ErrorDomain.STORAGE,
|
|
1938
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
1939
|
-
details: { resourceId: resource.id },
|
|
1940
|
-
},
|
|
1941
|
-
error,
|
|
1942
|
-
);
|
|
1943
|
-
this.logger?.error?.(mastraError.toString());
|
|
1944
|
-
this.logger?.trackException(mastraError);
|
|
1945
|
-
throw mastraError;
|
|
1946
|
-
}
|
|
1947
|
-
}
|
|
1948
|
-
|
|
1949
|
-
async updateResource({
|
|
1950
|
-
resourceId,
|
|
1951
|
-
workingMemory,
|
|
1952
|
-
metadata,
|
|
1953
|
-
}: {
|
|
1954
|
-
resourceId: string;
|
|
1955
|
-
workingMemory?: string;
|
|
1956
|
-
metadata?: Record<string, unknown>;
|
|
1957
|
-
}): Promise<StorageResourceType> {
|
|
1958
|
-
try {
|
|
1959
|
-
const existingResource = await this.getResourceById({ resourceId });
|
|
1960
|
-
|
|
1961
|
-
if (!existingResource) {
|
|
1962
|
-
const newResource: StorageResourceType = {
|
|
1963
|
-
id: resourceId,
|
|
1964
|
-
workingMemory,
|
|
1965
|
-
metadata: metadata || {},
|
|
1966
|
-
createdAt: new Date(),
|
|
1967
|
-
updatedAt: new Date(),
|
|
1968
|
-
};
|
|
1969
|
-
return this.saveResource({ resource: newResource });
|
|
1970
|
-
}
|
|
1971
|
-
|
|
1972
|
-
const updatedResource = {
|
|
1973
|
-
...existingResource,
|
|
1974
|
-
workingMemory: workingMemory !== undefined ? workingMemory : existingResource.workingMemory,
|
|
1975
|
-
metadata: {
|
|
1976
|
-
...existingResource.metadata,
|
|
1977
|
-
...metadata,
|
|
1978
|
-
},
|
|
1979
|
-
updatedAt: new Date(),
|
|
1980
|
-
};
|
|
1981
|
-
|
|
1982
|
-
const tableName = this.getTableName(TABLE_RESOURCES);
|
|
1983
|
-
const updates: string[] = [];
|
|
1984
|
-
const req = this.pool.request();
|
|
1985
|
-
|
|
1986
|
-
if (workingMemory !== undefined) {
|
|
1987
|
-
updates.push('workingMemory = @workingMemory');
|
|
1988
|
-
req.input('workingMemory', workingMemory);
|
|
1989
|
-
}
|
|
1990
|
-
|
|
1991
|
-
if (metadata) {
|
|
1992
|
-
updates.push('metadata = @metadata');
|
|
1993
|
-
req.input('metadata', JSON.stringify(updatedResource.metadata));
|
|
1994
|
-
}
|
|
1995
|
-
|
|
1996
|
-
updates.push('updatedAt = @updatedAt');
|
|
1997
|
-
req.input('updatedAt', updatedResource.updatedAt.toISOString());
|
|
1998
|
-
|
|
1999
|
-
req.input('id', resourceId);
|
|
2000
|
-
|
|
2001
|
-
await req.query(`UPDATE ${tableName} SET ${updates.join(', ')} WHERE id = @id`);
|
|
2002
|
-
|
|
2003
|
-
return updatedResource;
|
|
2004
|
-
} catch (error) {
|
|
2005
|
-
const mastraError = new MastraError(
|
|
2006
|
-
{
|
|
2007
|
-
id: 'MASTRA_STORAGE_MSSQL_UPDATE_RESOURCE_FAILED',
|
|
2008
|
-
domain: ErrorDomain.STORAGE,
|
|
2009
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
2010
|
-
details: { resourceId },
|
|
2011
|
-
},
|
|
2012
|
-
error,
|
|
2013
|
-
);
|
|
2014
|
-
this.logger?.error?.(mastraError.toString());
|
|
2015
|
-
this.logger?.trackException(mastraError);
|
|
2016
|
-
throw mastraError;
|
|
2017
|
-
}
|
|
2018
|
-
}
|
|
2019
|
-
|
|
2020
|
-
async getResourceById({ resourceId }: { resourceId: string }): Promise<StorageResourceType | null> {
|
|
2021
|
-
const tableName = this.getTableName(TABLE_RESOURCES);
|
|
2022
|
-
try {
|
|
2023
|
-
const req = this.pool.request();
|
|
2024
|
-
req.input('resourceId', resourceId);
|
|
2025
|
-
const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
|
|
2026
|
-
|
|
2027
|
-
if (!result) {
|
|
2028
|
-
return null;
|
|
2029
|
-
}
|
|
2030
|
-
|
|
2031
|
-
return {
|
|
2032
|
-
...result,
|
|
2033
|
-
workingMemory:
|
|
2034
|
-
typeof result.workingMemory === 'object' ? JSON.stringify(result.workingMemory) : result.workingMemory,
|
|
2035
|
-
metadata: typeof result.metadata === 'string' ? JSON.parse(result.metadata) : result.metadata,
|
|
2036
|
-
};
|
|
2037
|
-
} catch (error) {
|
|
2038
|
-
const mastraError = new MastraError(
|
|
2039
|
-
{
|
|
2040
|
-
id: 'MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED',
|
|
2041
|
-
domain: ErrorDomain.STORAGE,
|
|
2042
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
2043
|
-
details: { resourceId },
|
|
2044
|
-
},
|
|
2045
|
-
error,
|
|
2046
|
-
);
|
|
2047
|
-
this.logger?.error?.(mastraError.toString());
|
|
2048
|
-
this.logger?.trackException(mastraError);
|
|
2049
|
-
throw mastraError;
|
|
2050
|
-
}
|
|
2051
|
-
}
|
|
2052
|
-
|
|
2053
|
-
async getScoreById({ id }: { id: string }): Promise<ScoreRowData | null> {
|
|
2054
|
-
throw new MastraError({
|
|
2055
|
-
id: 'STORAGE_MONGODB_STORE_GET_SCORE_BY_ID_FAILED',
|
|
2056
|
-
domain: ErrorDomain.STORAGE,
|
|
2057
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
2058
|
-
details: { id },
|
|
2059
|
-
text: 'getScoreById is not implemented yet in MongoDBStore',
|
|
2060
|
-
});
|
|
2061
|
-
}
|
|
2062
|
-
|
|
2063
|
-
async saveScore(_score: Omit<ScoreRowData, 'id' | 'createdAt' | 'updatedAt'>): Promise<{ score: ScoreRowData }> {
|
|
2064
|
-
throw new MastraError({
|
|
2065
|
-
id: 'STORAGE_MONGODB_STORE_SAVE_SCORE_FAILED',
|
|
2066
|
-
domain: ErrorDomain.STORAGE,
|
|
2067
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
2068
|
-
details: {},
|
|
2069
|
-
text: 'saveScore is not implemented yet in MongoDBStore',
|
|
2070
|
-
});
|
|
414
|
+
/**
|
|
415
|
+
* Scorers
|
|
416
|
+
*/
|
|
417
|
+
async getScoreById({ id: _id }: { id: string }): Promise<ScoreRowData | null> {
|
|
418
|
+
return this.stores.scores.getScoreById({ id: _id });
|
|
2071
419
|
}
|
|
2072
420
|
|
|
2073
421
|
async getScoresByScorerId({
|
|
2074
|
-
scorerId,
|
|
422
|
+
scorerId: _scorerId,
|
|
2075
423
|
pagination: _pagination,
|
|
2076
|
-
entityId,
|
|
2077
|
-
entityType,
|
|
2078
424
|
}: {
|
|
2079
425
|
scorerId: string;
|
|
2080
426
|
pagination: StoragePagination;
|
|
2081
|
-
entityId?: string;
|
|
2082
|
-
entityType?: string;
|
|
2083
427
|
}): Promise<{ pagination: PaginationInfo; scores: ScoreRowData[] }> {
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
text: 'getScoresByScorerId is not implemented yet in MongoDBStore',
|
|
2090
|
-
});
|
|
428
|
+
return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async saveScore(_score: ScoreRowData): Promise<{ score: ScoreRowData }> {
|
|
432
|
+
return this.stores.scores.saveScore(_score);
|
|
2091
433
|
}
|
|
2092
434
|
|
|
2093
435
|
async getScoresByRunId({
|
|
2094
|
-
runId,
|
|
436
|
+
runId: _runId,
|
|
2095
437
|
pagination: _pagination,
|
|
2096
438
|
}: {
|
|
2097
439
|
runId: string;
|
|
2098
440
|
pagination: StoragePagination;
|
|
2099
441
|
}): Promise<{ pagination: PaginationInfo; scores: ScoreRowData[] }> {
|
|
2100
|
-
|
|
2101
|
-
id: 'STORAGE_MONGODB_STORE_GET_SCORES_BY_RUN_ID_FAILED',
|
|
2102
|
-
domain: ErrorDomain.STORAGE,
|
|
2103
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
2104
|
-
details: { runId },
|
|
2105
|
-
text: 'getScoresByRunId is not implemented yet in MongoDBStore',
|
|
2106
|
-
});
|
|
442
|
+
return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
|
|
2107
443
|
}
|
|
2108
444
|
|
|
2109
445
|
async getScoresByEntityId({
|
|
2110
|
-
entityId,
|
|
2111
|
-
entityType,
|
|
446
|
+
entityId: _entityId,
|
|
447
|
+
entityType: _entityType,
|
|
2112
448
|
pagination: _pagination,
|
|
2113
449
|
}: {
|
|
2114
450
|
pagination: StoragePagination;
|
|
2115
451
|
entityId: string;
|
|
2116
452
|
entityType: string;
|
|
2117
453
|
}): Promise<{ pagination: PaginationInfo; scores: ScoreRowData[] }> {
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
details: { entityId, entityType },
|
|
2123
|
-
text: 'getScoresByEntityId is not implemented yet in MongoDBStore',
|
|
2124
|
-
});
|
|
2125
|
-
}
|
|
2126
|
-
|
|
2127
|
-
async dropTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {
|
|
2128
|
-
throw new MastraError({
|
|
2129
|
-
id: 'STORAGE_MONGODB_STORE_DROP_TABLE_FAILED',
|
|
2130
|
-
domain: ErrorDomain.STORAGE,
|
|
2131
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
2132
|
-
details: { tableName },
|
|
2133
|
-
text: 'dropTable is not implemented yet in MongoDBStore',
|
|
454
|
+
return this.stores.scores.getScoresByEntityId({
|
|
455
|
+
entityId: _entityId,
|
|
456
|
+
entityType: _entityType,
|
|
457
|
+
pagination: _pagination,
|
|
2134
458
|
});
|
|
2135
459
|
}
|
|
2136
460
|
}
|