Skip to content

Commit

Permalink
docs: migrations docs
Browse files Browse the repository at this point in the history
  • Loading branch information
RihanArfan committed Oct 25, 2024
1 parent aa3d09f commit 6ed8589
Show file tree
Hide file tree
Showing 4 changed files with 157 additions and 42 deletions.
61 changes: 61 additions & 0 deletions docs/content/1.docs/2.features/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,64 @@ The methods [`.all()`](#all) and [`.batch()`](#batch) return an object that cont
::callout
Read more on [Cloudflare D1 documentation](https://developers.cloudflare.com/d1/build-databases/query-databases/).
::

## Migrations

Database migrations are a system for managing incremental, version-controlled changes to database schemas that tracks modifications and ensures consistent database evolution across all environments.

### Applying migrations

Database migrations are automatically applied during:
- Deploying via [CLI](/docs/getting-started/deploy#nuxthub-cli) or [Cloudflare Pages CI](/docs/getting-started/deploy#cloudflare-pages-ci) for projects linked to NuxtHub
- Starting the development server `npm run dev [--remote]`
- Locally previewing a build with [nuxthub preview](/changelog/nuxthub-preview)

::callout
Applied migrations are tracked within the `hub_migrations` database table.
::

### Create new migration

You can create a new blank database migration file by running this command.

```bash [Terminal]
npx nuxthub database migrations create <name>
```

::note
The migration name can only include alphanumeric characters and `-`. Spaces are converted into `-`.
::

Migration files are created in the `server/database/migrations/` directory.

### List applied and pending migrations

List migrations which are pending, and which have been applied to local/preview/production.

```bash [Terminal]
npx nuxthub database migrations list [--preview] [--production]
```

By default it will show you applied and pending migrations for the local environment.

### Migrating from Drizzle ORM

NuxtHub will attempt to rerun all migrations within `server/database/migrations/*.sql` since it is unaware they are already applied, as migrations previously applied with Drizzle ORM are stored within the `__drizzle_migrations` table.

Run the command `nuxthub database migrations mark-all-applied` on each environment to mark all existing migration files as applied.

```bash [Terminal]
nuxthub database migrations mark-all-applied --local|preview|production
```

By default it will mark all migrations as applied on the local environment.

::collapsible{name="self-hosting docs"}

If you are [self-hosting](/docs/getting-started/deploy#self-hosted) NuxtHub, set the `NUXT_HUB_PROJECT_SECRET_KEY` environment variable before running the command. <br><br>

```bash [Terminal]
NUXT_HUB_PROJECT_SECRET_KEY=<secret> nuxthub database migrations mark-all-applied --local|preview|production
```

::
20 changes: 6 additions & 14 deletions docs/content/1.docs/3.recipes/1.hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,18 @@ description: Use lifecycle hooks to stay synced with NuxtHub.

## `onHubReady()`

Use `onHubReady()` to ensure the execution of some code once NuxtHub environment bindings are set up.
Use `onHubReady()` to ensure the execution of some code once NuxtHub environment bindings are set up and migrations are applied.

::note
`onHubReady()` is a shortcut using the [`hubHooks`](#hubhooks) object under the hood to listen to the `bindings:ready` event.
`onHubReady()` is a shortcut using the [`hubHooks`](#hubhooks) object under the hood to listen to the `migrations:done` event.
::

This is useful to run database migrations inside your [server/plugins/](https://nuxt.com/docs/guide/directory-structure/server#server-plugins).

```ts [server/plugins/migrations.ts]
export default defineNitroPlugin(() => {
// Only run migrations in development
// Only run in development
if (import.meta.dev) {
onHubReady(async () => {
await hubDatabase().exec(`
CREATE TABLE IF NOT EXISTS todos (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
completed INTEGER NOT NULL DEFAULT 0
)
`.replace(/\n/g, ''))
console.log('NuxtHub is ready! 🚀')
})
}
})
Expand All @@ -40,12 +32,13 @@ The `hubHooks` object is a collection of hooks that can be used to stay synced w
```ts [Signature]
export interface HubHooks {
'bindings:ready': () => any | void
'migrations:done': () => any | void
}
```

### Usage

You can use the `hubHooks` object to listen to the `bindings:ready` event in your server plugins:
You can use the `hubHooks` object to listen to `HubHooks` events in your server plugins:

```ts [server/plugins/hub.ts]
export default defineNitroPlugin(() => {
Expand All @@ -59,4 +52,3 @@ export default defineNitroPlugin(() => {
::note
Note that `hubHooks` is a [hookable](https://hookable.unjs.io) instance.
::

31 changes: 3 additions & 28 deletions docs/content/1.docs/3.recipes/2.drizzle.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,35 +92,10 @@ When running the `npm run db:generate` command, `drizzle-kit` will generate the

### Migrations

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 () => {
await migrate(useDrizzle(), { migrationsFolder: 'server/database/migrations' })
.then(() => {
consola.success('Database migrations done')
})
.catch((err) => {
consola.error('Database migrations failed', err)
})
})
})
```

::callout
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).
Migrations created with `npm run db:generate` are automatically applied during deployment, preview and when starting the development server.

::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.
::note{to="/docs/features/database#migrations"}
Learn more about migrations.
::

### `useDrizzle()`
Expand Down
87 changes: 87 additions & 0 deletions docs/content/4.changelog/migrations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
---
title: Database migrations
description: "Database migrations are now automatically applied during development and deployment."
date: 2024-10-25
image: '/images/changelog/migrations.png'
category: Core
authors:
- name: Rihan Arfan
avatar:
src: https://avatars.githubusercontent.com/u/20425781?v=4
to: https://x.com/RihanArfan
username: RihanArfan
---

::tip
This feature is available on both [free and pro plans](/pricing) and in [`@nuxthub/core >= v0.0.0`](https://github.com/nuxt-hub/core/releases).
::

We are excited to introduce [database migrations](/docs/features/database#migrations) in NuxtHub. Database migration files in `server/database/migrations/*.sql` are now applied automatically when starting the development server, or when deploying a project.

:nuxt-img{src="/images/changelog/migrations.png" alt="NuxtHub migrations" width="915" height="515"}


## Usage

Read the [full documentation](/docs/features/database#migrations) to learn more about migrations.

### Create new migration

You can create a new blank database migration file by running this command.

```bash [Terminal]
npx nuxthub database migrations create <name>
```

Once the migration is created, you can add SQL queries to modify your database, such as to add a new table.

### List applied and pending migrations

You can view all applied and pending migrations for an environment using this command.

```bash [Terminal]
npx nuxthub database migrations list [--preview] [--production]
```

By default it will show you applied and pending migrations for the local environment.

### Apply migrations

Database migrations are automatically applied during:
- Deploying via [CLI](/docs/getting-started/deploy#nuxthub-cli) or [Cloudflare Pages CI](/docs/getting-started/deploy#cloudflare-pages-ci) for projects linked to NuxtHub
- Starting the development server `npm run dev [--remote]`
- Locally previewing a build with [nuxthub preview](/changelog/nuxthub-preview)

## Migration from existing ORM

::important
**If you are using Drizzle ORM** with a Nuxt plugin to automatically apply migrations, follow this migration path.
::

NuxtHub will attempt to rerun all migrations within `server/database/migrations/*.sql` since it is unaware they are already applied, as migrations previously applied with Drizzle ORM are stored within the `__drizzle_migrations` table.

Run the command `nuxthub database migrations mark-all-applied` on each environment to mark all existing migration files as applied.

```bash [Terminal]
nuxthub database migrations mark-all-applied --local|preview|production
```

By default it will mark all migrations as applied on the local environment.

::collapsible{name="self-hosting docs"}

If you are [self-hosting](/docs/getting-started/deploy#self-hosted) NuxtHub, set the `NUXT_HUB_PROJECT_SECRET_KEY` environment variable before running the command. <br><br>

```bash [Terminal]
NUXT_HUB_PROJECT_SECRET_KEY=<secret> nuxthub database migrations mark-all-applied --local|preview|production
```

::

## What are database migrations?

Database migrations are a system for managing incremental, version-controlled changes to database schemas that tracks modifications and ensures consistent database evolution across all environments.

::note
This feature has been implemented in [nuxt-hub/core#333](https://github.com/nuxt-hub/core/pull/333).
::

0 comments on commit 6ed8589

Please sign in to comment.