Database migrations

The hub server comes with a database migration system that applies database schema changes when the hub server starts.

  1. Core migrations
  2. User migrations
  3. Configuration
  4. Resetting user migrations

Core migrations

When you start the hub server with startAndListen, it automatically runs its internal (core) set of database migrations against the configured database URL. These database changes are necessary for the currently installed version of hub to run.

Whenever you upgrade the hub server, it may run additional migrations on boot.

The changelog in the @moneypot/hub README announces when a hub version has core migrations that it will attempt to run.

You can see hub running its core migrations when you boot the server:

Schema "hub_core_versions" is on version 0
Schema "hub_core_versions" applying version 1
Schema "hub_core_versions" applying version 2

User migrations

You can optionally let hub run your migrations for you using the same system.

You simply make a folder that contains a consecutively-numbered list of migration files, tell hub about this folder, it will automatically run these files against SUPERUSER_DATABASE_URL whenever it launches.

Example folder:

├── migrations
│   ├── 001-initial.sql
│   ├── 002-triggers.sql
│   └── 003-seed-data.sql

Note

  • The leading sequence number in the filename must be sequential.
  • You cannot skip numbers.
  • @moneypot/hub tracks the latest successful migration that it ran in a hub_user_versions schema in your database.

Configuration

// src/server.ts
import { startAndListen, type ServerOptions } from "@moneypot/hub";
import { join } from "path";

const options: ServerOptions = {
  exportSchemaSDLPath: join(import.meta.dirname, "../schema.graphql"),
  // The path to our migrations folder
  userDatabaseMigrationsPath: join(import.meta.dirname, "../migrations"),
};

startAndListen(options).catch((e) => {
  console.error(e);
});

Once you boot the server, you can see the migrations being applied:

Schema "hub_user_versions" is on version 0
Schema "hub_user_versions" applying version 1
Schema "hub_user_versions" applying version 2
Will save generated graphql schema to: /users/demo/project/schema.graphql
Listening on 4000...

Resetting user migrations

Especially in development, you may want to re-migrate your migrations folder from the beginning. Maybe you want to keep modifying a single 001-initial.sql until you’re happy with it.

Just delete the versions schema and reboot your server:

DROP SCHEMA IF EXISTS hub_user_versions CASCADE;