Skip to content

DB migrations ​

BraDypUS uses a lightweight, code-first migration system. Each migration is an idempotent PHP class that runs exactly once per database and is tracked in bdus_migrations.


How migrations run ​

Pending migrations are not run on every request. The single migration point is POST /api/upgrade/minor (Upgrade::runMinor), reached through the login flow:

  1. Login::auth() calls Migrate::listPending() after a successful authentication.
  2. Pending and the user is an admin (privilege ≤ 10): the login succeeds and the response carries upgrade: {type: 'minor', pending: [...]}; the app asks the admin to confirm and calls POST /api/upgrade/minor.
  3. Pending and the user is not an admin: upgrade_pending error, no token.
  4. Nothing pending: Migrate::run() only stamps the version.

The same minor upgrade can also be run from the command line, with no login: php bin/upgrade-app.php --app <slug> | --all [--dry-run] [--json]. Both callers go through DB\System\Upgrader::apply(), which refuses an app that needs the major upgrade and otherwise calls Migrate::run() (with no pending migration it only records the running version, via Migrate::syncProjectVersion(), when the app still carries an older one: that is what the login page's "update available" tag compares); --all starts one child process per app (the PROJ_DIR constant is per process, and a fatal error in one app must not stop the others). It takes no snapshot or backup: that is the caller's job (bdus-ops' bdus update does it first). Exit codes: 0 ok, 1 an app failed, 2 bad invocation, 3 an app needs the major upgrade.

A new application is created with all migrations applied: CreateApp::createAll() (bin/create-app.php, POST /api/new-app) ends with Migrate::run(), so non-admin users can log in immediately.

For each pending migration Migrate::run():

  1. Checks bdus_migrations — if already applied, skips it.
  2. Calls Mxxx::run($manage).
  3. Records its NAME in bdus_migrations so it never runs again.

The v4 → v5 major upgrade has its own flow (Upgrade::runMajor).

Order matters — ALL_MIGRATIONS in Migrate.php is the canonical ordered list. Never reorder existing entries.


Writing a new migration ​

1. Create the class ​

php
// lib/DB/System/Migrations/M023_MyChange.php
namespace DB\System\Migrations;

use DB\System\Manage;

class M023_MyChange
{
    public const NAME = 'M023_my_change';   // unique snake_case string

    public static function run(Manage $manage): void
    {
        $db = $manage->getDb();

        // ── Guard: check preconditions before acting ──────────────────────
        $tables = $db->query(
            "SELECT name FROM sqlite_master WHERE type='table' AND name='bdus_users'",
            [], 'read'
        ) ?: [];
        if (empty($tables)) {
            return;  // table absent — no-op
        }

        // ── Add a column (idempotent) ─────────────────────────────────────
        $cols = $db->query('PRAGMA table_info(bdus_users)', [], 'read') ?: [];
        $existing = array_column($cols, 'name');

        if (!in_array('new_column', $existing, true)) {
            $db->query(
                "ALTER TABLE bdus_users ADD COLUMN new_column TEXT",
                [], 'boolean'
            );
        }

        // ── Create a table (use Manage for cross-engine compat) ───────────
        // $manage->createTable('bdus_new_table');

        // ── Data migration ────────────────────────────────────────────────
        // $db->query("UPDATE bdus_users SET new_column = 'default' WHERE …", [], 'boolean');
    }
}

2. Register in Migrate.php ​

Add the class to the ALL_MIGRATIONS array in lib/DB/System/Migrate.php, at the end:

php
use DB\System\Migrations\M024_MyChange;

public const ALL_MIGRATIONS = [
    // … existing migrations …
    M023_ZoteroTables::class,
    M024_MyChange::class,     // ← append here
];

3. Write an integration test ​

php
// tests/Integration/M024MyChangeTest.php
class M024MyChangeTest extends BdusTestCase
{
    public function testColumnAdded(): void
    {
        // Run migration
        M024_MyChange::run(new Manage(static::$db));

        // Verify
        $cols = static::$db->query('PRAGMA table_info(bdus_users)', [], 'read');
        $names = array_column($cols, 'name');
        $this->assertContains('new_column', $names);
    }

    public function testIdempotent(): void
    {
        M024_MyChange::run(new Manage(static::$db));
        M024_MyChange::run(new Manage(static::$db));  // must not throw
        $this->assertTrue(true);
    }
}

Rules for migration authors ​

RuleRationale
Always guard — check whether the column / table / index already exists before creating itMigrations run on upgrade; the object may already be there
Never drop user dataMigrations are irreversible once deployed
Use Manage::createTable() for new system tablesHandles engine differences automatically
Use $db->query() with bound params for data migrationsPrevents SQL injection even in DDL context
Keep NAME unique and descriptiveIt is the idempotency key
Append only — never reorderMigration order matters for dependencies
SQLite-only DDL is OKAll production installs use SQLite; MySQL / PG users are expected to apply DDL manually if needed

Migration history (M001–M027) ​

MigrationWhat it does
M001Create bdus_user_table_privs (per-table privilege overrides)
M002Create bdus_file_links (file ↔ record associations)
M003Refactor bdus_queries schema
M004Refactor bdus_charts schema
M005Create bdus_api_keys
M006Add privilege column to bdus_api_keys
M007Repair orphaned file links
M008Rename bare system tables to bdus_*
M009Add operation column to bdus_versions
M010Fix bdus_versions schema inconsistencies
M011Move YAML config → DB (bdus_cfg_* tables)
M012Add extra columns to bdus_cfg_tables
M013Create bdus_cfg_relations (initial v1 schema)
M014Move GeoFace config → DB (bdus_cfg_geoface)
M015Delete now-redundant JSON config files from cfg/
M016Rename cfg/app_data.json → cfg/config.json
M017Cleanup orphaned files in cfg/
M018Move cfg/config.json → config.json (project root)
M019Move app settings → DB (bdus_cfg_app)
M020Deduplicate relation entries; add UNIQUE(from_tb, to_tb)
M021Back-fill plugin_of field in bdus_cfg_tables
M022Add oauth_provider + oauth_sub columns to bdus_users
M023Create bdus_zotero_libs and bdus_zotero_links for Zotero integration
M024Drop legacy v4 columns (date, text, vals from bdus_queries; sqltext, date from bdus_charts)
M025Add color column to bdus_cfg_app for runtime primary-colour customisation
M026Refactor bdus_cfg_relations — replaces (from_tb, to_tb, fld JSON, sort) with (from_tb, from_col, to_tb, to_col, on_delete, on_update). One row per FK column pair. UNIQUE moved to (from_tb, from_col). Expands existing JSON blobs into individual rows.
M027Create bdus_cfg_indexes — tracks user-defined and auto-generated (FK) indexes per table.
M028Add token_version column to bdus_users for per-user JWT invalidation.
M029Add label column to bdus_userlinks for typed manual links.
M030Migrate bdus_rs.first/.second from TEXT to INTEGER — converts stored RS identifiers (text values of the configured rs_field) to integer record primary keys. Also converts the per-table rs config from a field name string ("sigla") to a boolean flag (1). Existing apps are migrated automatically; new apps use the INTEGER schema from creation.
M046Groups & permissions groundwork (#78) — creates bdus_groups, bdus_user_groups, bdus_group_rules, bdus_table_locks; adds bdus_api_keys.group_id; drops bdus_user_table_privs (its overrides were never enforced). Tables start empty: no behaviour change.
M047File attribution — adds a nullable attribution column to bdus_files and registers its field config in bdus_cfg_fields for existing apps (new apps get both from Structure/files.json and CreateApp). Minor upgrade, no data touched.
M048Derived-image presets — adds a nullable TEXT image_presets column to bdus_cfg_app (JSON list of presets, see Image\Presets). Skipped when bdus_cfg_app does not exist. Minor upgrade, no data touched.
M049Group attributes and enforced values (#51) — adds nullable bdus_groups.attrs (TEXT, JSON attributes read as $GROUP.<key>), bdus_groups.is_system (INTEGER, 1 for groups BraDypUS owns) and bdus_group_rules.enforce (JSON map of values the server accepts on create/update). Each column is skipped when its table does not exist. Auth\Access and the Groups controller keep working on the old shape until it runs. Minor upgrade, no data touched.
M050Default groups — creates Reader, Writer and Self writer, each with rules for every table (*); a group that already has the name is left alone; nobody is assigned; the groups are system groups (bdus_groups.is_system = 1, a column M049 adds). Minor upgrade, no existing data touched.
M058Undo for moving levels to groups — adds nullable legacy_privilege and legacy_group_id (INTEGER) to bdus_users and legacy_privilege (INTEGER) to bdus_api_keys: where a user or key came from when Auth\LevelMigration moved it from level 20/25/30 to Enter + the system group (NULL = never moved; legacy_group_id NULL = the user already belonged to the group, so restoring leaves it). Minor upgrade, additive, nothing moves until an admin asks.
M060File uuid (files rework, step 1) — adds bdus_files.uuid (random v4, unique index bdus_files_uuid_uq) and public (INTEGER default 0), registers both field configs, gives every file a uuid, renames files/{id}.{ext} to files/{uuid}.{ext} (the old name uses the extension exactly as stored, JPG stays JPG on a case-sensitive file system; the new one is always lower-case, as every name File\Store builds), empties the derived-image cache and marks the existing files public = 1 (so published derived images keep working; new files start private). Idempotent and resumable: a missing binary is skipped, a failed rename makes the migration throw after trying all the others and stay pending. Flagged in FILE_AFFECTING_MIGRATIONS: back up first. The id ↔ uuid mapping lives in the database, so the renames can be reversed from it.
M061Files as a configured table — makes sure bdus_files has its row in bdus_cfg_tables and its system fields in bdus_cfg_fields (File\ConfigSeed, also used by CreateApp), so group rules, locks and the record layer can apply to files. Additive, nothing that exists is changed; the interface still skips the bdus_* system tables.
M062Preset access and state (files rework) — gives every stored image preset access = public and enabled = true, and writes the built-in thumb out explicitly as a public preset (it was never stored and was public), so what is published today stays published; idempotent, never overwrites an explicit choice. Skipped when bdus_cfg_app.image_presets does not exist.
M055API keys can be switched off — adds nullable disabled_at (INTEGER) to bdus_api_keys. Auth\ApiKeyAuth refuses a key with disabled_at set and still works (on revoked_at alone) until the migration runs; the key list uses SELECT * for the same reason. Minor upgrade, existing keys stay enabled.
M054MCP prompts — creates bdus_mcp_prompts (name unique, title, description, arguments JSON, template, sort), empty. Mcp\Prompts::all() answers an empty list until it runs. Minor upgrade, additive. See MCP server.
M053Provenance in the history — adds nullable channel (TEXT), key_id (INTEGER) and client_id (TEXT) to bdus_versions. DB::saveSnapshot() fills them only when the columns exist. From this version every INSERT of a record also writes an entry with operation = 'create' and no content. Minor upgrade, existing entries untouched.
M052MCP settings — adds mcp_enabled, mcp_write, mcp_delete (INTEGER, default 0) and mcp_guide (TEXT) to bdus_cfg_app. Config\AppSettings::getMcp() answers "everything off" until it runs. Minor upgrade, no data touched. See MCP server.
M051Record layouts per group — adds nullable bdus_groups.layouts (TEXT, JSON {table: [template]}: the templates the members must use on each table, see Template\Assign). Template\Assign and the Groups controller treat a missing column as "no layouts" until it runs. Minor upgrade, no data touched.

Pre-flight migrations (outside the normal loop) ​

Two one-time upgrades run before the normal migration loop, on every request, from Bdus\App::start():

Migrate::maybeRemovePrefix() — if tables are still named with the legacy APP__ prefix (v4 apps), renames them, strips the prefix from tables.json, field configs, and data columns.

Migrate::maybeAddBdusPrefix() — if system tables are still bare (e.g. users instead of bdus_users), renames them.

Both methods are fully idempotent and no-ops on already-migrated databases.