# Database Connection Guide

## Supported Database Layouts

The explorer backend supports **two deployment modes**:

1. **Standalone explorer DB**
   - User: usually `explorer`
   - Database: usually `explorer`
   - Migration mode: full Track 2-4 schema

2. **Shared Blockscout DB**
   - User: usually `blockscout`
   - Database: usually `blockscout`
   - Migration mode: explorer auth/operator subset only

Use `bash scripts/run-migration-0010.sh` for both modes. The helper auto-detects whether it is connected to a standalone explorer database or a shared Blockscout database and chooses the safe migration path automatically.

## Correct Connection Command

For a **standalone explorer database**, use:

```bash
export DB_PASSWORD='<your explorer DB password>'
PGPASSWORD="$DB_PASSWORD" psql -h localhost -U explorer -d explorer -c "SELECT 1;"
```

For a **shared Blockscout database**, use:

```bash
export DB_HOST=localhost
export DB_USER=blockscout
export DB_NAME=blockscout
export DB_PASSWORD='<your Blockscout DB password>'
PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;"
```

Do **not** run the full `0010_track_schema.up.sql` directly against the shared Blockscout DB.

**NOT:**
```bash
# ❌ Wrong - mismatched user/database pair
PGPASSWORD='blockscout' psql -h localhost -U blockscout -d explorer -c "SELECT 1;"
```

## Step-by-Step Database Setup

### 1. Test Connection

```bash
# Test connection to custom explorer database
export DB_PASSWORD='<your explorer DB password>'
PGPASSWORD="$DB_PASSWORD" psql -h localhost -U explorer -d explorer -c "SELECT version();"
```

### 2. Check if Tables Exist

```bash
# Check the database mode and required tables
bash scripts/check-database-connection.sh
```

### 3. Run Migration (if tables don't exist)

```bash
cd explorer-monorepo
export DB_PASSWORD='<your explorer DB password>'
bash scripts/run-migration-0010.sh
```

### 4. Verify Migration

```bash
# Standalone explorer DB should include Track 2-4 tables plus auth/operator tables.
# Shared Blockscout DB should include at least:
#   wallet_nonces, operator_roles, operator_events, operator_ip_whitelist
bash scripts/check-database-connection.sh
```

## Troubleshooting

### If Connection Fails

1. **Check if PostgreSQL is running:**
   ```bash
   systemctl status postgresql
   ```

2. **Check if user exists:**
   ```bash
   # Connect as postgres superuser
   sudo -u postgres psql -c "\du"
   ```
   
   You should see both `blockscout` and `explorer` users.

3. **Check if database exists:**
   ```bash
   sudo -u postgres psql -c "\l"
   ```
   
   You should see both `blockscout` and `explorer` databases.

4. **Create a standalone explorer user and database if you want a dedicated backend DB:**
   ```bash
   sudo -u postgres psql << EOF
   CREATE USER explorer WITH PASSWORD '<set-a-strong-password>';
   CREATE DATABASE explorer OWNER explorer;
   GRANT ALL PRIVILEGES ON DATABASE explorer TO explorer;
   \q
   EOF
   ```

### If Password Authentication Fails

1. **Verify the correct password is exported in `DB_PASSWORD`**
2. **Confirm you are connecting with the right mode pair**
   - standalone explorer DB: `explorer` / `explorer`
   - shared Blockscout DB: `blockscout` / `blockscout`

2. **Check pg_hba.conf:**
   ```bash
   sudo cat /etc/postgresql/*/main/pg_hba.conf | grep -E "(local|host.*explorer)"
   ```
   
   Should allow password authentication for local connections.

3. **Reload PostgreSQL:**
   ```bash
   sudo systemctl reload postgresql
   ```

## Quick Fix Script

Use the provided script:

```bash
cd explorer-monorepo
export DB_PASSWORD='<your explorer DB password>'
bash scripts/fix-database-connection.sh
```

This script will:
- Test the connection
- Check for existing tables
- Run migration if needed
- Provide next steps

## After Database is Connected

1. **Restart API server with database:**
   ```bash
   pkill -f api-server
   cd explorer-monorepo/backend
   export DB_PASSWORD='<your explorer DB password>'
   export JWT_SECRET='your-secret-here'
   ./bin/api-server
   ```

2. **Verify health endpoint:**
   ```bash
   curl http://localhost:8080/health
   ```
   
   Should show database as "ok" instead of "error".

3. **Test authentication:**
   ```bash
   curl -X POST http://localhost:8080/api/v1/auth/nonce \
     -H 'Content-Type: application/json' \
     -d '{"address":"0x1234567890123456789012345678901234567890"}'
   ```
   If the response mentions `wallet_nonces`, returns `service_unavailable`, or the wallet popup shows `Nonce: undefined`, rerun `bash scripts/run-migration-0010.sh`, restart the backend, and retry.

## Summary

- **Standalone explorer DB:** use the `explorer` user/database pair and the full Track 2-4 schema
- **Shared Blockscout DB:** use the Blockscout credentials and let `scripts/run-migration-0010.sh` apply only the auth/operator subset
- **Do not** apply `0010_track_schema.up.sql` directly to the shared Blockscout DB
