Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,8 @@ VERCEL_TEAM_ID=
# Local flag: enable production builds locally via experimental config for SQLite.
# This is required due to a bug: https://github.com/WiseLibs/better-sqlite3/issues/1155#issuecomment-1980454636
# LOCAL_FLAG_ENABLE_LOCAL_PRODUCTION_BUILDS=true

# Local flag: enable migration testing mode with production-like database behavior
# When enabled: disables schema push and enforces foreign keys to match Turso production
# Used automatically by pnpm test:migration - not needed for manual setting
# ENABLE_LOCAL_MIGRATIONS=true
82 changes: 82 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,85 @@ jobs:
env:
DATABASE_URI: 'file:./dev.db'
PAYLOAD_SECRET: ${{ secrets.PAYLOAD_SECRET }}

migration-safety:
name: migration-safety
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- name: 🏗 Setup repo
uses: actions/checkout@v4
with:
fetch-depth: 0 # Need full history to compare with base branch
- name: 🏗 Setup pnpm
uses: pnpm/action-setup@v4
- name: 🏗 Setup Node
uses: actions/setup-node@v4
with:
node-version: 22.x
cache: pnpm
- name: 📦 Install dependencies
run: pnpm ii
shell: bash
- name: 🔍 Check migration safety
id: check-migrations
run: |
# Get the base branch (main for PRs, or previous commit for direct pushes)
if [ "${{ github.event_name }}" = "pull_request" ]; then
BASE_REF="origin/${{ github.base_ref }}"
else
BASE_REF="HEAD^"
fi

# Find new or modified migration files
MIGRATION_FILES=$(git diff --name-only --diff-filter=AM "$BASE_REF" HEAD | grep "^src/migrations/.*\.ts$" | grep -v "index.ts" || true)

if [ -z "$MIGRATION_FILES" ]; then
echo "✅ No new or modified migrations detected"
echo "has_migrations=false" >> $GITHUB_OUTPUT
exit 0
fi

echo "🔍 Checking migration safety for:"
echo "$MIGRATION_FILES"
echo ""
echo "has_migrations=true" >> $GITHUB_OUTPUT

# Run safety check on each migration (don't exit on failure)
set +e
HAS_ISSUES=false
for file in $MIGRATION_FILES; do
echo "Checking: $file"
if ! pnpm migrate:check "$(basename $file)"; then
HAS_ISSUES=true
echo "⚠️ Safety issues detected in $file"
echo ""
fi
done
set -e

if [ "$HAS_ISSUES" = "true" ]; then
echo "has_issues=true" >> $GITHUB_OUTPUT
echo ""
echo "⚠️ Migration safety issues detected - will post comment on PR"
else
echo "has_issues=false" >> $GITHUB_OUTPUT
echo "✅ All migration safety checks passed"
fi
- name: Find existing migration safety comment
if: steps.check-migrations.outputs.has_issues == 'true' && github.event_name == 'pull_request'
id: find-comment
uses: peter-evans/find-comment@v2
with:
issue-number: ${{ github.event.pull_request.number }}
comment-author: 'github-actions[bot]'
body-includes: '### Migration Safety Check'
- name: Create or update PR comment
if: steps.check-migrations.outputs.has_issues == 'true' && github.event_name == 'pull_request'
uses: peter-evans/create-or-update-comment@v3
with:
comment-id: ${{ steps.find-comment.outputs.comment-id }}
issue-number: ${{ github.event.pull_request.number }}
body: ${{ steps.check-migrations.outputs.comment }}
edit-mode: replace
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public/sitemap*.xml
dev.db
dev.db-shm
dev.db-wal
*.db

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was this added? maybe consolidate it with line 16

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was messing around with creating temporary sqlite dbs during this PR and figured I would just add this preemptively.

.env.production
.env.development
tsconfig.tsbuildinfo
Expand Down
21 changes: 21 additions & 0 deletions .husky/check-migrations
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env sh

# Check for new or modified migration files
MIGRATION_FILES=$(git diff --cached --name-only --diff-filter=AM | grep "^src/migrations/.*\.ts$" | grep -v "index.ts")

if [ -n "$MIGRATION_FILES" ]; then
echo "🔍 Migration files detected in commit, running safety checks..."

for file in $MIGRATION_FILES; do
echo "\nChecking: $file"
pnpm run migrate:check -- "$(basename $file)"

if [ $? -ne 0 ]; then
echo "\n⚠️ Migration safety check failed!"
echo "Review the warnings above. To commit anyway, use: git commit --no-verify"
exit 1
fi
done

echo "\n✅ Migration safety checks passed"
fi
1 change: 1 addition & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pnpm run lint-staged
pnpm run tsc
pnpm test
.husky/check-migrations
127 changes: 127 additions & 0 deletions docs/migration-safety.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Migration Safety Checks

This document explains the automated checks in place to prevent data loss during database migrations.

## Background

Payload's `migrate:create` command generates migrations based on schema changes, but doesn't warn about potentially destructive commands.

### Known issue: foreign key cascade delete behavior differences
There is also a difference in behavior between Turso's libSQL servers and our local SQLite databases: Turso does not respect `PRAGMA FOREIGN_KEYS=off` statements inside of transactions. Payload/Drizzle uses this strategy to temporarily disable cascade deletes of foreign key relationships. Because this doesn't work on Turso servers (a libSQL behavior), this can result in data losss in `_rels` tables.

