Skip to content

fix(api): baseline Prisma migration and fail-fast migrate - #6

Merged
tulubyev merged 1 commit into
mainfrom
fix/prisma-baseline-migration
Oct 13, 2026
Merged

tulubyev merged 1 commit into
mainfrom
fix/prisma-baseline-migration

Conversation

@tulubyev

@tulubyev tulubyev commented Oct 13, 2026 •

Copy link
Copy Markdown
Owner

Что сделано

  1. Начальная миграция. В prisma/migrations лежали только ALTER-миграции (исходную схему создавали через db push), поэтому prisma migrate deploy не работал на пустой БД. Добавлена 20260101_baseline (схема до первой ALTER-миграции, 30 таблиц, 18 enum) и migration_lock.toml.
  2. Ошибки миграций не маскируются. В CMD Dockerfile убран || echo 'Migration skipped (already applied)'. Если migrate deploy падает, контейнер не стартует, причина видна в docker logs.
  3. CLAUDE.md: описание миграций приведено в соответствие с новым поведением и добавлен порядок выкатки.

Как проверено

На одноразовой PostgreSQL 16:

  • Пустая БД: baseline + 4 существующие миграции применяются подряд без ошибок.
  • prisma migrate diff итоговой БД против schema.prisma расходится только в трёх колонках: clients.contract_date, organizations.contract_date, users.phone_otp_expires_at. Старые миграции создали их как TIMESTAMPTZ, схема ждёт TIMESTAMP(3). Это расхождение уже есть на проде, функционально безвредно, здесь не менял.
  • Прод-подобная БД (4 миграции записаны, baseline нет): migrate deploy падает с type "UserRole" already exists, после migrate resolve --applied 20260101_baseline проходит с No pending migrations.
  • Dockerfile локально не собирался (нет Docker), изменена одна строка CMD.

⚠️ Порядок выкатки на прод (обязательно)

Сначала пометить baseline применённым, иначе новый контейнер не стартует (в логе UserRole already exists):

cd /var/www/lastmiles && sudo git pull --ff-only origin main
sudo docker compose build api
sudo docker compose run --rm --no-deps api sh -c "/app/node_modules/.pnpm/node_modules/.bin/prisma migrate resolve --applied 20260101_baseline --schema=/app/apps/api/prisma/schema.prisma"
sudo docker compose up -d api

Что осталось

  • Типы трёх TIMESTAMPTZ-колонок можно выровнять отдельной миграцией, но ALTER TYPE на боевых данных зависит от часового пояса сессии, так что это отдельная задача.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Deployment
    • Empty databases are now initialized automatically when the API starts.
    • Existing databases must have the baseline migration marked as applied before deploying the new image.
    • The API now starts only after database migrations succeed; if a migration fails, the API remains stopped. This helps prevent the service from running against an out-of-date database.

The migrations folder held only ALTER migrations (the original schema was
created with `db push`), so `prisma migrate deploy` failed on an empty
database. Add 20260101_baseline = schema as it was before the first
ALTER migration, plus migration_lock.toml.

Verified on a throwaway PostgreSQL 16: baseline + the 4 existing
migrations apply cleanly on an empty DB, and the resulting schema matches
schema.prisma except 3 pre-existing TIMESTAMPTZ columns (contract_date x2,
phone_otp_expires_at) that the old migrations created as timestamptz.

The container CMD no longer masks a failed `migrate deploy` with
`|| echo 'Migration skipped'`; it now exits so the error is visible in
`docker logs`. Prod must run `migrate resolve --applied 20260101_baseline`
once before starting the new image (documented in CLAUDE.md).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: dc54574f-abc3-4dd9-a83d-7084c290eb8c
📥 Commits

Reviewing files that changed from the base of the PR and between 856abe8 and f29dd51.

📒 Files selected for processing (4)
  • CLAUDE.md
  • apps/api/Dockerfile
  • apps/api/prisma/migrations/20260101_baseline/migration.sql
  • apps/api/prisma/migrations/migration_lock.toml

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

📝 Walkthrough

The API container now runs prisma migrate deploy before starting the application. The change adds a PostgreSQL baseline migration, migration provider configuration, and deployment instructions for existing-schema and empty databases.

Changes: Database Migration and API Startup

Layer / File(s) Summary
Foundational schema
apps/api/prisma/migrations/20260101_baseline/migration.sql
The baseline defines enums and tables for organizations, tenant configuration, users, profiles, delivery locations, and shifts.
Delivery and tracking schema
apps/api/prisma/migrations/20260101_baseline/migration.sql
The baseline defines orders, dispatch offers, routes, route stops, courier location logs, geofence events, and ETA snapshots.
Communications and finance schema
apps/api/prisma/migrations/20260101_baseline/migration.sql
The baseline defines alerts, notifications, tracking tokens, payments, agent reports, payouts, and audit logs.
Schema constraints and provider
apps/api/prisma/migrations/20260101_baseline/migration.sql, apps/api/prisma/migrations/migration_lock.toml
The migration adds unique constraints, lookup indexes, and foreign keys. The migration lock declares PostgreSQL as the provider.
Migration-gated API startup
apps/api/Dockerfile, CLAUDE.md
The container starts the API only after migrations succeed. Deployment instructions cover marking the baseline as applied for an existing schema and automatic migration for an empty database.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Container as API container
  participant Prisma as prisma migrate deploy
  participant PostgreSQL
  participant Node as node dist/app.js
  Container->>Prisma: Run migrations
  Prisma->>PostgreSQL: Apply migrations
  PostgreSQL-->>Prisma: Migration result
  Prisma-->>Container: Success or failure
  Container->>Node: Start only after success
Loading
Merge Risk: ⚪ Minimal · up to f29dd

No concrete issue blocks merging. Follow the documented baseline-resolution step before deploying to an existing database.

Pre-merge checks · Passed 5
Passed Passed checks (5 passed)
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly summarizes the two main changes: adding a baseline Prisma migration and making migration startup fail fast.
Docstring Coverage Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 0…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@tulubyev
tulubyev merged commit 22872f1 into main Oct 13, 2026
5 checks passed
@tulubyev
tulubyev deleted the fix/prisma-baseline-migration branch October 13, 2026 15:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant