@mastra/mssql 0.0.0-update-stores-peerDeps-20250723031338 → 0.0.0-vector-query-tool-provider-options-20250828222356

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