@mastra/pg 0.0.0-commonjs-20250227130920

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.
@@ -0,0 +1,592 @@
1
+ import type { MessageType, StorageThreadType } from '@mastra/core/memory';
2
+ import { MastraStorage } from '@mastra/core/storage';
3
+ import type { EvalRow, StorageColumn, StorageGetMessagesArg, TABLE_NAMES } from '@mastra/core/storage';
4
+ import type { WorkflowRunState } from '@mastra/core/workflows';
5
+ import pgPromise from 'pg-promise';
6
+
7
+ export type PostgresConfig =
8
+ | {
9
+ host: string;
10
+ port: number;
11
+ database: string;
12
+ user: string;
13
+ password: string;
14
+ }
15
+ | {
16
+ connectionString: string;
17
+ };
18
+
19
+ export class PostgresStore extends MastraStorage {
20
+ private db: pgPromise.IDatabase<{}>;
21
+ private pgp: pgPromise.IMain;
22
+
23
+ constructor(config: PostgresConfig) {
24
+ super({ name: 'PostgresStore' });
25
+ this.pgp = pgPromise();
26
+ this.db = this.pgp(
27
+ `connectionString` in config
28
+ ? { connectionString: config.connectionString }
29
+ : {
30
+ host: config.host,
31
+ port: config.port,
32
+ database: config.database,
33
+ user: config.user,
34
+ password: config.password,
35
+ },
36
+ );
37
+ }
38
+
39
+ getEvalsByAgentName(_agentName: string, _type?: 'test' | 'live'): Promise<EvalRow[]> {
40
+ throw new Error('Method not implemented.');
41
+ }
42
+
43
+ async batchInsert({ tableName, records }: { tableName: TABLE_NAMES; records: Record<string, any>[] }): Promise<void> {
44
+ try {
45
+ await this.db.query('BEGIN');
46
+ for (const record of records) {
47
+ await this.insert({ tableName, record });
48
+ }
49
+ await this.db.query('COMMIT');
50
+ } catch (error) {
51
+ console.error(`Error inserting into ${tableName}:`, error);
52
+ await this.db.query('ROLLBACK');
53
+ throw error;
54
+ }
55
+ }
56
+
57
+ async getTraces({
58
+ name,
59
+ scope,
60
+ page,
61
+ perPage,
62
+ attributes,
63
+ }: {
64
+ name?: string;
65
+ scope?: string;
66
+ page: number;
67
+ perPage: number;
68
+ attributes?: Record<string, string>;
69
+ }): Promise<any[]> {
70
+ let idx = 1;
71
+ const limit = perPage;
72
+ const offset = page * perPage;
73
+
74
+ const args: (string | number)[] = [];
75
+
76
+ const conditions: string[] = [];
77
+ if (name) {
78
+ conditions.push(`name LIKE CONCAT(\$${idx++}, '%')`);
79
+ }
80
+ if (scope) {
81
+ conditions.push(`scope = \$${idx++}`);
82
+ }
83
+ if (attributes) {
84
+ Object.keys(attributes).forEach(key => {
85
+ conditions.push(`attributes->>'${key}' = \$${idx++}`);
86
+ });
87
+ }
88
+
89
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
90
+
91
+ if (name) {
92
+ args.push(name);
93
+ }
94
+
95
+ if (scope) {
96
+ args.push(scope);
97
+ }
98
+
99
+ if (attributes) {
100
+ for (const [_key, value] of Object.entries(attributes)) {
101
+ args.push(value);
102
+ }
103
+ }
104
+
105
+ console.log(
106
+ 'QUERY',
107
+ `SELECT * FROM ${MastraStorage.TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
108
+ args,
109
+ );
110
+
111
+ const result = await this.db.manyOrNone<{
112
+ id: string;
113
+ parentSpanId: string;
114
+ traceId: string;
115
+ name: string;
116
+ scope: string;
117
+ kind: string;
118
+ events: any[];
119
+ links: any[];
120
+ status: any;
121
+ attributes: Record<string, any>;
122
+ startTime: string;
123
+ endTime: string;
124
+ other: any;
125
+ createdAt: string;
126
+ }>(
127
+ `SELECT * FROM ${MastraStorage.TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
128
+ args,
129
+ );
130
+
131
+ if (!result) {
132
+ return [];
133
+ }
134
+
135
+ return result.map(row => ({
136
+ id: row.id,
137
+ parentSpanId: row.parentSpanId,
138
+ traceId: row.traceId,
139
+ name: row.name,
140
+ scope: row.scope,
141
+ kind: row.kind,
142
+ status: row.status,
143
+ events: row.events,
144
+ links: row.links,
145
+ attributes: row.attributes,
146
+ startTime: row.startTime,
147
+ endTime: row.endTime,
148
+ other: row.other,
149
+ createdAt: row.createdAt,
150
+ })) as any;
151
+ }
152
+
153
+ async createTable({
154
+ tableName,
155
+ schema,
156
+ }: {
157
+ tableName: TABLE_NAMES;
158
+ schema: Record<string, StorageColumn>;
159
+ }): Promise<void> {
160
+ try {
161
+ const columns = Object.entries(schema)
162
+ .map(([name, def]) => {
163
+ const constraints = [];
164
+ if (def.primaryKey) constraints.push('PRIMARY KEY');
165
+ if (!def.nullable) constraints.push('NOT NULL');
166
+ return `"${name}" ${def.type.toUpperCase()} ${constraints.join(' ')}`;
167
+ })
168
+ .join(',\n');
169
+
170
+ const sql = `
171
+ CREATE TABLE IF NOT EXISTS ${tableName} (
172
+ ${columns}
173
+ );
174
+ ${
175
+ tableName === MastraStorage.TABLE_WORKFLOW_SNAPSHOT
176
+ ? `
177
+ DO $$ BEGIN
178
+ IF NOT EXISTS (
179
+ SELECT 1 FROM pg_constraint WHERE conname = 'mastra_workflow_snapshot_workflow_name_run_id_key'
180
+ ) THEN
181
+ ALTER TABLE ${tableName}
182
+ ADD CONSTRAINT mastra_workflow_snapshot_workflow_name_run_id_key
183
+ UNIQUE (workflow_name, run_id);
184
+ END IF;
185
+ END $$;
186
+ `
187
+ : ''
188
+ }
189
+ `;
190
+
191
+ await this.db.none(sql);
192
+ } catch (error) {
193
+ console.error(`Error creating table ${tableName}:`, error);
194
+ throw error;
195
+ }
196
+ }
197
+
198
+ async clearTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {
199
+ try {
200
+ await this.db.none(`TRUNCATE TABLE ${tableName} CASCADE`);
201
+ } catch (error) {
202
+ console.error(`Error clearing table ${tableName}:`, error);
203
+ throw error;
204
+ }
205
+ }
206
+
207
+ async insert({ tableName, record }: { tableName: TABLE_NAMES; record: Record<string, any> }): Promise<void> {
208
+ try {
209
+ const columns = Object.keys(record);
210
+ const values = Object.values(record);
211
+ const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
212
+
213
+ await this.db.none(
214
+ `INSERT INTO ${tableName} (${columns.map(c => `"${c}"`).join(', ')}) VALUES (${placeholders})`,
215
+ values,
216
+ );
217
+ } catch (error) {
218
+ console.error(`Error inserting into ${tableName}:`, error);
219
+ throw error;
220
+ }
221
+ }
222
+
223
+ async load<R>({ tableName, keys }: { tableName: TABLE_NAMES; keys: Record<string, string> }): Promise<R | null> {
224
+ try {
225
+ const keyEntries = Object.entries(keys);
226
+ const conditions = keyEntries.map(([key], index) => `"${key}" = $${index + 1}`).join(' AND ');
227
+ const values = keyEntries.map(([_, value]) => value);
228
+
229
+ const result = await this.db.oneOrNone<R>(`SELECT * FROM ${tableName} WHERE ${conditions}`, values);
230
+
231
+ if (!result) {
232
+ return null;
233
+ }
234
+
235
+ // If this is a workflow snapshot, parse the snapshot field
236
+ if (tableName === MastraStorage.TABLE_WORKFLOW_SNAPSHOT) {
237
+ const snapshot = result as any;
238
+ if (typeof snapshot.snapshot === 'string') {
239
+ snapshot.snapshot = JSON.parse(snapshot.snapshot);
240
+ }
241
+ return snapshot;
242
+ }
243
+
244
+ return result;
245
+ } catch (error) {
246
+ console.error(`Error loading from ${tableName}:`, error);
247
+ throw error;
248
+ }
249
+ }
250
+
251
+ async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {
252
+ try {
253
+ const thread = await this.db.oneOrNone<StorageThreadType>(
254
+ `SELECT
255
+ id,
256
+ "resourceId",
257
+ title,
258
+ metadata,
259
+ "createdAt",
260
+ "updatedAt"
261
+ FROM "${MastraStorage.TABLE_THREADS}"
262
+ WHERE id = $1`,
263
+ [threadId],
264
+ );
265
+
266
+ if (!thread) {
267
+ return null;
268
+ }
269
+
270
+ return {
271
+ ...thread,
272
+ metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
273
+ createdAt: thread.createdAt,
274
+ updatedAt: thread.updatedAt,
275
+ };
276
+ } catch (error) {
277
+ console.error(`Error getting thread ${threadId}:`, error);
278
+ throw error;
279
+ }
280
+ }
281
+
282
+ async getThreadsByResourceId({ resourceId }: { resourceId: string }): Promise<StorageThreadType[]> {
283
+ try {
284
+ const threads = await this.db.manyOrNone<StorageThreadType>(
285
+ `SELECT
286
+ id,
287
+ "resourceId",
288
+ title,
289
+ metadata,
290
+ "createdAt",
291
+ "updatedAt"
292
+ FROM "${MastraStorage.TABLE_THREADS}"
293
+ WHERE "resourceId" = $1`,
294
+ [resourceId],
295
+ );
296
+
297
+ return threads.map(thread => ({
298
+ ...thread,
299
+ metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
300
+ createdAt: thread.createdAt,
301
+ updatedAt: thread.updatedAt,
302
+ }));
303
+ } catch (error) {
304
+ console.error(`Error getting threads for resource ${resourceId}:`, error);
305
+ throw error;
306
+ }
307
+ }
308
+
309
+ async saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType> {
310
+ try {
311
+ await this.db.none(
312
+ `INSERT INTO "${MastraStorage.TABLE_THREADS}" (
313
+ id,
314
+ "resourceId",
315
+ title,
316
+ metadata,
317
+ "createdAt",
318
+ "updatedAt"
319
+ ) VALUES ($1, $2, $3, $4, $5, $6)
320
+ ON CONFLICT (id) DO UPDATE SET
321
+ "resourceId" = EXCLUDED."resourceId",
322
+ title = EXCLUDED.title,
323
+ metadata = EXCLUDED.metadata,
324
+ "createdAt" = EXCLUDED."createdAt",
325
+ "updatedAt" = EXCLUDED."updatedAt"`,
326
+ [
327
+ thread.id,
328
+ thread.resourceId,
329
+ thread.title,
330
+ thread.metadata ? JSON.stringify(thread.metadata) : null,
331
+ thread.createdAt,
332
+ thread.updatedAt,
333
+ ],
334
+ );
335
+
336
+ return thread;
337
+ } catch (error) {
338
+ console.error('Error saving thread:', error);
339
+ throw error;
340
+ }
341
+ }
342
+
343
+ async updateThread({
344
+ id,
345
+ title,
346
+ metadata,
347
+ }: {
348
+ id: string;
349
+ title: string;
350
+ metadata: Record<string, unknown>;
351
+ }): Promise<StorageThreadType> {
352
+ try {
353
+ // First get the existing thread to merge metadata
354
+ const existingThread = await this.getThreadById({ threadId: id });
355
+ if (!existingThread) {
356
+ throw new Error(`Thread ${id} not found`);
357
+ }
358
+
359
+ // Merge the existing metadata with the new metadata
360
+ const mergedMetadata = {
361
+ ...existingThread.metadata,
362
+ ...metadata,
363
+ };
364
+
365
+ const thread = await this.db.one<StorageThreadType>(
366
+ `UPDATE "${MastraStorage.TABLE_THREADS}"
367
+ SET title = $1,
368
+ metadata = $2,
369
+ "updatedAt" = $3
370
+ WHERE id = $4
371
+ RETURNING *`,
372
+ [title, mergedMetadata, new Date().toISOString(), id],
373
+ );
374
+
375
+ return {
376
+ ...thread,
377
+ metadata: typeof thread.metadata === 'string' ? JSON.parse(thread.metadata) : thread.metadata,
378
+ createdAt: thread.createdAt,
379
+ updatedAt: thread.updatedAt,
380
+ };
381
+ } catch (error) {
382
+ console.error('Error updating thread:', error);
383
+ throw error;
384
+ }
385
+ }
386
+
387
+ async deleteThread({ threadId }: { threadId: string }): Promise<void> {
388
+ try {
389
+ await this.db.tx(async t => {
390
+ // First delete all messages associated with this thread
391
+ await t.none(`DELETE FROM "${MastraStorage.TABLE_MESSAGES}" WHERE thread_id = $1`, [threadId]);
392
+
393
+ // Then delete the thread
394
+ await t.none(`DELETE FROM "${MastraStorage.TABLE_THREADS}" WHERE id = $1`, [threadId]);
395
+ });
396
+ } catch (error) {
397
+ console.error('Error deleting thread:', error);
398
+ throw error;
399
+ }
400
+ }
401
+
402
+ async getMessages<T = unknown>({ threadId, selectBy }: StorageGetMessagesArg): Promise<T> {
403
+ try {
404
+ const messages: any[] = [];
405
+ const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
406
+ const include = selectBy?.include || [];
407
+
408
+ if (include.length) {
409
+ const includeResult = await this.db.manyOrNone(
410
+ `
411
+ WITH ordered_messages AS (
412
+ SELECT
413
+ *,
414
+ ROW_NUMBER() OVER (ORDER BY "createdAt") as row_num
415
+ FROM "${MastraStorage.TABLE_MESSAGES}"
416
+ WHERE thread_id = $1
417
+ )
418
+ SELECT DISTINCT ON (m.id)
419
+ m.id,
420
+ m.content,
421
+ m.role,
422
+ m.type,
423
+ m."createdAt",
424
+ m.thread_id AS "threadId"
425
+ FROM ordered_messages m
426
+ WHERE m.id = ANY($2)
427
+ OR EXISTS (
428
+ SELECT 1 FROM ordered_messages target
429
+ WHERE target.id = ANY($2)
430
+ AND (
431
+ -- Get previous messages based on the max withPreviousMessages
432
+ (m.row_num >= target.row_num - $3 AND m.row_num < target.row_num)
433
+ OR
434
+ -- Get next messages based on the max withNextMessages
435
+ (m.row_num <= target.row_num + $4 AND m.row_num > target.row_num)
436
+ )
437
+ )
438
+ ORDER BY m.id, m."createdAt"
439
+ `,
440
+ [
441
+ threadId,
442
+ include.map(i => i.id),
443
+ Math.max(...include.map(i => i.withPreviousMessages || 0)),
444
+ Math.max(...include.map(i => i.withNextMessages || 0)),
445
+ ],
446
+ );
447
+
448
+ messages.push(...includeResult);
449
+ }
450
+
451
+ // Then get the remaining messages, excluding the ids we just fetched
452
+ const result = await this.db.manyOrNone(
453
+ `
454
+ SELECT
455
+ id,
456
+ content,
457
+ role,
458
+ type,
459
+ "createdAt",
460
+ thread_id AS "threadId"
461
+ FROM "${MastraStorage.TABLE_MESSAGES}"
462
+ WHERE thread_id = $1
463
+ AND id != ALL($2)
464
+ ORDER BY "createdAt" DESC
465
+ LIMIT $3
466
+ `,
467
+ [threadId, messages.map(m => m.id), limit],
468
+ );
469
+
470
+ messages.push(...result);
471
+
472
+ // Sort all messages by creation date
473
+ messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
474
+
475
+ // Parse message content
476
+ messages.forEach(message => {
477
+ if (typeof message.content === 'string') {
478
+ try {
479
+ message.content = JSON.parse(message.content);
480
+ } catch {
481
+ // If parsing fails, leave as string
482
+ }
483
+ }
484
+ });
485
+
486
+ return messages as T;
487
+ } catch (error) {
488
+ console.error('Error getting messages:', error);
489
+ throw error;
490
+ }
491
+ }
492
+
493
+ async saveMessages({ messages }: { messages: MessageType[] }): Promise<MessageType[]> {
494
+ if (messages.length === 0) return messages;
495
+
496
+ try {
497
+ const threadId = messages[0]?.threadId;
498
+ if (!threadId) {
499
+ throw new Error('Thread ID is required');
500
+ }
501
+
502
+ // Check if thread exists
503
+ const thread = await this.getThreadById({ threadId });
504
+ if (!thread) {
505
+ throw new Error(`Thread ${threadId} not found`);
506
+ }
507
+
508
+ await this.db.tx(async t => {
509
+ for (const message of messages) {
510
+ await t.none(
511
+ `INSERT INTO "${MastraStorage.TABLE_MESSAGES}" (id, thread_id, content, "createdAt", role, type)
512
+ VALUES ($1, $2, $3, $4, $5, $6)`,
513
+ [
514
+ message.id,
515
+ threadId,
516
+ typeof message.content === 'string' ? message.content : JSON.stringify(message.content),
517
+ message.createdAt || new Date().toISOString(),
518
+ message.role,
519
+ message.type,
520
+ ],
521
+ );
522
+ }
523
+ });
524
+
525
+ return messages;
526
+ } catch (error) {
527
+ console.error('Error saving messages:', error);
528
+ throw error;
529
+ }
530
+ }
531
+
532
+ async persistWorkflowSnapshot({
533
+ workflowName,
534
+ runId,
535
+ snapshot,
536
+ }: {
537
+ workflowName: string;
538
+ runId: string;
539
+ snapshot: WorkflowRunState;
540
+ }): Promise<void> {
541
+ try {
542
+ const now = new Date().toISOString();
543
+ await this.db.none(
544
+ `INSERT INTO "${MastraStorage.TABLE_WORKFLOW_SNAPSHOT}" (
545
+ workflow_name,
546
+ run_id,
547
+ snapshot,
548
+ "createdAt",
549
+ "updatedAt"
550
+ ) VALUES ($1, $2, $3, $4, $5)
551
+ ON CONFLICT (workflow_name, run_id) DO UPDATE
552
+ SET snapshot = EXCLUDED.snapshot,
553
+ "updatedAt" = EXCLUDED."updatedAt"`,
554
+ [workflowName, runId, JSON.stringify(snapshot), now, now],
555
+ );
556
+ } catch (error) {
557
+ console.error('Error persisting workflow snapshot:', error);
558
+ throw error;
559
+ }
560
+ }
561
+
562
+ async loadWorkflowSnapshot({
563
+ workflowName,
564
+ runId,
565
+ }: {
566
+ workflowName: string;
567
+ runId: string;
568
+ }): Promise<WorkflowRunState | null> {
569
+ try {
570
+ const result = await this.load({
571
+ tableName: MastraStorage.TABLE_WORKFLOW_SNAPSHOT,
572
+ keys: {
573
+ workflow_name: workflowName,
574
+ run_id: runId,
575
+ },
576
+ });
577
+
578
+ if (!result) {
579
+ return null;
580
+ }
581
+
582
+ return (result as any).snapshot;
583
+ } catch (error) {
584
+ console.error('Error loading workflow snapshot:', error);
585
+ throw error;
586
+ }
587
+ }
588
+
589
+ async close(): Promise<void> {
590
+ this.pgp.end();
591
+ }
592
+ }