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