@mastra/pg 1.0.0-beta.11 → 1.0.0-beta.12
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 +80 -0
- package/dist/docs/README.md +36 -0
- package/dist/docs/SKILL.md +37 -0
- package/dist/docs/SOURCE_MAP.json +6 -0
- package/dist/docs/memory/01-storage.md +181 -0
- package/dist/docs/memory/02-working-memory.md +386 -0
- package/dist/docs/memory/03-semantic-recall.md +235 -0
- package/dist/docs/memory/04-reference.md +135 -0
- package/dist/docs/processors/01-reference.md +295 -0
- package/dist/docs/rag/01-overview.md +74 -0
- package/dist/docs/rag/02-vector-databases.md +638 -0
- package/dist/docs/rag/03-retrieval.md +549 -0
- package/dist/docs/rag/04-reference.md +351 -0
- package/dist/docs/storage/01-reference.md +667 -0
- package/dist/docs/tools/01-reference.md +440 -0
- package/dist/docs/vectors/01-reference.md +307 -0
- package/dist/index.cjs +159 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +159 -7
- package/dist/index.js.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +2 -1
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/package.json +9 -8
|
@@ -0,0 +1,667 @@
|
|
|
1
|
+
# Storage API Reference
|
|
2
|
+
|
|
3
|
+
> API reference for storage - 3 entries
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Reference: Storage Composition
|
|
9
|
+
|
|
10
|
+
> Documentation for combining multiple storage backends in Mastra.
|
|
11
|
+
|
|
12
|
+
MastraStorage can compose storage domains from different adapters. Use it when you need different databases for different purposes. For example, use LibSQL for memory and PostgreSQL for workflows.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
MastraStorage is included in `@mastra/core`:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @mastra/core@beta
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
You'll also need to install the storage adapters you want to compose:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install @mastra/pg@beta @mastra/libsql@beta
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Storage Domains
|
|
29
|
+
|
|
30
|
+
Mastra organizes storage into five specialized domains, each handling a specific type of data. Each domain can be backed by a different storage adapter, and domain classes are exported from each storage package.
|
|
31
|
+
|
|
32
|
+
| Domain | Description |
|
|
33
|
+
|--------|-------------|
|
|
34
|
+
| `memory` | Conversation persistence for agents. Stores threads (conversation sessions), messages, resources (user identities), and working memory (persistent context across conversations). |
|
|
35
|
+
| `workflows` | Workflow execution state. When workflows suspend for human input, external events, or scheduled resumption, their state is persisted here to enable resumption after server restarts. |
|
|
36
|
+
| `scores` | Evaluation results from Mastra's evals system. Scores and metrics are persisted here for analysis and comparison over time. |
|
|
37
|
+
| `observability` | Telemetry data including traces and spans. Agent interactions, tool calls, and LLM requests generate spans collected into traces for debugging and performance analysis. |
|
|
38
|
+
| `agents` | Agent configurations for stored agents. Enables agents to be defined and updated at runtime without code deployments. |
|
|
39
|
+
|
|
40
|
+
## Usage
|
|
41
|
+
|
|
42
|
+
### Basic composition
|
|
43
|
+
|
|
44
|
+
Import domain classes directly from each store package and compose them:
|
|
45
|
+
|
|
46
|
+
```typescript
|
|
47
|
+
import { MastraStorage } from "@mastra/core/storage";
|
|
48
|
+
import { WorkflowsPG, ScoresPG } from "@mastra/pg";
|
|
49
|
+
import { MemoryLibSQL } from "@mastra/libsql";
|
|
50
|
+
import { Mastra } from "@mastra/core";
|
|
51
|
+
|
|
52
|
+
const mastra = new Mastra({
|
|
53
|
+
storage: new MastraStorage({
|
|
54
|
+
id: "composite",
|
|
55
|
+
domains: {
|
|
56
|
+
memory: new MemoryLibSQL({ url: "file:./local.db" }),
|
|
57
|
+
workflows: new WorkflowsPG({ connectionString: process.env.DATABASE_URL }),
|
|
58
|
+
scores: new ScoresPG({ connectionString: process.env.DATABASE_URL }),
|
|
59
|
+
},
|
|
60
|
+
}),
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### With a default storage
|
|
65
|
+
|
|
66
|
+
Use `default` to specify a fallback storage, then override specific domains:
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
import { MastraStorage } from "@mastra/core/storage";
|
|
70
|
+
import { PostgresStore } from "@mastra/pg";
|
|
71
|
+
import { MemoryLibSQL } from "@mastra/libsql";
|
|
72
|
+
import { Mastra } from "@mastra/core";
|
|
73
|
+
|
|
74
|
+
const pgStore = new PostgresStore({
|
|
75
|
+
id: "pg",
|
|
76
|
+
connectionString: process.env.DATABASE_URL,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const mastra = new Mastra({
|
|
80
|
+
storage: new MastraStorage({
|
|
81
|
+
id: "composite",
|
|
82
|
+
default: pgStore,
|
|
83
|
+
domains: {
|
|
84
|
+
memory: new MemoryLibSQL({ url: "file:./local.db" }),
|
|
85
|
+
},
|
|
86
|
+
}),
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Options
|
|
91
|
+
|
|
92
|
+
## Initialization
|
|
93
|
+
|
|
94
|
+
MastraStorage initializes each configured domain independently. When passed to the Mastra class, `init()` is called automatically:
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
import { MastraStorage } from "@mastra/core/storage";
|
|
98
|
+
import { MemoryPG, WorkflowsPG, ScoresPG } from "@mastra/pg";
|
|
99
|
+
import { Mastra } from "@mastra/core";
|
|
100
|
+
|
|
101
|
+
const storage = new MastraStorage({
|
|
102
|
+
id: "composite",
|
|
103
|
+
domains: {
|
|
104
|
+
memory: new MemoryPG({ connectionString: process.env.DATABASE_URL }),
|
|
105
|
+
workflows: new WorkflowsPG({ connectionString: process.env.DATABASE_URL }),
|
|
106
|
+
scores: new ScoresPG({ connectionString: process.env.DATABASE_URL }),
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const mastra = new Mastra({
|
|
111
|
+
storage, // init() called automatically
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
If using storage directly, call `init()` explicitly:
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
import { MastraStorage } from "@mastra/core/storage";
|
|
119
|
+
import { MemoryPG } from "@mastra/pg";
|
|
120
|
+
|
|
121
|
+
const storage = new MastraStorage({
|
|
122
|
+
id: "composite",
|
|
123
|
+
domains: {
|
|
124
|
+
memory: new MemoryPG({ connectionString: process.env.DATABASE_URL }),
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
await storage.init();
|
|
129
|
+
|
|
130
|
+
// Access domain-specific stores via getStore()
|
|
131
|
+
const memoryStore = await storage.getStore("memory");
|
|
132
|
+
const thread = await memoryStore?.getThreadById({ threadId: "..." });
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Use Cases
|
|
136
|
+
|
|
137
|
+
### Separate databases for different workloads
|
|
138
|
+
|
|
139
|
+
Use a local database for development while keeping production data in a managed service:
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
import { MastraStorage } from "@mastra/core/storage";
|
|
143
|
+
import { MemoryPG, WorkflowsPG, ScoresPG } from "@mastra/pg";
|
|
144
|
+
import { MemoryLibSQL } from "@mastra/libsql";
|
|
145
|
+
|
|
146
|
+
const storage = new MastraStorage({
|
|
147
|
+
id: "composite",
|
|
148
|
+
domains: {
|
|
149
|
+
// Use local SQLite for development, PostgreSQL for production
|
|
150
|
+
memory:
|
|
151
|
+
process.env.NODE_ENV === "development"
|
|
152
|
+
? new MemoryLibSQL({ url: "file:./dev.db" })
|
|
153
|
+
: new MemoryPG({ connectionString: process.env.DATABASE_URL }),
|
|
154
|
+
workflows: new WorkflowsPG({ connectionString: process.env.DATABASE_URL }),
|
|
155
|
+
scores: new ScoresPG({ connectionString: process.env.DATABASE_URL }),
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Specialized storage for observability
|
|
161
|
+
|
|
162
|
+
Use a time-series database for traces while keeping other data in PostgreSQL:
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
import { MastraStorage } from "@mastra/core/storage";
|
|
166
|
+
import { MemoryPG, WorkflowsPG, ScoresPG } from "@mastra/pg";
|
|
167
|
+
import { ObservabilityStorageClickhouse } from "@mastra/clickhouse";
|
|
168
|
+
|
|
169
|
+
const storage = new MastraStorage({
|
|
170
|
+
id: "composite",
|
|
171
|
+
domains: {
|
|
172
|
+
memory: new MemoryPG({ connectionString: process.env.DATABASE_URL }),
|
|
173
|
+
workflows: new WorkflowsPG({ connectionString: process.env.DATABASE_URL }),
|
|
174
|
+
scores: new ScoresPG({ connectionString: process.env.DATABASE_URL }),
|
|
175
|
+
observability: new ObservabilityStorageClickhouse({
|
|
176
|
+
url: process.env.CLICKHOUSE_URL,
|
|
177
|
+
username: process.env.CLICKHOUSE_USERNAME,
|
|
178
|
+
password: process.env.CLICKHOUSE_PASSWORD,
|
|
179
|
+
}),
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
## Reference: DynamoDB Storage
|
|
187
|
+
|
|
188
|
+
> Documentation for the DynamoDB storage implementation in Mastra, using a single-table design with ElectroDB.
|
|
189
|
+
|
|
190
|
+
The DynamoDB storage implementation provides a scalable and performant NoSQL database solution for Mastra, leveraging a single-table design pattern with [ElectroDB](https://electrodb.dev/).
|
|
191
|
+
|
|
192
|
+
## Features
|
|
193
|
+
|
|
194
|
+
- Efficient single-table design for all Mastra storage needs
|
|
195
|
+
- Based on ElectroDB for type-safe DynamoDB access
|
|
196
|
+
- Support for AWS credentials, regions, and endpoints
|
|
197
|
+
- Compatible with AWS DynamoDB Local for development
|
|
198
|
+
- Stores Thread, Message, Trace, Eval, and Workflow data
|
|
199
|
+
- Optimized for serverless environments
|
|
200
|
+
|
|
201
|
+
## Installation
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
npm install @mastra/dynamodb@beta
|
|
205
|
+
# or
|
|
206
|
+
pnpm add @mastra/dynamodb@beta
|
|
207
|
+
# or
|
|
208
|
+
yarn add @mastra/dynamodb@beta
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## Prerequisites
|
|
212
|
+
|
|
213
|
+
Before using this package, you **must** create a DynamoDB table with a specific structure, including primary keys and Global Secondary Indexes (GSIs). This adapter expects the DynamoDB table and its GSIs to be provisioned externally.
|
|
214
|
+
|
|
215
|
+
Detailed instructions for setting up the table using AWS CloudFormation or AWS CDK are available in [TABLE_SETUP.md](https://github.com/mastra-ai/mastra/blob/main/stores/dynamodb/TABLE_SETUP.md). Please ensure your table is configured according to those instructions before proceeding.
|
|
216
|
+
|
|
217
|
+
## Usage
|
|
218
|
+
|
|
219
|
+
### Basic Usage
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
import { Memory } from "@mastra/memory";
|
|
223
|
+
import { DynamoDBStore } from "@mastra/dynamodb";
|
|
224
|
+
|
|
225
|
+
// Initialize the DynamoDB storage
|
|
226
|
+
const storage = new DynamoDBStore({
|
|
227
|
+
name: "dynamodb", // A name for this storage instance
|
|
228
|
+
config: {
|
|
229
|
+
tableName: "mastra-single-table", // Name of your DynamoDB table
|
|
230
|
+
region: "us-east-1", // Optional: AWS region, defaults to 'us-east-1'
|
|
231
|
+
// endpoint: "http://localhost:8000", // Optional: For local DynamoDB
|
|
232
|
+
// credentials: { accessKeyId: "YOUR_ACCESS_KEY", secretAccessKey: "YOUR_SECRET_KEY" } // Optional
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// Example: Initialize Memory with DynamoDB storage
|
|
237
|
+
const memory = new Memory({
|
|
238
|
+
storage,
|
|
239
|
+
options: {
|
|
240
|
+
lastMessages: 10,
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Local Development with DynamoDB Local
|
|
246
|
+
|
|
247
|
+
For local development, you can use [DynamoDB Local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html).
|
|
248
|
+
|
|
249
|
+
1. **Run DynamoDB Local (e.g., using Docker):**
|
|
250
|
+
|
|
251
|
+
```bash
|
|
252
|
+
docker run -p 8000:8000 amazon/dynamodb-local
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
2. **Configure `DynamoDBStore` to use the local endpoint:**
|
|
256
|
+
|
|
257
|
+
```typescript
|
|
258
|
+
import { DynamoDBStore } from "@mastra/dynamodb";
|
|
259
|
+
|
|
260
|
+
const storage = new DynamoDBStore({
|
|
261
|
+
name: "dynamodb-local",
|
|
262
|
+
config: {
|
|
263
|
+
tableName: "mastra-single-table", // Ensure this table is created in your local DynamoDB
|
|
264
|
+
region: "localhost", // Can be any string for local, 'localhost' is common
|
|
265
|
+
endpoint: "http://localhost:8000",
|
|
266
|
+
// For DynamoDB Local, credentials are not typically required unless configured.
|
|
267
|
+
// If you've configured local credentials:
|
|
268
|
+
// credentials: { accessKeyId: "fakeMyKeyId", secretAccessKey: "fakeSecretAccessKey" }
|
|
269
|
+
},
|
|
270
|
+
});
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
You will still need to create the table and GSIs in your local DynamoDB instance, for example, using the AWS CLI pointed to your local endpoint.
|
|
274
|
+
|
|
275
|
+
## Parameters
|
|
276
|
+
|
|
277
|
+
## AWS IAM Permissions
|
|
278
|
+
|
|
279
|
+
The IAM role or user executing the code needs appropriate permissions to interact with the specified DynamoDB table and its indexes. Below is a sample policy. Replace `${YOUR_TABLE_NAME}` with your actual table name and `${YOUR_AWS_REGION}` and `${YOUR_AWS_ACCOUNT_ID}` with appropriate values.
|
|
280
|
+
|
|
281
|
+
```json
|
|
282
|
+
{
|
|
283
|
+
"Version": "2012-10-17",
|
|
284
|
+
"Statement": [
|
|
285
|
+
{
|
|
286
|
+
"Effect": "Allow",
|
|
287
|
+
"Action": [
|
|
288
|
+
"dynamodb:DescribeTable",
|
|
289
|
+
"dynamodb:GetItem",
|
|
290
|
+
"dynamodb:PutItem",
|
|
291
|
+
"dynamodb:UpdateItem",
|
|
292
|
+
"dynamodb:DeleteItem",
|
|
293
|
+
"dynamodb:Query",
|
|
294
|
+
"dynamodb:Scan",
|
|
295
|
+
"dynamodb:BatchGetItem",
|
|
296
|
+
"dynamodb:BatchWriteItem"
|
|
297
|
+
],
|
|
298
|
+
"Resource": [
|
|
299
|
+
"arn:aws:dynamodb:${YOUR_AWS_REGION}:${YOUR_AWS_ACCOUNT_ID}:table/${YOUR_TABLE_NAME}",
|
|
300
|
+
"arn:aws:dynamodb:${YOUR_AWS_REGION}:${YOUR_AWS_ACCOUNT_ID}:table/${YOUR_TABLE_NAME}/index/*"
|
|
301
|
+
]
|
|
302
|
+
}
|
|
303
|
+
]
|
|
304
|
+
}
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
## Key Considerations
|
|
308
|
+
|
|
309
|
+
Before diving into the architectural details, keep these key points in mind when working with the DynamoDB storage adapter:
|
|
310
|
+
|
|
311
|
+
- **External Table Provisioning:** This adapter _requires_ you to create and configure the DynamoDB table and its Global Secondary Indexes (GSIs) yourself, prior to using the adapter. Follow the guide in [TABLE_SETUP.md](https://github.com/mastra-ai/mastra/blob/main/stores/dynamodb/TABLE_SETUP.md).
|
|
312
|
+
- **Single-Table Design:** All Mastra data (threads, messages, etc.) is stored in one DynamoDB table. This is a deliberate design choice optimized for DynamoDB, differing from relational database approaches.
|
|
313
|
+
- **Understanding GSIs:** Familiarity with how the GSIs are structured (as per `TABLE_SETUP.md`) is important for understanding data retrieval and potential query patterns.
|
|
314
|
+
- **ElectroDB:** The adapter uses ElectroDB to manage interactions with DynamoDB, providing a layer of abstraction and type safety over raw DynamoDB operations.
|
|
315
|
+
|
|
316
|
+
## Architectural Approach
|
|
317
|
+
|
|
318
|
+
This storage adapter utilizes a **single-table design pattern** leveraging [ElectroDB](https://electrodb.dev/), a common and recommended approach for DynamoDB. This differs architecturally from relational database adapters (like `@mastra/pg` or `@mastra/libsql`) that typically use multiple tables, each dedicated to a specific entity (threads, messages, etc.).
|
|
319
|
+
|
|
320
|
+
Key aspects of this approach:
|
|
321
|
+
|
|
322
|
+
- **DynamoDB Native:** The single-table design is optimized for DynamoDB's key-value and query capabilities, often leading to better performance and scalability compared to mimicking relational models.
|
|
323
|
+
- **External Table Management:** Unlike some adapters that might offer helper functions to create tables via code, this adapter **expects the DynamoDB table and its associated Global Secondary Indexes (GSIs) to be provisioned externally** before use. Please refer to [TABLE_SETUP.md](https://github.com/mastra-ai/mastra/blob/main/stores/dynamodb/TABLE_SETUP.md) for detailed instructions using tools like AWS CloudFormation or CDK. The adapter focuses solely on interacting with the pre-existing table structure.
|
|
324
|
+
- **Consistency via Interface:** While the underlying storage model differs, this adapter adheres to the same `MastraStorage` interface as other adapters, ensuring it can be used interchangeably within the Mastra `Memory` component.
|
|
325
|
+
|
|
326
|
+
### Mastra Data in the Single Table
|
|
327
|
+
|
|
328
|
+
Within the single DynamoDB table, different Mastra data entities (such as Threads, Messages, Traces, Evals, and Workflows) are managed and distinguished using ElectroDB. ElectroDB defines specific models for each entity type, which include unique key structures and attributes. This allows the adapter to store and retrieve diverse data types efficiently within the same table.
|
|
329
|
+
|
|
330
|
+
For example, a `Thread` item might have a primary key like `THREAD#<threadId>`, while a `Message` item belonging to that thread might use `THREAD#<threadId>` as a partition key and `MESSAGE#<messageId>` as a sort key. The Global Secondary Indexes (GSIs), detailed in `TABLE_SETUP.md`, are strategically designed to support common access patterns across these different entities, such as fetching all messages for a thread or querying traces associated with a particular workflow.
|
|
331
|
+
|
|
332
|
+
### Advantages of Single-Table Design
|
|
333
|
+
|
|
334
|
+
This implementation uses a single-table design pattern with ElectroDB, which offers several advantages within the context of DynamoDB:
|
|
335
|
+
|
|
336
|
+
1. **Lower cost (potentially):** Fewer tables can simplify Read/Write Capacity Unit (RCU/WCU) provisioning and management, especially with on-demand capacity.
|
|
337
|
+
2. **Better performance:** Related data can be co-located or accessed efficiently through GSIs, enabling fast lookups for common access patterns.
|
|
338
|
+
3. **Simplified administration:** Fewer distinct tables to monitor, back up, and manage.
|
|
339
|
+
4. **Reduced complexity in access patterns:** ElectroDB helps manage the complexity of item types and access patterns on a single table.
|
|
340
|
+
5. **Transaction support:** DynamoDB transactions can be used across different "entity" types stored within the same table if needed.
|
|
341
|
+
|
|
342
|
+
---
|
|
343
|
+
|
|
344
|
+
## Reference: PostgreSQL Storage
|
|
345
|
+
|
|
346
|
+
> Documentation for the PostgreSQL storage implementation in Mastra.
|
|
347
|
+
|
|
348
|
+
The PostgreSQL storage implementation provides a production-ready storage solution using PostgreSQL databases.
|
|
349
|
+
|
|
350
|
+
## Installation
|
|
351
|
+
|
|
352
|
+
```bash
|
|
353
|
+
npm install @mastra/pg@beta
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
## Usage
|
|
357
|
+
|
|
358
|
+
```typescript
|
|
359
|
+
import { PostgresStore } from "@mastra/pg";
|
|
360
|
+
|
|
361
|
+
const storage = new PostgresStore({
|
|
362
|
+
id: 'pg-storage',
|
|
363
|
+
connectionString: process.env.DATABASE_URL,
|
|
364
|
+
});
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
## Parameters
|
|
368
|
+
|
|
369
|
+
## Constructor Examples
|
|
370
|
+
|
|
371
|
+
You can instantiate `PostgresStore` in the following ways:
|
|
372
|
+
|
|
373
|
+
```ts
|
|
374
|
+
import { PostgresStore } from "@mastra/pg";
|
|
375
|
+
|
|
376
|
+
// Using a connection string only
|
|
377
|
+
const store1 = new PostgresStore({
|
|
378
|
+
id: 'pg-storage-1',
|
|
379
|
+
connectionString: "postgresql://user:password@localhost:5432/mydb",
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
// Using a connection string with a custom schema name
|
|
383
|
+
const store2 = new PostgresStore({
|
|
384
|
+
id: 'pg-storage-2',
|
|
385
|
+
connectionString: "postgresql://user:password@localhost:5432/mydb",
|
|
386
|
+
schemaName: "custom_schema", // optional
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
// Using individual connection parameters
|
|
390
|
+
const store4 = new PostgresStore({
|
|
391
|
+
id: 'pg-storage-3',
|
|
392
|
+
host: "localhost",
|
|
393
|
+
port: 5432,
|
|
394
|
+
database: "mydb",
|
|
395
|
+
user: "user",
|
|
396
|
+
password: "password",
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
// Individual parameters with schemaName
|
|
400
|
+
const store5 = new PostgresStore({
|
|
401
|
+
id: 'pg-storage-4',
|
|
402
|
+
host: "localhost",
|
|
403
|
+
port: 5432,
|
|
404
|
+
database: "mydb",
|
|
405
|
+
user: "user",
|
|
406
|
+
password: "password",
|
|
407
|
+
schemaName: "custom_schema", // optional
|
|
408
|
+
});
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
## Additional Notes
|
|
412
|
+
|
|
413
|
+
### Schema Management
|
|
414
|
+
|
|
415
|
+
The storage implementation handles schema creation and updates automatically. It creates the following tables:
|
|
416
|
+
|
|
417
|
+
- `mastra_workflow_snapshot`: Stores workflow state and execution data
|
|
418
|
+
- `mastra_evals`: Stores evaluation results and metadata
|
|
419
|
+
- `mastra_threads`: Stores conversation threads
|
|
420
|
+
- `mastra_messages`: Stores individual messages
|
|
421
|
+
- `mastra_traces`: Stores telemetry and tracing data
|
|
422
|
+
- `mastra_scorers`: Stores scoring and evaluation data
|
|
423
|
+
- `mastra_resources`: Stores resource working memory data
|
|
424
|
+
|
|
425
|
+
### Initialization
|
|
426
|
+
|
|
427
|
+
When you pass storage to the Mastra class, `init()` is called automatically before any storage operation:
|
|
428
|
+
|
|
429
|
+
```typescript
|
|
430
|
+
import { Mastra } from "@mastra/core";
|
|
431
|
+
import { PostgresStore } from "@mastra/pg";
|
|
432
|
+
|
|
433
|
+
const storage = new PostgresStore({
|
|
434
|
+
connectionString: process.env.DATABASE_URL,
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
const mastra = new Mastra({
|
|
438
|
+
storage, // init() is called automatically
|
|
439
|
+
});
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
If you're using storage directly without Mastra, you must call `init()` explicitly to create the tables:
|
|
443
|
+
|
|
444
|
+
```typescript
|
|
445
|
+
import { PostgresStore } from "@mastra/pg";
|
|
446
|
+
|
|
447
|
+
const storage = new PostgresStore({
|
|
448
|
+
id: 'pg-storage',
|
|
449
|
+
connectionString: process.env.DATABASE_URL,
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
// Required when using storage directly
|
|
453
|
+
await storage.init();
|
|
454
|
+
|
|
455
|
+
// Access domain-specific stores via getStore()
|
|
456
|
+
const memoryStore = await storage.getStore('memory');
|
|
457
|
+
const thread = await memoryStore?.getThreadById({ threadId: "..." });
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
> **Note:**
|
|
461
|
+
If `init()` is not called, tables won't be created and storage operations will fail silently or throw errors.
|
|
462
|
+
|
|
463
|
+
### Direct Database and Pool Access
|
|
464
|
+
|
|
465
|
+
`PostgresStore` exposes both the underlying database object and the pg-promise instance as public fields:
|
|
466
|
+
|
|
467
|
+
```typescript
|
|
468
|
+
store.db; // pg-promise database instance
|
|
469
|
+
store.pgp; // pg-promise main instance
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
This enables direct queries and custom transaction management. When using these fields:
|
|
473
|
+
|
|
474
|
+
- You are responsible for proper connection and transaction handling.
|
|
475
|
+
- Closing the store (`store.close()`) will destroy the associated connection pool.
|
|
476
|
+
- Direct access bypasses any additional logic or validation provided by PostgresStore methods.
|
|
477
|
+
|
|
478
|
+
This approach is intended for advanced scenarios where low-level access is required.
|
|
479
|
+
|
|
480
|
+
## Usage Example
|
|
481
|
+
|
|
482
|
+
### Adding memory to an agent
|
|
483
|
+
|
|
484
|
+
To add PostgreSQL memory to an agent use the `Memory` class and create a new `storage` key using `PostgresStore`. The `connectionString` can either be a remote location, or a local database connection.
|
|
485
|
+
|
|
486
|
+
```typescript title="src/mastra/agents/example-pg-agent.ts"
|
|
487
|
+
import { Memory } from "@mastra/memory";
|
|
488
|
+
import { Agent } from "@mastra/core/agent";
|
|
489
|
+
import { PostgresStore } from "@mastra/pg";
|
|
490
|
+
|
|
491
|
+
export const pgAgent = new Agent({
|
|
492
|
+
id: "pg-agent",
|
|
493
|
+
name: "PG Agent",
|
|
494
|
+
instructions:
|
|
495
|
+
"You are an AI agent with the ability to automatically recall memories from previous interactions.",
|
|
496
|
+
model: "openai/gpt-5.1",
|
|
497
|
+
memory: new Memory({
|
|
498
|
+
storage: new PostgresStore({
|
|
499
|
+
id: 'pg-agent-storage',
|
|
500
|
+
connectionString: process.env.DATABASE_URL!,
|
|
501
|
+
}),
|
|
502
|
+
options: {
|
|
503
|
+
generateTitle: true, // Explicitly enable automatic title generation
|
|
504
|
+
},
|
|
505
|
+
}),
|
|
506
|
+
});
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
### Using the agent
|
|
510
|
+
|
|
511
|
+
Use `memoryOptions` to scope recall for this request. Set `lastMessages: 5` to limit recency-based recall, and use `semanticRecall` to fetch the `topK: 3` most relevant messages, including `messageRange: 2` neighboring messages for context around each match.
|
|
512
|
+
|
|
513
|
+
```typescript title="src/test-pg-agent.ts"
|
|
514
|
+
import "dotenv/config";
|
|
515
|
+
|
|
516
|
+
import { mastra } from "./mastra";
|
|
517
|
+
|
|
518
|
+
const threadId = "123";
|
|
519
|
+
const resourceId = "user-456";
|
|
520
|
+
|
|
521
|
+
const agent = mastra.getAgent("pg-agent");
|
|
522
|
+
|
|
523
|
+
const message = await agent.stream("My name is Mastra", {
|
|
524
|
+
memory: {
|
|
525
|
+
thread: threadId,
|
|
526
|
+
resource: resourceId,
|
|
527
|
+
},
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
await message.textStream.pipeTo(new WritableStream());
|
|
531
|
+
|
|
532
|
+
const stream = await agent.stream("What's my name?", {
|
|
533
|
+
memory: {
|
|
534
|
+
thread: threadId,
|
|
535
|
+
resource: resourceId,
|
|
536
|
+
},
|
|
537
|
+
memoryOptions: {
|
|
538
|
+
lastMessages: 5,
|
|
539
|
+
semanticRecall: {
|
|
540
|
+
topK: 3,
|
|
541
|
+
messageRange: 2,
|
|
542
|
+
},
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
|
|
546
|
+
for await (const chunk of stream.textStream) {
|
|
547
|
+
process.stdout.write(chunk);
|
|
548
|
+
}
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
## Index Management
|
|
552
|
+
|
|
553
|
+
PostgreSQL storage provides index management to optimize query performance.
|
|
554
|
+
|
|
555
|
+
### Default Indexes
|
|
556
|
+
|
|
557
|
+
PostgreSQL storage creates composite indexes during initialization for common query patterns:
|
|
558
|
+
|
|
559
|
+
- `mastra_threads_resourceid_createdat_idx`: (resourceId, createdAt DESC)
|
|
560
|
+
- `mastra_messages_thread_id_createdat_idx`: (thread_id, createdAt DESC)
|
|
561
|
+
- `mastra_ai_spans_traceid_startedat_idx`: (traceId, startedAt DESC)
|
|
562
|
+
- `mastra_ai_spans_parentspanid_startedat_idx`: (parentSpanId, startedAt DESC)
|
|
563
|
+
- `mastra_ai_spans_name_startedat_idx`: (name, startedAt DESC)
|
|
564
|
+
- `mastra_ai_spans_scope_startedat_idx`: (scope, startedAt DESC)
|
|
565
|
+
- `mastra_scores_trace_id_span_id_created_at_idx`: (traceId, spanId, createdAt DESC)
|
|
566
|
+
|
|
567
|
+
These indexes improve performance for filtered queries with sorting, including `dateRange` filters on message queries.
|
|
568
|
+
|
|
569
|
+
### Configuring Indexes
|
|
570
|
+
|
|
571
|
+
You can control index creation via constructor options:
|
|
572
|
+
|
|
573
|
+
```typescript
|
|
574
|
+
import { PostgresStore } from "@mastra/pg";
|
|
575
|
+
|
|
576
|
+
// Skip default indexes (manage indexes separately)
|
|
577
|
+
const store = new PostgresStore({
|
|
578
|
+
id: 'pg-storage',
|
|
579
|
+
connectionString: process.env.DATABASE_URL,
|
|
580
|
+
skipDefaultIndexes: true,
|
|
581
|
+
});
|
|
582
|
+
|
|
583
|
+
// Add custom indexes during initialization
|
|
584
|
+
const storeWithCustomIndexes = new PostgresStore({
|
|
585
|
+
id: 'pg-storage',
|
|
586
|
+
connectionString: process.env.DATABASE_URL,
|
|
587
|
+
indexes: [
|
|
588
|
+
{
|
|
589
|
+
name: "idx_threads_metadata_type",
|
|
590
|
+
table: "mastra_threads",
|
|
591
|
+
columns: ["metadata->>'type'"],
|
|
592
|
+
},
|
|
593
|
+
{
|
|
594
|
+
name: "idx_messages_status",
|
|
595
|
+
table: "mastra_messages",
|
|
596
|
+
columns: ["metadata->>'status'"],
|
|
597
|
+
},
|
|
598
|
+
],
|
|
599
|
+
});
|
|
600
|
+
```
|
|
601
|
+
|
|
602
|
+
For advanced index types, you can specify additional options:
|
|
603
|
+
|
|
604
|
+
- `unique: true` for unique constraints
|
|
605
|
+
- `where: 'condition'` for partial indexes
|
|
606
|
+
- `method: 'brin'` for time-series data
|
|
607
|
+
- `storage: { fillfactor: 90 }` for update-heavy tables
|
|
608
|
+
- `concurrent: true` for non-blocking creation (default)
|
|
609
|
+
|
|
610
|
+
### Index Options
|
|
611
|
+
|
|
612
|
+
### Schema-Specific Indexes
|
|
613
|
+
|
|
614
|
+
When using custom schemas, index names are prefixed with the schema name:
|
|
615
|
+
|
|
616
|
+
```typescript
|
|
617
|
+
const storage = new PostgresStore({
|
|
618
|
+
id: 'pg-storage',
|
|
619
|
+
connectionString: process.env.DATABASE_URL,
|
|
620
|
+
schemaName: "custom_schema",
|
|
621
|
+
indexes: [
|
|
622
|
+
{
|
|
623
|
+
name: "idx_threads_status",
|
|
624
|
+
table: "mastra_threads",
|
|
625
|
+
columns: ["status"],
|
|
626
|
+
},
|
|
627
|
+
],
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
// Creates index as: custom_schema_idx_threads_status
|
|
631
|
+
```
|
|
632
|
+
|
|
633
|
+
### Managing Indexes via SQL
|
|
634
|
+
|
|
635
|
+
For advanced index management (listing, dropping, analyzing), use direct SQL queries via the `db` accessor:
|
|
636
|
+
|
|
637
|
+
```typescript
|
|
638
|
+
// List indexes for a table
|
|
639
|
+
const indexes = await storage.db.any(`
|
|
640
|
+
SELECT indexname, indexdef
|
|
641
|
+
FROM pg_indexes
|
|
642
|
+
WHERE tablename = 'mastra_messages'
|
|
643
|
+
`);
|
|
644
|
+
|
|
645
|
+
// Drop an index
|
|
646
|
+
await storage.db.none('DROP INDEX IF EXISTS idx_my_custom_index');
|
|
647
|
+
|
|
648
|
+
// Analyze index usage
|
|
649
|
+
const stats = await storage.db.one(`
|
|
650
|
+
SELECT idx_scan, idx_tup_read
|
|
651
|
+
FROM pg_stat_user_indexes
|
|
652
|
+
WHERE indexrelname = 'mastra_messages_thread_id_createdat_idx'
|
|
653
|
+
`);
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
### Index Types and Use Cases
|
|
657
|
+
|
|
658
|
+
PostgreSQL offers different index types optimized for specific scenarios:
|
|
659
|
+
|
|
660
|
+
| Index Type | Best For | Storage | Speed |
|
|
661
|
+
| ------------------- | --------------------------------------- | ---------- | -------------------------- |
|
|
662
|
+
| **btree** (default) | Range queries, sorting, general purpose | Moderate | Fast |
|
|
663
|
+
| **hash** | Equality comparisons only | Small | Very fast for `=` |
|
|
664
|
+
| **gin** | JSONB, arrays, full-text search | Large | Fast for contains |
|
|
665
|
+
| **gist** | Geometric data, full-text search | Moderate | Fast for nearest-neighbor |
|
|
666
|
+
| **spgist** | Non-balanced data, text patterns | Small | Fast for specific patterns |
|
|
667
|
+
| **brin** | Large tables with natural ordering | Very small | Fast for ranges |
|