Skip to Content
リファレンスストレージPostgreSQL ストレージ

PostgreSQLストレージ

PostgreSQLストレージ実装は、PostgreSQLデータベースを使用した本番環境対応のストレージソリューションを提供します。

インストール

npm install @mastra/pg@latest

使い方

import { PostgresStore } from "@mastra/pg"; const storage = new PostgresStore({ connectionString: process.env.DATABASE_URL, });

パラメーター

connectionString:

string
PostgreSQL の接続文字列(例: postgresql://user:pass@host:5432/dbname)

schemaName?:

string
ストレージで使用したいスキーマ名。指定しない場合はデフォルトのスキーマが使用されます。

コンストラクタの例

PostgresStore は以下の方法でインスタンス化できます。

import { PostgresStore } from "@mastra/pg"; // 接続文字列のみを使用する場合 const store1 = new PostgresStore({ connectionString: "postgresql://user:password@localhost:5432/mydb", }); // 接続文字列とカスタムスキーマ名を使用する場合 const store2 = new PostgresStore({ connectionString: "postgresql://user:password@localhost:5432/mydb", schemaName: "custom_schema", // オプション }); // 個別の接続パラメータを使用する場合 const store4 = new PostgresStore({ host: "localhost", port: 5432, database: "mydb", user: "user", password: "password", }); // 個別パラメータと schemaName を使用する場合 const store5 = new PostgresStore({ host: "localhost", port: 5432, database: "mydb", user: "user", password: "password", schemaName: "custom_schema", // オプション });

追加の注意事項

スキーマ管理

ストレージの実装は、スキーマの作成と更新を自動的に処理します。以下のテーブルを作成します:

  • threads: 会話スレッドを保存
  • messages: 個別のメッセージを保存
  • metadata: スレッドとメッセージの追加メタデータを保存

データベースとプールへの直接アクセス

PostgresStoreは、基盤となるデータベースオブジェクトとpg-promiseインスタンスの両方をパブリックフィールドとして公開します:

store.db // pg-promise database instance store.pgp // pg-promise main instance

これにより、直接クエリとカスタムトランザクション管理が可能になります。これらのフィールドを使用する際は:

  • 適切な接続とトランザクション処理はあなたの責任です。
  • ストアを閉じる(store.close())と、関連する接続プールが破棄されます。
  • 直接アクセスは、PostgresStoreメソッドが提供する追加のロジックや検証をバイパスします。

このアプローチは、低レベルアクセスが必要な高度なシナリオを想定しています。