@mastra/pg 0.1.0-alpha.2

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,14 @@
1
+ services:
2
+ db:
3
+ image: pgvector/pgvector:pg16
4
+ container_name: 'pg-test-db'
5
+ ports:
6
+ - '5434:5432'
7
+ environment:
8
+ POSTGRES_USER: ${POSTGRES_USER:-postgres}
9
+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
10
+ POSTGRES_DB: ${POSTGRES_DB:-mastra}
11
+ volumes:
12
+ - pgdata:/var/lib/postgresql/data
13
+ volumes:
14
+ pgdata:
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@mastra/pg",
3
+ "version": "0.1.0-alpha.2",
4
+ "description": "Postgres provider for Mastra - includes both vector and db storage capabilities",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "dependencies": {
18
+ "pg": "^8.13.1",
19
+ "pg-promise": "^11.5.4",
20
+ "@mastra/core": "^0.2.0-alpha.92"
21
+ },
22
+ "devDependencies": {
23
+ "@tsconfig/recommended": "^1.0.7",
24
+ "@types/node": "^22.9.0",
25
+ "@types/pg": "^8.11.10",
26
+ "tsup": "^8.0.1",
27
+ "vitest": "^3.0.4"
28
+ },
29
+ "scripts": {
30
+ "build": "tsup-node src/index.ts --format esm --dts --clean --treeshake",
31
+ "dev": "tsup-node src/index.ts --format esm --dts --clean --treeshake --watch",
32
+ "pretest": "docker compose up -d && (for i in $(seq 1 30); do docker compose exec -T db pg_isready -U postgres && break || (sleep 1; [ $i -eq 30 ] && exit 1); done)",
33
+ "test": "vitest run",
34
+ "posttest": "docker compose down -v",
35
+ "pretest:watch": "docker compose up -d",
36
+ "test:watch": "vitest watch",
37
+ "posttest:watch": "docker compose down -v"
38
+ }
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './vector';
2
+ export * from './storage';
@@ -0,0 +1,379 @@
1
+ import { WorkflowRunState } from '@mastra/core/workflows';
2
+ import { randomUUID } from 'crypto';
3
+ import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
4
+
5
+ import { PostgresStore, type PostgresConfig } from '.';
6
+
7
+ const TEST_CONFIG: PostgresConfig = {
8
+ host: process.env.POSTGRES_HOST || 'localhost',
9
+ port: Number(process.env.POSTGRES_PORT) || 5434,
10
+ database: process.env.POSTGRES_DB || 'postgres',
11
+ user: process.env.POSTGRES_USER || 'postgres',
12
+ password: process.env.POSTGRES_PASSWORD || 'postgres',
13
+ };
14
+
15
+ // Sample test data factory functions
16
+ const createSampleThread = () => ({
17
+ id: `thread-${randomUUID()}`,
18
+ resourceId: `resource-${randomUUID()}`,
19
+ title: 'Test Thread',
20
+ createdAt: new Date(),
21
+ updatedAt: new Date(),
22
+ metadata: { key: 'value' },
23
+ });
24
+
25
+ const createSampleMessage = (threadId: string) =>
26
+ ({
27
+ id: `msg-${randomUUID()}`,
28
+ role: 'user',
29
+ type: 'text',
30
+ threadId,
31
+ content: [{ type: 'text', text: 'Hello' }],
32
+ createdAt: new Date(),
33
+ }) as any;
34
+
35
+ describe('PostgresStore', () => {
36
+ let store: PostgresStore;
37
+
38
+ beforeAll(async () => {
39
+ store = new PostgresStore(TEST_CONFIG);
40
+ await store.init();
41
+ });
42
+
43
+ beforeEach(async () => {
44
+ // Clear tables before each test
45
+ await store.clearTable({ tableName: 'mastra_workflow_snapshot' });
46
+ await store.clearTable({ tableName: 'mastra_messages' });
47
+ await store.clearTable({ tableName: 'mastra_threads' });
48
+ });
49
+
50
+ describe('Thread Operations', () => {
51
+ it('should create and retrieve a thread', async () => {
52
+ const thread = createSampleThread();
53
+ console.log('Saving thread:', thread);
54
+
55
+ // Save thread
56
+ const savedThread = await store.__saveThread({ thread });
57
+ expect(savedThread).toEqual(thread);
58
+
59
+ // Retrieve thread
60
+ const retrievedThread = await store.__getThreadById({ threadId: thread.id });
61
+ expect(retrievedThread?.title).toEqual(thread.title);
62
+ });
63
+
64
+ it('should return null for non-existent thread', async () => {
65
+ const result = await store.__getThreadById({ threadId: 'non-existent' });
66
+ expect(result).toBeNull();
67
+ });
68
+
69
+ it('should get threads by resource ID', async () => {
70
+ const thread1 = createSampleThread();
71
+ const thread2 = { ...createSampleThread(), resourceId: thread1.resourceId };
72
+
73
+ await store.__saveThread({ thread: thread1 });
74
+ await store.__saveThread({ thread: thread2 });
75
+
76
+ const threads = await store.__getThreadsByResourceId({ resourceId: thread1.resourceId });
77
+ expect(threads).toHaveLength(2);
78
+ expect(threads.map(t => t.id)).toEqual(expect.arrayContaining([thread1.id, thread2.id]));
79
+ });
80
+
81
+ it('should update thread title and metadata', async () => {
82
+ const thread = createSampleThread();
83
+ console.log('Saving thread:', thread);
84
+ await store.__saveThread({ thread });
85
+
86
+ const newMetadata = { newKey: 'newValue' };
87
+ const updatedThread = await store.__updateThread({
88
+ id: thread.id,
89
+ title: 'Updated Title',
90
+ metadata: newMetadata,
91
+ });
92
+
93
+ expect(updatedThread.title).toBe('Updated Title');
94
+ expect(updatedThread.metadata).toEqual({
95
+ ...thread.metadata,
96
+ ...newMetadata,
97
+ });
98
+
99
+ // Verify persistence
100
+ const retrievedThread = await store.__getThreadById({ threadId: thread.id });
101
+ expect(retrievedThread).toEqual(updatedThread);
102
+ });
103
+
104
+ it('should delete thread and its messages', async () => {
105
+ const thread = createSampleThread();
106
+ await store.__saveThread({ thread });
107
+
108
+ // Add some messages
109
+ const messages = [createSampleMessage(thread.id), createSampleMessage(thread.id)];
110
+ await store.__saveMessages({ messages });
111
+
112
+ await store.__deleteThread({ threadId: thread.id });
113
+
114
+ const retrievedThread = await store.__getThreadById({ threadId: thread.id });
115
+ expect(retrievedThread).toBeNull();
116
+
117
+ // Verify messages were also deleted
118
+ const retrievedMessages = await store.__getMessages({ threadId: thread.id });
119
+ expect(retrievedMessages).toHaveLength(0);
120
+ });
121
+ });
122
+
123
+ describe('Message Operations', () => {
124
+ it('should save and retrieve messages', async () => {
125
+ const thread = createSampleThread();
126
+ await store.__saveThread({ thread });
127
+
128
+ const messages = [createSampleMessage(thread.id), createSampleMessage(thread.id)];
129
+
130
+ // Save messages
131
+ const savedMessages = await store.__saveMessages({ messages });
132
+ expect(savedMessages).toEqual(messages);
133
+
134
+ // Retrieve messages
135
+ const retrievedMessages = await store.__getMessages({ threadId: thread.id });
136
+ expect(retrievedMessages).toHaveLength(2);
137
+ expect(retrievedMessages).toEqual(expect.arrayContaining(messages));
138
+ });
139
+
140
+ it('should handle empty message array', async () => {
141
+ const result = await store.__saveMessages({ messages: [] });
142
+ expect(result).toEqual([]);
143
+ });
144
+
145
+ it('should maintain message order', async () => {
146
+ const thread = createSampleThread();
147
+ await store.__saveThread({ thread });
148
+
149
+ const messages = [
150
+ { ...createSampleMessage(thread.id), content: [{ type: 'text', text: 'First' }] },
151
+ { ...createSampleMessage(thread.id), content: [{ type: 'text', text: 'Second' }] },
152
+ { ...createSampleMessage(thread.id), content: [{ type: 'text', text: 'Third' }] },
153
+ ];
154
+
155
+ await store.__saveMessages({ messages });
156
+
157
+ const retrievedMessages = await store.__getMessages({ threadId: thread.id });
158
+ expect(retrievedMessages).toHaveLength(3);
159
+
160
+ // Verify order is maintained
161
+ retrievedMessages.forEach((msg, idx) => {
162
+ expect(msg.content[0].text).toBe(messages[idx].content[0].text);
163
+ });
164
+ });
165
+
166
+ it('should rollback on error during message save', async () => {
167
+ const thread = createSampleThread();
168
+ await store.__saveThread({ thread });
169
+
170
+ const messages = [
171
+ createSampleMessage(thread.id),
172
+ { ...createSampleMessage(thread.id), id: null }, // This will cause an error
173
+ ];
174
+
175
+ await expect(store.__saveMessages({ messages })).rejects.toThrow();
176
+
177
+ // Verify no messages were saved
178
+ const savedMessages = await store.__getMessages({ threadId: thread.id });
179
+ expect(savedMessages).toHaveLength(0);
180
+ });
181
+ });
182
+
183
+ describe('Edge Cases and Error Handling', () => {
184
+ it('should handle large metadata objects', async () => {
185
+ const thread = createSampleThread();
186
+ const largeMetadata = {
187
+ ...thread.metadata,
188
+ largeArray: Array.from({ length: 1000 }, (_, i) => ({ index: i, data: 'test'.repeat(100) })),
189
+ };
190
+
191
+ const threadWithLargeMetadata = {
192
+ ...thread,
193
+ metadata: largeMetadata,
194
+ };
195
+
196
+ await store.__saveThread({ thread: threadWithLargeMetadata });
197
+ const retrieved = await store.__getThreadById({ threadId: thread.id });
198
+
199
+ expect(retrieved?.metadata).toEqual(largeMetadata);
200
+ });
201
+
202
+ it('should handle special characters in thread titles', async () => {
203
+ const thread = {
204
+ ...createSampleThread(),
205
+ title: 'Special \'quotes\' and "double quotes" and emoji 🎉',
206
+ };
207
+
208
+ await store.__saveThread({ thread });
209
+ const retrieved = await store.__getThreadById({ threadId: thread.id });
210
+
211
+ expect(retrieved?.title).toBe(thread.title);
212
+ });
213
+
214
+ it('should handle concurrent thread updates', async () => {
215
+ const thread = createSampleThread();
216
+ await store.__saveThread({ thread });
217
+
218
+ // Perform multiple updates concurrently
219
+ const updates = Array.from({ length: 5 }, (_, i) =>
220
+ store.__updateThread({
221
+ id: thread.id,
222
+ title: `Update ${i}`,
223
+ metadata: { update: i },
224
+ }),
225
+ );
226
+
227
+ await expect(Promise.all(updates)).resolves.toBeDefined();
228
+
229
+ // Verify final state
230
+ const finalThread = await store.__getThreadById({ threadId: thread.id });
231
+ expect(finalThread).toBeDefined();
232
+ });
233
+ });
234
+
235
+ describe('Workflow Snapshots', () => {
236
+ it('should persist and load workflow snapshots', async () => {
237
+ const workflowName = 'test-workflow';
238
+ const runId = `run-${randomUUID()}`;
239
+ const snapshot = {
240
+ status: 'running',
241
+ context: {
242
+ stepResults: {},
243
+ attempts: {},
244
+ triggerData: { type: 'manual' },
245
+ },
246
+ } as any;
247
+
248
+ await store.persistWorkflowSnapshot({
249
+ workflowName,
250
+ runId,
251
+ snapshot,
252
+ });
253
+
254
+ const loadedSnapshot = await store.loadWorkflowSnapshot({
255
+ workflowName,
256
+ runId,
257
+ });
258
+
259
+ expect(loadedSnapshot).toEqual(snapshot);
260
+ });
261
+
262
+ it('should return null for non-existent workflow snapshot', async () => {
263
+ const result = await store.loadWorkflowSnapshot({
264
+ workflowName: 'non-existent',
265
+ runId: 'non-existent',
266
+ });
267
+
268
+ expect(result).toBeNull();
269
+ });
270
+
271
+ it('should update existing workflow snapshot', async () => {
272
+ const workflowName = 'test-workflow';
273
+ const runId = `run-${randomUUID()}`;
274
+ const initialSnapshot = {
275
+ status: 'running',
276
+ context: {
277
+ stepResults: {},
278
+ attempts: {},
279
+ triggerData: { type: 'manual' },
280
+ },
281
+ };
282
+
283
+ await store.persistWorkflowSnapshot({
284
+ workflowName,
285
+ runId,
286
+ snapshot: initialSnapshot as any,
287
+ });
288
+
289
+ const updatedSnapshot = {
290
+ status: 'completed',
291
+ context: {
292
+ stepResults: {
293
+ 'step-1': { status: 'success', result: { data: 'test' } },
294
+ },
295
+ attempts: { 'step-1': 1 },
296
+ triggerData: { type: 'manual' },
297
+ },
298
+ } as any;
299
+
300
+ await store.persistWorkflowSnapshot({
301
+ workflowName,
302
+ runId,
303
+ snapshot: updatedSnapshot,
304
+ });
305
+
306
+ const loadedSnapshot = await store.loadWorkflowSnapshot({
307
+ workflowName,
308
+ runId,
309
+ });
310
+
311
+ expect(loadedSnapshot).toEqual(updatedSnapshot);
312
+ });
313
+
314
+ it('should handle complex workflow state', async () => {
315
+ const workflowName = 'complex-workflow';
316
+ const runId = `run-${randomUUID()}`;
317
+ const complexSnapshot = {
318
+ value: { currentState: 'running' },
319
+ context: {
320
+ stepResults: {
321
+ 'step-1': {
322
+ status: 'success',
323
+ result: {
324
+ nestedData: {
325
+ array: [1, 2, 3],
326
+ object: { key: 'value' },
327
+ date: new Date().toISOString(),
328
+ },
329
+ },
330
+ },
331
+ 'step-2': {
332
+ status: 'waiting',
333
+ dependencies: ['step-3', 'step-4'],
334
+ },
335
+ },
336
+ attempts: { 'step-1': 1, 'step-2': 0 },
337
+ triggerData: {
338
+ type: 'scheduled',
339
+ metadata: {
340
+ schedule: '0 0 * * *',
341
+ timezone: 'UTC',
342
+ },
343
+ },
344
+ },
345
+ activePaths: [
346
+ {
347
+ stepPath: ['step-1'],
348
+ stepId: 'step-1',
349
+ status: 'success',
350
+ },
351
+ {
352
+ stepPath: ['step-2'],
353
+ stepId: 'step-2',
354
+ status: 'waiting',
355
+ },
356
+ ],
357
+ runId: runId,
358
+ timestamp: Date.now(),
359
+ };
360
+
361
+ await store.persistWorkflowSnapshot({
362
+ workflowName,
363
+ runId,
364
+ snapshot: complexSnapshot as WorkflowRunState,
365
+ });
366
+
367
+ const loadedSnapshot = await store.loadWorkflowSnapshot({
368
+ workflowName,
369
+ runId,
370
+ });
371
+
372
+ expect(loadedSnapshot).toEqual(complexSnapshot);
373
+ });
374
+ });
375
+
376
+ afterAll(async () => {
377
+ await store.close();
378
+ });
379
+ });