> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # Aurora DSQL 스토리지 Aurora DSQL 스토리지 구현은 IAM 인증과 함께 Amazon Aurora DSQL을 사용하는 스토리지를 제공합니다. Aurora DSQL은 PostgreSQL 확장 기능(`CREATE EXTENSION`), including `pgvector`. 벡터 저장의 경우 다음과 같은 별도의 벡터 저장소를 사용하십시오.`@mastra/s3vectors`. ## 설치 ```bash npm install @mastra/dsql@beta ``` ## 전제조건 - Amazon Aurora DSQL 클러스터 - DSQL 클러스터에 대한 액세스 권한이 있는 AWS 자격 증명(IAM 인증) ## 용법 ```typescript import { DSQLStore } from '@mastra/dsql' const storage = new DSQLStore({ id: 'my-dsql-store', host: 'abc123.dsql.us-east-1.on.aws', // region is auto-detected from host, or specify explicitly: // region: 'us-east-1', // user: 'admin', // default // database: 'postgres', // default }) // Initialize the store (creates tables if needed) await storage.init() ``` ## 매개변수 **id** (`string`): 이 스토어 인스턴스의 고유 식별자 **host** (`string`): DSQL 클러스터 엔드포인트(예: abc123.dsql.us-east-1.on.aws) **pool** (`pg.Pool`): 미리 구성된 pg.Pool 인스턴스입니다. 연결 풀을 직접 제어하려면 사용하세요. host 구성과 함께 사용할 수 없습니다. **user** (`string`): 데이터베이스 사용자입니다. Aurora DSQL의 관리자 역할은 'admin'입니다. **database** (`string`): 데이터베이스 이름입니다. Aurora DSQL은 클러스터마다 'postgres'라는 단일 데이터베이스를 제공합니다. **region** (`string`): AWS 리전입니다. 제공하지 않으면 host에서 추출합니다. **schemaName** (`string`): Mastra 테이블과 인덱스가 생성되는 PostgreSQL 스키마 이름입니다. **customCredentialsProvider** (`AwsCredentialIdentityProvider`): IAM 인증을 위한 사용자 지정 AWS 자격 증명 Provider입니다. **max** (`number`): 풀의 최대 연결 수입니다. **min** (`number`): 풀의 최소 연결 수입니다. **idleTimeoutMillis** (`number`): 유휴 연결을 이 시간(밀리초)이 지나면 닫습니다. **maxLifetimeSeconds** (`number`): 최대 연결 수명(초)입니다. Aurora DSQL의 60분 연결 제한으로 인해 3600보다 작아야 합니다. **connectionTimeoutMillis** (`number`): 연결 획득 제한 시간(밀리초)입니다. **allowExitOnIdle** (`boolean`): 모든 연결이 유휴 상태일 때 프로세스가 종료되도록 허용합니다. ## 생성자 예 다음과 같은 방법으로 `DSQLStore`를 인스턴스화할 수 있습니다. ```typescript import { DSQLStore } from '@mastra/dsql' // Basic configuration (region auto-detected from host) const store1 = new DSQLStore({ id: 'my-dsql-store', host: 'abc123.dsql.us-east-1.on.aws', }) // With explicit region and schema const store2 = new DSQLStore({ id: 'my-dsql-store', host: 'abc123.dsql.us-east-1.on.aws', region: 'us-east-1', schemaName: 'my_app', }) // With custom credentials provider import { fromNodeProviderChain } from '@aws-sdk/credential-providers' const store3 = new DSQLStore({ id: 'my-dsql-store', host: 'abc123.dsql.us-east-1.on.aws', customCredentialsProvider: fromNodeProviderChain(), }) // With connection pool settings const store4 = new DSQLStore({ id: 'my-dsql-store', host: 'abc123.dsql.us-east-1.on.aws', max: 20, min: 2, idleTimeoutMillis: 300000, maxLifetimeSeconds: 3000, connectionTimeoutMillis: 10000, }) // Using a pre-configured pg.Pool import { Pool } from 'pg' import { AuroraDSQLClient } from '@aws/aurora-dsql-node-postgres-connector' const pool = new Pool({ host: 'abc123.dsql.us-east-1.on.aws', Client: AuroraDSQLClient, region: 'us-east-1', }) const store5 = new DSQLStore({ id: 'my-dsql-store', pool, }) ``` ## 추가 참고사항 ### 스키마 관리 저장소 구현은 스키마 생성 및 업데이트를 자동으로 처리합니다. 다음 테이블이 생성됩니다. - `mastra_workflow_snapshot`: Workflow 상태 및 실행 데이터를 저장합니다. - `mastra_threads`: 대화 스레드를 저장합니다. - `mastra_messages`: 개별 메시지를 저장합니다. - `mastra_ai_spans`: Observability을 위해 범위 데이터를 저장합니다. - `mastra_scorers`: 점수 및 평가 데이터를 저장합니다. - `mastra_resources`: 자원 작업 Memory 데이터를 저장합니다. - `mastra_agents`: Agent 데이터를 저장합니다. ### 초기화 스토리지를 Mastra 클래스에 전달하면 스토리지 작업 전에 `init()`이 자동으로 호출됩니다. ```typescript import { Mastra } from '@mastra/core' import { DSQLStore } from '@mastra/dsql' const storage = new DSQLStore({ id: 'my-dsql-store', host: 'abc123.dsql.us-east-1.on.aws', }) const mastra = new Mastra({ storage, // init() is called automatically }) ``` Mastra 없이 스토어를 직접 사용하는 경우 테이블을 생성하려면 `init()`을 명시적으로 호출해야 합니다. ```typescript import { DSQLStore } from '@mastra/dsql' const storage = new DSQLStore({ id: 'my-dsql-store', host: 'abc123.dsql.us-east-1.on.aws', }) // Required when using storage directly await storage.init() // Access domain-specific stores via getStore() const memoryStore = await storage.getStore('memory') const thread = await memoryStore?.getThreadById({ threadId: '...' }) ``` > **경고:** `init()`을 호출하지 않으면 테이블이 생성되지 않으며 스토리지 작업이 아무 알림 없이 실패하거나 오류를 발생시킵니다. ### 직접 데이터베이스 및 풀 액세스 `DSQLStore`기본 데이터베이스 클라이언트와 pg.Pool 인스턴스를 모두 공개 필드로 노출합니다. ```typescript storage.db // Database client for executing queries storage.pool // Underlying pg.Pool instance ``` 직접 쿼리 및 사용자 정의 트랜잭션 관리를 지원합니다. 다음 필드를 사용하는 경우: - 적절한 연결 및 트랜잭션 처리는 사용자의 책임입니다. - 스토어를 닫으면(`storage.close()`) 스토어가 생성한 연결 풀이 제거됩니다. - 직접 액세스하면 DSQLStore 메서드가 제공하는 추가 로직이나 유효성 검사를 우회합니다. 이 접근 방식은 낮은 수준의 액세스가 필요한 고급 시나리오를 위한 것입니다. ### Aurora DSQL 세부 사항 #### IAM 전용 인증 연결은 IAM으로 인증되므로 데이터베이스 비밀번호가 필요하지 않습니다. `@mastra/dsql`은 `@aws/aurora-dsql-node-postgres-connector`를 사용하여 수명이 짧은 인증 토큰을 생성합니다. `customCredentialsProvider`를 통해 사용자 지정 자격 증명 Provider를 제공할 수 있습니다. #### 단일 데이터베이스, 스키마 기반 격리 각 클러스터는 `postgres`라는 단일 데이터베이스를 제공합니다. 논리적 분리는 스키마를 통해 이루어집니다. `schemaName` 옵션은 Mastra 테이블이 생성될 위치를 제어합니다. #### PostgreSQL 확장 없음 `CREATE EXTENSION`은 지원되지 않습니다. 여기에는 `pgvector`, `PostGIS` 등이 포함됩니다. 벡터 스토리지에는 `DSQLStore`와 함께 `@mastra/s3vectors` 같은 별도의 스토어를 사용하세요. #### JSON이 텍스트로 저장됨 JSON/JSONB는 쿼리 유형으로 사용할 수 있지만 열 유형으로는 사용할 수 없습니다. `@mastra/dsql`은 구조화된 필드(메타데이터, 콘텐츠 등)를 `TEXT` 열에 저장하고 쿼리 시점에 JSON으로 캐스팅합니다. #### 스키마 및 DDL 제약조건 일부 PostgreSQL 기능은 사용할 수 없습니다. - 외래 키 제약조건 - `TRUNCATE` - 동기식`CREATE INDEX` 인덱스는 `CREATE INDEX ASYNC`를 사용하여 비동기식으로 생성됩니다. 스토어의 `init()` 및 인덱스 도우미 API는 이러한 제약 조건을 준수합니다. #### 트랜잭션 및 낙관적 동시성 Aurora DSQL은 낙관적 동시성 제어(OCC)를 사용하며 경합이 있는 경우 재시도 가능한 OCC 오류를 반환할 수 있습니다. 거래 기간과 규모에 제한이 있습니다. 대규모 대량 작업은 애플리케이션 수준에서 더 작은 배치로 분할되어야 합니다. #### 연결 수명 개별 연결은 약 60분으로 제한됩니다. 기본값 `maxLifetimeSeconds: 3300`을 사용하면 이 제한에 도달하기 전에 연결이 재활용됩니다. ## 사용예 ### Agent에 Memory 추가 Agent에 Aurora DSQL Memory를 추가하려면 `Memory` 클래스를 사용하고 `DSQLStore`를 사용하는 새 `storage` 키를 생성하세요. `host`는 Aurora DSQL 클러스터 엔드포인트를 가리켜야 합니다. ```typescript import { Memory } from '@mastra/memory' import { Agent } from '@mastra/core/agent' import { DSQLStore } from '@mastra/dsql' export const dsqlAgent = new Agent({ id: 'dsql-agent', name: 'DSQL Agent', instructions: 'You are an AI agent with the ability to automatically recall memories from previous interactions.', model: 'openai/gpt-5.6-sol', memory: new Memory({ storage: new DSQLStore({ id: 'dsql-agent-storage', host: process.env.DSQL_HOST!, }), options: { generateTitle: true, // Explicitly enable automatic title generation }, }), }) ``` ### Agent 사용 `memoryOptions`를 사용하여 이 요청의 회상 범위를 지정하세요. `lastMessages: 5`를 설정하여 최신 메시지 기반 회상을 제한하고, `semanticRecall`을 사용하여 가장 관련성이 높은 `topK: 3`개의 메시지를 가져오세요. 각 일치 항목 주변의 컨텍스트를 제공하도록 인접 메시지 `messageRange: 2`개도 포함됩니다. ```typescript import 'dotenv/config' import { mastra } from './mastra' const threadId = '123' const resourceId = 'user-456' const agent = mastra.getAgent('dsql-agent') const message = await agent.stream('My name is Mastra', { memory: { thread: threadId, resource: resourceId, }, }) await message.textStream.pipeTo(new WritableStream()) const stream = await agent.stream("What's my name?", { memory: { thread: threadId, resource: resourceId, }, memoryOptions: { lastMessages: 5, semanticRecall: { topK: 3, messageRange: 2, }, }, }) for await (const chunk of stream.textStream) { process.stdout.write(chunk) } ``` ## 인덱스 관리 Aurora DSQL 스토리지는 쿼리 성능을 최적화하는 인덱스 관리 기능을 제공합니다. ### 자동 성과 지표 Aurora DSQL 스토리지는 일반적인 쿼리 패턴에 대해 초기화 중에 복합 인덱스를 자동으로 생성합니다. - `mastra_threads_resourceid_createdat_idx`: (resourceId, createdAt) - `mastra_messages_thread_id_createdat_idx`: (thread\_id, createdAt) - `mastra_ai_spans_traceid_startedat_idx`: (traceId, startedAt) - `mastra_ai_spans_parentspanid_startedat_idx`: (parentSpanId, startedAt) - `mastra_ai_spans_name_idx`: (name) - `mastra_ai_spans_spantype_startedat_idx`: (spanType, startedAt) - `mastra_scores_trace_id_span_id_created_at_idx`: (traceId,spanId,createdAt) Aurora DSQL은 `CREATE INDEX ASYNC`를 사용하여 이러한 인덱스를 비동기식으로 생성합니다. 인덱스 생성이 비동기식이므로 `init()` 직후에는 새 인덱스를 사용하지 못할 수 있습니다. 인덱스가 없어도 스토어는 계속 작동하지만, 인덱스 생성이 완료될 때까지 쿼리가 느려질 수 있습니다. ### 사용자 정의 색인 생성 특정 쿼리 패턴을 최적화하기 위해 추가 인덱스를 만듭니다. ```typescript await storage.createIndex({ name: 'idx_threads_resource', table: 'mastra_threads', columns: ['resourceId'], }) await storage.createIndex({ name: 'idx_messages_composite', table: 'mastra_messages', columns: ['thread_id', 'createdAt'], }) ``` Aurora DSQL은 `CREATE INDEX ASYNC`에서 `ASC`/`DESC`를 허용하지 않습니다. 이를 포함하면 자동으로 제거됩니다. ### 인덱스 옵션 **name** (`string`): 인덱스의 고유 이름 **table** (`string`): 테이블 이름(예: 'mastra\_threads') **columns** (`string[]`): 열 이름 배열입니다. Aurora DSQL 호환성을 위해 ASC/DESC 수정자는 자동으로 제거됩니다. **unique** (`boolean`): 고유 인덱스를 생성합니다. **concurrent** (`boolean`): Aurora DSQL에서는 무시됩니다. 인덱스는 항상 비동기식으로 생성됩니다. **where** (`string`): 부분 인덱스 조건입니다. **method** (`string`): Aurora DSQL에서는 무시됩니다. btree 인덱스만 지원됩니다. **opclass** (`string`): Aurora DSQL에서는 무시됩니다. **storage** (`Record`): Aurora DSQL에서는 무시됩니다. **tablespace** (`string`): Aurora DSQL에서는 무시됩니다. 테이블스페이스는 지원되지 않습니다. ### 인덱스 관리 기존 인덱스를 나열하고 모니터링합니다. ```typescript // List all indexes const allIndexes = await storage.listIndexes() console.log(allIndexes) // [ // { // name: 'mastra_threads_pkey', // table: 'mastra_threads', // columns: ['id'], // unique: true, // size: '16 KB', // definition: 'CREATE UNIQUE INDEX...' // }, // ... // ] // List indexes for a specific table const threadIndexes = await storage.listIndexes('mastra_threads') // Get detailed statistics for an index const stats = await storage.describeIndex('idx_threads_resource') console.log(stats) // { // name: 'idx_threads_resource', // table: 'mastra_threads', // columns: ['resourceId'], // unique: false, // size: '128 KB', // definition: 'CREATE INDEX idx_threads_resource...', // method: 'btree', // scans: 1542, // tuples_read: 45230, // tuples_fetched: 12050 // } // Drop an index await storage.dropIndex('idx_threads_status') ``` ### 스키마별 인덱스 사용자 정의 스키마를 사용하면 스키마 접두사를 사용하여 인덱스가 생성됩니다. ```typescript const storage = new DSQLStore({ id: 'my-dsql-store', host: 'abc123.dsql.us-east-1.on.aws', schemaName: 'custom_schema', }) // Creates index as: custom_schema_idx_threads_status await storage.createIndex({ name: 'idx_threads_status', table: 'mastra_threads', columns: ['status'], }) ``` ## 관련 자료 - [Aurora DSQL 설명서](https://docs.aws.amazon.com/aurora-dsql/) - [SQL 참조](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-aurora-dsql-sql.html) - [지원되는 SQL 기능](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-postgresql-compatibility-supported-sql-features.html) - [지원되지 않는 PostgreSQL 기능](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-postgresql-compatibility-unsupported-features.html) - [지원되는 데이터 유형](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-postgresql-compatibility-supported-data-types.html) - [비동기 인덱스](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-create-index-async.html)