@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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,46 @@
1
+ # @mastra/pg
2
+
3
+ ## 0.1.0-alpha.2
4
+
5
+ ### Minor Changes
6
+
7
+ - c87eb4e: Combine PostgreSQL packages into `@mastra/pg`.
8
+
9
+ - Move and combine packages to `stores/pg`
10
+ - Reorganize source files into `src/vector` and `src/store`
11
+ - Add deprecation notices to old packages
12
+ - Update documentation and examples
13
+ - No breaking changes in functionality
14
+
15
+ ## 0.1.0-alpha.1
16
+
17
+ ### Major Changes
18
+
19
+ - Combined @mastra/vector-pg and @mastra/store-pg into a single package
20
+ - Unified configuration and connection handling
21
+ - Updated documentation to cover both vector and storage capabilities
22
+
23
+ ### Previous Changes from @mastra/vector-pg
24
+
25
+ #### 0.1.0-alpha.26
26
+
27
+ - Updated dependencies [4d4f6b6]
28
+ - @mastra/core@0.2.0-alpha.92
29
+
30
+ #### 0.1.0-alpha.25
31
+
32
+ - a10b7a3: Implemented new filtering for vectorQueryTool and updated docs
33
+ - Updated dependencies [d7d465a, 2017553, a10b7a3, 16e5b04]
34
+ - @mastra/core@0.2.0-alpha.91
35
+
36
+ ### Previous Changes from @mastra/store-pg
37
+
38
+ #### 0.0.0-alpha.11
39
+
40
+ - Updated dependencies [4d4f6b6]
41
+ - @mastra/core@0.2.0-alpha.92
42
+
43
+ #### 0.0.0-alpha.10
44
+
45
+ - Updated dependencies [d7d465a, 2017553, a10b7a3, 16e5b04]
46
+ - @mastra/core@0.2.0-alpha.91
package/LICENSE ADDED
@@ -0,0 +1,44 @@
1
+ Elastic License 2.0 (ELv2)
2
+
3
+ **Acceptance**
4
+ By using the software, you agree to all of the terms and conditions below.
5
+
6
+ **Copyright License**
7
+ The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below
8
+
9
+ **Limitations**
10
+ You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
11
+
12
+ You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
13
+
14
+ You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
15
+
16
+ **Patents**
17
+ The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
18
+
19
+ **Notices**
20
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
21
+
22
+ If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
23
+
24
+ **No Other Rights**
25
+ These terms do not imply any licenses other than those expressly granted in these terms.
26
+
27
+ **Termination**
28
+ If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
29
+
30
+ **No Liability**
31
+ As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
32
+
33
+ **Definitions**
34
+ The _licensor_ is the entity offering these terms, and the _software_ is the software the licensor makes available under these terms, including any portion of it.
35
+
36
+ _you_ refers to the individual or entity agreeing to these terms.
37
+
38
+ _your company_ is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. _control_ means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
39
+
40
+ _your licenses_ are all the licenses granted to you for the software under these terms.
41
+
42
+ _use_ means anything you do with the software requiring one of your licenses.
43
+
44
+ _trademark_ means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # @mastra/pg
2
+
3
+ PostgreSQL implementation for Mastra, providing both vector similarity search (using pgvector) and general storage capabilities with connection pooling and transaction support.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @mastra/pg
9
+ ```
10
+
11
+ ## Prerequisites
12
+
13
+ - PostgreSQL server with pgvector extension installed (if using vector store)
14
+ - PostgreSQL 11 or higher
15
+
16
+ ## Usage
17
+
18
+ ### Vector Store
19
+
20
+ ```typescript
21
+ import { PgVector } from '@mastra/pg';
22
+
23
+ const vectorStore = new PgVector('postgresql://user:pass@localhost:5432/db');
24
+
25
+ // Create a new table with vector support
26
+ await vectorStore.createIndex('my_vectors', 1536, 'cosine');
27
+
28
+ // Add vectors
29
+ const ids = await vectorStore.upsert(
30
+ 'my_vectors',
31
+ [[0.1, 0.2, ...], [0.3, 0.4, ...]],
32
+ [{ text: 'doc1' }, { text: 'doc2' }]
33
+ );
34
+
35
+ // Query vectors
36
+ const results = await vectorStore.query(
37
+ 'my_vectors',
38
+ [0.1, 0.2, ...],
39
+ 10, // topK
40
+ { text: 'doc1' }, // filter
41
+ false, // includeVector
42
+ 0.5 // minScore
43
+ );
44
+
45
+ // Clean up
46
+ await vectorStore.disconnect();
47
+ ```
48
+
49
+ ### Storage
50
+
51
+ ```typescript
52
+ import { PostgresStore } from '@mastra/pg';
53
+
54
+ const store = new PostgresStore({
55
+ host: 'localhost',
56
+ port: 5432,
57
+ database: 'mastra',
58
+ user: 'postgres',
59
+ password: 'postgres'
60
+ });
61
+
62
+ // Create a thread
63
+ await store.saveThread({
64
+ id: 'thread-123',
65
+ resourceId: 'resource-456',
66
+ title: 'My Thread',
67
+ metadata: { key: 'value' }
68
+ });
69
+
70
+ // Add messages to thread
71
+ await store.saveMessages([{
72
+ id: 'msg-789',
73
+ threadId: 'thread-123',
74
+ role: 'user',
75
+ type: 'text',
76
+ content: [{ type: 'text', text: 'Hello' }]
77
+ }]);
78
+
79
+ // Query threads and messages
80
+ const savedThread = await store.getThread('thread-123');
81
+ const messages = await store.getMessages('thread-123');
82
+ ```
83
+
84
+ ## Configuration
85
+
86
+ The PostgreSQL store can be initialized with either:
87
+
88
+ - `connectionString`: PostgreSQL connection string (for vector store)
89
+ - Configuration object with host, port, database, user, and password (for storage)
90
+
91
+ Connection pool settings:
92
+
93
+ - Maximum connections: 20
94
+ - Idle timeout: 30 seconds
95
+ - Connection timeout: 2 seconds
96
+
97
+ ## Features
98
+
99
+ ### Vector Store Features
100
+ - Vector similarity search with cosine, euclidean, and dot product metrics
101
+ - Advanced metadata filtering with MongoDB-like query syntax
102
+ - Minimum score threshold for queries
103
+ - Automatic UUID generation for vectors
104
+ - Table management (create, list, describe, delete, truncate)
105
+ - Uses pgvector's IVFFLAT indexing with 100 lists
106
+
107
+ ### Storage Features
108
+ - Thread and message storage with JSON support
109
+ - Atomic transactions for data consistency
110
+ - Efficient batch operations
111
+ - Rich metadata support
112
+ - Timestamp tracking
113
+ - Cascading deletes
114
+
115
+ ## Supported Filter Operators
116
+
117
+ The following filter operators are supported for metadata queries:
118
+
119
+ - Comparison: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`
120
+ - Logical: `$and`, `$or`
121
+ - Array: `$in`, `$nin`
122
+ - Text: `$regex`, `$like`
123
+
124
+ Example filter:
125
+
126
+ ```typescript
127
+ {
128
+ $and: [{ age: { $gt: 25 } }, { tags: { $in: ['tag1', 'tag2'] } }];
129
+ }
130
+ ```
131
+
132
+ ## Vector Store Methods
133
+
134
+ - `createIndex(indexName, dimension, metric?)`: Create a new table with vector support
135
+ - `upsert(indexName, vectors, metadata?, ids?)`: Add or update vectors
136
+ - `query(indexName, queryVector, topK?, filter?, includeVector?, minScore?)`: Search for similar vectors
137
+ - `listIndexes()`: List all vector-enabled tables
138
+ - `describeIndex(indexName)`: Get table statistics
139
+ - `deleteIndex(indexName)`: Delete a table
140
+ - `truncateIndex(indexName)`: Remove all data from a table
141
+ - `disconnect()`: Close all database connections
142
+
143
+ ## Storage Methods
144
+
145
+ - `saveThread(thread)`: Create or update a thread
146
+ - `getThread(threadId)`: Get a thread by ID
147
+ - `deleteThread(threadId)`: Delete a thread and its messages
148
+ - `saveMessages(messages)`: Save multiple messages in a transaction
149
+ - `getMessages(threadId)`: Get all messages for a thread
150
+ - `deleteMessages(messageIds)`: Delete specific messages
151
+
152
+ ## Related Links
153
+
154
+ - [pgvector Documentation](https://github.com/pgvector/pgvector)
155
+ - [PostgreSQL Documentation](https://www.postgresql.org/docs/)
@@ -0,0 +1,82 @@
1
+ import { Filter } from '@mastra/core/filter';
2
+ import { MastraVector, QueryResult, IndexStats } from '@mastra/core/vector';
3
+ import { StorageThreadType, MessageType } from '@mastra/core/memory';
4
+ import { MastraStorage, TABLE_NAMES, StorageColumn, StorageGetMessagesArg } from '@mastra/core/storage';
5
+ import { WorkflowRunState } from '@mastra/core/workflows';
6
+
7
+ declare class PgVector extends MastraVector {
8
+ private pool;
9
+ constructor(connectionString: string);
10
+ transformFilter(filter?: Filter): Filter;
11
+ query(indexName: string, queryVector: number[], topK?: number, filter?: Filter, includeVector?: boolean, minScore?: number): Promise<QueryResult[]>;
12
+ upsert(indexName: string, vectors: number[][], metadata?: Record<string, any>[], ids?: string[]): Promise<string[]>;
13
+ createIndex(indexName: string, dimension: number, metric?: 'cosine' | 'euclidean' | 'dotproduct'): Promise<void>;
14
+ listIndexes(): Promise<string[]>;
15
+ describeIndex(indexName: string): Promise<IndexStats>;
16
+ deleteIndex(indexName: string): Promise<void>;
17
+ truncateIndex(indexName: string): Promise<void>;
18
+ disconnect(): Promise<void>;
19
+ }
20
+
21
+ type PostgresConfig = {
22
+ host: string;
23
+ port: number;
24
+ database: string;
25
+ user: string;
26
+ password: string;
27
+ } | {
28
+ connectionString: string;
29
+ };
30
+ declare class PostgresStore extends MastraStorage {
31
+ private db;
32
+ private pgp;
33
+ constructor(config: PostgresConfig);
34
+ createTable({ tableName, schema, }: {
35
+ tableName: TABLE_NAMES;
36
+ schema: Record<string, StorageColumn>;
37
+ }): Promise<void>;
38
+ clearTable({ tableName }: {
39
+ tableName: TABLE_NAMES;
40
+ }): Promise<void>;
41
+ insert({ tableName, record }: {
42
+ tableName: TABLE_NAMES;
43
+ record: Record<string, any>;
44
+ }): Promise<void>;
45
+ load<R>({ tableName, keys }: {
46
+ tableName: TABLE_NAMES;
47
+ keys: Record<string, string>;
48
+ }): Promise<R | null>;
49
+ getThreadById({ threadId }: {
50
+ threadId: string;
51
+ }): Promise<StorageThreadType | null>;
52
+ getThreadsByResourceId({ resourceId }: {
53
+ resourceId: string;
54
+ }): Promise<StorageThreadType[]>;
55
+ saveThread({ thread }: {
56
+ thread: StorageThreadType;
57
+ }): Promise<StorageThreadType>;
58
+ updateThread({ id, title, metadata, }: {
59
+ id: string;
60
+ title: string;
61
+ metadata: Record<string, unknown>;
62
+ }): Promise<StorageThreadType>;
63
+ deleteThread({ threadId }: {
64
+ threadId: string;
65
+ }): Promise<void>;
66
+ getMessages<T = unknown>({ threadId, selectBy }: StorageGetMessagesArg): Promise<T>;
67
+ saveMessages({ messages }: {
68
+ messages: MessageType[];
69
+ }): Promise<MessageType[]>;
70
+ persistWorkflowSnapshot({ workflowName, runId, snapshot, }: {
71
+ workflowName: string;
72
+ runId: string;
73
+ snapshot: WorkflowRunState;
74
+ }): Promise<void>;
75
+ loadWorkflowSnapshot({ workflowName, runId, }: {
76
+ workflowName: string;
77
+ runId: string;
78
+ }): Promise<WorkflowRunState | null>;
79
+ close(): Promise<void>;
80
+ }
81
+
82
+ export { PgVector, type PostgresConfig, PostgresStore };