Database migrations

A migration is a PHP class with an up() that changes the database schema (or data) and a down() that undoes it. yf runs migrations with db()->migrator() (yf_db_migrator, one class per driver family: MySQL / MariaDB, PostgreSQL, SQLite) and the console commands db:migrate, migrate:rollback and migrate:reset. New tables of a plugin need no migration: the installer creates a missing table from its definition (share/db/sql_php/<table>.sql_php.php). Migrations are for changes to tables that already exist on live sites.

Writing one

The file is db_migration_<name>.class.php in a db/migrations/ folder; the class is db_migration_<name>. The name is usually a date and a short description, and it is the name you apply it by:

<?php

load('db_migrator', '', 'classes/db/');

class db_migration_20261201_orders_note extends yf_db_migrator
{
    protected function up()
    {
        $table = $this->db->_fix_table_name('orders');
        $utils = $this->db->utils();
        if ( ! $utils->table_exists($table) || $utils->column_info($table, 'note')) {
            return;   // nothing to do: re-running is safe
        }
        if (false === $utils->add_column($table, ['name' => 'note', 'type' => 'varchar', 'length' => 255, 'nullable' => false, 'default' => ''])) {
            throw new RuntimeException('orders_note: cannot add the column');
        }
    }

    protected function down()
    {
        $table = $this->db->_fix_table_name('orders');
        if ($this->db->utils()->column_info($table, 'note')) {
            $this->db->utils()->drop_column($table, 'note');
        }
    }
}
  • $this->db is the connection the migration runs on; use $this->db->utils() (table and column helpers) or $this->db->query(), and _fix_table_name() for the table prefix.
  • Check before you change: a table that is missing or a column that is already there is a normal case on some sites.
  • The utils helpers and query() return false on an error instead of throwing. Throw yourself, as above, so the migration is rolled back and not recorded.
  • Keep the old data in down(): the framework's migration of comments.ip refuses to narrow the column while an address would be cut, instead of cutting it.
  • Write the table definition (sql_php) of the new shape too, so new installs get it without the migration.

Where the migrator looks (_list()): db/migrations/ of the framework, the app and the project, the same folder of every plugin of the framework, the app and the project, and share/db/migrations/ of the framework, app and project. A later folder with the same migration name wins. db:migrate create writes a generated migration to APP_PATH share/db/migrations/.

Running them

php vendor/bin/yf db:migrate list                                 # name => file of every migration found
php vendor/bin/yf db:migrate apply name=20261201_orders_note      # run up()
php vendor/bin/yf migrate:rollback                                # down() of the last applied one
php vendor/bin/yf migrate:rollback 20261201_orders_note           # down() of this one
php vendor/bin/yf migrate:reset                                   # down() of every applied one, newest first

Each up() / down() runs in a transaction with foreign key checks off. The console commands record the applied migrations in the table sys_db_migrations (name, time): apply refuses a migration that is already applied, and rollback / reset work from that list. They also refuse to record a migration whose statements failed (STRICT_QUERY_ERRORS). --no-track runs apply without the table; rollback and reset then answer "migrations are not tracked".

From PHP, db()->migrator()->apply('20261201_orders_note') returns 'Success' or an error text. There the tracking and the strict errors are off by default (db_migrator.TRACK_MIGRATIONS, db_migrator.STRICT_QUERY_ERRORS, both true in yf 4.0): turn them on to get the console behaviour.

Two things to know:

  • MySQL and MariaDB commit before every ALTER, CREATE or DROP: the transaction cannot undo a schema change that ran before the error. Keep one schema change per migration, or make up() safe to run again.
  • db:migrate prints the result and exits with 0 even when it is an error text (Error: ...), unless db_migrator.EXIT_CODE_ON_ERROR is on (true in yf 4.0): then it exits with 1, as migrate:rollback and migrate:reset do. Set it in the site config ($PROJECT_CONF['db_migrator_mysql']['EXIT_CODE_ON_ERROR'] = true;, the key is the loaded class, db_migrator_<driver family>) or check the output in a deploy script.

Schema tools

CommandWhat it does
db:migrate compareThe live tables against the table definitions of the installer: new, missing and changed tables, columns, indexes and foreign keys.
db:migrate generateThe up and down commands that would make the live database match the definitions (printed, nothing written).
db:migrate createThe same, written as a migration file named by the current time.
db:migrate dump, syncWrite the sql and sql_php definition files of the new and changed tables from the live database. sync is an alias of dump: the full sync its name promises (every table, sql and sql_php in step) was never written. It passes dump_all, which only a site's own dump() may read.

Read a generated migration before you apply it: it describes the difference, not your intent (a renamed column comes out as a drop and an add). The framework ships migrations of its own (for example 20261201_comments_ip_varchar45, 20261201_user_verify_time); their class comment says what they change, and the upgrade notes say when a site must apply them.