Skip to content

Database Migrations

Package git repository

https://github.com/phalcon/migrations

Requirements

  • PHP >= 8.2
  • The PDO extension and the PDO driver for your database: pdo_mysql, pdo_pgsql or pdo_sqlite
  • The yaml extension, only if you use a YAML configuration file
  • The posix extension (optional, Linux and macOS). Without it, the output has no colors.

Supported databases

Database adapter value Notes
MySQL mysql Default port: 3306. The connection uses the charset value of the configuration. Default: utf8mb4.
PostgreSQL postgresql Default port: 5432. Default schema: public.
SQLite sqlite The dbname value is the path to the database file.

The adapter value is not case-sensitive.

Installing via Composer

composer require --dev phalcon/migrations

Using the PHAR

Each release on GitHub has a phalcon-migrations.phar file. Download it from the releases page. Run it with PHP:

php phalcon-migrations.phar list

The PHAR accepts the same arguments and options as vendor/bin/phalcon-migrations.

Quick start

What you need for a quick start:

  • Configuration file in the root of your project (you can also pass them as parameters inside CLI environment)
  • Create database table structure
  • Execute command to generate migrations

After that, you can execute that migration (run) in another environment to create the same DB structure.

Create the configuration file

The configuration file is a PHP file that returns an array. You can use any file name, for example migrations.php.

<?php

return [
    'database'    => [
        'adapter'  => 'mysql',
        'host'     => '127.0.0.1',
        'port'     => 3306,
        'username' => 'root',
        'password' => '',
        'dbname'   => 'db-name',
    ],
    'application' => [
        'log-in-db'               => true,
        'migrations'              => 'db/migrations',
        // true - TIMESTAMP, false - versions
        'ts-based'                => true,
        'export-data-from-tables' => [
            // Tables names
        ],
    ],
];

For all the configuration keys, see Configuration.

Generate migrations

Basic generation

vendor/bin/phalcon-migrations generate

Generate a specific table and export data from it

vendor/bin/phalcon-migrations generate \
    --config=migrations.php \
    --table=users \
    --data=oncreate

The --table option accepts:

  • One table name: --table=users
  • A comma-separated list of table names: --table=users,roles
  • A table prefix with an asterisk: --table=user*

For the data options, see Export data.

generate does not write a migration for the SQLite internal tables, for example sqlite_sequence, or for the PostgreSQL tables of an extension, for example spatial_ref_sys of PostGIS.

generate compares each table with the newest migration file of that table, in all the migrations directories. If no table changed, generate creates no version and shows this message:

Info: Nothing to generate: no table changed since the last version

The compare ignores the version and the MySQL AUTO_INCREMENT value. If one table changed, generate writes the files of all the tables. With --data or --export-data-from-tables, generate always creates a version.

Run migrations

vendor/bin/phalcon-migrations run

Roll back migrations

To roll back, use run with --version. Set --version to a version that is earlier than the current version:

vendor/bin/phalcon-migrations run --version=1.0.1

The package goes back one version at a time. For each table, it calls the down() and afterDown() methods of the version that it removes. Then it calls the morph() method of the previous version. See Migration methods.

List existing migrations

vendor/bin/phalcon-migrations list

The command shows each version and if it was applied:

┌───────────────────────────┬──────────────┐
│ Version                   │  Was applied │
├───────────────────────────┼──────────────┤
│ 1.0.0                     │            Y │
│ 1.0.1                     │            N │
└───────────────────────────┴──────────────┘

Configuration

The configuration has two sections: database and application.

Database options

Key Description
adapter Database adapter: mysql, postgresql or sqlite
host Database server host (MySQL and PostgreSQL)
port Database server port. Default: 3306 (MySQL), 5432 (PostgreSQL)
username Database user name
password Database password
dbname Database name. For SQLite, the path to the database file
schema Schema that the package reads and changes. Default: the dbname value (MySQL), public (PostgreSQL). For PostgreSQL, the package also sets search_path to this schema
charset Character set of the connection (MySQL only). Default: utf8mb4

Application options

Key Description
migrations Migrations directory. To use more than one directory, separate them with commas
log-in-db true - keep the migrations log in the database. false - keep it in a file. See Migrations log
log-path Path of the log file. Default: .phalcon/migration-version. A relative path starts in the project directory. With the database log, run reads this file when the log table is empty
log-table Name of the log table (database log). Default: phalcon_migrations
ts-based true - run, list, export and generate use timestamp based versions. false (default) - incremental versions
descr Description for timestamp based versions. When you set it, generate always creates a timestamp based version
export-data-from-tables Tables to export data from. An array, or a comma-separated string. The data is exported with every migration
namespace Namespace of the generated migration classes
truncate true - same as the --truncate option
no-auto-increment true - same as the --no-auto-increment option
skip-ref-schema true - same as the --skip-ref-schema option
skip-foreign-checks true - same as the --skip-foreign-checks option

Each key has the same name as its CLI option. When you set a key and its CLI option, the CLI option wins.

To turn off a boolean key of the configuration from the CLI, give the option the value false, for example --log-in-db=false. A boolean option accepts these values:

  • true, yes, y, on, 1
  • false, no, n, off, 0

Other values stop the command with an error. --force=false is the same as no --force.

