Skip to main content

Getting Started with PHP Database Migration

Why Pure SQL Commands?

Most frameworks use programming statements for database versioning instead of pure SQL. While framework-specific approaches have advantages like:

  • Framework commands for complex tasks
  • Database-agnostic code
  • Built-in framework integration

However, in real-world projects, developers often use tools like MySQL Workbench or DataGrip to make database changes and then spend time translating SQL to framework code. This library embraces SQL-first approach, allowing you to use your database tools' native SQL output directly.

Installation

composer require "byjg/migration"

The package includes both the library and a built-in CLI tool (no additional packages needed).

tip

The CLI is automatically available at vendor/bin/migrate. See the CLI documentation for detailed commands and options.

Basic Usage

  1. Create your migration directory structure:
<root dir>
|
+-- base.sql # Initial database schema
|
+-- /migrations
|
+-- /up # Scripts to upgrade version
| |
| +-- 00001.sql
| +-- 00002.sql
|
+-- /down # Scripts to downgrade version (optional)
|
+-- 00001.sql
+-- 00000.sql
  1. Initialize in your code:
<?php
// Create database connection
$connectionUri = new \ByJG\Util\Uri('mysql://user:pass@localhost/database');

// Register database handler
\ByJG\DbMigration\Migration::registerDatabase(\ByJG\DbMigration\Database\MySqlDatabase::class);

// Create migration instance
$migration = new \ByJG\DbMigration\Migration($connectionUri, '/path/to/migrations');

// Optional: Add progress callback
$migration->addCallbackProgress(function ($action, $currentVersion, $fileInfo) {
echo "$action, $currentVersion, ${fileInfo['description']}\n";
});

// Create version table (first time only)
$migration->createVersion();

// Run migrations
$migration->update();

CLI Usage

Alternatively, you can use the built-in command-line tool:

# Create version table
vendor/bin/migrate create \
--connection mysql://user:pass@localhost/database \
--path /path/to/migrations

# Run migrations to latest version
vendor/bin/migrate update \
--connection mysql://user:pass@localhost/database \
--path /path/to/migrations

# Check current version
vendor/bin/migrate version \
--connection mysql://user:pass@localhost/database

For complete CLI documentation, see CLI Usage.

Next Steps