Skip to content

Migration Methods

The methods of a migration class: drop a table, the helper methods, custom SQL and the data.

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, in all the migrations directories.

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

Drop a table

The morph does not drop a table. Thus:

  • A rollback does not drop a table that the version created. The earlier versions have no file for the table, so no morph() runs for it.
  • generate does not write the drop of a table. When you drop a table in your development database, and no other table changed, generate shows Nothing to generate: no table changed since the last version.

Write the drops in the migration methods. In the version that creates a table, drop the table in down():

<?php

declare(strict_types=1);

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

// Version 1.0.1, file audit_log.php: the version creates the table audit_log
return new class extends Migration {
    public const TABLE_NAME = 'audit_log';

    public function morph(): void
    {
        $this->morphTable(self::TABLE_NAME, [
            'columns' => [
                new Column('id', [
                    'type'          => Column::TYPE_INTEGER,
                    'unsigned'      => true,
                    'autoIncrement' => true,
                    'primary'       => true,
                ]),
                new Column('action', [
                    'type' => Column::TYPE_VARCHAR,
                    'size' => 64,
                ]),
            ],
            'indexes' => [
                new Index('PRIMARY', ['id'], 'PRIMARY KEY'),
            ],
        ]);
    }

    public function down(): void
    {
        $this->getConnection()->dropTable(self::TABLE_NAME);
    }
};

To drop a table in a new version, add a file for the table to the version, and drop the table in up():

<?php

declare(strict_types=1);

use Phalcon\Migrations\Mvc\Model\Migration;

// Version 1.0.2, file invoice_notes.php: the version drops the table invoice_notes
return new class extends Migration {
    public const TABLE_NAME = 'invoice_notes';

    public function up(): void
    {
        $this->getConnection()->dropTable(self::TABLE_NAME);
    }
};

A rollback of version 1.0.2 calls the morph() of the newest earlier version that has a file for invoice_notes. That morph creates the table again. The rows that the table had are lost.

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

Other values stop generate with an error, and generate writes no files. For example, --data=alway gives:

The option data (exportData) accepts only always or oncreate, not 'alway'

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

generate writes the rows in the order of the primary key, if the table has one. Thus two exports of the same data give the same file. On MySQL, generate reads the rows one at a time, so a large table does not have to fit in the memory of PHP.

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.

A version can also run again, for example after a failure in the middle of the version. A version has no transaction (see Migration methods). batchInsert() only inserts, so the table then gets the rows two times, or the insert fails on the primary key. With --truncate, a version that runs again gives the same rows.

generate reads the data of each table in a separate query, with no transaction. If the database changes during the export, the data of two tables can be from different times, and the foreign keys between them can be wrong. Export the data from a database that does not change during the export.

The .dat file is a CSV file. These values have a special form:

Value in the table Field in the .dat file Value after the import
SQL NULL NULL SQL NULL
An empty value in a numeric column NULL SQL NULL
The text NULL \NULL The text NULL
A boolean value 1 or 0 true or false

A .dat file from an earlier version of the package has the text NULL as NULL. That field imports as SQL NULL. The file can also have a boolean false as an empty field. That field imports as false.

batchInsert() puts each column name in quotes. Thus a column name that is a reserved word, for example order, or a PostgreSQL name with upper case letters, for example userId, works. A name in quotes in a file that you wrote does not change.

Navigation

Type to search…

↑↓ navigate↵ selectEsc close