# nself db Comprehensive database management for nself projects. All database operations in one clean interface with smart defaults. ## Usage ```bash nself db [OPTIONS] ``` ## Subcommands | 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 | | `hasura` | Hasura console and metadata management | --- ## Migrations Manage database schema changes with versioned migrations. ### Commands ```bash # Show migration status nself db migrate status # Run all pending migrations nself db migrate up # Run specific number of migrations nself db migrate up 3 # Rollback last migration nself db migrate down # Rollback specific number nself db migrate down 2 # Create new migration nself db migrate create add_user_preferences # Fresh: Drop all and re-run (NON-PRODUCTION ONLY) nself db migrate fresh # Repair migration tracking table nself db migrate repair ``` ### Migration Files Migrations are stored in `nself/migrations/`: ``` nself/migrations/ ├── 001_create_users.sql ├── 002_add_preferences.sql └── 003_create_orders.sql ``` ### Migration File Format ```sql -- 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 Variables | Variable | Default | Description | |----------|---------|-------------| | `NSELF_MIGRATIONS_DIR` | `nself/migrations` | Migrations directory | --- ## Seeding Environment-aware data seeding with special handling for user accounts. ### Commands ```bash # Run all seeds for current environment nself db seed # Run common seeds only nself db seed common # Run environment-specific seeds nself db seed env # Seed users (environment-aware) nself db seed users # Create new seed file nself db seed create products # Show seed status nself db seed status ``` ### Seed Directory Structure ``` nself/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 ``` ### User Seeding by Environment **Local/Development:** - Generates 20 mock users by default - Simple passwords ("password123") - Test accounts: user@test.local, admin@test.local **Staging:** - Generates 100 mock users for load testing - Stronger test passwords ("TestUser123!") - QA accounts for testing **Production:** - **NO mock users** - only explicit configuration - Reads from `NSELF_PROD_USERS` or `nself/config/prod-users.json` - Generates secure random passwords ### Production User Configuration Environment variable: ```bash NSELF_PROD_USERS='admin@company.com:Admin User:admin,support@company.com:Support Team:moderator' ``` Or config file (`nself/config/prod-users.json`): ```json { "users": [ { "email": "admin@company.com", "display_name": "Admin User", "role": "admin" }, { "email": "support@company.com", "display_name": "Support Team", "role": "moderator" } ] } ``` ### Environment Variables | Variable | Default | Description | |----------|---------|-------------| | `NSELF_SEEDS_DIR` | `nself/seeds` | Seeds directory | | `NSELF_MOCK_USER_COUNT` | `20` (local), `100` (staging) | Mock users to create | | `NSELF_PROD_USERS` | - | Production users (email:name:role,...) | --- ## Mock Data Generate deterministic, shareable mock data for development and testing. ### Commands ```bash # Auto-generate mock data from schema (recommended) nself db mock auto # Generate mock data with default settings nself db mock # Generate with specific seed (reproducible) nself db mock --seed 12345 # Generate with row count nself db mock --count 1000 # Preview what would be generated nself db mock preview # Clear all mock data nself db mock clear # Show mock configuration nself db mock config ``` ### Auto-Generation (Schema-Aware) The `mock auto` command analyzes your database schema and generates appropriate mock data: ```bash nself db mock auto ``` It 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) ### Features - **Deterministic**: Same seed produces same data every time - **Shareable**: Team members can reproduce exact data sets - **Schema-aware**: Respects foreign keys and constraints - **Configurable**: Control row counts per table ### Configuration File Create `nself/mock/config.json`: ```json { "seed": 12345, "tables": { "users": { "count": 100, "exclude_columns": ["password_hash"] }, "orders": { "count": 500 }, "products": { "count": 50 } }, "exclude_tables": ["schema_migrations", "audit_logs"] } ``` ### Environment Variables | Variable | Default | Description | |----------|---------|-------------| | `NSELF_MOCK_SEED` | Random | Seed for deterministic generation | | `NSELF_MOCK_COUNT` | `100` | Default row count per table | | `NSELF_MOCK_DIR` | `nself/mock` | Mock configuration directory | --- ## Backup Create and manage database backups with scheduling support. ### Commands ```bash # Create backup nself db backup # Create backup with custom name nself db backup --name pre-migration # List all backups nself db backup list # Create data-only backup (no schema) nself db backup --data-only # Create schema-only backup nself db backup --schema-only # Compressed backup nself db backup --compress # Schedule automated backups nself db backup schedule # Prune old backups (keep last N) nself db backup prune 10 ``` ### Backup Types | Type | Contents | Use Case | |------|----------|----------| | `full` | Schema + data | Complete restoration | | `data` | Data only | Preserve schema, restore data | | `schema` | Schema only | Structure backup | ### Backup Location Backups are stored in `_backups/`: ``` _backups/ ├── nself_full_20260122_143000.sql ├── nself_full_20260122_143000.sql.gz └── nself_data_20260121_120000.sql ``` ### Scheduling The schedule command creates a cron job for automated backups: ```bash # Daily backups at 2 AM nself db backup schedule --daily # Weekly backups on Sunday nself db backup schedule --weekly # Custom schedule nself db backup schedule --cron "0 2 * * *" ``` ### Environment Variables | Variable | Default | Description | |----------|---------|-------------| | `NSELF_BACKUPS_DIR` | `_backups` | Backup storage directory | | `NSELF_BACKUP_COMPRESS` | `true` | Compress backups by default | | `NSELF_BACKUP_RETENTION` | `30` | Days to keep backups | --- ## Restore Restore database from backups with safety guards. ### Commands ```bash # Restore from latest backup nself db restore # Restore from specific backup nself db restore nself_full_20260122_143000.sql # List available backups nself db restore --list # Restore from URL nself db restore https://backups.example.com/latest.sql.gz # Restore to different database nself db restore backup.sql --database test_db ``` ### Safety Features - **Production Protection**: Requires explicit confirmation - **Staging Warning**: Prompts before restore - **Local**: Restores without confirmation ### Cross-Environment Restore ```bash # 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.sql ``` --- ## Schema Tools Design, import, and manage database schemas with full DBML support. ### Quick Start (Recommended Workflow) ```bash # 1. Create a starter schema from template nself db schema scaffold basic # Also: ecommerce, saas, blog # 2. Edit schema.dbml (or use dbdiagram.io to design) # 3. Apply everything in one command: nself db schema apply schema.dbml # Import → migrate → seed ``` ### Commands ```bash # Design & Import nself db schema scaffold