CLI & Migrations

bulletinbored ships with a zero-dependency CLI (bb.php) and a file-based migration system.

CLI (bb.php)

Run commands from the forum root:

php bb.php <command> [options]

Commands

Command Description
migrate Run all pending migrations
migrate:rollback Rollback the last batch of migrations
migrate:status Show migration status (pending/ran) with source
plugin:list List all plugins with version and status
plugin:enable <name> Enable a plugin
plugin:disable <name> Disable a plugin
cache:flush Clear cache and session files
ratelimit:stats Show rate-limit buckets, sizes, ages and top offenders
ratelimit:gc [seconds] Remove expired rate-limit buckets (default 86400s, minimum 60s)
doctor Run system diagnostics
help Show help

Examples

# Check migration status
php bb.php migrate:status

# Run pending migrations
php bb.php migrate

# Rollback last batch
php bb.php migrate:rollback

# List plugins
php bb.php plugin:list

# Enable a plugin
php bb.php plugin:enable hellobored

# Flush caches
php bb.php cache:flush

# Show rate-limit buckets
php bb.php ratelimit:stats

# Remove buckets idle for more than one day (the default)
php bb.php ratelimit:gc
php bb.php ratelimit:gc 3600

# Run diagnostics
php bb.php doctor

Note: the CLI reads config.json from the forum root. If it is missing, a legacy config.php in the same directory is accepted; the CLI exits with an error only when neither file exists.

Example output of php bb.php migrate:status:

+--------------------------------+----------+---------+-------+
| Migration                      | Source   | Status  | Batch |
+--------------------------------+----------+---------+-------+
| core:20260829_initial_schema   | core     | Ran     | 1     |
| core:20260831_upgrade_05x      | core     | Ran     | 2     |
| myplugin:20260901_create_tags  | myplugin | Ran     | 2     |
| myplugin:20260902_add_custom   | myplugin | Pending | -     |
+--------------------------------+----------+---------+-------+

The four columns are Migration | Source | Status | Batch. There is no Ran At column in the CLI output; the timestamp is stored in the migrations table but not printed.

Migration System (lib/Migrator.php)

How It Works

  1. Migration files live in migrations/ directory
  2. Each file has up() and down() methods, plus optional irreversible() method
  3. Migration IDs are namespaced: core:filename for core, pluginname:filename for plugins
  4. Applied migrations are tracked in the migrations table
  5. Migrations run in batches — rollback reverses the last batch
  6. File-based locking is implemented by Migrator::migrate() and Migrator::rollback(), which take an exclusive lock on data/.migration_lock. The CLI migrate command does not call migrate(): bb.php calls getPending() and runUp() directly, so that path does no locking and no interrupted-migration policy check. Use the CLI as a single-process tool, or call $migrator->migrate() from code when concurrent runs are possible.
  7. Transactions wrap a migration only when the driver supports transactional DDL (SQLite). MySQL DDL is not transactional, so a migration that issues several ALTER TABLE statements is not automatically atomic on MySQL: each migration must clean up after itself. The core foreign-key migration does this by dropping any constraint it created if a later ALTER fails, and by skipping constraints that already exist (so a re-run completes a previous partial run). A failed migration is never recorded as applied.

Interrupted migration recovery

ensureMigrationsTable() creates both migrations and migration_progress. Before up() runs, the migration is announced in migration_progress; the row is cleared when the migration completes. A leftover row means the migration started but did not finish, which is the normal outcome of a failed multi-statement DDL migration on MySQL/MariaDB.

// List migrations that started but never completed
$migrator->getInterruptedMigrations(); // name, batch, started_at, error

// Schema was repaired by hand: record the migration as applied without re-running up()
$migrator->recoverInterrupted($name, $batch);

// Discard the marker so the migration runs again
$migrator->forgetInterrupted($name);

Migrator::migrate() applies a retry policy. Core migrations are written to be idempotent (CREATE TABLE IF NOT EXISTS, guarded ALTERs), so an interrupted core:* migration is retried automatically. An interrupted plugin migration is retried only when its class implements isIdempotent() and returns true:

public function isIdempotent(): bool
{
    return true;
}

Otherwise migrate() refuses to retry it and tells the operator to repair the schema and call recoverInterrupted(), or call forgetInterrupted() before a deliberate retry. Because the CLI migrate command bypasses migrate(), it also bypasses this policy.

Migration Contract

class MyMigration
{
    /**
     * Apply the schema change.
     */
    public function up(PDO $pdo): void
    {
        // ...
    }

    /**
     * Reverse the schema change.
     * Skipped if irreversible() returns true.
     */
    public function down(PDO $pdo): void
    {
        // ...
    }

    /**
     * Declare this migration as one-way.
     * When true, rollback() skips down() and only removes the tracking record.
     */
    public function irreversible(): bool
    {
        return false;
    }
}

Creating a Migration

File naming convention: YYYYMMDD_description.php

<?php
/**
 * Migration: 20260830_add_user_bio.php
 */

class AddUserBio
{
    public function up(PDO $pdo): void
    {
        $driver = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME);

