Skip to content

Commit

Permalink
docs: simplify migrations using drizzle
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux committed Apr 11, 2024
1 parent ed57a6e commit f8b3ff7
Showing 1 changed file with 15 additions and 37 deletions.
52 changes: 15 additions & 37 deletions docs/content/docs/3.recipes/2.drizzle.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,57 +91,35 @@ When running the `npm run db:generate` command, `drizzle-kit` will generate the

### Migrations

::important
We are planning to update this section to leverage [Nitro Tasks](https://nitro.unjs.io/guide/tasks) instead of a server plugin very soon.
::

We can create a server plugin to run the migrations in development automatically:

```ts [server/plugins/migrations.ts]
import { consola } from 'consola'
import { migrate } from 'drizzle-orm/d1/migrator'

export default defineNitroPlugin(async () => {
if (!import.meta.dev) return

onHubReady(async () => {
const migrationsStorage = useStorage('root/server/database/migrations')
let migrationFiles = await migrationsStorage.getKeys()
migrationFiles = migrationFiles.filter(key => key.endsWith('.sql'))

const database = hubDatabase()

// Make sure to create the _hub_migrations table if it doesn't exist
await database.prepare('CREATE TABLE IF NOT EXISTS _hub_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, created_at INTEGER NOT NULL)').run()

// Get applied migrations from database
const hubMigrations = await database.prepare('SELECT * FROM _hub_migrations').all()
const appliedMigrations = (hubMigrations.results || []).map((row) => row.name)
const missingMigrations = migrationFiles.filter(file => !appliedMigrations.includes(file))
if (!missingMigrations.length) {
consola.success('Database up-to-date and ready')
return
}

// Apply missing migrations
const appliedMigrationsStmts = []
for (const file of missingMigrations) {
consola.info(`Applying database migrations from ${file}...`)
const migration = (await migrationsStorage.getItem<string>(file)) || ''
const statements = migration.split('--> statement-breakpoint')
for (let stmt of statements) {
await database.prepare(stmt.trim()).run()
}
appliedMigrationsStmts.push(database.prepare('INSERT INTO _hub_migrations (name, created_at) VALUES (?, ?)').bind(file, Date.now()))
}
await database.batch(appliedMigrationsStmts)
consola.success('Database migrations done')
await migrate(useDB(), { migrationsFolder: 'server/database/migrations' })
.then(() => {
consola.success('Database migrations done')
})
.catch((err) => {
consola.error('Database migrations failed', err)
})
})
})

```

::callout
This solution is will create a `_hub_migrations` table in your database to keep track of the applied migrations. It will also run the migrations automatically in development mode.
Drizzle will create a `__drizzle_migrations` table in your database to keep track of the applied migrations. It will also run the migrations automatically in development mode.
::

To apply the migrations in staging or production, you can run the server using `npx nuxi dev --remote` command to connect your local server to the remote database, learn more about [remote storage](/docs/getting-started/remote-storage).

::note
We are planning to update this section to leverage [Nitro Tasks](https://nitro.unjs.io/guide/tasks) instead of a server plugin in the future.
::

### `useDrizzle()`
Expand Down

2 comments on commit f8b3ff7

@sondh0127
Copy link

@sondh0127 sondh0127 commented on f8b3ff7 Apr 12, 2024

Choose a reason for hiding this comment

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

await migrate(useDB(), { migrationsFolder: 'server/database/migrations' })

image
HI @atinux thanks for new update. but how can we get useDB

@sondh0127
Copy link

Choose a reason for hiding this comment

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

import { consola } from 'consola'
import { migrate } from 'drizzle-orm/d1/migrator'

export default defineNitroPlugin(async () => {
  if (!import.meta.dev)
    return

  onHubReady(async () => {
    await migrate(useDrizzle(), { migrationsFolder: 'server/database/migrations' })
      .then(() => {
        consola.success('Database migrations done')
      })
      .catch((err) => {
        consola.error('Database migrations failed', err)
      })
  })
})

oh! it's useDrizzle in my case

Please sign in to comment.