In the configuration, a boolean key can have a text value, for example a quoted INI value (truncate = "false") or a value from an environment variable. A text uses the same words, with no case: false, no, n, off, 0 and an empty text are false. Other texts are true.

Other configuration formats

The package also reads .ini, .json, .yaml and .yml files. These files use the same database and application sections. A YAML file needs the yaml PHP extension.

[database]
adapter  = mysql
host     = 127.0.0.1
username = root
password =
dbname   = db-name

[application]
log-in-db               = true
migrations              = db/migrations
ts-based                = true
export-data-from-tables = users,roles

Project directory

The project directory is the value of the --directory option. The default is the current directory.

These paths are relative to the project directory:

  • A relative --config file. The package uses an absolute path as it is.
  • A relative --migrations or migrations directory
  • A relative --log-path or log-path file

If the configuration file does not exist, the command stops with the error Can't locate the configuration file.

Configuration file discovery

If you do not use --config, the package looks for a configuration file in the project directory. It looks in app/config/ first, then in config/. In each directory, it looks for these files, in this order:

  1. config.ini
  2. config.php
  3. config.json
  4. config.yaml
  5. config.yml

The package uses the first file that it finds. If it finds no file, the command stops with an error.

Default migrations directory

If you do not set --migrations or migrations, the package uses the first of these directories that applies:

  1. app/migrations, if the app directory exists
  2. apps/migrations, if the apps directory exists
  3. migrations

If you set more than one migrations directory, generate asks which directory to use.

Migrations log

The package records each version that it applies. It uses the log to find the versions to run, and to show the status in list.

  • File. The log is the .phalcon/migration-version file in the project directory. To use a different file, set log-path or --log-path. If the directory of the file does not exist, the package creates it.
  • Database. Set log-in-db to true, or use the --log-in-db option. The log is the phalcon_migrations table. To use a different table, set log-table or --log-table. If the table does not exist, the package creates it. The table has the columns version, start_time and end_time. When generate runs for all the tables, it skips the log table.

The default log

In version 5, the file log is the default. In version 6.0, the database log becomes the default.

If no setting chooses the log, run, list and clean give this PHP deprecation notice:

The file log is the default in 5.x. 6.0 uses the database log. Set log-in-db (migrationsInDb in PHP) to true, then run import-log, or set it to false to keep the file log.

To stop the notice, choose the log with one of these settings:

  • log-in-db in the configuration, true or false
  • --log-in-db or --log-in-db=false on the CLI
  • The migrationsInDb key in a call to Migrations::run(), Migrations::listAll() or Migrations::clean()

Move the file log to the database

The import-log action copies the versions of the file log into the log table of the database. It does this one time, for a new log table.

To move a project to the database log:

  1. Set log-in-db to true in the configuration.

  2. Run import-log for each database that the file log describes:

    vendor/bin/phalcon-migrations import-log --config=migrations.php
  3. Run list and make sure that the versions are applied.

  4. Delete the file log.

import-log uses the database of the configuration, and the file log and the log table of your settings (log-path and log-table, or the defaults). It puts all the versions in one transaction. The start_time and end_time values are the time of the import. The file log does not change.

import-log stops with an error, and changes nothing, in these conditions:

  • The log table has a line.
  • The database has no table other than the log table. The file log cannot describe an empty database.
  • The file log does not exist, or has no version.

When you use the database log, run stops before it changes the database if all these conditions are true:

  • The log table is empty.
  • The file log has versions.
  • The database has a table other than the log table.

The error is:

The log table '<table>' is empty, but the file log '<file>' has <N> versions. If the file is the log of this log table, run import-log. If not, delete or rename the file.

This stops run from applying all the versions again on a database that already has the tables. On an empty database, run applies all the versions as usual. The empty database can be a new database, or a database after clean --force.

Migrations::importLog() does the same in PHP. It accepts the config, directory, log-path and log-table keys.

Many databases

To keep the migrations of more than one database, use one configuration file for each database.

  • With the file log, give each configuration its own log-path.
  • With the database log, each database has its own log table.
  • For two sets of migrations in one database, give each set its own log-table.
vendor/bin/phalcon-migrations run --config=config/main.php
vendor/bin/phalcon-migrations run --config=config/reports.php

Usage example

Run migrations from specific migrations directory

<?php

use Phalcon\Migrations\Migrations;
use Phalcon\Migrations\Utils\Config;

$config = Config::fromArray([
    'database' => [
        'adapter'  => 'mysql',
        'host'     => 'phalcon-db-mysql',
        'username' => 'root',
        'password' => 'root',
        'dbname'   => 'vokuro',
    ],
]);

Migrations::run([
    'directory'      => __DIR__,
    'migrationsDir'  => [
        __DIR__ . '/migrations',
    ],
    'config'         => $config,
    'migrationsInDb' => true,
]);

The config value must be a Phalcon\Migrations\Utils\Config object. Use Config::fromArray() to create it from an array with the database and application sections. If you use a plain array, Migrations::run() throws an exception with the message Internal error. Config should be an instance of Phalcon\Migrations\Utils\Config.

Migrations::run() does not read the log-in-db key of the configuration. Use the migrationsInDb key.

Migrations::run() accepts these options:

