@mastra/mssql 0.2.3 → 0.3.0-alpha.1
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/.turbo/turbo-build.log +2 -21
- package/CHANGELOG.md +42 -1
- package/dist/index.cjs +1573 -1104
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +2 -4
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1573 -1104
- package/dist/index.js.map +1 -0
- package/dist/storage/domains/legacy-evals/index.d.ts +20 -0
- package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +90 -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/{_tsup-dts-rollup.d.cts → storage/index.d.ts} +81 -117
- package/dist/storage/index.d.ts.map +1 -0
- package/package.json +9 -8
- package/src/storage/domains/legacy-evals/index.ts +175 -0
- package/src/storage/domains/memory/index.ts +1024 -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 +147 -1835
- package/tsconfig.build.json +9 -0
- package/tsconfig.json +1 -1
- package/tsup.config.ts +17 -0
- package/dist/_tsup-dts-rollup.d.ts +0 -251
- package/dist/index.d.cts +0 -4
|
@@ -0,0 +1,1024 @@
|
|
|
1
|
+
import { MessageList } from '@mastra/core/agent';
|
|
2
|
+
import type { MastraMessageContentV2 } from '@mastra/core/agent';
|
|
3
|
+
import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
|
|
4
|
+
import type { MastraMessageV1, MastraMessageV2, StorageThreadType } from '@mastra/core/memory';
|
|
5
|
+
import {
|
|
6
|
+
MemoryStorage,
|
|
7
|
+
resolveMessageLimit,
|
|
8
|
+
TABLE_MESSAGES,
|
|
9
|
+
TABLE_RESOURCES,
|
|
10
|
+
TABLE_THREADS,
|
|
11
|
+
} from '@mastra/core/storage';
|
|
12
|
+
import type {
|
|
13
|
+
StorageGetMessagesArg,
|
|
14
|
+
PaginationInfo,
|
|
15
|
+
PaginationArgs,
|
|
16
|
+
StorageResourceType,
|
|
17
|
+
ThreadSortOptions,
|
|
18
|
+
} from '@mastra/core/storage';
|
|
19
|
+
import sql from 'mssql';
|
|
20
|
+
import type { StoreOperationsMSSQL } from '../operations';
|
|
21
|
+
import { getTableName, getSchemaName } from '../utils';
|
|
22
|
+
|
|
23
|
+
export class MemoryMSSQL extends MemoryStorage {
|
|
24
|
+
private pool: sql.ConnectionPool;
|
|
25
|
+
private schema: string;
|
|
26
|
+
private operations: StoreOperationsMSSQL;
|
|
27
|
+
|
|
28
|
+
private _parseAndFormatMessages(messages: any[], format?: 'v1' | 'v2') {
|
|
29
|
+
// Parse content back to objects if they were stringified during storage
|
|
30
|
+
const messagesWithParsedContent = messages.map(message => {
|
|
31
|
+
if (typeof message.content === 'string') {
|
|
32
|
+
try {
|
|
33
|
+
return { ...message, content: JSON.parse(message.content) };
|
|
34
|
+
} catch {
|
|
35
|
+
// If parsing fails, leave as string (V1 message)
|
|
36
|
+
return message;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return message;
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// Remove seq_id from all messages before formatting
|
|
43
|
+
const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
|
|
44
|
+
|
|
45
|
+
// Use MessageList to ensure proper structure for both v1 and v2
|
|
46
|
+
const list = new MessageList().add(cleanMessages, 'memory');
|
|
47
|
+
return format === 'v2' ? list.get.all.v2() : list.get.all.v1();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
constructor({
|
|
51
|
+
pool,
|
|
52
|
+
schema,
|
|
53
|
+
operations,
|
|
54
|
+
}: {
|
|
55
|
+
pool: sql.ConnectionPool;
|
|
56
|
+
schema: string;
|
|
57
|
+
operations: StoreOperationsMSSQL;
|
|
58
|
+
}) {
|
|
59
|
+
super();
|
|
60
|
+
this.pool = pool;
|
|
61
|
+
this.schema = schema;
|
|
62
|
+
this.operations = operations;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {
|
|
66
|
+
try {
|
|
67
|
+
const sql = `SELECT
|
|
68
|
+
id,
|
|
69
|
+
[resourceId],
|
|
70
|
+
title,
|
|
71
|
+
metadata,
|
|
72
|
+
[createdAt],
|
|
73
|
+
[updatedAt]
|
|
74
|
+
FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })}
|
|
75
|
+
WHERE id = @threadId`;
|
|
76
|
+
const request = this.pool.request();
|
|
77
|
+
request.input('threadId', threadId);
|
|
78
|
+
const resultSet = await request.query(sql);
|
|
79
|
+
const thread = resultSet.recordset[0] || null;
|
|
80
|
+
if (!thread) {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
...thread,
|
|
85
|
+
metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
|
|
86
|
+
createdAt: thread.createdAt,
|
|
87
|
+
updatedAt: thread.updatedAt,
|
|
88
|
+
};
|
|
89
|
+
} catch (error) {
|
|
90
|
+
throw new MastraError(
|
|
91
|
+
{
|
|
92
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED',
|
|
93
|
+
domain: ErrorDomain.STORAGE,
|
|
94
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
95
|
+
details: {
|
|
96
|
+
threadId,
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
error,
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
public async getThreadsByResourceIdPaginated(
|
|
105
|
+
args: {
|
|
106
|
+
resourceId: string;
|
|
107
|
+
} & PaginationArgs &
|
|
108
|
+
ThreadSortOptions,
|
|
109
|
+
): Promise<PaginationInfo & { threads: StorageThreadType[] }> {
|
|
110
|
+
const { resourceId, page = 0, perPage: perPageInput, orderBy = 'createdAt', sortDirection = 'DESC' } = args;
|
|
111
|
+
try {
|
|
112
|
+
const perPage = perPageInput !== undefined ? perPageInput : 100;
|
|
113
|
+
const currentOffset = page * perPage;
|
|
114
|
+
const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
|
|
115
|
+
|
|
116
|
+
const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
|
|
117
|
+
const countRequest = this.pool.request();
|
|
118
|
+
countRequest.input('resourceId', resourceId);
|
|
119
|
+
const countResult = await countRequest.query(countQuery);
|
|
120
|
+
const total = parseInt(countResult.recordset[0]?.count ?? '0', 10);
|
|
121
|
+
|
|
122
|
+
if (total === 0) {
|
|
123
|
+
return {
|
|
124
|
+
threads: [],
|
|
125
|
+
total: 0,
|
|
126
|
+
page,
|
|
127
|
+
perPage,
|
|
128
|
+
hasMore: false,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const orderByField = orderBy === 'createdAt' ? '[createdAt]' : '[updatedAt]';
|
|
133
|
+
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${sortDirection} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
|
|
134
|
+
const dataRequest = this.pool.request();
|
|
135
|
+
dataRequest.input('resourceId', resourceId);
|
|
136
|
+
dataRequest.input('perPage', perPage);
|
|
137
|
+
dataRequest.input('offset', currentOffset);
|
|
138
|
+
const rowsResult = await dataRequest.query(dataQuery);
|
|
139
|
+
const rows = rowsResult.recordset || [];
|
|
140
|
+
const threads = rows.map(thread => ({
|
|
141
|
+
...thread,
|
|
142
|
+
metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
|
|
143
|
+
createdAt: thread.createdAt,
|
|
144
|
+
updatedAt: thread.updatedAt,
|
|
145
|
+
}));
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
threads,
|
|
149
|
+
total,
|
|
150
|
+
page,
|
|
151
|
+
perPage,
|
|
152
|
+
hasMore: currentOffset + threads.length < total,
|
|
153
|
+
};
|
|
154
|
+
} catch (error) {
|
|
155
|
+
const mastraError = new MastraError(
|
|
156
|
+
{
|
|
157
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED',
|
|
158
|
+
domain: ErrorDomain.STORAGE,
|
|
159
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
160
|
+
details: {
|
|
161
|
+
resourceId,
|
|
162
|
+
page,
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
error,
|
|
166
|
+
);
|
|
167
|
+
this.logger?.error?.(mastraError.toString());
|
|
168
|
+
this.logger?.trackException?.(mastraError);
|
|
169
|
+
return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
public async saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType> {
|
|
174
|
+
try {
|
|
175
|
+
const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
176
|
+
const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
|
|
177
|
+
USING (SELECT @id AS id) AS source
|
|
178
|
+
ON (target.id = source.id)
|
|
179
|
+
WHEN MATCHED THEN
|
|
180
|
+
UPDATE SET
|
|
181
|
+
[resourceId] = @resourceId,
|
|
182
|
+
title = @title,
|
|
183
|
+
metadata = @metadata,
|
|
184
|
+
[updatedAt] = @updatedAt
|
|
185
|
+
WHEN NOT MATCHED THEN
|
|
186
|
+
INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
|
|
187
|
+
VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
|
|
188
|
+
const req = this.pool.request();
|
|
189
|
+
req.input('id', thread.id);
|
|
190
|
+
req.input('resourceId', thread.resourceId);
|
|
191
|
+
req.input('title', thread.title);
|
|
192
|
+
req.input('metadata', thread.metadata ? JSON.stringify(thread.metadata) : null);
|
|
193
|
+
req.input('createdAt', sql.DateTime2, thread.createdAt);
|
|
194
|
+
req.input('updatedAt', sql.DateTime2, thread.updatedAt);
|
|
195
|
+
await req.query(mergeSql);
|
|
196
|
+
// Return the exact same thread object to preserve timestamp precision
|
|
197
|
+
return thread;
|
|
198
|
+
} catch (error) {
|
|
199
|
+
throw new MastraError(
|
|
200
|
+
{
|
|
201
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED',
|
|
202
|
+
domain: ErrorDomain.STORAGE,
|
|
203
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
204
|
+
details: {
|
|
205
|
+
threadId: thread.id,
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
error,
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
215
|
+
*/
|
|
216
|
+
public async getThreadsByResourceId(args: { resourceId: string } & ThreadSortOptions): Promise<StorageThreadType[]> {
|
|
217
|
+
const { resourceId, orderBy = 'createdAt', sortDirection = 'DESC' } = args;
|
|
218
|
+
try {
|
|
219
|
+
const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
|
|
220
|
+
const orderByField = orderBy === 'createdAt' ? '[createdAt]' : '[updatedAt]';
|
|
221
|
+
const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${sortDirection}`;
|
|
222
|
+
const request = this.pool.request();
|
|
223
|
+
request.input('resourceId', resourceId);
|
|
224
|
+
const resultSet = await request.query(dataQuery);
|
|
225
|
+
const rows = resultSet.recordset || [];
|
|
226
|
+
return rows.map(thread => ({
|
|
227
|
+
...thread,
|
|
228
|
+
metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
|
|
229
|
+
createdAt: thread.createdAt,
|
|
230
|
+
updatedAt: thread.updatedAt,
|
|
231
|
+
}));
|
|
232
|
+
} catch (error) {
|
|
233
|
+
this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
|
|
234
|
+
return [];
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
|
|
240
|
+
*/
|
|
241
|
+
async updateThread({
|
|
242
|
+
id,
|
|
243
|
+
title,
|
|
244
|
+
metadata,
|
|
245
|
+
}: {
|
|
246
|
+
id: string;
|
|
247
|
+
title: string;
|
|
248
|
+
metadata: Record<string, unknown>;
|
|
249
|
+
}): Promise<StorageThreadType> {
|
|
250
|
+
const existingThread = await this.getThreadById({ threadId: id });
|
|
251
|
+
if (!existingThread) {
|
|
252
|
+
throw new MastraError({
|
|
253
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED',
|
|
254
|
+
domain: ErrorDomain.STORAGE,
|
|
255
|
+
category: ErrorCategory.USER,
|
|
256
|
+
text: `Thread ${id} not found`,
|
|
257
|
+
details: {
|
|
258
|
+
threadId: id,
|
|
259
|
+
title,
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const mergedMetadata = {
|
|
265
|
+
...existingThread.metadata,
|
|
266
|
+
...metadata,
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
try {
|
|
270
|
+
const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
271
|
+
const sql = `UPDATE ${table}
|
|
272
|
+
SET title = @title,
|
|
273
|
+
metadata = @metadata,
|
|
274
|
+
[updatedAt] = @updatedAt
|
|
275
|
+
OUTPUT INSERTED.*
|
|
276
|
+
WHERE id = @id`;
|
|
277
|
+
const req = this.pool.request();
|
|
278
|
+
req.input('id', id);
|
|
279
|
+
req.input('title', title);
|
|
280
|
+
req.input('metadata', JSON.stringify(mergedMetadata));
|
|
281
|
+
req.input('updatedAt', new Date());
|
|
282
|
+
const result = await req.query(sql);
|
|
283
|
+
let thread = result.recordset && result.recordset[0];
|
|
284
|
+
if (thread && 'seq_id' in thread) {
|
|
285
|
+
const { seq_id, ...rest } = thread;
|
|
286
|
+
thread = rest;
|
|
287
|
+
}
|
|
288
|
+
if (!thread) {
|
|
289
|
+
throw new MastraError({
|
|
290
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED',
|
|
291
|
+
domain: ErrorDomain.STORAGE,
|
|
292
|
+
category: ErrorCategory.USER,
|
|
293
|
+
text: `Thread ${id} not found after update`,
|
|
294
|
+
details: {
|
|
295
|
+
threadId: id,
|
|
296
|
+
title,
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
...thread,
|
|
302
|
+
metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
|
|
303
|
+
createdAt: thread.createdAt,
|
|
304
|
+
updatedAt: thread.updatedAt,
|
|
305
|
+
};
|
|
306
|
+
} catch (error) {
|
|
307
|
+
throw new MastraError(
|
|
308
|
+
{
|
|
309
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED',
|
|
310
|
+
domain: ErrorDomain.STORAGE,
|
|
311
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
312
|
+
details: {
|
|
313
|
+
threadId: id,
|
|
314
|
+
title,
|
|
315
|
+
},
|
|
316
|
+
},
|
|
317
|
+
error,
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async deleteThread({ threadId }: { threadId: string }): Promise<void> {
|
|
323
|
+
const messagesTable = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
324
|
+
const threadsTable = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
325
|
+
const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
|
|
326
|
+
const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
|
|
327
|
+
const tx = this.pool.transaction();
|
|
328
|
+
try {
|
|
329
|
+
await tx.begin();
|
|
330
|
+
const req = tx.request();
|
|
331
|
+
req.input('threadId', threadId);
|
|
332
|
+
await req.query(deleteMessagesSql);
|
|
333
|
+
await req.query(deleteThreadSql);
|
|
334
|
+
await tx.commit();
|
|
335
|
+
} catch (error) {
|
|
336
|
+
await tx.rollback().catch(() => {});
|
|
337
|
+
throw new MastraError(
|
|
338
|
+
{
|
|
339
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_DELETE_THREAD_FAILED',
|
|
340
|
+
domain: ErrorDomain.STORAGE,
|
|
341
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
342
|
+
details: {
|
|
343
|
+
threadId,
|
|
344
|
+
},
|
|
345
|
+
},
|
|
346
|
+
error,
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
private async _getIncludedMessages({
|
|
352
|
+
threadId,
|
|
353
|
+
selectBy,
|
|
354
|
+
orderByStatement,
|
|
355
|
+
}: {
|
|
356
|
+
threadId: string;
|
|
357
|
+
selectBy: StorageGetMessagesArg['selectBy'];
|
|
358
|
+
orderByStatement: string;
|
|
359
|
+
}) {
|
|
360
|
+
const include = selectBy?.include;
|
|
361
|
+
if (!include) return null;
|
|
362
|
+
|
|
363
|
+
const unionQueries: string[] = [];
|
|
364
|
+
const paramValues: any[] = [];
|
|
365
|
+
let paramIdx = 1;
|
|
366
|
+
const paramNames: string[] = [];
|
|
367
|
+
|
|
368
|
+
for (const inc of include) {
|
|
369
|
+
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
370
|
+
const searchId = inc.threadId || threadId;
|
|
371
|
+
|
|
372
|
+
const pThreadId = `@p${paramIdx}`;
|
|
373
|
+
const pId = `@p${paramIdx + 1}`;
|
|
374
|
+
const pPrev = `@p${paramIdx + 2}`;
|
|
375
|
+
const pNext = `@p${paramIdx + 3}`;
|
|
376
|
+
|
|
377
|
+
unionQueries.push(
|
|
378
|
+
`
|
|
379
|
+
SELECT
|
|
380
|
+
m.id,
|
|
381
|
+
m.content,
|
|
382
|
+
m.role,
|
|
383
|
+
m.type,
|
|
384
|
+
m.[createdAt],
|
|
385
|
+
m.thread_id AS threadId,
|
|
386
|
+
m.[resourceId],
|
|
387
|
+
m.seq_id
|
|
388
|
+
FROM (
|
|
389
|
+
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
390
|
+
FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
|
|
391
|
+
WHERE [thread_id] = ${pThreadId}
|
|
392
|
+
) AS m
|
|
393
|
+
WHERE m.id = ${pId}
|
|
394
|
+
OR EXISTS (
|
|
395
|
+
SELECT 1
|
|
396
|
+
FROM (
|
|
397
|
+
SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
|
|
398
|
+
FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
|
|
399
|
+
WHERE [thread_id] = ${pThreadId}
|
|
400
|
+
) AS target
|
|
401
|
+
WHERE target.id = ${pId}
|
|
402
|
+
AND (
|
|
403
|
+
(m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
|
|
404
|
+
OR
|
|
405
|
+
(m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
|
|
406
|
+
)
|
|
407
|
+
)
|
|
408
|
+
`,
|
|
409
|
+
);
|
|
410
|
+
|
|
411
|
+
paramValues.push(searchId, id, withPreviousMessages, withNextMessages);
|
|
412
|
+
paramNames.push(`p${paramIdx}`, `p${paramIdx + 1}`, `p${paramIdx + 2}`, `p${paramIdx + 3}`);
|
|
413
|
+
paramIdx += 4;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const finalQuery = `
|
|
417
|
+
SELECT * FROM (
|
|
418
|
+
${unionQueries.join(' UNION ALL ')}
|
|
419
|
+
) AS union_result
|
|
420
|
+
ORDER BY [seq_id] ASC
|
|
421
|
+
`;
|
|
422
|
+
|
|
423
|
+
const req = this.pool.request();
|
|
424
|
+
for (let i = 0; i < paramValues.length; ++i) {
|
|
425
|
+
req.input(paramNames[i] as string, paramValues[i]);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const result = await req.query(finalQuery);
|
|
429
|
+
const includedRows = result.recordset || [];
|
|
430
|
+
|
|
431
|
+
const seen = new Set<string>();
|
|
432
|
+
const dedupedRows = includedRows.filter((row: any) => {
|
|
433
|
+
if (seen.has(row.id)) return false;
|
|
434
|
+
seen.add(row.id);
|
|
435
|
+
return true;
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
return dedupedRows;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* @deprecated use getMessagesPaginated instead
|
|
443
|
+
*/
|
|
444
|
+
public async getMessages(args: StorageGetMessagesArg & { format?: 'v1' }): Promise<MastraMessageV1[]>;
|
|
445
|
+
public async getMessages(args: StorageGetMessagesArg & { format: 'v2' }): Promise<MastraMessageV2[]>;
|
|
446
|
+
public async getMessages(
|
|
447
|
+
args: StorageGetMessagesArg & {
|
|
448
|
+
format?: 'v1' | 'v2';
|
|
449
|
+
},
|
|
450
|
+
): Promise<MastraMessageV1[] | MastraMessageV2[]> {
|
|
451
|
+
const { threadId, format, selectBy } = args;
|
|
452
|
+
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
|
|
453
|
+
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
454
|
+
const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
455
|
+
try {
|
|
456
|
+
let rows: any[] = [];
|
|
457
|
+
const include = selectBy?.include || [];
|
|
458
|
+
if (include?.length) {
|
|
459
|
+
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
460
|
+
if (includeMessages) {
|
|
461
|
+
rows.push(...includeMessages);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
const excludeIds = rows.map(m => m.id).filter(Boolean);
|
|
465
|
+
|
|
466
|
+
let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
|
|
467
|
+
const request = this.pool.request();
|
|
468
|
+
request.input('threadId', threadId);
|
|
469
|
+
|
|
470
|
+
if (excludeIds.length > 0) {
|
|
471
|
+
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
472
|
+
query += ` AND id NOT IN (${excludeParams.join(', ')})`;
|
|
473
|
+
excludeIds.forEach((id, idx) => {
|
|
474
|
+
request.input(`id${idx}`, id);
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
query += ` ${orderByStatement} OFFSET 0 ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
479
|
+
request.input('limit', limit);
|
|
480
|
+
const result = await request.query(query);
|
|
481
|
+
const remainingRows = result.recordset || [];
|
|
482
|
+
rows.push(...remainingRows);
|
|
483
|
+
rows.sort((a, b) => {
|
|
484
|
+
const timeDiff = a.seq_id - b.seq_id;
|
|
485
|
+
return timeDiff;
|
|
486
|
+
});
|
|
487
|
+
rows = rows.map(({ seq_id, ...rest }) => rest);
|
|
488
|
+
return this._parseAndFormatMessages(rows, format);
|
|
489
|
+
} catch (error) {
|
|
490
|
+
const mastraError = new MastraError(
|
|
491
|
+
{
|
|
492
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_FAILED',
|
|
493
|
+
domain: ErrorDomain.STORAGE,
|
|
494
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
495
|
+
details: {
|
|
496
|
+
threadId,
|
|
497
|
+
},
|
|
498
|
+
},
|
|
499
|
+
error,
|
|
500
|
+
);
|
|
501
|
+
this.logger?.error?.(mastraError.toString());
|
|
502
|
+
this.logger?.trackException(mastraError);
|
|
503
|
+
return [];
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
public async getMessagesPaginated(
|
|
508
|
+
args: StorageGetMessagesArg & {
|
|
509
|
+
format?: 'v1' | 'v2';
|
|
510
|
+
},
|
|
511
|
+
): Promise<PaginationInfo & { messages: MastraMessageV1[] | MastraMessageV2[] }> {
|
|
512
|
+
const { threadId, selectBy } = args;
|
|
513
|
+
const { page = 0, perPage: perPageInput } = selectBy?.pagination || {};
|
|
514
|
+
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
515
|
+
let messages: any[] = [];
|
|
516
|
+
if (selectBy?.include?.length) {
|
|
517
|
+
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
518
|
+
if (includeMessages) {
|
|
519
|
+
messages.push(...includeMessages);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
try {
|
|
523
|
+
const { threadId, format, selectBy } = args;
|
|
524
|
+
const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
|
|
525
|
+
const fromDate = dateRange?.start;
|
|
526
|
+
const toDate = dateRange?.end;
|
|
527
|
+
|
|
528
|
+
const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
|
|
529
|
+
const orderByStatement = `ORDER BY [seq_id] DESC`;
|
|
530
|
+
|
|
531
|
+
let messages: any[] = [];
|
|
532
|
+
|
|
533
|
+
if (selectBy?.include?.length) {
|
|
534
|
+
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
535
|
+
if (includeMessages) messages.push(...includeMessages);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const perPage =
|
|
539
|
+
perPageInput !== undefined ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
540
|
+
const currentOffset = page * perPage;
|
|
541
|
+
|
|
542
|
+
const conditions: string[] = ['[thread_id] = @threadId'];
|
|
543
|
+
const request = this.pool.request();
|
|
544
|
+
request.input('threadId', threadId);
|
|
545
|
+
|
|
546
|
+
if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
|
|
547
|
+
conditions.push('[createdAt] >= @fromDate');
|
|
548
|
+
request.input('fromDate', fromDate.toISOString());
|
|
549
|
+
}
|
|
550
|
+
if (toDate instanceof Date && !isNaN(toDate.getTime())) {
|
|
551
|
+
conditions.push('[createdAt] <= @toDate');
|
|
552
|
+
request.input('toDate', toDate.toISOString());
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const whereClause = `WHERE ${conditions.join(' AND ')}`;
|
|
556
|
+
const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
|
|
557
|
+
const countResult = await request.query(countQuery);
|
|
558
|
+
const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
|
|
559
|
+
|
|
560
|
+
if (total === 0 && messages.length > 0) {
|
|
561
|
+
const parsedIncluded = this._parseAndFormatMessages(messages, format);
|
|
562
|
+
return {
|
|
563
|
+
messages: parsedIncluded,
|
|
564
|
+
total: parsedIncluded.length,
|
|
565
|
+
page,
|
|
566
|
+
perPage,
|
|
567
|
+
hasMore: false,
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
const excludeIds = messages.map(m => m.id);
|
|
572
|
+
if (excludeIds.length > 0) {
|
|
573
|
+
const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
|
|
574
|
+
conditions.push(`id NOT IN (${excludeParams.join(', ')})`);
|
|
575
|
+
excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
const finalWhereClause = `WHERE ${conditions.join(' AND ')}`;
|
|
579
|
+
const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
|
|
580
|
+
|
|
581
|
+
request.input('offset', currentOffset);
|
|
582
|
+
request.input('limit', perPage);
|
|
583
|
+
|
|
584
|
+
const rowsResult = await request.query(dataQuery);
|
|
585
|
+
const rows = rowsResult.recordset || [];
|
|
586
|
+
rows.sort((a, b) => a.seq_id - b.seq_id);
|
|
587
|
+
messages.push(...rows);
|
|
588
|
+
|
|
589
|
+
const parsed = this._parseAndFormatMessages(messages, format);
|
|
590
|
+
return {
|
|
591
|
+
messages: parsed,
|
|
592
|
+
total: total + excludeIds.length,
|
|
593
|
+
page,
|
|
594
|
+
perPage,
|
|
595
|
+
hasMore: currentOffset + rows.length < total,
|
|
596
|
+
};
|
|
597
|
+
} catch (error) {
|
|
598
|
+
const mastraError = new MastraError(
|
|
599
|
+
{
|
|
600
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED',
|
|
601
|
+
domain: ErrorDomain.STORAGE,
|
|
602
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
603
|
+
details: {
|
|
604
|
+
threadId,
|
|
605
|
+
page,
|
|
606
|
+
},
|
|
607
|
+
},
|
|
608
|
+
error,
|
|
609
|
+
);
|
|
610
|
+
this.logger?.error?.(mastraError.toString());
|
|
611
|
+
this.logger?.trackException(mastraError);
|
|
612
|
+
return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
async saveMessages(args: { messages: MastraMessageV1[]; format?: undefined | 'v1' }): Promise<MastraMessageV1[]>;
|
|
617
|
+
async saveMessages(args: { messages: MastraMessageV2[]; format: 'v2' }): Promise<MastraMessageV2[]>;
|
|
618
|
+
async saveMessages({
|
|
619
|
+
messages,
|
|
620
|
+
format,
|
|
621
|
+
}:
|
|
622
|
+
| { messages: MastraMessageV1[]; format?: undefined | 'v1' }
|
|
623
|
+
| { messages: MastraMessageV2[]; format: 'v2' }): Promise<MastraMessageV2[] | MastraMessageV1[]> {
|
|
624
|
+
if (messages.length === 0) return messages;
|
|
625
|
+
const threadId = messages[0]?.threadId;
|
|
626
|
+
if (!threadId) {
|
|
627
|
+
throw new MastraError({
|
|
628
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED',
|
|
629
|
+
domain: ErrorDomain.STORAGE,
|
|
630
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
631
|
+
text: `Thread ID is required`,
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
const thread = await this.getThreadById({ threadId });
|
|
635
|
+
if (!thread) {
|
|
636
|
+
throw new MastraError({
|
|
637
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED',
|
|
638
|
+
domain: ErrorDomain.STORAGE,
|
|
639
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
640
|
+
text: `Thread ${threadId} not found`,
|
|
641
|
+
details: { threadId },
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
const tableMessages = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
645
|
+
const tableThreads = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
646
|
+
try {
|
|
647
|
+
const transaction = this.pool.transaction();
|
|
648
|
+
await transaction.begin();
|
|
649
|
+
try {
|
|
650
|
+
for (const message of messages) {
|
|
651
|
+
if (!message.threadId) {
|
|
652
|
+
throw new Error(
|
|
653
|
+
`Expected to find a threadId for message, but couldn't find one. An unexpected error has occurred.`,
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
if (!message.resourceId) {
|
|
657
|
+
throw new Error(
|
|
658
|
+
`Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred.`,
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
const request = transaction.request();
|
|
662
|
+
request.input('id', message.id);
|
|
663
|
+
request.input('thread_id', message.threadId);
|
|
664
|
+
request.input(
|
|
665
|
+
'content',
|
|
666
|
+
typeof message.content === 'string' ? message.content : JSON.stringify(message.content),
|
|
667
|
+
);
|
|
668
|
+
request.input('createdAt', sql.DateTime2, message.createdAt);
|
|
669
|
+
request.input('role', message.role);
|
|
670
|
+
request.input('type', message.type || 'v2');
|
|
671
|
+
request.input('resourceId', message.resourceId);
|
|
672
|
+
const mergeSql = `MERGE INTO ${tableMessages} AS target
|
|
673
|
+
USING (SELECT @id AS id) AS src
|
|
674
|
+
ON target.id = src.id
|
|
675
|
+
WHEN MATCHED THEN UPDATE SET
|
|
676
|
+
thread_id = @thread_id,
|
|
677
|
+
content = @content,
|
|
678
|
+
[createdAt] = @createdAt,
|
|
679
|
+
role = @role,
|
|
680
|
+
type = @type,
|
|
681
|
+
resourceId = @resourceId
|
|
682
|
+
WHEN NOT MATCHED THEN INSERT (id, thread_id, content, [createdAt], role, type, resourceId)
|
|
683
|
+
VALUES (@id, @thread_id, @content, @createdAt, @role, @type, @resourceId);`;
|
|
684
|
+
await request.query(mergeSql);
|
|
685
|
+
}
|
|
686
|
+
const threadReq = transaction.request();
|
|
687
|
+
threadReq.input('updatedAt', sql.DateTime2, new Date());
|
|
688
|
+
threadReq.input('id', threadId);
|
|
689
|
+
await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
|
|
690
|
+
await transaction.commit();
|
|
691
|
+
} catch (error) {
|
|
692
|
+
await transaction.rollback();
|
|
693
|
+
throw error;
|
|
694
|
+
}
|
|
695
|
+
const messagesWithParsedContent = messages.map(message => {
|
|
696
|
+
if (typeof message.content === 'string') {
|
|
697
|
+
try {
|
|
698
|
+
return { ...message, content: JSON.parse(message.content) };
|
|
699
|
+
} catch {
|
|
700
|
+
return message;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return message;
|
|
704
|
+
});
|
|
705
|
+
const list = new MessageList().add(messagesWithParsedContent, 'memory');
|
|
706
|
+
if (format === 'v2') return list.get.all.v2();
|
|
707
|
+
return list.get.all.v1();
|
|
708
|
+
} catch (error) {
|
|
709
|
+
throw new MastraError(
|
|
710
|
+
{
|
|
711
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED',
|
|
712
|
+
domain: ErrorDomain.STORAGE,
|
|
713
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
714
|
+
details: { threadId },
|
|
715
|
+
},
|
|
716
|
+
error,
|
|
717
|
+
);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
async updateMessages({
|
|
722
|
+
messages,
|
|
723
|
+
}: {
|
|
724
|
+
messages: (Partial<Omit<MastraMessageV2, 'createdAt'>> & {
|
|
725
|
+
id: string;
|
|
726
|
+
content?: {
|
|
727
|
+
metadata?: MastraMessageContentV2['metadata'];
|
|
728
|
+
content?: MastraMessageContentV2['content'];
|
|
729
|
+
};
|
|
730
|
+
})[];
|
|
731
|
+
}): Promise<MastraMessageV2[]> {
|
|
732
|
+
if (!messages || messages.length === 0) {
|
|
733
|
+
return [];
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
const messageIds = messages.map(m => m.id);
|
|
737
|
+
const idParams = messageIds.map((_, i) => `@id${i}`).join(', ');
|
|
738
|
+
let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}`;
|
|
739
|
+
if (idParams.length > 0) {
|
|
740
|
+
selectQuery += ` WHERE id IN (${idParams})`;
|
|
741
|
+
} else {
|
|
742
|
+
return [];
|
|
743
|
+
}
|
|
744
|
+
const selectReq = this.pool.request();
|
|
745
|
+
messageIds.forEach((id, i) => selectReq.input(`id${i}`, id));
|
|
746
|
+
const existingMessagesDb = (await selectReq.query(selectQuery)).recordset;
|
|
747
|
+
if (!existingMessagesDb || existingMessagesDb.length === 0) {
|
|
748
|
+
return [];
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
const existingMessages: MastraMessageV2[] = existingMessagesDb.map(msg => {
|
|
752
|
+
if (typeof msg.content === 'string') {
|
|
753
|
+
try {
|
|
754
|
+
msg.content = JSON.parse(msg.content);
|
|
755
|
+
} catch {}
|
|
756
|
+
}
|
|
757
|
+
return msg as MastraMessageV2;
|
|
758
|
+
});
|
|
759
|
+
|
|
760
|
+
const threadIdsToUpdate = new Set<string>();
|
|
761
|
+
const transaction = this.pool.transaction();
|
|
762
|
+
|
|
763
|
+
try {
|
|
764
|
+
await transaction.begin();
|
|
765
|
+
for (const existingMessage of existingMessages) {
|
|
766
|
+
const updatePayload = messages.find(m => m.id === existingMessage.id);
|
|
767
|
+
if (!updatePayload) continue;
|
|
768
|
+
const { id, ...fieldsToUpdate } = updatePayload;
|
|
769
|
+
if (Object.keys(fieldsToUpdate).length === 0) continue;
|
|
770
|
+
threadIdsToUpdate.add(existingMessage.threadId!);
|
|
771
|
+
if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
|
|
772
|
+
threadIdsToUpdate.add(updatePayload.threadId);
|
|
773
|
+
}
|
|
774
|
+
const setClauses: string[] = [];
|
|
775
|
+
const req = transaction.request();
|
|
776
|
+
req.input('id', id);
|
|
777
|
+
const columnMapping: Record<string, string> = { threadId: 'thread_id' };
|
|
778
|
+
const updatableFields = { ...fieldsToUpdate };
|
|
779
|
+
if (updatableFields.content) {
|
|
780
|
+
const newContent = {
|
|
781
|
+
...existingMessage.content,
|
|
782
|
+
...updatableFields.content,
|
|
783
|
+
...(existingMessage.content?.metadata && updatableFields.content.metadata
|
|
784
|
+
? { metadata: { ...existingMessage.content.metadata, ...updatableFields.content.metadata } }
|
|
785
|
+
: {}),
|
|
786
|
+
};
|
|
787
|
+
setClauses.push(`content = @content`);
|
|
788
|
+
req.input('content', JSON.stringify(newContent));
|
|
789
|
+
delete updatableFields.content;
|
|
790
|
+
}
|
|
791
|
+
for (const key in updatableFields) {
|
|
792
|
+
if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
|
|
793
|
+
const dbColumn = columnMapping[key] || key;
|
|
794
|
+
setClauses.push(`[${dbColumn}] = @${dbColumn}`);
|
|
795
|
+
req.input(dbColumn, updatableFields[key as keyof typeof updatableFields]);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
if (setClauses.length > 0) {
|
|
799
|
+
const updateSql = `UPDATE ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} SET ${setClauses.join(', ')} WHERE id = @id`;
|
|
800
|
+
await req.query(updateSql);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
if (threadIdsToUpdate.size > 0) {
|
|
804
|
+
const threadIdParams = Array.from(threadIdsToUpdate)
|
|
805
|
+
.map((_, i) => `@tid${i}`)
|
|
806
|
+
.join(', ');
|
|
807
|
+
const threadReq = transaction.request();
|
|
808
|
+
Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
|
|
809
|
+
threadReq.input('updatedAt', new Date().toISOString());
|
|
810
|
+
const threadSql = `UPDATE ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
|
|
811
|
+
await threadReq.query(threadSql);
|
|
812
|
+
}
|
|
813
|
+
await transaction.commit();
|
|
814
|
+
} catch (error) {
|
|
815
|
+
await transaction.rollback();
|
|
816
|
+
throw new MastraError(
|
|
817
|
+
{
|
|
818
|
+
id: 'MASTRA_STORAGE_MSSQL_UPDATE_MESSAGES_FAILED',
|
|
819
|
+
domain: ErrorDomain.STORAGE,
|
|
820
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
821
|
+
},
|
|
822
|
+
error,
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
const refetchReq = this.pool.request();
|
|
827
|
+
messageIds.forEach((id, i) => refetchReq.input(`id${i}`, id));
|
|
828
|
+
const updatedMessages = (await refetchReq.query(selectQuery)).recordset;
|
|
829
|
+
return (updatedMessages || []).map(message => {
|
|
830
|
+
if (typeof message.content === 'string') {
|
|
831
|
+
try {
|
|
832
|
+
message.content = JSON.parse(message.content);
|
|
833
|
+
} catch {}
|
|
834
|
+
}
|
|
835
|
+
return message;
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
async deleteMessages(messageIds: string[]): Promise<void> {
|
|
840
|
+
if (!messageIds || messageIds.length === 0) {
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
try {
|
|
845
|
+
const messageTableName = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
846
|
+
const threadTableName = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
847
|
+
|
|
848
|
+
// Build placeholders for the IN clause
|
|
849
|
+
const placeholders = messageIds.map((_, idx) => `@p${idx + 1}`).join(',');
|
|
850
|
+
|
|
851
|
+
// Get thread IDs for all messages first
|
|
852
|
+
const request = this.pool.request();
|
|
853
|
+
messageIds.forEach((id, idx) => {
|
|
854
|
+
request.input(`p${idx + 1}`, id);
|
|
855
|
+
});
|
|
856
|
+
|
|
857
|
+
const messages = await request.query(
|
|
858
|
+
`SELECT DISTINCT [thread_id] FROM ${messageTableName} WHERE [id] IN (${placeholders})`,
|
|
859
|
+
);
|
|
860
|
+
|
|
861
|
+
const threadIds = messages.recordset?.map(msg => msg.thread_id).filter(Boolean) || [];
|
|
862
|
+
|
|
863
|
+
// Use transaction for the actual delete and update operations
|
|
864
|
+
const transaction = this.pool.transaction();
|
|
865
|
+
await transaction.begin();
|
|
866
|
+
|
|
867
|
+
try {
|
|
868
|
+
// Delete all messages
|
|
869
|
+
const deleteRequest = transaction.request();
|
|
870
|
+
messageIds.forEach((id, idx) => {
|
|
871
|
+
deleteRequest.input(`p${idx + 1}`, id);
|
|
872
|
+
});
|
|
873
|
+
|
|
874
|
+
await deleteRequest.query(`DELETE FROM ${messageTableName} WHERE [id] IN (${placeholders})`);
|
|
875
|
+
|
|
876
|
+
// Update thread timestamps sequentially to avoid transaction conflicts
|
|
877
|
+
if (threadIds.length > 0) {
|
|
878
|
+
for (const threadId of threadIds) {
|
|
879
|
+
const updateRequest = transaction.request();
|
|
880
|
+
updateRequest.input('p1', threadId);
|
|
881
|
+
await updateRequest.query(`UPDATE ${threadTableName} SET [updatedAt] = GETDATE() WHERE [id] = @p1`);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
await transaction.commit();
|
|
886
|
+
} catch (error) {
|
|
887
|
+
try {
|
|
888
|
+
await transaction.rollback();
|
|
889
|
+
} catch {
|
|
890
|
+
// Ignore rollback errors as they're usually not critical
|
|
891
|
+
}
|
|
892
|
+
throw error;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// TODO: Delete from vector store if semantic recall is enabled
|
|
896
|
+
} catch (error) {
|
|
897
|
+
throw new MastraError(
|
|
898
|
+
{
|
|
899
|
+
id: 'MASTRA_STORAGE_MSSQL_STORE_DELETE_MESSAGES_FAILED',
|
|
900
|
+
domain: ErrorDomain.STORAGE,
|
|
901
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
902
|
+
details: { messageIds: messageIds.join(', ') },
|
|
903
|
+
},
|
|
904
|
+
error,
|
|
905
|
+
);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async getResourceById({ resourceId }: { resourceId: string }): Promise<StorageResourceType | null> {
|
|
910
|
+
const tableName = getTableName({ indexName: TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
|
|
911
|
+
try {
|
|
912
|
+
const req = this.pool.request();
|
|
913
|
+
req.input('resourceId', resourceId);
|
|
914
|
+
const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
|
|
915
|
+
|
|
916
|
+
if (!result) {
|
|
917
|
+
return null;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
return {
|
|
921
|
+
...result,
|
|
922
|
+
workingMemory:
|
|
923
|
+
typeof result.workingMemory === 'object' ? JSON.stringify(result.workingMemory) : result.workingMemory,
|
|
924
|
+
metadata: typeof result.metadata === 'string' ? JSON.parse(result.metadata) : result.metadata,
|
|
925
|
+
};
|
|
926
|
+
} catch (error) {
|
|
927
|
+
const mastraError = new MastraError(
|
|
928
|
+
{
|
|
929
|
+
id: 'MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED',
|
|
930
|
+
domain: ErrorDomain.STORAGE,
|
|
931
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
932
|
+
details: { resourceId },
|
|
933
|
+
},
|
|
934
|
+
error,
|
|
935
|
+
);
|
|
936
|
+
this.logger?.error?.(mastraError.toString());
|
|
937
|
+
this.logger?.trackException(mastraError);
|
|
938
|
+
throw mastraError;
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
async saveResource({ resource }: { resource: StorageResourceType }): Promise<StorageResourceType> {
|
|
943
|
+
await this.operations.insert({
|
|
944
|
+
tableName: TABLE_RESOURCES,
|
|
945
|
+
record: {
|
|
946
|
+
...resource,
|
|
947
|
+
metadata: JSON.stringify(resource.metadata),
|
|
948
|
+
},
|
|
949
|
+
});
|
|
950
|
+
|
|
951
|
+
return resource;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
async updateResource({
|
|
955
|
+
resourceId,
|
|
956
|
+
workingMemory,
|
|
957
|
+
metadata,
|
|
958
|
+
}: {
|
|
959
|
+
resourceId: string;
|
|
960
|
+
workingMemory?: string;
|
|
961
|
+
metadata?: Record<string, unknown>;
|
|
962
|
+
}): Promise<StorageResourceType> {
|
|
963
|
+
try {
|
|
964
|
+
const existingResource = await this.getResourceById({ resourceId });
|
|
965
|
+
|
|
966
|
+
if (!existingResource) {
|
|
967
|
+
const newResource: StorageResourceType = {
|
|
968
|
+
id: resourceId,
|
|
969
|
+
workingMemory,
|
|
970
|
+
metadata: metadata || {},
|
|
971
|
+
createdAt: new Date(),
|
|
972
|
+
updatedAt: new Date(),
|
|
973
|
+
};
|
|
974
|
+
return this.saveResource({ resource: newResource });
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
const updatedResource = {
|
|
978
|
+
...existingResource,
|
|
979
|
+
workingMemory: workingMemory !== undefined ? workingMemory : existingResource.workingMemory,
|
|
980
|
+
metadata: {
|
|
981
|
+
...existingResource.metadata,
|
|
982
|
+
...metadata,
|
|
983
|
+
},
|
|
984
|
+
updatedAt: new Date(),
|
|
985
|
+
};
|
|
986
|
+
|
|
987
|
+
const tableName = getTableName({ indexName: TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
|
|
988
|
+
const updates: string[] = [];
|
|
989
|
+
const req = this.pool.request();
|
|
990
|
+
|
|
991
|
+
if (workingMemory !== undefined) {
|
|
992
|
+
updates.push('workingMemory = @workingMemory');
|
|
993
|
+
req.input('workingMemory', workingMemory);
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
if (metadata) {
|
|
997
|
+
updates.push('metadata = @metadata');
|
|
998
|
+
req.input('metadata', JSON.stringify(updatedResource.metadata));
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
updates.push('updatedAt = @updatedAt');
|
|
1002
|
+
req.input('updatedAt', updatedResource.updatedAt.toISOString());
|
|
1003
|
+
|
|
1004
|
+
req.input('id', resourceId);
|
|
1005
|
+
|
|
1006
|
+
await req.query(`UPDATE ${tableName} SET ${updates.join(', ')} WHERE id = @id`);
|
|
1007
|
+
|
|
1008
|
+
return updatedResource;
|
|
1009
|
+
} catch (error) {
|
|
1010
|
+
const mastraError = new MastraError(
|
|
1011
|
+
{
|
|
1012
|
+
id: 'MASTRA_STORAGE_MSSQL_UPDATE_RESOURCE_FAILED',
|
|
1013
|
+
domain: ErrorDomain.STORAGE,
|
|
1014
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1015
|
+
details: { resourceId },
|
|
1016
|
+
},
|
|
1017
|
+
error,
|
|
1018
|
+
);
|
|
1019
|
+
this.logger?.error?.(mastraError.toString());
|
|
1020
|
+
this.logger?.trackException(mastraError);
|
|
1021
|
+
throw mastraError;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
}
|