Skip to content

Database migrations

Greg Bowler edited this page Mar 3, 2026 · 8 revisions

Here, we will run migrations as numbered SQL files and let the migrator track progress and integrity.

Migration location and file naming

Default location:

query/_migration/

Example files:

  • 0001-create-user.sql
  • 0002-add-created-at.sql
  • 0003-index-email.sql

Rules to keep in mind:

  • migration files must use the .sql extension
  • numbering must be continuous, with no gaps
  • file hashes are stored and checked for integrity

Programmatic migration flow

use Gt\Database\Connection\Settings;
use Gt\Database\Migration\Migrator;

$settings = new Settings(__DIR__ . "/query", Settings::DRIVER_SQLITE, __DIR__ . "/app.sqlite");
$migrator = new Migrator($settings, __DIR__ . "/query/_migration");

$migrator->createMigrationTable();
$files = $migrator->getMigrationFileList();
$migrator->checkFileListOrder($files);
$current = $migrator->getMigrationCount();
$migrator->checkIntegrity($files, $current);
$migrator->performMigration($files, $current);

Now we can rerun the migration process safely and only apply new files.

CLI migration command

This package includes bin/migrate:

php bin/migrate execute
php bin/migrate execute --force

--force recreates the schema for non-sqlite drivers.

The command reads project configuration from database.* keys, including:

  • database.query_path
  • database.migration_path
  • database.migration_table
  • database.driver
  • database.schema
  • database.host
  • database.port
  • database.username
  • database.password

Example code: example/05-database-migrations.php

Clone this wiki locally