Updated for nself v0.4.8
Comprehensive database management for nself projects. All database operations in one clean interface with smart defaults and environment awareness.
nself db <subcommand> [OPTIONS]| Command | Description |
|---|---|
migrate | Database migrations (up, down, create, status) |
seed | Environment-aware data seeding |
mock | Deterministic mock data generation |
backup | Backup management and scheduling |
restore | Restore from backups |
schema | Schema tools (diff, diagram, indexes) |
types | Generate TypeScript/Go/Python types from schema |
shell | Interactive PostgreSQL shell |
query | Execute SQL queries |
inspect | Database inspection and analysis |
data | Data export/import/anonymize |
optimize | Database maintenance (vacuum, analyze) |
reset | Reset database to clean state |
status | Quick database status overview |
The fastest way to get started with a database schema:
# Create a schema from template
nself db schema scaffold saas
# Apply everything (import -> migrate -> seed)
nself db schema apply schema.dbmlDesign, import, and manage database schemas with full DBML support.
Create a starter schema from pre-built templates:
nself db schema scaffold <template>
# Available templates:
nself db schema scaffold basic # Users, profiles, posts
nself db schema scaffold ecommerce # Products, orders, cart
nself db schema scaffold saas # Organizations, members, projects
nself db schema scaffold blog # Posts, categories, commentsConvert DBML schema to SQL migration:
nself db schema import schema.dbml
# Creates:
# nself/migrations/20260122_imported_schema.up.sql
# nself/migrations/20260122_imported_schema.down.sqlFull workflow: import DBML, run migrations, generate mock data, and seed:
nself db schema apply schema.dbml
# This automatically:
# 1. Imports DBML -> creates SQL migration
# 2. Runs migration
# 3. Generates mock data (local/staging only)
# 4. Seeds sample usersDisplay current database schema:
nself db schema # Show all tables
nself db schema show users # Show specific table schemaGenerate DBML from database (reverse engineer):
nself db schema diagram > schema.dbml
# Open at dbdiagram.io to visualizeCompare schemas between environments:
nself db schema diff staging # Compare local vs staging
nself db schema diff prod # Compare local vs production
# Output example:
# Schema Differences (local vs staging)
# + Table: user_preferences (missing in staging)
# ~ Column: users.last_login (different type)
# - Index: idx_orders_date (missing in local)Analyze and suggest missing indexes:
nself db schema indexes
# Output:
# Index Recommendations
# [HIGH] orders.user_id - Frequently joined, no index
# [MEDIUM] products.category_id - Used in WHERE clauses
# [LOW] users.created_at - Occasional range queriesManage database schema changes with versioned migrations.
Show migration status:
nself db migrate status
# Shows: Applied, pending, and failed migrationsRun pending migrations:
nself db migrate up # Run all pending
nself db migrate up 3 # Run next 3 onlyRollback migrations:
nself db migrate down # Rollback last 1
nself db migrate down 2 # Rollback last 2Warning: In production, migrate down requires typing yes-destroy-production to confirm.
Create a new migration file:
nself db migrate create add_user_preferences
# Creates: nself/migrations/001_add_user_preferences.sqlDrop all tables and re-run migrations:
nself db migrate fresh # LOCAL ONLY - blocked in productionRepair migration tracking table:
nself db migrate repair # Fix corrupted migration state-- Migration: 001_create_users
-- Created: 2026-01-22
-- UP
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email TEXT UNIQUE NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- DOWN
DROP TABLE IF EXISTS users;Environment-aware data seeding with special handling for user accounts.
Run seeds for current environment:
nself db seed # Run all seeds
nself db seed common # Run common seeds only
nself db seed env # Run environment-specific seeds
nself db seed users # Seed users (environment-aware)| Environment | Behavior |
|---|---|
| Local/Dev | 20 mock users with simple passwords ("password123") |
| Staging | 100 mock users for load testing ("TestUser123!") |
| Production | NO mock users - reads from NSELF_PROD_USERS |
Create a new seed file:
nself db seed create products
# Creates: nself/seeds/common/products.sqlShow seed status:
nself db seed statusnself/seeds/
├── common/ # Always runs first
│ ├── 01_categories.sql
│ └── 02_settings.sql
├── local/ # Development only
│ ├── 01_test_data.sql
│ └── 02_mock_users.sql
├── staging/ # Staging only
│ └── 01_qa_data.sql
└── production/ # Production only
└── 01_admin_users.sql# Environment variable format:
NSELF_PROD_USERS='admin@company.com:Admin User:admin,support@company.com:Support Team:moderator'
# Or config file (nself/config/prod-users.json):
{
"users": [
{
"email": "admin@company.com",
"display_name": "Admin User",
"role": "admin"
}
]
}Generate deterministic, shareable mock data for development and testing.
Auto-generate mock data from schema analysis (recommended):
nself db mock auto
# Automatically:
# - Detects column types (generates appropriate data)
# - Handles email columns -> fake emails
# - Handles name columns -> fake names
# - Handles URL columns -> fake URLs
# - Handles timestamps -> random dates
# - Uses deterministic seed (reproducible across team)Generate mock data with options:
nself db mock # Generate with defaults
nself db mock --seed 12345 # Reproducible data
nself db mock --count 1000 # Specific row count
nself db mock preview # Preview what would be generated
nself db mock config # Show mock configurationClear all mock data:
nself db mock clear # LOCAL ONLYCreate nself/mock/config.json for fine-grained control:
{
"seed": 12345,
"tables": {
"users": { "count": 100, "exclude_columns": ["password_hash"] },
"orders": { "count": 500 },
"products": { "count": 50 }
},
"exclude_tables": ["schema_migrations", "audit_logs"]
}Create and manage database backups with scheduling support.
Create database backup:
nself db backup # Full backup
nself db backup --compress # Compressed (.tar.gz)
nself db backup --data-only # Data without schema
nself db backup --schema-only # Schema without data
nself db backup --name pre-migration # Custom nameList available backups:
nself db backup listSchedule automated backups:
nself db backup schedule --daily # Daily at 2 AM
nself db backup schedule --weekly # Weekly on Sunday
nself db backup schedule --cron "0 2 * * *" # Custom scheduleRemove old backups:
nself db backup prune 10 # Keep last 10 backupsRestore from backup:
nself db restore # Restore from latest
nself db restore nself_full_20260122.sql # Specific backup
nself db restore --list # List available backups
nself db restore https://backups.example.com/latest.sql.gz # From URL
nself db restore backup.sql --database test_db # Different databaseSafety: In production, restore requires typing yes-destroy-production.
# Restore production backup to staging (with anonymization)
ENV=staging nself db restore prod_backup.sql --anonymize
# Restore to local development
ENV=local nself db restore staging_backup.sqlDatabase analysis and performance insights (similar to Supabase inspect db).
Database overview:
nself db inspect # Overview: tables, size, connections
# Example output:
# Database Overview: nhost
# Tables: 15
# Total Size: 256 MB
# Connections: 12/100
# Cache Hit Ratio: 98.5% (healthy)nself db inspect size # Table sizes
nself db inspect cache # Cache hit ratios
nself db inspect index # Index usage analysis
nself db inspect unused-indexes # Find unused indexes
nself db inspect bloat # Table bloat (dead tuples)
nself db inspect slow # Slow query analysis
nself db inspect locks # Current locks
nself db inspect connections # Active connectionsGenerate typed interfaces from your database schema.
nself db types typescript
nself db types typescript --output src/types/
nself db types typescript --commentsExample output:
// Generated by nself db types
export interface User {
id: string;
email: string;
display_name: string | null;
created_at: Date;
updated_at: Date;
}nself db types go
# Generates types/models.gonself db types python
# Generates types/models.py with dataclassesOpen interactive psql shell:
nself db shell # Full access
nself db shell --readonly # Read-only (safe for production)Execute SQL queries:
nself db query "SELECT * FROM users LIMIT 10"
nself db query "SELECT * FROM users" --json
nself db query "SELECT * FROM users" --csv
nself db query -f query.sql # Execute from fileExport, import, and anonymize data.
# Export
nself db data export users --format csv
nself db data export users --format json
nself db data export orders --where "created_at > '2026-01-01'"
# Import
nself db data import users.csv
# Anonymize PII data
nself db data anonymize
# Sync from another environment
nself db data sync staging --anonymizeRun VACUUM ANALYZE:
nself db optimize # Standard vacuum
nself db optimize users # Specific table
nself db optimize --full # Full vacuum (reclaims disk space)Reset database to clean state:
nself db reset # LOCAL ONLY
nself db reset --force # Skip confirmation# Directories
NSELF_MIGRATIONS_DIR=nself/migrations
NSELF_SEEDS_DIR=nself/seeds
NSELF_BACKUPS_DIR=_backups
NSELF_TYPES_DIR=types
NSELF_MOCK_DIR=nself/mock
# Mock data
NSELF_MOCK_SEED= # Deterministic seed (optional)
NSELF_MOCK_COUNT=100 # Default rows per table
# Backup
NSELF_BACKUP_COMPRESS=true
NSELF_BACKUP_RETENTION=30 # Days to keep
# Production users (for seeding)
NSELF_PROD_USERS='admin@company.com:Admin:admin'
NSELF_MOCK_USER_COUNT=20 # local: 20, staging: 100Operations are blocked or require confirmation based on environment:
| Operation | Local | Staging | Production |
|---|---|---|---|
migrate fresh | Allowed | Blocked | Blocked |
mock | Allowed | Allowed | Blocked |
reset | Allowed | Confirm | Blocked |
restore | Auto | Confirm | Type phrase |
migrate down | Allowed | Confirm | Type phrase |
# Quick Start (Recommended)
nself db schema scaffold saas # Create starter schema
nself db schema apply schema.dbml # Import -> migrate -> seed
# Schema Design
nself db schema scaffold basic # Create from template
nself db schema import file.dbml # DBML -> SQL migration
nself db schema diagram # Database -> DBML
nself db schema diff staging # Compare schemas
# Migrations
nself db migrate status # Check status
nself db migrate up # Run pending
nself db migrate down # Rollback last
nself db migrate create NAME # Create new
# Seeding
nself db seed # Run all seeds
nself db seed users # Seed users (env-aware)
# Mock Data
nself db mock auto # Auto-generate from schema
nself db mock --seed 123 # Reproducible data
# Backup/Restore
nself db backup # Create backup
nself db restore # Restore latest
# Types
nself db types typescript # Generate TS types
# Inspection
nself db inspect # Database overview
nself db shell # Interactive psql