# Database Provisioning

## What this skill covers
How databases are declared, provisioned, and connected on the Tawa platform.

## How It Works

1. Declare databases in `catalog-info.yaml` under `spec.databases`
2. On deploy, the builder generates connection strings and creates K8s secrets
3. Environment variables are injected into your pod automatically
4. Your app reads from `process.env` — identical code across all environments

## Supported Types

| Type | Env Variable | Connection Format |
|------|-------------|-------------------|
| `mongodb` | `MONGODB_URI` | `mongodb://{host}:27017/{service}-{env}` |
| `redis` | `REDIS_URL` | `redis://{host}:6379/0` |
| `neo4j` | `NEO4J_URI` | `bolt://{host}:7687` |

Only these three types are supported. Using `postgres`, `mysql`, or any other type will fail during `tawa preflight`.

## YAML Configuration

```yaml
spec:
  databases:
    - type: mongodb          # Creates MONGODB_URI
    - type: redis            # Creates REDIS_URL
    - type: neo4j            # Creates NEO4J_URI
```

### Custom MongoDB Name

```yaml
spec:
  databases:
    - type: mongodb
      name: shared-data      # Uses "shared-data" instead of "{service}-{env}"
```

## Database Naming

MongoDB databases are named `{service}-{environment}` by default:

| Service | Environment | Database Name |
|---------|-------------|---------------|
| my-api | sandbox | my-api-sandbox |
| my-api | prod | my-api-prod |
| my-api | uat | my-api-uat |

## Connecting from Your App

### MongoDB (Mongoose)
```typescript
import mongoose from 'mongoose'

const uri = process.env.MONGODB_URI
if (!uri) throw new Error('MONGODB_URI not configured')
await mongoose.connect(uri)
```

### Redis (ioredis)
```typescript
import Redis from 'ioredis'

const url = process.env.REDIS_URL
if (!url) throw new Error('REDIS_URL not configured')
const redis = new Redis(url)
```

### Neo4j
```typescript
import neo4j from 'neo4j-driver'

const uri = process.env.NEO4J_URI
if (!uri) throw new Error('NEO4J_URI not configured')
const driver = neo4j.driver(uri)
```

## Local Development

Set env vars in `.env` for local dev:
```
MONGODB_URI=mongodb://localhost:27017/my-api-dev
REDIS_URL=redis://localhost:6379/0
NEO4J_URI=bolt://localhost:7687
```

## Key Facts
- The platform creates the connection string, not the database itself
- MongoDB auto-creates databases on first write
- Redis and Neo4j are shared instances — use key prefixes in Redis
- Each environment gets its own K8s secret with different connection strings
- Redeploying does NOT touch your data — databases are persistent
- Adding a database to an existing service: just add it to catalog-info.yaml and redeploy