Key Type Description
config Config Database configuration (required)
migrationsDir array / string Migrations directories (required)
directory string Project directory, which holds the file log. Default: the BASE_PATH constant, or the parent directory of APP_PATH. Set it if you do not define these constants
version string Version to migrate to. Default: the latest version
tableName string Table name, comma-separated table names or a prefix with an asterisk. Default: @ (all tables)
tsBased bool true - use timestamp based versions
migrationsInDb bool true - keep the migrations log in the database. false - keep it in a file. If you do not set it, the package uses the file log and gives a deprecation notice
log-path string Path of the log file (file log). Default: .phalcon/migration-version in the project directory
log-table string Name of the log table (database log). Default: phalcon_migrations
verbose bool true - show debugging information
skip-foreign-checks bool true - disable the foreign key checks during the run
truncate bool true - empty each table before batchInsert() imports its data

Other actions in PHP

The other actions also have a static method in Phalcon\Migrations\Migrations. Each method needs the config key, with a Phalcon\Migrations\Utils\Config object.

Migrations::generate()

Key Type Description
config Config Database configuration (required)
migrationsDir array Migrations directories (required)
tableName string Table name, comma-separated table names or a prefix with an asterisk. @ - all the tables (required)
version string Version to generate. Default: the next version
force bool true - overwrite the files of an existing version
tsBased bool true - generate a timestamp based version
descr string Description of a timestamp based version
exportData string always or oncreate. See Export data
exportDataFromTables array Tables to export data from
noAutoIncrement bool true - leave out the AUTO_INCREMENT value of the table
skip-ref-schema bool true - leave out the schema of the referenced table in the foreign keys
namespace string Namespace of the generated migration classes
log-table string Name of the log table, which generate skips. Default: phalcon_migrations
verbose bool true - dry run. generate writes no files. The --dry option of the CLI sets this key

Migrations::listAll()

Key Type Description
config Config Database configuration (required)
migrationsDir array Migrations directories (required)
tsBased bool true - use timestamp based versions (required)

listAll() also accepts the directory, migrationsInDb, log-path and log-table keys of Migrations::run().

Migrations::clean()

Key Type Description
config Config Database configuration (required)
tableName string Comma-separated table names. Default: @ (all the tables)
data-only bool true - delete the rows and keep the tables

clean() also accepts the directory, migrationsInDb, log-path and log-table keys of Migrations::run().

Migrations::export()

Key Type Description
config Config Database configuration (required)
migrationsDir array / string Migrations directories (required)
version string Version to export. Default: the newest version
tableName string Comma-separated table names. Default: @ (all the tables)
tsBased bool true - use timestamp based versions

export() prints the SQL. See Export the schema.

<?php

use Phalcon\Migrations\Migrations;
use Phalcon\Migrations\Utils\Config;

$config = Config::fromArray([
    'database' => [
        'adapter'  => 'mysql',
        'host'     => '127.0.0.1',
        'username' => 'root',
        'password' => '',
        'dbname'   => 'shop',
    ],
]);

Migrations::generate([
    'config'        => $config,
    'migrationsDir' => [__DIR__ . '/db/migrations'],
    'tableName'     => 'invoices,customers',
]);

Migration files

Each version is a directory in the migrations directory. The version directory has one PHP file for each table. The name of the file is the table name, for example users.php.

Each file returns an object of an anonymous class, which extends Phalcon\Migrations\Mvc\Model\Migration. The TABLE_NAME constant of the class has the table name. The methods use self::TABLE_NAME in place of the table name. Any table name works, also a name with a space or a quote.

A generated file is similar to this (shortened) example:

<?php

declare(strict_types=1);

use Phalcon\Migrations\Db\Column;
use Phalcon\Migrations\Db\Index;
use Phalcon\Migrations\Db\Reference;
use Phalcon\Migrations\Mvc\Model\Migration;

// The migration of the table in TABLE_NAME
return new class extends Migration {
    public const TABLE_NAME = 'users';

    /**
     * Define the table structure
     *
     * @return void
     * @throws \Exception
     */
    public function morph(): void
    {
        $this->morphTable(self::TABLE_NAME, [
            'columns' => [
                new Column(
                    'id',
                    [
                        'type' => Column::TYPE_INTEGER,
                        'unsigned' => true,
                        'notNull' => true,
                        'autoIncrement' => true,
                        'first' => true
                    ]
                ),
                new Column(
                    'email',
                    [
                        'type' => Column::TYPE_VARCHAR,
                        'notNull' => true,
                        'size' => 255,
                        'comment' => "Login email",
                        'after' => 'id'
                    ]
                ),
                new Column(
                    'created_at',
                    [
                        'type' => Column::TYPE_TIMESTAMP,
                        'default' => "CURRENT_TIMESTAMP",
                        'notNull' => true,
                        'after' => 'email'
                    ]
                ),
            ],
            'indexes' => [
                new Index('PRIMARY', ['id'], 'PRIMARY KEY'),
                new Index('users_email_uindex', ['email'], 'UNIQUE'),
            ],
            'references' => [],
            'options' => [
                'ENGINE' => 'InnoDB',
                'TABLE_COLLATION' => 'utf8mb4_unicode_ci',
            ],
        ]);
    }

    /**
     * Run the migrations
     *
     * @return void
     */
    public function up(): void
    {
    }

    /**
     * Reverse the migrations
     *
     * @return void
     */
    public function down(): void
    {
    }
};

To put the generated classes in a namespace, use the --namespace option or the namespace key, for example --namespace=App\Migrations. The file then has a namespace App\Migrations; line. Files with a namespace and files with no namespace run together.

