-
Notifications
You must be signed in to change notification settings - Fork 1
Implement ORM migrator #896
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
64e8cf4
Implement orm migrator
d39b9f6
fix linting
96a61a9
fix tests
e7a8bad
fix tests
0d704d6
fixes
10dff2e
add init file
f6fd4fe
support CLI usage
kibertoad eda89fd
implement CLI tests
kibertoad 32a8720
cleanup
kibertoad f9a9d05
add support for cockroachdb
kibertoad 33194f6
improve validation
kibertoad eb474d7
address updatedAt topic
kibertoad File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| DATABASE_URL=postgresql://testuser:pass@localhost:5432/test | ||
| MYSQL_DATABASE_URL=mysql://root:pass@localhost:3306/test |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
108 changes: 108 additions & 0 deletions
108
packages/app/drizzle-utils/docs/migrating-from-prisma.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| # Migrating from Prisma to Drizzle | ||
|
|
||
| This is the recommended workflow when migrating from Prisma. The same approach applies to any ORM. | ||
|
|
||
| ## Step 1: Install Drizzle | ||
|
|
||
| ```bash | ||
| npm install drizzle-orm drizzle-kit | ||
| ``` | ||
|
|
||
| ## Step 2: Create your Drizzle schema | ||
|
|
||
| You have three options: | ||
|
|
||
| - **Introspect from the database** (recommended): Run `npx drizzle-kit introspect` to generate a Drizzle schema from your existing database. This is the safest option because it reflects the actual database state, not the Prisma schema which may have drifted. | ||
| - **Convert from Prisma schema manually**: Rewrite your `schema.prisma` models as Drizzle table definitions. Be careful to match column types, defaults, and constraints exactly. | ||
| - **Use a Prisma generator**: Community tools like [`prisma-generator-drizzle`](https://github.com/fdarian/prisma-generator-drizzle) can generate a Drizzle schema from your `schema.prisma`, but always review the output. | ||
|
|
||
| See also: [Drizzle official guide — Migrate from Prisma](https://orm.drizzle.team/docs/migrate/migrate-from-prisma) | ||
|
|
||
| ## Step 3: Configure `drizzle.config.ts` | ||
|
|
||
| ```typescript | ||
| import { defineConfig } from 'drizzle-kit' | ||
|
|
||
| export default defineConfig({ | ||
| schema: './src/db/schema.ts', | ||
| out: './drizzle/migrations', | ||
| dialect: 'postgresql', // or 'mysql' | ||
| }) | ||
| ``` | ||
|
|
||
| ## Step 4: Generate the initial migration | ||
|
|
||
| ```bash | ||
| npx drizzle-kit generate | ||
| ``` | ||
|
|
||
| This produces SQL migration files that describe your full schema (`CREATE TABLE`, etc.). These describe the *target state*, which your database already has — they must NOT be executed directly. | ||
|
|
||
| Review the generated SQL to verify it matches your existing database. If there are differences, fix your Drizzle schema and regenerate. | ||
|
|
||
| ## Step 5: Mark migrations as applied (the baseline) | ||
|
|
||
| Since your `drizzle.config.ts` already has the connection details and migrations folder, just run the CLI: | ||
|
|
||
| ```bash | ||
| npx @lokalise/drizzle-utils mark-migrations-applied ./drizzle.config.ts | ||
| ``` | ||
|
|
||
| The CLI reads `dialect`, `dbCredentials`, and `out` from your config, connects to the database, and marks all existing migrations as applied. | ||
|
|
||
| Run this **once per environment** (local, staging, production). The command is idempotent, so running it again is safe — already-tracked migrations are skipped. | ||
|
|
||
| <details> | ||
| <summary>Alternative: use the function directly in a script</summary> | ||
|
|
||
| If you need more control (e.g. custom table name, schema, or executor), create a one-time script: | ||
|
|
||
| ```typescript | ||
| import { markMigrationsApplied } from '@lokalise/drizzle-utils' | ||
| import postgres from 'postgres' | ||
|
|
||
| const sql = postgres(process.env.DATABASE_URL!) | ||
|
|
||
| const result = await markMigrationsApplied({ | ||
| migrationsFolder: './drizzle/migrations', | ||
| executor: { | ||
| run: (query) => sql.unsafe(query).then(() => {}), | ||
| all: (query) => sql.unsafe(query) as Promise<Record<string, unknown>[]>, | ||
| }, | ||
| }) | ||
|
|
||
| console.log(`Baseline complete — Applied: ${result.applied}, Skipped: ${result.skipped}`) | ||
| await sql.end() | ||
| ``` | ||
|
|
||
| </details> | ||
|
|
||
| ## Step 6: Verify the baseline | ||
|
|
||
| ```bash | ||
| npx drizzle-kit migrate | ||
| ``` | ||
|
|
||
| This should be a **no-op** — all migrations are already tracked, so nothing is executed. If Drizzle tries to run migrations here, your baseline was not applied correctly. | ||
|
|
||
| ## Step 7: Remove Prisma and deploy | ||
|
|
||
| - Remove `prisma` and `@prisma/client` from your dependencies | ||
| - Delete `schema.prisma` and the `prisma/` migrations folder | ||
| - Replace all `PrismaClient` usage with Drizzle queries | ||
| - Drop the Prisma shadow database and `_prisma_migrations` table when you are confident the migration is complete | ||
|
|
||
| From this point on, all new schema changes go through the normal Drizzle workflow: | ||
|
|
||
| ```bash | ||
| # Edit your Drizzle schema, then: | ||
| npx drizzle-kit generate # generates a new migration | ||
| npx drizzle-kit migrate # applies only the new migration | ||
| ``` | ||
|
|
||
| ## Important notes | ||
|
|
||
| - **Run the baseline before `drizzle-kit migrate`**: If you run `migrate` first, Drizzle will attempt to execute `CREATE TABLE` statements and fail. | ||
CarlosGamero marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| - **Schema drift**: If your Prisma schema and actual database have drifted apart, use `drizzle-kit introspect` rather than converting from Prisma — the database is the source of truth. | ||
| - **Parallel ORM usage**: During the transition you can run Prisma and Drizzle side-by-side. Just make sure all new migrations go through one ORM only (Drizzle) to avoid conflicts. | ||
| - **CI/CD**: Add the baseline script to your deployment pipeline so it runs before `drizzle-kit migrate`. Since it's idempotent, it's safe to run on every deploy. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
packages/app/drizzle-utils/src/cli/markMigrationsApplied.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| import { resolve } from 'node:path' | ||
| import { execCommand } from 'cli-testlab' | ||
| import { describe, it } from 'vitest' | ||
|
|
||
| const CLI_PATH = resolve(__dirname, 'markMigrationsApplied.ts') | ||
| const FIXTURES_DIR = resolve(__dirname, '../../test/fixtures') | ||
| const CLI = `node --experimental-strip-types ${CLI_PATH}` | ||
|
|
||
| describe('mark-migrations-applied CLI', () => { | ||
| describe('argument validation', () => { | ||
| it('shows usage and exits with error when no arguments provided', async () => { | ||
| await execCommand(CLI, { | ||
| expectedErrorMessage: 'Usage:', | ||
| }) | ||
| }) | ||
|
|
||
| it('shows help with --help flag', async () => { | ||
| await execCommand(`${CLI} --help`, { | ||
| expectedOutput: ['Usage:', '--help'], | ||
| }) | ||
| }) | ||
|
|
||
| it('shows help with -h flag', async () => { | ||
| await execCommand(`${CLI} -h`, { | ||
| expectedOutput: 'Usage:', | ||
| }) | ||
| }) | ||
| }) | ||
|
|
||
| describe('config validation', () => { | ||
| it('exits with error for unsupported dialect', async () => { | ||
| await execCommand(`${CLI} ${FIXTURES_DIR}/drizzle-invalid-dialect.config.ts`, { | ||
| expectedErrorMessage: 'Unsupported or missing dialect', | ||
| }) | ||
| }) | ||
|
|
||
| it('exits with error when dbCredentials is missing', async () => { | ||
| await execCommand(`${CLI} ${FIXTURES_DIR}/drizzle-no-credentials.config.ts`, { | ||
| expectedErrorMessage: 'Missing dbCredentials', | ||
| }) | ||
| }) | ||
|
|
||
| it('exits with error for non-existent config file', async () => { | ||
| await execCommand(`${CLI} ./nonexistent.config.ts`, { | ||
| expectedErrorMessage: 'nonexistent', | ||
| }) | ||
| }) | ||
| }) | ||
|
|
||
| describe('PostgreSQL integration', () => { | ||
| it('marks migrations as applied', async () => { | ||
| await execCommand(`${CLI} ${FIXTURES_DIR}/drizzle-pg-url.config.ts`, { | ||
| expectedOutput: ['Dialect: postgresql', 'Done', '0000_init', '0001_add_users'], | ||
| env: { DATABASE_URL: process.env.DATABASE_URL }, | ||
| }) | ||
| }) | ||
|
|
||
| it('is idempotent — skips already applied migrations on second run', async () => { | ||
| await execCommand(`${CLI} ${FIXTURES_DIR}/drizzle-pg-url.config.ts`, { | ||
| expectedOutput: ['Skipped: 2'], | ||
| env: { DATABASE_URL: process.env.DATABASE_URL }, | ||
| }) | ||
| }) | ||
| }) | ||
|
|
||
| describe('MySQL integration', () => { | ||
| it('marks migrations as applied', async () => { | ||
| await execCommand(`${CLI} ${FIXTURES_DIR}/drizzle-mysql-url.config.ts`, { | ||
| expectedOutput: ['Dialect: mysql', 'Done', '0000_init'], | ||
| env: { MYSQL_DATABASE_URL: process.env.MYSQL_DATABASE_URL }, | ||
| }) | ||
| }) | ||
|
|
||
| it('is idempotent — skips already applied migrations on second run', async () => { | ||
| await execCommand(`${CLI} ${FIXTURES_DIR}/drizzle-mysql-url.config.ts`, { | ||
| expectedOutput: ['Skipped: 1'], | ||
| env: { MYSQL_DATABASE_URL: process.env.MYSQL_DATABASE_URL }, | ||
| }) | ||
| }) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.