Database 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.

You can see hub running its core migrations when you boot he 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

import { startAndListen, type ServerOptions } from "@moneypot/hub";
import { dirname, join } from "path";
import { fileURLToPath } from "url";

const exportSchemaSDLPath = join(
  dirname(fileURLToPath(import.meta.url)),
  "../schema.graphql"
);

const userDatabaseMigrationsPath = join(
  dirname(fileURLToPath(import.meta.url)),
  "../db-migrations"
);

const options: ServerOptions = {
  exportSchemaSDLPath,
  userDatabaseMigrationsPath, // <-- The path to our migrations folder
};

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;