A migration file must not declare functions or named classes. The package can load a file more than one time in a run. A file that declares a named class is an old file (see below).

Old migration files

In version 4.0.1 and earlier, each file has a named class. The class name is the table name in CamelCase, then Migration_, then the version stamp, for example UsersMigration_100. These files run as before, also next to new files of the same table. migrate-files does not change them. To get the new format for a table, run generate again.

Column types

The type option of a column takes one of the Column::TYPE_* constants of Phalcon\Migrations\Db\Column. The table shows the SQL type that each database gets.

Constant MySQL PostgreSQL SQLite
Column::TYPE_BIGINTEGER BIGINT BIGINT INTEGER
Column::TYPE_BIT BIT BIT INTEGER
Column::TYPE_BLOB BLOB BYTEA BLOB
Column::TYPE_BOOLEAN TINYINT(1) BOOLEAN INTEGER
Column::TYPE_CHAR CHAR CHARACTER CHARACTER
Column::TYPE_DATE DATE DATE DATE
Column::TYPE_DATETIME DATETIME TIMESTAMP DATETIME
Column::TYPE_DECIMAL DECIMAL NUMERIC NUMERIC
Column::TYPE_DOUBLE DOUBLE DOUBLE PRECISION REAL
Column::TYPE_ENUM ENUM VARCHAR TEXT
Column::TYPE_FLOAT FLOAT FLOAT REAL
Column::TYPE_INTEGER INT INTEGER INTEGER
Column::TYPE_JSON JSON JSON TEXT
Column::TYPE_JSONB JSON JSONB TEXT
Column::TYPE_LONGBLOB LONGBLOB BYTEA BLOB
Column::TYPE_LONGTEXT LONGTEXT TEXT TEXT
Column::TYPE_MEDIUMBLOB MEDIUMBLOB BYTEA BLOB
Column::TYPE_MEDIUMINTEGER MEDIUMINT INTEGER INTEGER
Column::TYPE_MEDIUMTEXT MEDIUMTEXT TEXT TEXT
Column::TYPE_SET SET No mapping No mapping
Column::TYPE_SMALLINTEGER SMALLINT SMALLINT INTEGER
Column::TYPE_TEXT TEXT TEXT TEXT
Column::TYPE_TIME TIME TIME TEXT
Column::TYPE_TIMESTAMP TIMESTAMP TIMESTAMP DATETIME
Column::TYPE_TINYBLOB TINYBLOB BYTEA BLOB
Column::TYPE_TINYINTEGER TINYINT SMALLINT INTEGER
Column::TYPE_TINYTEXT TINYTEXT TEXT TEXT
Column::TYPE_UUID No mapping UUID No mapping
Column::TYPE_VARCHAR VARCHAR CHARACTER VARYING TEXT

No mapping means that the database has no type for the constant. Do not use the constant with that database.

PostgreSQL and SQLite create a Column::TYPE_ENUM column as a text column. They do not keep the list of values.

The size option applies to these types:

  • MySQL: all the types, except the BLOB and TEXT types, BOOLEAN, DATE, DATETIME, DOUBLE, FLOAT, JSON, TIME and TIMESTAMP. For the integer types, the size is only a display width.
  • PostgreSQL: only BIT, CHAR, DECIMAL, ENUM and VARCHAR.
  • SQLite: no type. The package does not write a size for SQLite.

Column options

The second argument of new Column() is an array of options:

Option Type Default Description
type string Column::TYPE_VARCHAR Type of the column. See Column types
size int None Size of the column, for example 255 for VARCHAR(255). See Column types
scale int None Number of digits after the decimal point. Use it with size, for example 'size' => 10, 'scale' => 2 for DECIMAL(10,2)
unsigned bool false true - UNSIGNED (MySQL only)
notNull bool true true - NOT NULL. false - the column accepts NULL
default mixed None Default value. null gives DEFAULT NULL. CURRENT_TIMESTAMP, CURRENT_TIMESTAMP() and NOW() have no quotes. Other values are texts in quotes
defaultExpression bool false true - the default is an expression, with no quotes (PostgreSQL only)
onUpdate string None CURRENT_TIMESTAMP gives ON UPDATE CURRENT_TIMESTAMP (MySQL only)
autoIncrement bool false MySQL: AUTO_INCREMENT. PostgreSQL: SERIAL, with primary, when the morph creates the table. SQLite: INTEGER PRIMARY KEY AUTOINCREMENT, with primary
primary bool false The column is part of the primary key. When the morph creates the table and the indexes have no primary key, the primary key has the columns with this option
first bool false true - the morph adds the column as the first column of the table (MySQL only)
after string None The morph adds the column after this column (MySQL only)
comment string '' Comment of the column (MySQL and PostgreSQL)
options array None Values of a Column::TYPE_ENUM or Column::TYPE_SET column (MySQL only)
<?php

declare(strict_types=1);

use Phalcon\Migrations\Db\Column;
use Phalcon\Migrations\Db\Index;
use Phalcon\Migrations\Mvc\Model\Migration;

