Skip to main content
Autonome uses PostgreSQL with Drizzle ORM for type-safe database access. This guide covers database setup, migrations, and best practices for production deployments.

Database Requirements

  • PostgreSQL: Version 15 or higher
  • Extensions: None required (uses standard SQL)
  • SSL: Recommended for production
  • Connection Pooling: Built-in with Drizzle

Schema Overview

The database schema includes:
  • "Models": AI trading model configurations
  • "Orders": Trading positions and closed trades (SSOT)
  • "PortfolioSnapshots": Historical portfolio value tracking
  • "Conversations": AI chat history and decision logs
  • "CryptoPrice": Real-time and historical price data
Table names use quoted identifiers with capital letters (e.g., "Models"). Always quote them in SQL queries to avoid case-sensitivity issues.

Drizzle Configuration

The drizzle.config.ts file defines the ORM settings:
drizzle.config.ts

Configuration Details

  • schema: TypeScript schema definitions at src/db/schema.ts
  • out: Generated SQL migrations stored in drizzle/
  • ssl: Enabled with rejectUnauthorized: false for self-signed certs

Database Connection

The application uses T3 Env for type-safe environment variable access:
src/env.ts

Connection String Format

Components:
  • user: Database username
  • password: Database password
  • host: Database server hostname or IP
  • port: PostgreSQL port (default: 5432)
  • database: Database name
  • sslmode: require, prefer, or disable
Never commit DATABASE_URL to version control. Use .env files locally and environment variables in production.

Migration Workflow

Generate Migrations

After modifying src/db/schema.ts, generate migration files:
This creates timestamped SQL files in drizzle/ like:

Apply Migrations

Run migrations against the database:
This executes all pending migrations in order.

Push Schema (Development)

For rapid prototyping, push schema changes directly:
db:push bypasses migrations and directly syncs schema. Use only in development or when you don’t need migration history.

Schema Management

Key Schema Rules

  1. Quoted Identifiers: All table names use capital letters and require quotes
  2. Text IDs: Primary keys are TEXT (UUID), not SERIAL or INTEGER
  3. Monetary Fields: Stored as TEXT, cast to NUMERIC for calculations
  4. JSONB for Complex Data: Exit plans, AI reasoning stored as JSONB

Example Schema Definition

src/db/schema.ts

Database Seeding

Seed initial data for development:
This runs scripts/seed.ts which:
  1. Clears existing data
  2. Creates default AI models (Apex, Trendsurfer, Contrarian, Sovereign)
  3. Optionally creates sample trades and positions

Seed Script Example

scripts/seed.ts

Production Database Setup

Use a managed service for automatic backups, scaling, and monitoring:
  • Neon: Serverless PostgreSQL with free tier
  • Supabase: PostgreSQL with additional features
  • Railway: Simple managed PostgreSQL
  • AWS RDS: Enterprise-grade with multi-AZ
Neon Example:
  1. Create project at neon.tech
  2. Copy connection string
  3. Set DATABASE_URL environment variable
  4. Run migrations: bun run db:migrate

Option 2: Self-Hosted with Docker

Included in docker-compose.yml:
Start with:

Database Initialization

1

Create Database

If using self-hosted PostgreSQL:
2

Configure Connection

Set DATABASE_URL in .env:
3

Run Migrations

4

Seed Data

5

Verify Schema

This launches Drizzle Studio at https://local.drizzle.studio

Database Maintenance

Backups

Manual Backup:
Automated Backups (cron job):
Docker Backup:

Restore

Or with Docker:

Vacuum and Analyze

Regularly optimize database performance:

Index Optimization

Add indexes for frequently queried columns:

Monitoring

Connection Pool Status

Drizzle automatically manages connection pooling. Monitor active connections:

Slow Query Log

Enable slow query logging in postgresql.conf:

Database Size

Table Sizes

Troubleshooting

Migration Fails

Problem: db:migrate returns errors Solutions:
  1. Check drizzle/meta/_journal.json for migration state
  2. Manually inspect SQL files in drizzle/
  3. Verify database connection: psql $DATABASE_URL
  4. Check for schema conflicts (duplicate tables/columns)
  5. Use db:push to force sync (development only)

Connection Timeouts

Problem: API can’t connect to database Solutions:
  1. Verify DATABASE_URL format and credentials
  2. Check firewall rules (port 5432)
  3. Ensure PostgreSQL is running: systemctl status postgresql
  4. Test connection: psql $DATABASE_URL
  5. Check SSL settings (remove ?sslmode=require if not using SSL)

Quoted Identifier Errors

Problem: relation "models" does not exist Solutions:
  1. PostgreSQL lowercases unquoted identifiers
  2. Always quote table names: SELECT * FROM "Models"
  3. Use Drizzle ORM to avoid manual SQL
  4. Check that migrations preserve quotes

Data Type Mismatch

Problem: Cannot cast TEXT to NUMERIC Solutions:
  1. Use explicit casts: CAST("netPortfolio" AS NUMERIC)
  2. Ensure monetary values are valid numbers (no empty strings)
  3. Validate data before insert/update
  4. Use Drizzle’s type system to catch errors at compile time

Best Practices

  1. Always Use Migrations: Don’t manually modify production schema
  2. Test Locally First: Run migrations on dev database before production
  3. Backup Before Migration: Create backup before applying schema changes
  4. Monitor Performance: Use EXPLAIN ANALYZE for slow queries
  5. Use Indexes: Add indexes for foreign keys and frequently filtered columns
  6. Connection Pooling: Let Drizzle handle connection management
  7. SSL in Production: Always use encrypted connections

Next Steps

Backend Deployment

Deploy the API server with database access

Schema Reference

Detailed schema documentation