# Database Setup

Turso (SQLite at edge) with Drizzle ORM for type-safe database access.

## Structure

```
src/db/
├── schema/          # Database schema definitions
│   ├── index.ts     # Schema exports
│   ├── users.ts     # User accounts
│   ├── projects.ts  # Projects
│   ├── scripts.ts   # Scripts
│   ├── characters.ts # Characters
│   └── scenes.ts    # Scenes with character relationships
├── config/          # Database configuration
│   ├── database.ts  # Primary database manager
│   ├── edge-database.ts # Edge replica manager
│   └── migrations.ts # Drizzle ORM setup
└── migrations/      # Migration files (generated)
```

## Environment Variables

```bash
TURSO_DATABASE_URL="libsql://<region>-<project>.turso.io"
TURSO_AUTH_TOKEN="<auth-token>"
```

## Installation

```bash
npm install @libsql/client drizzle-orm drizzle-kit
```

## Usage

### Primary Database

```typescript
import { db } from "./config/migrations";
import { users } from "../schema";

// Query
const allUsers = await db.select().from(users);

// Insert
const newUser = await db.insert(users).values({
  email: "user@example.com",
  username: "johndoe",
  role: "editor",
}).returning();
```

### Edge Database

```typescript
import { createEdgeDatabaseManager } from "./config/edge-database";

const edgeDb = createEdgeDatabaseManager({
  primaryRegion: {
    region: "primary",
    url: "libsql://primary.turso.io",
    authToken: process.env.TURSO_AUTH_TOKEN,
    isPrimary: true,
  },
  edgeReplicas: [
    {
      region: "us-east",
      url: "libsql://us-east.turso.io",
      authToken: process.env.TURSO_AUTH_TOKEN,
    },
    {
      region: "eu-west",
      url: "libsql://eu-west.turso.io",
      authToken: process.env.TURSO_AUTH_TOKEN,
    },
  ],
});

// Query on edge
const users = await edgeDb.queryOnDefaultEdge<User>("SELECT * FROM users");
```

## Migrations

```bash
# Generate migrations
npx drizzle-kit generate

# Push schema changes
npx drizzle-kit push

# Run migrations
npx drizzle-kit migrate
```

## Schema Overview

### users
- User accounts with roles (admin, editor, viewer)
- Authentication and authorization

### projects
- Project containers owned by users
- Public/private visibility

### scripts
- Screenplay documents within projects
- Version tracking and status management

### characters
- Character definitions for scripts
- Role-based categorization

### scenes
- Scene content with character relationships
- Many-to-many relationship between scenes and characters
