> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Database and migrations

> How GatoJS organizes its multi-file Prisma schema, connects to Postgres, and how your project creates, commits and deploys migrations, including after gato add and gato remove.

GatoJS uses Prisma with PostgreSQL. This page covers the schema files, the client and connection pool, and how to run migrations in your project. For the data model and the `organizationId` rule, see [Organizations](https://docs.gatojs.com/concepts/organizations.md).

## Schema files

The schema is a **directory**, `prisma/schema/`, not a single file. Each module ships its own schema file, so adding a module never means editing core files.

| File | Contents |
| - | - |
| `prisma/schema/base.prisma` | The `prisma-client` generator (output `../../src/generated/prisma`) and a `postgresql` datasource without a URL. |
| `prisma/schema/auth.prisma` | better-auth models: `User`, `Session`, `Account`, `Verification`. |
| `prisma/schema/organizations.prisma` | better-auth `organization` plugin models: `Organization`, `Member`, `Invitation`. |
| `prisma/schema/<module>.prisma` | A module's models, e.g. `api-keys.prisma`, `audit-logs.prisma`, `uploads.prisma`. |

Back-relation fields on `User` and `Organization` are written by the kit's generator into `wa:relations` regions. Don't edit inside them by hand. `npx gato generate` rewrites them from installed modules:

```prisma prisma/schema/organizations.prisma theme={null}
model Organization {
  id        String    @id @default(cuid())
  name      String
  slug      String    @unique
  // …
  members     Member[]
  invitations Invitation[]

  // wa:relations:start
  apiKeys ApiKey[]
  auditLogs AuditLog[]
  uploads Upload[]
  // wa:relations:end

  @@map("organizations")
}
```

A typical domain model for your own feature looks like the kit's modules: a required, indexed `organizationId` with a cascading relation.

```prisma prisma/schema/invoices.prisma theme={null}
model Invoice {
  id             String   @id @default(cuid())
  organizationId String   @map("organization_id")
  number         String
  createdAt      DateTime @default(now()) @map("created_at")

  organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)

  @@index([organizationId, createdAt])
  @@map("invoices")
}
```

Because `Invoice` has an `organizationId` field, the [runtime tenant-scope guard](https://docs.gatojs.com/concepts/organizations.md#runtime-guard) covers it automatically.

### Configuration

Prisma CLI commands read `prisma.config.ts`:

```ts prisma.config.ts theme={null}
import dotenv from "dotenv";
import { defineConfig } from "prisma/config";

dotenv.config({ path: [".env.local", ".env"] });

export default defineConfig({
  schema: "prisma/schema",
  migrations: {
    path: "prisma/migrations",
  },
  datasource: {
    url: process.env["DATABASE_URL"],
  },
});
```

The database URL comes only from `DATABASE_URL`. A value in `.env.local` wins over `.env`, and a variable set in your shell wins over both. The app reads the same variable.

## Client and connection

`prisma generate` writes the client to `src/generated/prisma`, which is git-ignored. It runs on `postinstall`, and manually with:

```bash theme={null}
npm run db:generate
```

> [!WARNING]
>
> `npx prisma migrate dev` doesn't run the generator in current Prisma versions. After any schema change, also run `npm run db:generate`, or TypeScript won't know your new models and fields.

Import the client from `@/generated/prisma/client` for types, and use the shared instance for queries:

```ts src/shared/lib/prisma.ts theme={null}
function createPrismaClient() {
  const adapter = new PrismaPg({
    connectionString: process.env.DATABASE_URL,
    max: parsePoolMax(),
    idleTimeoutMillis: 30_000,
    connectionTimeoutMillis: 10_000,
    statement_timeout: 30_000,
  });
  return new PrismaClient({ adapter }).$extends(tenantScopeExtension);
}

export const prisma = globalForPrisma.prisma ?? createPrismaClient();

globalForPrisma.prisma = prisma;
```

* Prisma connects through `@prisma/adapter-pg` with a `pg` pool of up to `DATABASE_POOL_MAX` connections (default `10` when missing or not a positive integer).
* Idle connections close after 30 s, waiting for a free connection times out after 10 s, and Postgres cancels statements running longer than 30 s.
* The client carries the [tenant-scope extension](https://docs.gatojs.com/concepts/organizations.md#runtime-guard).
* The instance is cached on `globalThis` so `next dev` hot reloads reuse the pool.

Use Prisma only in commands, queries and services, never in components or pages. See [Code patterns](https://docs.gatojs.com/guides/code-patterns.md).

## Migrations

> [!NOTE]
>
> **The kit doesn't commit migrations; your project does.** A project's schema depends on which modules you picked, since each module adds its own schema file and relations. A migration history shipped by the kit wouldn't match a project with a different set of modules, so each project starts its own history with an `init` migration.

In the kit repository, `prisma/migrations/` is ignored by a `prisma/migrations/.gitignore` that `gato create` doesn't copy. In a project created with `create-gato-app` / `gato create`, `prisma/migrations/` is **not** ignored, so migrations go into git with no extra steps.

Production applies only migrations committed to the repo: the deploy runs `npx prisma migrate deploy`, which never creates migrations from the schema. Without a committed migrations directory, the production database gets no tables. See [Railway](https://docs.gatojs.com/deployment/railway.md) and [Docker](https://docs.gatojs.com/deployment/docker.md).

### Your first migration

If you let `create-gato-app` run setup, it already ran `npx prisma migrate dev --name init`. That happens after the initial commit, so the migration is still uncommitted. Otherwise, create it yourself:

**1. Make sure migrations aren't ignored**

This command prints nothing when the directory isn't ignored:

```bash theme={null}
git check-ignore -v prisma/migrations/migration_lock.toml
```

**2. Create the initial migration (only if the directory is empty)**

```bash theme={null}
npx prisma migrate dev --name init
```

**3. Commit the whole directory**

Commit every migration folder with its `migration.sql` and `prisma/migrations/migration_lock.toml`.

```bash theme={null}
git add prisma/migrations && git commit -m "chore: initial migration"
```

### Every schema change

```bash theme={null}
npx prisma migrate dev --name add-invoices
npm run db:generate
```

Commit the new migration together with the schema change.

* If the change could drop data or fail on existing rows (for example a new unique field with duplicates), Prisma prints `Warnings for the current datasource:` and asks for confirmation. If the effect isn't intended, answer `n`.
* Changes that can't be executed are reported as `We found changes that cannot be executed:` and nothing is created.
* **Never edit a migration that has been applied anywhere.** Fix it with a new migration. Prisma treats a changed, already-applied migration as history drift.

### After `gato add`, `gato remove` and `gato update`

Adding or removing a module changes `prisma/schema/` (a module schema file and the `wa:relations` regions). The CLI prints the migration command to run next:

```bash gato add theme={null}
npx gato add audit-logs
npx prisma migrate dev --name add-audit-logs
```

```bash gato remove theme={null}
npx gato remove audit-logs
npx prisma migrate dev --name remove-audit-logs
```

```bash gato update theme={null}
npx gato update
npx prisma migrate dev --name kit-<version>
```

`gato update` suggests a migration only when the kit's schema files changed between versions. Then run `npm run db:generate` and commit the migration with the rest of the change.

> [!WARNING]
>
> Removing a module drops its tables in the generated migration. Review the SQL before applying it anywhere with real data.

See [`gato add`](https://docs.gatojs.com/cli/add), [`gato remove`](https://docs.gatojs.com/cli/remove) and [`gato update`](https://docs.gatojs.com/cli/update).

### Tests don't use migrations

Integration tests build their schema with `prisma db push`; end-to-end tests use `prisma db push --force-reset`, or `prisma migrate reset --force` when migrations exist. Both wipe their database, so they refuse to run unless the database name ends in `_test` or `_e2e` respectively. See [Testing](https://docs.gatojs.com/guides/testing.md).

## Migration history drift

Prisma records applied migrations in the `_prisma_migrations` table. `npx prisma migrate dev` applies new migrations from `prisma/migrations/`, but refuses in two cases:

* **History mismatch**: the database has an applied migration that's missing from the directory, or whose file changed since it was applied.
* **Drift** (`Drift detected`): the database schema differs from what the migrations produce, for example because tables were created by `prisma db push`.

Prisma then prints the reason, suggests `prisma migrate reset`, and exits **without changing anything**:

```text theme={null}
Datasource "db": PostgreSQL database "my_app", schema "public" at "localhost:5432"

- Drift detected: Your database schema is not in sync with your migration history.
…
- The following migration(s) are applied to the database but missing from the local migrations directory: 20261027212719_init

We need to reset the "public" schema at "localhost:5432"

You may use prisma migrate reset to drop the development database.
All data will be lost.
```

### First, confirm it's your database

On a fresh clone, this message often means you're connected to **someone else's** database, for example a local Postgres or another project's container on the same port. Migration names you never created in the `missing from the local migrations directory` line are the strongest signal. A reset deletes everything in the database at `DATABASE_URL`, so confirm all of the following first:

1. **Address.** The `Datasource "db": …` line shows `localhost` or `127.0.0.1`, the port you expect (`DB_PORT`, default `5432`) and your project's database name from `docker-compose.yml`. A `DATABASE_URL` in your shell overrides `.env.local`, which overrides `.env`; check with `echo "$DATABASE_URL"`.
2. **Port.** After `docker compose stop`, nothing else is listening on that port.
3. **Repeatable.** After `docker compose up -d` and a healthy `db` service, `npx prisma migrate dev` reports the same problem.
4. **History in the container.** Reading the history directly inside your container matches Prisma's message:

   ```bash theme={null}
   docker compose exec -T db psql -U postgres -d <db_name> -Atc 'SELECT migration_name FROM _prisma_migrations'
   ```

If any check fails, don't reset anything. Find out what you're connected to first.

### What to do

| | Local data not needed | Local data needed |
| - | - | - |
| **Your project** | Restore migrations from git and run `npx prisma migrate dev`. If drift remains: reset, then `npx prisma migrate dev` (no `--name init`). | Restore migrations from git and run `npx prisma migrate dev`. If drift remains: back up, reset, then `npx prisma migrate dev`. |
| **Kit repository** | Reset, then `npx prisma migrate dev --name init` and `npm run admin:create`. | Back up, then as on the left. |

**Restore migrations from git:**

```bash theme={null}
git restore --source=HEAD --staged --worktree prisma/migrations
```

If the deletion is already committed, use the commit before it as `--source` (find it with `git log --oneline -- prisma/migrations`).

> [!WARNING]
>
> In a project, never create a new `init` migration to replace deleted ones. It won't match the history in your databases, and the committed migrations may already be applied on staging, production and teammates' machines.

**Back up before a reset** (save the file outside the repo):

```bash theme={null}
docker compose exec -T db pg_dump -U postgres <db_name> > ~/<db_name>-backup.sql
```

**Reset** only after all four checks pass, and never on a shared, staging or production database:

```bash theme={null}
npx prisma migrate reset
```

It asks for confirmation, then drops all data and applies the migrations from `prisma/migrations/`. Check the `Datasource` line once more before answering `y`.

## Command reference

| Command | What it does | Data |
| - | - | - |
| `npm run db:generate` | Generates the client into `src/generated/prisma`. | Untouched |
| `npx prisma migrate dev --name <name>` | Applies pending migrations, creates a migration from schema changes and applies it. Refuses on drift. | Kept; destructive changes ask first |
| `npx prisma migrate status` | Shows migration state. Doesn't detect schema drift or migrations missing from the end of the history. | Read-only |
| `npx prisma migrate deploy` | Applies committed migrations; creates nothing. Used on deploy. | Kept |
| `npx prisma migrate reset` | Drops all data and re-applies migrations. `--force` skips the prompt. | **Deleted** |
| `npx prisma db push` | Syncs the database to the schema without migrations or history. Used by tests. | Kept; `--force-reset` deletes |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.