Skip to main content

Shared Database

Database connectivity and ORM functionality using Prisma ORM with support for both PostgreSQL and SQLite.

For detailed usage documentation, see the Shared Database documentation on the docs site.

Contributing

Prerequisites

  • Node.js 20+ and Yarn
  • Understanding of Prisma ORM and database concepts
  • Access to PostgreSQL (for production) or SQLite (for development)

Commands

# Build the package
nx build shared-db

# Run tests
nx test shared-db

# Generate Prisma client
nx prisma-generate shared-db

# Run Prisma migrations (development)
nx run shared-db:prisma:migrate

# Push schema to database (development)
nx run shared-db:prisma:push

# Open Prisma Studio
cd packages/shared-db
npx prisma studio

# Lint the package
nx lint shared-db

Environment Variables

The package uses environment variables to configure database connections:

Required Variables

VariableDescriptionExample
DATABASE_URLFull database connection stringfile:./dev.db or postgres://user:pass@host:5432/db

PostgreSQL-specific Variables (Optional)

VariableDescriptionDefault
POSTGRES_HOSTPostgreSQL hostlocalhost
POSTGRES_PORTPostgreSQL port5432
POSTGRES_DBDatabase namesubstrate
POSTGRES_USERDatabase userpostgres
POSTGRES_PASSWORDDatabase password-
POSTGRES_SSLEnable SSL connectionfalse

Database Selection

The package automatically selects the appropriate database adapter based on the DATABASE_URL protocol:

  • file: protocol → SQLite adapter (development/testing)
  • postgres:// or postgresql:// protocol → PostgreSQL adapter (production)

Project Structure

packages/shared-db/
├── prisma/ # Prisma schema and migrations
│ ├── schema.prisma # Main Prisma schema
│ └── migrations/ # Database migrations
├── src/
│ ├── index.ts # Package exports
│ └── generated/ # Prisma generated client
├── docs/ # Documentation (built to docs site)
└── README.md # This file

Working with the Database

Local Development (SQLite)

For local development, use SQLite:

# Set up SQLite database
export DATABASE_URL="file:./dev.db"

# Push schema to database
nx run shared-db:prisma:push

# Open Prisma Studio to view data
cd packages/shared-db
npx prisma studio

Production (PostgreSQL)

For production, use PostgreSQL:

# Set up PostgreSQL database
export DATABASE_URL="postgresql://user:password@localhost:5432/substrate"

# Run migrations
nx run shared-db:prisma:migrate

Adding New Models

  1. Edit packages/shared-db/prisma/schema.prisma
  2. Run nx prisma-generate shared-db to update the client
  3. Run nx run shared-db:prisma:migrate to create a migration
  4. Update related code and tests