return new class extends Migration {
    public const TABLE_NAME = 'invoices';

    public function morph(): void
    {
        $this->morphTable(self::TABLE_NAME, [
            'columns' => [
                new Column('id', [
                    'type'          => Column::TYPE_INTEGER,
                    'unsigned'      => true,
                    'autoIncrement' => true,
                    'first'         => true,
                ]),
                new Column('total', [
                    'type'    => Column::TYPE_DECIMAL,
                    'size'    => 10,
                    'scale'   => 2,
                    'default' => '0.00',
                    'after'   => 'id',
                ]),
                new Column('status', [
                    'type'    => Column::TYPE_ENUM,
                    'options' => ['draft', 'sent', 'paid'],
                    'default' => 'draft',
                    'after'   => 'total',
                ]),
                new Column('paid_at', [
                    'type'    => Column::TYPE_DATETIME,
                    'notNull' => false,
                    'after'   => 'status',
                ]),
            ],
            'indexes' => [
                new Index('PRIMARY', ['id'], 'PRIMARY KEY'),
            ],
        ]);
    }
};

On MySQL, export shows this SQL for the file:

CREATE TABLE `invoices` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `total` DECIMAL(10,2) NOT NULL DEFAULT '0.00',
    `status` ENUM('draft', 'sent', 'paid') NOT NULL DEFAULT 'draft',
    `paid_at` DATETIME NULL,
    PRIMARY KEY (`id`)
);

Columns

These rules apply to the column definitions of a generated file:

Column Rule
Integer On MySQL 8.0.19 and later, generate writes no size. On MariaDB, the size is the display width, for example 11. The size of an integer is only a display width. The morph does not compare it
Column::TYPE_BOOLEAN No size
JSON and JSONB No size
Column::TYPE_UUID PostgreSQL UUID. No size. MySQL and SQLite have no mapping for this type
Column::TYPE_SET MySQL SET. The values are in 'options' => [...], as for Column::TYPE_ENUM
'comment' Part of the column. The morph applies a change of only the comment. If the file has no comment for a column, the morph clears the comment of the live column. PostgreSQL writes the comment with COMMENT ON COLUMN. SQLite has no column comments
'default' => "CURRENT_TIMESTAMP" generate writes a plain CURRENT_TIMESTAMP default (MySQL and PostgreSQL). It does not write a default with a precision, for example CURRENT_TIMESTAMP(6), or a different expression
'onUpdate' => "CURRENT_TIMESTAMP" MySQL ON UPDATE CURRENT_TIMESTAMP. Only the plain form. The morph compares it
'defaultExpression' => true PostgreSQL. The default is an expression, for example gen_random_uuid(). The SQL has the default with no quotes. generate sets it for a default in the form of a function call with no quotes. The morph does not compare it
'primary' => true Written on the primary key columns on PostgreSQL and SQLite
'autoIncrement' => true On SQLite, written for an AUTOINCREMENT column

Renamed columns

The morph renames a column of the table when the file has a column with a new name at the place of that column, and the definition in the file is the same as the definition that the database gives for that column. The place is the column before it, or the column after it. The data of the column stays. MySQL, PostgreSQL and SQLite (3.25.0 and later) rename the column.

<?php

use Phalcon\Migrations\Db\Column;

// Version 1.0.0
$email = new Column('email', [
    'type'    => Column::TYPE_VARCHAR,
    'size'    => 255,
    'notNull' => true,
    'after'   => 'id',
]);

// Version 1.0.1: the same definition with a new name. On MySQL and PostgreSQL, the morph renames email to login.
$login = new Column('login', [
    'type'    => Column::TYPE_VARCHAR,
    'size'    => 255,
    'notNull' => true,
    'after'   => 'id',
]);

The morph compares the file with the definition that the database reads. A file that generate wrote has this definition. A definition that you wrote can be different. For example:

  • SQLite creates a Column::TYPE_VARCHAR column as TEXT, and reads it as Column::TYPE_TEXT with no size. For this reason, the example above does not rename on SQLite.
  • For a TEXT column, MySQL gives the size 65535, and SQLite gives no size.

If the definition is not the same, the morph adds the new column and drops the old column. The data of the old column is lost. On SQLite and PostgreSQL, a new NOT NULL column with no default stops the run when the table has rows.

To rename a column, rename it in your development database (ALTER TABLE ... RENAME COLUMN), then run generate. Change the definition of the column in a different version.

UUID primary keys

The package does not make UUID values. Use one of these two methods for a UUID primary key.

A default of the database. On PostgreSQL, use DEFAULT gen_random_uuid(), or uuid_generate_v4() with the uuid-ossp extension. generate writes the column like this:

<?php

use Phalcon\Migrations\Db\Column;

new Column(
    'id',
    [
        'type' => Column::TYPE_UUID,
        'default' => "gen_random_uuid()",
        'defaultExpression' => true,
        'primary' => true,
        'notNull' => true,
        'first' => true
    ]
);

A value from the application. Use Phalcon\Encryption\Security\Uuid. Set the value before the insert, for example in the beforeValidationOnCreate() method of the model. The column then needs no default. This works on MySQL, PostgreSQL and SQLite. v7() gives time-ordered values, which are better for indexes than the random values of v4().

<?php

use Phalcon\Encryption\Security\Uuid;
use Phalcon\Mvc\Model;

class Invoices extends Model
{
    public string $id;

    public function beforeValidationOnCreate(): void
    {
        $this->id = (string) (new Uuid())->v7();
    }
}

Index definition