Background reading:
- [SQLite docs highlighting foreign_keys behavior in transactions](https://www.sqlite.org/foreignkeys.html#fk_enable:~:text=It%20is%20not%20possible%20to%20enable%20or%20disable%20foreign%20key%20constraints%20in%20the%20middle%20of%20a%20multi%2Dstatement%20transaction)
- https://github.com/tursodatabase/libsql-client-ts/issues/173

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow wow wow 😨

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hahaha yes, exactly @yuliadub

- https://github.com/ariga/atlas/issues/3317
- https://github.com/launchbadge/sqlx/issues/2085#issuecomment-1237474188

## Automated Checks

### Static Analysis

**What it does:** Scans migration files for dangerous patterns.

**When it runs:**
- Automatically on `git commit` via Husky pre-commit hook
- In CI when migrations are added or modified in pull requests

**Manual usage:**
```bash
# Check all migrations
pnpm migrate:check

# Check specific migration
pnpm migrate:check {migration file name}.ts
```

**Potentially dangerous patterns it detects:**
- `DROP TABLE` operations
- `PRAGMA foreign_keys=OFF` (an indicator that we may lose data in production due to the known issue mentioned above)
- Table recreation pattern (`__new_*`)
- `DROP COLUMN` operations
- `DELETE FROM` without WHERE clause
- `TRUNCATE TABLE` operations
- Column type changes
- Constraint drops

## Workflow

### Creating a new migration

1. Make schema changes in your Payload config
2. Run `pnpm payload migrate:create`
3. Review generated migration file
4. **Optional:** Manually run `pnpm migrate:check <filename>` to preview warnings
Comment thread
busbyk marked this conversation as resolved.
Resolved
5. Commit changes (pre-commit hook runs checks automatically)
6. If warnings appear in the pre-commit check:
- Review the migration for potential data loss
- Manually modify migration to ensure it runs without unintentional data loss
- Use `git commit --no-verify` if you're certain it's safe
7. **Recommended** Test the migration locally using the instructions below

### Testing a migration locally

To manually test the effects of a migration locally, follow these steps:

1. Use a local Turso libSQL server to test migrations to mimic the different behavior of Turso in production: `turso dev`
2. Set this url `http://127.0.0.1:8080` as the `DATABASE_URI` in your `.env`
3. Make sure `ENABLE_LOCAL_MIGRATIONS=true` is set in `.env`
4. If you have already created the migration that you want to test, you must first comment it out from the list of migrations in `/src/migrations/index.ts` **and** move the files outside of the `/src/migrations` directory. Payload will still run migration files in `/src/migrations` even if they're not listed in `/src/migrations/index.ts`.
5. Run migrations prior to the migration you're testing: `pnpm migrate`
6. Seed the db: `pnpm seed:standalone`
7. Run `pnpm dev` and inspect any data you want to make sure persists through the migration to verify it's been created correctly.
8. Move the migration(s) you're testing back into `/src/migrations` and back into the list of migrations in `/src/migrations/index.ts`
9. Run the migration(s) you're testing by running: `pnpm migrate`
10. Inspect the data you expected to persist to ensure the migration has not resulted in data loss.

### CI Integration

When you create a pull request with new or modified migrations:
- The `migration-safety` CI job runs automatically
- If issues are detected, a comment is posted on the PR with details
- Review the warnings and update the migration if needed

## Bypassing Checks

If you're certain a migration is safe despite warnings:

```bash
# Commit without pre-commit hook
git commit --no-verify
```

**⚠️ Use with caution & make sure other checks have passed**

## Fixing migrations with PRAGMA foreign_keys=OFF

When Payload/Drizzle generates migrations that recreate tables (the `__new_*` pattern), they use `PRAGMA foreign_keys=OFF` to prevent cascade deletes. However, **Turso does not respect this pragma inside transactions**, which means relationship tables (like `*_rels`) will still have their data cascade-deleted when the original table is dropped.

### The fix: keep old attributes + mark as disabled/hidden and make a note in the code
Comment thread
stevekuznetsov marked this conversation as resolved.
Resolved

Unfortunately, several solutions we tried still result in data loss due to the foreign key behavior in libSQL. We tried:
- Using `defer_foreign_keys` instead of `foreign_keys` to temporarily disable the cascade delete behavior
- Using backup tables (same foreign key cascade delete issue)
- Temporarily disabling the cascade delete behavior (complex and still resulted in data loss when using a backup table strategy)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one more "wow wow wow 😨 " thanks for digging into this, this is kind of blowing my mind

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea it was quite the journey


The simplest solution here is to keep fields that we want to remove and avoid migrations that use the create new, drop, rename strategy that causes data loss in foreign key relations due to libSQL's inability to disable foreign key constraints inside of a transaction. We can mark these fields as `hidden: true` in our Payload collection configs and leave a code comment explaining that they are deprecated.

This avoids needing the migration at all. It would be ideal to remove the data since we would be making the decision that we don't need it anymore but it is an acceptable trade off.

## Known issues

## Implementation Details

**Pre-commit Hook:** `.husky/check-migrations`
- Runs on new/modified migration files only
- Uses `git diff --cached` to detect staged migration files
- Runs `pnpm migrate:check` on each detected migration

**CI Job:** `.github/workflows/ci.yaml` (migration-safety job)
- Runs on all pull requests
- Compares branch against base to find new/modified migrations
- Posts GitHub comment with findings if issues detected

**Check Script:** `src/scripts/check-migrations.ts`
- Pattern-based analysis of migration file contents
- Focuses only on the `up` function to avoid false positives
- Outputs GitHub-formatted comments when run in CI
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"test": "jest",
"test:watch": "jest --watch",
"migrate": "payload migrate",
"migrate:check": "cross-env NODE_OPTIONS=--no-deprecation payload run ./src/scripts/check-migrations.ts",
"email:build": "email build",
"email:dev": "email dev --dir ./src/emails --port 3001",
"email:export": "email export"
Expand Down
Loading