From 6ed85893e5ff267396a6b98d35a5efc0811063d7 Mon Sep 17 00:00:00 2001 From: Rihan Arfan Date: Fri, 25 Oct 2024 06:53:55 +0100 Subject: [PATCH] docs: migrations docs --- docs/content/1.docs/2.features/database.md | 61 +++++++++++++++ docs/content/1.docs/3.recipes/1.hooks.md | 20 ++--- docs/content/1.docs/3.recipes/2.drizzle.md | 31 +------- docs/content/4.changelog/migrations.md | 87 ++++++++++++++++++++++ 4 files changed, 157 insertions(+), 42 deletions(-) create mode 100644 docs/content/4.changelog/migrations.md diff --git a/docs/content/1.docs/2.features/database.md b/docs/content/1.docs/2.features/database.md index 41e17adb..ce17272c 100644 --- a/docs/content/1.docs/2.features/database.md +++ b/docs/content/1.docs/2.features/database.md @@ -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 +``` + +::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.

+ +```bash [Terminal] +NUXT_HUB_PROJECT_SECRET_KEY= nuxthub database migrations mark-all-applied --local|preview|production +``` + +:: diff --git a/docs/content/1.docs/3.recipes/1.hooks.md b/docs/content/1.docs/3.recipes/1.hooks.md index e011c1e5..03b354ee 100644 --- a/docs/content/1.docs/3.recipes/1.hooks.md +++ b/docs/content/1.docs/3.recipes/1.hooks.md @@ -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! 🚀') }) } }) @@ -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(() => { @@ -59,4 +52,3 @@ export default defineNitroPlugin(() => { ::note Note that `hubHooks` is a [hookable](https://hookable.unjs.io) instance. :: - \ No newline at end of file diff --git a/docs/content/1.docs/3.recipes/2.drizzle.md b/docs/content/1.docs/3.recipes/2.drizzle.md index 1b07fef1..bf3e1412 100644 --- a/docs/content/1.docs/3.recipes/2.drizzle.md +++ b/docs/content/1.docs/3.recipes/2.drizzle.md @@ -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()` diff --git a/docs/content/4.changelog/migrations.md b/docs/content/4.changelog/migrations.md new file mode 100644 index 00000000..93d8fb06 --- /dev/null +++ b/docs/content/4.changelog/migrations.md @@ -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 +``` + +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.

+ +```bash [Terminal] +NUXT_HUB_PROJECT_SECRET_KEY= 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). +::