        if ($driver === 'mysql') {
            $pdo->exec("ALTER TABLE users ADD COLUMN bio TEXT DEFAULT NULL");
        } else {
            $pdo->exec("ALTER TABLE users ADD COLUMN bio TEXT DEFAULT NULL");
        }
    }

    public function down(PDO $pdo): void
    {
        $driver = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME);

        if ($driver === 'mysql') {
            $pdo->exec("ALTER TABLE users DROP COLUMN bio");
        } else {
            // SQLite supports DROP COLUMN only from version 3.35.0 (2021-03-12).
            // For maximum compatibility, recreate the table instead:
            $pdo->exec("CREATE TABLE users_new (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT NOT NULL,
                email TEXT
            )");
            $pdo->exec("INSERT INTO users_new (id, username, email) SELECT id, username, email FROM users");
            $pdo->exec("DROP TABLE users");
            $pdo->exec("ALTER TABLE users_new RENAME TO users");
        }
    }
}

Class Name Convention

The class name is derived from the filename:

Filename Class Name
20260830_add_user_bio.php AddUserBio
20260901_create_tags_table.php CreateTagsTable
20260101_fix_thread_status.php FixThreadStatus

The date prefix (YYYYMMDD_) is stripped, then snake_case becomes PascalCase.

Migration Batches

Migrations are grouped into batches. When you run migrate, all pending migrations get the same batch number. When you run migrate:rollback, all migrations from the last batch are reversed.

Batch 1: 20260829_initial_schema
Batch 2: 20260830_add_user_bio, 20260830_add_post_likes
Batch 3: 20260901_create_tags_table

Running migrate:rollback would reverse batch 3 only.

The doctor Command

The doctor command runs a full system diagnostic, checking:

  • PHP version — requires 8.1+
  • Extensions — required (pdo, pdo_sqlite, json, mbstring, fileinfo) and optional (pdo_mysql, zip, curl, gd)
  • Directory permissions: verifies data, data/cache, data/sessions, data/logs, data/uploads, plugins, themes and migrations are writable
  • Database: driver-aware connection check and table count (SQLite checks the database file; MySQL connects to the configured server). Table counts use sqlite_master on SQLite and information_schema.TABLES on MySQL
  • Security — display_errors, expose_php settings
=== bulletinbored diagnostics ===

  ✓ PHP version: 8.2.12
  ✓ Extension: pdo
  ✓ Extension: pdo_sqlite
  ✓ Extension: json
  ✓ Extension: mbstring
  ✓ Extension: fileinfo
  ✓ Extension: zip (optional)

Directory permissions:
  ✓ data: writable
  ✓ data/cache: writable
  ✓ data/sessions: writable
  ✓ data/logs: writable
  ✓ data/uploads: writable
  ✓ plugins: writable
  ✓ themes: writable
  ✓ migrations: writable

Database:
  ✓ Driver: sqlite (database exists)
  ✓ Tables: 15

Security:
  ✓ display_errors is OFF
  ✓ expose_php is OFF

✓ All checks passed!

With db_driver set to mysql, the database section reports Driver: mysql (connected) and counts tables through information_schema instead of sqlite_master.

Custom CLI Commands (Plugin API)

Plugins can register custom CLI commands via the cli hook:

function myplugin_init() {
    global $pluginManager;
    
    $pluginManager->addHook('cli', function($registry) {
        $registry->register(
            'myplugin:clear',
            'Clear my plugin cache',
            function($args) {
                // Command logic
                echo "Cache cleared!\n";
            }
        );
    });
}

Usage: php bb.php myplugin:clear

The $registry object provides:

Method Description
register($name, $description, $handler) Register a new command
has($name) Check if a command exists
$args Array of arguments passed after the command name

Best Practices

  1. Always make down() reversible — if up() adds a column, down() should drop it
  2. Use IF NOT EXISTS in up() for safety
  3. Handle both SQLite and MySQL — check $pdo->getAttribute(PDO::ATTR_DRIVER_NAME)
  4. Never modify a published migration — create a new one instead
  5. Never rename a migration that has already been run — the migrations table tracks names; renaming breaks the tracking and would re-run the migration
  6. Test migrations — run migrate then migrate:rollback to verify both directions
  7. Use irreversible() for destructive changes — if down() cannot safely reverse the change (e.g., data migration), declare it irreversible

Upgrade Fixtures

The test suite includes upgrade fixtures in tests/fixtures/upgrades/ that simulate old database states (e.g., 0.5.x schema). These verify that migrations correctly transform old data without loss:

tests/
  fixtures/
    upgrades/
      0.5.x.php    — Schema + data for pre-0.6.0 installations
  UpgradeTest.php   — Upgrade pipeline tests

Plugin Migrations

Plugins can provide their own migrations by creating a migrations/ folder in their directory:

plugins/
  myplugin/
    migrations/
      20260829_add_my_table.php
    manifest.json
    myplugin.php

The Migrator automatically scans plugins/*/migrations/ when running bb migrate. Plugin migrations are tracked alongside core migrations with a namespaced ID (myplugin:20260829_add_my_table) that prevents collisions with core migrations.

// In bb.php — plugin paths are auto-discovered
$migrator->addPluginPaths(BB_ROOT . '/plugins');

You can also register custom migration paths manually:

$migrator->addPath('/path/to/custom/migrations');

File Structure

bulletinbored/
├── bb.php                    # CLI entry point (extensible command registry)
├── migrations/               # Core migrations
│   └── 20260829_initial_schema.php
├── lib/
│   └── Migrator.php          # Migration engine (supports plugin paths)
└── tests/
    ├── MigratorTest.php            # Migration engine tests
    ├── MigrationRecoveryTest.php   # migration_progress, retry policy, recovery
    ├── MySqlDialectTest.php        # MySQL-specific SQL and driver behavior
    ├── UpgradeCompatibilityTest.php # Upgrade path compatibility
    └── E2eFlowTest.php             # End-to-end flow tests