new Index($name, $columns, $type) defines an index in the indexes key of the definition. The $type argument gives the kind of index:

Type Index
'PRIMARY KEY' or 'PRIMARY' Primary key. An index with the name PRIMARY is also a primary key
'UNIQUE' Unique index
'' Index. This is the default. Other values also give an index
<?php

use Phalcon\Migrations\Db\Index;

$indexes = [
    new Index('PRIMARY', ['id'], 'PRIMARY KEY'),
    new Index('invoices_number_uindex', ['number'], 'UNIQUE'),
    new Index('invoices_customer_status_index', ['customer_id', 'status'], ''),
];

Foreign key definition

new Reference($name, $definition) defines a foreign key in the references key of the definition. The $definition argument has these keys:

Key Type Description
referencedTable string Table that the foreign key refers to (required)
columns array Columns of this table (required)
referencedColumns array Columns of the referenced table, in the same order as columns (required)
referencedSchema string Schema of the referenced table. Default: none, the database uses its current schema
onDelete string Action on delete, for example CASCADE, SET NULL or RESTRICT
onUpdate string Action on update, for example CASCADE, SET NULL or RESTRICT

A foreign key can have more than one column. Put the columns in the same order in columns and referencedColumns.

generate writes a foreign key like this:

<?php

use Phalcon\Migrations\Db\Reference;

$references = [
    new Reference(
        'invoices_customers_fk',
        [
            'referencedSchema' => 'shop',
            'referencedTable' => 'customers',
            'columns' => ['customer_id'],
            'referencedColumns' => ['id'],
            'onUpdate' => 'RESTRICT',
            'onDelete' => 'CASCADE'
        ]
    ),
];

When the morph adds this foreign key to the invoices table of the MySQL database shop, the SQL is:

ALTER TABLE `shop`.`invoices` ADD CONSTRAINT `invoices_customers_fk` FOREIGN KEY (`customer_id`) REFERENCES `shop`.`customers` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT

On MySQL, the schema is the database name. If the database has a different name in each environment, use --skip-ref-schema (or skip-ref-schema) with generate. The file then has no referencedSchema, and the foreign key refers to the table in the current database.

SQLite creates a foreign key only with the table. See Supported databases.

Indexes and foreign keys

A generated file always has the indexes and references keys, also when the lists are empty. The morph changes the indexes and the foreign keys only when the file has the key:

  • With the key, the morph adds, changes and removes indexes or foreign keys, so that the table matches the file.
  • With no key, for example in a file that you wrote, the morph does not change them.

Before the morph drops a column, it drops the foreign keys that use that column.

Table options

generate writes the options of the table, for example ENGINE, TABLE_COLLATION, AUTO_INCREMENT and, if the MySQL table sets it, ROW_FORMAT. The options apply only when the morph creates the table. The morph does not change the options of a table that exists.

Files from version 4.0.1 or earlier

Some migration files from version 4.0.1 or earlier do not have all the data of the table. Generate again the versions that did not run yet in these conditions:

  • The table has a PostgreSQL uuid column. The old file has Column::TYPE_VARCHAR with 'size' => 1.
  • The table has a CURRENT_TIMESTAMP default. The old file has no default, so its run removes the default from the live column.
  • The table has a MySQL ON UPDATE CURRENT_TIMESTAMP column. The old file has no onUpdate, so its run removes it from the live column.
  • The table has a PostgreSQL default that is an expression, for example gen_random_uuid(). The old file has no defaultExpression, so a new table gets the default as a text.
  • The table is a SQLite table. The old file has no primary key, so a table that the file creates has no primary key.

Migration methods

Each migration file is for one table. Its class can have the methods below. The package calls each method that the class has. A method can contain any code.

The package calls the methods for each table, not one time for the run. In each version, it takes the tables in the alphabetical order of the file names, or in the order of --table.

Running to up

For each table of the version, the package calls:

  1. morph(). When morphTable() creates the table, it calls afterCreateTable(). It does not call afterCreateTable() for a table that exists.
  2. up().
  3. afterUp(), only if the class has an up() method.

After all the tables of the version, the package adds the version to the log.

Running to down

For each table of the version that the package removes, it calls:

  1. down() of the version that it removes.
  2. afterDown(), only if the class has a down() method.
  3. morph() of the previous version. If the previous version has no file for the table, the package uses the newest earlier version that has one.

After all the tables of the version, the package removes the version from the log.

Helper methods

The Phalcon\Migrations\Mvc\Model\Migration class has these methods, which you can use in your migration methods:

Method Description
morphTable(string $tableName, array $definition): void Creates the table, or changes the table to match the columns, indexes, references and options in the definition
batchInsert(string $tableName, array $fields, int $size = 1024): void Inserts the rows of the <table>.dat file of the version, in one transaction. It inserts $size rows in each query. With --truncate, it first deletes all the rows of the table
batchDelete(string $tableName): void Deletes all the rows of the table, if the <table>.dat file of the version exists
getConnection(): AdapterInterface Returns the database adapter (Phalcon\Migrations\Db\Adapter\AdapterInterface)

Custom SQL

To run SQL in a migration method, use the adapter that getConnection() returns. The adapter has these methods:

Method Description
execute(string $sql, array $values = []): void Runs a statement. $values has the values of the ? placeholders, or named values
fetchAll(string $sql, array $values = []): array Returns all the rows. Each row is an array with the column names as keys
fetchOne(string $sql, array $values = []): array Returns the first row, or an empty array
tableExists(string $table, string $schema = ''): bool Returns true if the table exists
listTables(string $schema): array Returns the names of the tables of the schema
getCurrentSchema(): string Returns the current schema. SQLite gives main
begin(), commit(), rollback() Starts, commits or rolls back a transaction
<?php

declare(strict_types=1);

use Phalcon\Migrations\Mvc\Model\Migration;

return new class extends Migration {
    public const TABLE_NAME = 'invoices';

    public function up(): void
    {
        $this->getConnection()->execute(
            'UPDATE invoices SET status = ? WHERE status IS NULL',
            ['draft']
        );
    }
};

Export data

generate can export the data of a table. It writes the rows to a <table>.dat file (CSV format) in the version directory. The --data option controls how the migration imports the data:

Value Generated code
oncreate afterCreateTable() calls batchInsert(). The data is imported only when the table is created
always up() calls batchInsert() and down() calls batchDelete(). The data is imported on each run

The tables in export-data-from-tables (or --export-data-from-tables) get the same code as always.

With always, each version that has data inserts its rows. A later version then inserts the rows again, over the rows of an earlier version. To prevent this, use --truncate (or truncate in the configuration) with run. Before batchInsert() imports the data of a table, it deletes all the rows of the table with DELETE FROM, in the same transaction.

Other actions

Clean the database

The clean action drops the tables of the database, or deletes their data. It does not drop the log table, the SQLite internal tables (for example sqlite_sequence) or the PostgreSQL tables of an extension. Without --force, it stops with the error The clean action drops tables or deletes data: add --force to run it.

vendor/bin/phalcon-migrations clean --force
Command Result
clean --force Drops all the tables and empties the log. The next run starts from the first version
clean --force --table=users,roles Drops only these tables. The log does not change
clean --force --data-only Deletes the rows of all the tables, and keeps the tables. The log does not change

--table accepts table names, separated with commas. Tables that refer to each other work.

Export the schema

The export action shows the SQL of the schema of the migration files at a version. The default is the newest version.

vendor/bin/phalcon-migrations export --config=migrations.php --version=1.0.0

The output has the CREATE TABLE statements first. Then it has the other statements of the tables, for example the PostgreSQL and SQLite indexes and the PostgreSQL column comments. Then it has the foreign keys. For the example file above, the output on MySQL is:

CREATE TABLE `users` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `email` VARCHAR(255) NOT NULL COMMENT 'Login email',
    `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `users_email_uindex` (`email`)
) ENGINE=InnoDB COLLATE=utf8mb4_unicode_ci;
  • To export only some tables, use --table with table names, separated with commas.
  • The names have no schema.
  • The output has no data.
  • The database does not change. If a morph() method has code other than morphTable(), export runs that code.

To write the SQL to a file, redirect the output. The banner and the error messages go to stderr, so the file has only the SQL:

vendor/bin/phalcon-migrations export --config=migrations.php > schema.sql

CLI Arguments and options

Arguments

Argument Description
generate Generate a Migration
run Run a Migration
list List all available migrations
clean Drop the tables, or delete their data. See Clean the database
export Show the SQL of the schema at a version. See Export the schema
import-log Copy the file log into the empty log table. See Move the file log to the database
migrate-files Update migration files to use the Phalcon\Migrations\Db classes. See Upgrade from 3.x to 4.0
help Shows the help

Options

Action Description
--config=s Configuration file. A relative path starts in the project directory
--migrations=s Migrations directory. Use comma separated string to specify multiple directories
--directory=s Directory where the project was created
--table=s Table to migrate. Table name, comma-separated table names, or table prefix with an asterisk. Default: all. clean and export accept only table names
--version=s Version to generate, version to migrate to, or version to export
--descr=s Migration description (used for timestamp-based migration)
--data=s Export data [‘always’ or ‘oncreate’] (Data is imported during migration run)
--export-data-from-tables=s Export data from specific tables, use comma-separated string
--truncate Empty each table before its data is imported (Running only). See Export data
--force Forces to overwrite existing migrations, or confirms the clean action
--data-only Delete the data and keep the tables (clean only)
--ts-based Timestamp based migration version
--log-in-db Keep migrations log in the database table rather than in file. See Migrations log
--log-path=s Path of the log file. With the database log, run reads it when the log table is empty. Default: .phalcon/migration-version
--log-table=s Name of the log table (database log only). Default: phalcon_migrations
--namespace=s Namespace of the generated migration classes (Generating only)
--dry Attempt requested operation without making changes to system (Generating only). run --dry stops with the error The --dry option is for generate only.
--dry-run Show the files to change, but do not change them (migrate-files only)
--verbose Output of debugging information during operation (Running only)
--no-auto-increment Leave out the AUTO_INCREMENT value of the table (Generating only)
--skip-ref-schema Leave out the schema of the referenced table in the foreign keys (Generating only)
--skip-foreign-checks Disable the foreign key checks during the run. MySQL: SET FOREIGN_KEY_CHECKS. PostgreSQL: SET session_replication_role (Running only)
--help Shows this help

A boolean option takes =false to turn off a value of the configuration, for example --log-in-db=false. See Application options.

The command writes the banner Phalcon Migrations and the error messages to stderr. The output of the action goes to stdout.

Incremental versions

By default, generate creates incremental versions. The first version is 1.0.0. Each new version adds one to the last number: 1.0.1, 1.0.2 and so on.

To set the version name, use --version:

vendor/bin/phalcon-migrations generate --version=2.0.0

A version with fewer than three parts gets zeros. For example, --version=1.1 creates the version 1.1.0.

If the version already exists, the command stops with an error. To overwrite the files of the existing version, add --force.

A version with another name can be the same version, for example 1.0.0.0 and 1.0.0 (see Order of the versions). generate --version=1.0.0.0 next to 1.0.0 stops with the error Version 1.0.0 already exists. With --force, it overwrites the files of 1.0.0.

Order of the versions

The package compares incremental versions part by part, as numbers:

  • 1.0.9 < 1.0.10 < 1.0.11 < 1.1.0
  • 1.0.0 < 1.0.0.1
  • 1.0.0 and 1.0.0.0 are the same version. A missing part is 0.

run and export stop with an error, before they change the database, in these conditions:

  • Two versions are the same version. If they are in two migrations directories, use one configuration for each set of migrations, each with its own log (--log-table or --log-path). If they are in one directory, for example 1.0.0 and 1.0.0.0, remove or rename one of the two version directories.
  • Two versions have the same old order number, for example 1.0.10 and 1.1.0, and old files make the order unsafe. This is true when both versions have old files. It is also true when only one of the two versions is in the log, and the other version has old files. In version 4.0.1 and earlier, only one of the two versions ran. The error names the two versions. It also names the version that is not in the log, if there is one: that version did not run on this database. Remove the version, or generate it again.

The old order number is the version stamp of the old class names, X * 100 + Y * 10 + Z. See Old migration files.

Timestamp based migrations

Using this approach is useful when more than one developer is participating in the database structure management.

  • To generate a timestamp based version, set a description with the --descr option, or with descr in the config file. --ts-based, or ts-based in the config file, also creates a timestamp based version, with no description.
  • To run, list or export timestamp based versions, use 'ts-based' => true in the config file, or the --ts-based option.

The description can contain only lowercase letters, digits and underscores (_). If it has other characters, the command stops with an error. For example:

vendor/bin/phalcon-migrations generate --descr=create_users

The command creates a version directory with a name like this:

* 1582539287636860_create_users

The name is the current Unix time in microseconds, then _, then the description.

Migrations will be executed from oldest to newest.

Upgrade from 4.x to 5.0

Version 5.0.0 changes some behavior of version 4. To upgrade:

  1. Use the new names of the configuration keys, and --export-data-from-tables in place of --exportDataFromTables. The old names give a PHP deprecation notice. Version 6.0 removes them. See Application options.
  2. Choose the migrations log with log-in-db. Version 6.0 makes the database log the default. To move to the database log, run import-log. See Migrations log.
  3. Examine your scripts. A CLI option now wins over the configuration for each setting, also --descr.
  4. MySQL: the connection uses the utf8mb4 character set. In version 4, it used utf8. To keep utf8, set charset in the database section. See Database options.
  5. Generate again the versions that did not run yet, if their files do not have all the data of the table. See Files from version 4.0.1 or earlier.
  6. Make sure that your migration files have the comments of the columns. The morph now compares the comment. A column with no comment in the file loses the comment of the live column.
  7. Examine your incremental versions. run and export can stop with an error for two versions with the same old order number. See Order of the versions.
  8. Remove --dry from run. In version 4, run --dry ran the migrations. Now it stops with an error.
  9. Examine the boolean keys of the configuration that have a text value. A text such as "false" or "off" is now false. In version 4, it was true.

The first generate after the update creates a version, because the format of the generated files changed. The old files run as before. See Old migration files.

If your code uses the classes of the package, also examine these changes:

  • Config::$logInDb is null when the configuration does not set log-in-db. In version 4, it was false.
  • Generate::getEntity() gives only the header of the file: the declare line, the namespace and the use lines. Use Generate::getCode() for the text of the file.

Upgrade from 3.x to 4.0

Version 4.0.0 removes the dependency on the Phalcon extension. To upgrade:

  1. Use PHP 8.2 or later.
  2. Change your PHP configuration file to return an array. See Create the configuration file.
  3. If you call Migrations::run() in your code, use Config::fromArray() for the config option. See Usage example.
  4. Update your migration files with the migrate-files command.

First, see the files that the command changes:

vendor/bin/phalcon-migrations migrate-files --migrations=db/migrations --dry-run

Then change the files:

vendor/bin/phalcon-migrations migrate-files --migrations=db/migrations

--dry-run=false is the same as no --dry-run: the command changes the files.

The --migrations option is required. The path is relative to the current directory. The command reads all the .php files in the directory and its subdirectories, and replaces these lines:

Old line New line
use Phalcon\Db\Column; use Phalcon\Migrations\Db\Column;
use Phalcon\Db\Index; use Phalcon\Migrations\Db\Index;
use Phalcon\Db\Reference; use Phalcon\Migrations\Db\Reference;

Migration files that you do not update continue to work if the Phalcon\Db classes are available, for example from the Phalcon extension. The package converts the Phalcon\Db\Column, Phalcon\Db\Index and Phalcon\Db\Reference objects when the migration runs.

Navigation

Type to search…

↑↓ navigate↵ selectEsc close