Skip to content

Commit d057776

Browse files
committed
docs: improve migration with Drizzle ORM
1 parent 3ed0c20 commit d057776

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

docs/content/docs/3.recipes/2.drizzle.md

+20-8
Original file line numberDiff line numberDiff line change
@@ -110,26 +110,38 @@ export default defineNitroPlugin(async () => {
110110

111111
const database = hubDatabase()
112112

113-
for (const file of migrationFiles) {
113+
// Make sure to create the _hub_migrations table if it doesn't exist
114+
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()
115+
116+
// Get applied migrations from database
117+
const hubMigrations = await database.prepare('SELECT * FROM _hub_migrations').all()
118+
const appliedMigrations = (hubMigrations.results || []).map((row) => row.name)
119+
const missingMigrations = migrationFiles.filter(file => !appliedMigrations.includes(file))
120+
if (!missingMigrations.length) {
121+
consola.success('Database up-to-date and ready')
122+
return
123+
}
124+
125+
// Apply missing migrations
126+
const appliedMigrationsStmts = []
127+
for (const file of missingMigrations) {
114128
consola.info(`Applying database migrations from ${file}...`)
115129
const migration = (await migrationsStorage.getItem<string>(file)) || ''
116130
const statements = migration.split('--> statement-breakpoint')
117131
for (let stmt of statements) {
118-
stmt = stmt
119-
.trim()
120-
.replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS')
121-
.replace('CREATE INDEX', 'CREATE INDEX IF NOT EXISTS')
122-
.replace('CREATE UNIQUE INDEX', 'CREATE UNIQUE INDEX IF NOT EXISTS')
123-
await database.prepare(stmt).run()
132+
await database.prepare(stmt.trim()).run()
124133
}
134+
appliedMigrationsStmts.push(database.prepare('INSERT INTO _hub_migrations (name, created_at) VALUES (?, ?)').bind(file, Date.now()))
125135
}
136+
await database.batch(appliedMigrationsStmts)
126137
consola.success('Database migrations done')
127138
})
128139
})
140+
129141
```
130142

131143
::callout
132-
This solution is not perfect as it will run the migrations every time the server starts. You can improve it by keeping track of the migrations that have been applied and only run the new ones.
144+
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.
133145
::
134146

135147
### `useDrizzle()`

0 commit comments

Comments
 (0)