PostgreSQL Setup
Option 1: Docker Compose (Development)
The easiest way to run PostgreSQL locally:Start PostgreSQL with Docker Compose
54320 to avoid conflicts with system PostgreSQL.Option 2: Managed PostgreSQL (Production)
For production, use a managed PostgreSQL service:Option 3: Local PostgreSQL Installation
If you have PostgreSQL installed locally:Database Schema
Better Hub’s database schema is defined inapps/web/prisma/schema.prisma.
Core Models
User accounts with GitHub authenticationKey fields:
id: Unique user identifieremail: User email addressgithubPat: Optional GitHub Personal Access TokenonboardingDone: Onboarding completion statusstripeCustomerId: Stripe customer reference
Active user sessionsKey fields:
token: Session token (unique)expiresAt: Expiration timestampipAddress: Client IP addressuserAgent: Client user agent
OAuth provider accounts (GitHub)Key fields:
providerId: OAuth provider (“github”)accessToken: Encrypted OAuth access tokenrefreshToken: Encrypted refresh tokenscope: Granted OAuth scopes
Feature Models
Ghost AI chat conversationsRelations:
- Has many
ChatMessagerecords - Unique per
userId+contextKey
Cached GitHub API responsesKey fields:
cacheKey: Cache identifiercacheType: Type of cached datadataJson: Serialized response dataetag: GitHub ETag for conditional requests
AI usage tracking for billingKey fields:
taskType: Type of AI operationcostUsd: Cost in USDcreditUsed: Credits consumedstripeReported: Whether usage was reported to Stripe
Vector embeddings for semantic searchKey fields:
contentType: Type of content (issue, PR, discussion)embeddingJson: Vector embedding datasnippet: Text snippet for display
Full Schema Reference
View the complete schema atapps/web/prisma/schema.prisma.
Prisma Configuration
Client Generation
Prisma Client is generated to a custom location:npm install(via postinstall script)npm run build- Manual:
npx prisma generate
Import Prisma Client
Use the centralized Prisma instance:Connection Pooling
For serverless environments (Vercel, AWS Lambda), use Prisma’s connection pooling:apps/web/src/lib/db.ts.
Database Migrations
Development Workflow
Create migration
- Creates a new migration file
- Applies it to your database
- Regenerates Prisma Client
Production Deployment
Apply migrations
Run migrations before deploying new code:This applies all pending migrations without interactive prompts.
Migration Best Practices
- Test migrations locally before deploying
- Backup production database before applying migrations
- Make backwards-compatible changes when possible:
- Add new optional fields instead of required ones
- Add new tables instead of modifying existing ones
- Use multi-step migrations for breaking changes
- Review generated SQL in migration files before applying
Database Operations
Reset Database (Development)
Wipe database and reapply all migrations:View Data with Prisma Studio
Open a visual database browser:http://localhost:5555.
Seed Database
Create initial data for development:package.json:
Indexing Strategy
Better Hub uses indexes for query performance:User Queries
Session Queries
GitHub Cache
Usage Tracking
apps/web/prisma/schema.prisma.
Performance Optimization
Query Optimization
Use select to fetch only needed fields:Connection Pooling
For serverless environments, limit connection pool size:Pagination
Use cursor-based pagination for large datasets:Backup and Recovery
Automated Backups
Most managed PostgreSQL services provide automated backups:- Neon: Automatic point-in-time recovery
- Supabase: Daily automated backups
- Railway: Automatic snapshots
Manual Backup
Create a manual backup:Restore from Backup
Troubleshooting
Connection Refused
Error:Can't reach database server
Solutions:
- Verify database is running:
docker ps(Docker) or check service status - Check connection string format
- Verify firewall rules allow connections
Migration Failed
Error: Migration fails midway Solutions:- Check migration SQL for syntax errors
- Verify database permissions
- Manually fix database state and mark migration as applied:
Schema Out of Sync
Error:Prisma schema is out of sync with database
Solutions:
- Development:
npx prisma migrate dev - Production:
npx prisma migrate deploy - Force sync (development only):
npx prisma db push
Too Many Connections
Error:too many connections
Solutions:
- Reduce connection pool size
- Use connection pooler (PgBouncer)
- Check for connection leaks in code
Security
Connection Security
Data Encryption
Sensitive fields are encrypted at the application level:- OAuth tokens (via Better Auth)
- GitHub Personal Access Tokens
- API keys
BETTER_AUTH_SECRET as the key.