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.
The name of an incremental version directory is only the full version, for example 1.0.0 or 1.0.0.1. The package skips these directories:
-
A directory with a version and other text in its name, for example the backup
1.0.0-old, is not a version. The package shows a notice one time in each action:Info: The folder /var/www/shop/db/migrations/1.0.0-old is skipped: the name of a version folder is only its version (for example 1.0.0) -
A directory with no version in its name, for example
docs, is not a version. The package shows no notice.
A directory with fewer than three parts in its name, for example 1.1, stops run, list, export and generate before they change the database or write a file. Rename the directory:
The name of the version folder '1.1' (in '/var/www/shop/db/migrations') is not a full version. Rename the folder to '1.1.0'.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. The first generate creates a version in the new format, also when no table changed. See Generate migrations.
A PHP process loads an old file one time. If an old file changes while the process runs, for example in a worker or in a test suite that runs the migrations more than one time, the process continues to use the class of the first load. To load the changed file, start a new process. A file in the new format loads again each time that the package uses it.
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
BLOBandTEXTtypes,BOOLEAN,DATE,DATETIME,DOUBLE,FLOAT,JSON,TIMEandTIMESTAMP. For the integer types, the size is only a display width. - PostgreSQL: only
BIT,CHAR,DECIMAL,ENUMandVARCHAR. - SQLite: no type. The package does not write a size for SQLite.
Stored types
Some databases store a type as a different type. When the package reads a table, for example in generate and in the morph, it gets the stored type. The package does not show a message for these types. Same means that the database stores the type of the file.
| Constant | MySQL | PostgreSQL | SQLite |
|---|---|---|---|
Column::TYPE_BIGINTEGER |
Same | Same | Column::TYPE_INTEGER |
Column::TYPE_BIT |
Same | Same | Column::TYPE_INTEGER |
Column::TYPE_BOOLEAN |
Same | Same | Column::TYPE_INTEGER |
Column::TYPE_CHAR |
Same | Same | Column::TYPE_VARCHAR |
Column::TYPE_DATETIME |
Same | Column::TYPE_TIMESTAMP |
Same |
Column::TYPE_DOUBLE |
Same | Same | Column::TYPE_FLOAT |
Column::TYPE_ENUM |
Same | Column::TYPE_VARCHAR |
Column::TYPE_TEXT |
Column::TYPE_FLOAT |
Same | Column::TYPE_DOUBLE |
Same |
Column::TYPE_JSON |
Same | Same | Column::TYPE_TEXT |
Column::TYPE_JSONB |
Column::TYPE_JSON |
Same | Column::TYPE_TEXT |
Column::TYPE_LONGBLOB |
Same | Column::TYPE_BLOB |
Column::TYPE_BLOB |
Column::TYPE_LONGTEXT |
Same | Column::TYPE_TEXT |
Column::TYPE_TEXT |
Column::TYPE_MEDIUMBLOB |
Same | Column::TYPE_BLOB |
Column::TYPE_BLOB |
Column::TYPE_MEDIUMINTEGER |
Same | Column::TYPE_INTEGER |
Column::TYPE_INTEGER |
Column::TYPE_MEDIUMTEXT |
Same | Column::TYPE_TEXT |
Column::TYPE_TEXT |
Column::TYPE_SMALLINTEGER |
Same | Same | Column::TYPE_INTEGER |
Column::TYPE_TIME |
Same | Same | Column::TYPE_TEXT |
Column::TYPE_TIMESTAMP |
Same | Same | Column::TYPE_DATETIME |
Column::TYPE_TINYBLOB |
Same | Column::TYPE_BLOB |
Column::TYPE_BLOB |
Column::TYPE_TINYINTEGER |
Same | Column::TYPE_SMALLINTEGER |
Column::TYPE_INTEGER |
Column::TYPE_TINYTEXT |
Same | Column::TYPE_TEXT |
Column::TYPE_TEXT |
Column::TYPE_VARCHAR |
Same | Same | Column::TYPE_TEXT |
generate writes the stored type in the file. In a file that you write, also use the stored type. If the file has a constant that the database stores as a different type, the morph finds a change of the column on each run:
- MySQL and PostgreSQL change the column again, to the same stored type.
- SQLite ignores the change. See Supported databases.
For example, a Column::TYPE_TINYINTEGER column priority of the PostgreSQL table invoices gets this statement on each run:
ALTER TABLE "public"."invoices" ALTER COLUMN "priority" TYPE SMALLINTOn SQLite, the morph compares a Column::TYPE_VARCHAR column of the file as Column::TYPE_TEXT with no size. Thus a file from MySQL or PostgreSQL, or a file that you wrote, finds no change for this type, and a rename of the column works. See Renamed columns.
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) |
The morph compares the default of each column with the default of the live column. It compares a numeric default by its value, so 'default' => '0' and the default 0 of the table are the same. If the file has no default for a column, the morph removes the default of the live column (MySQL and PostgreSQL). SQLite ignores a change of a column. See Supported databases.
<?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. 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 stores some types as other types. For
Column::TYPE_VARCHAR, the morph uses the stored type in the compare. For the other types, use the stored type in the file. See Stored types. - For a
TEXTcolumn, MySQL gives the size65535, 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 RESTRICTOn 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.
An index with a part on an expression, for example lower(email), is not in the files of generate. For each such index, generate prints this message:
The index <name> of the table <table> has a part on an expression. Generate does not write it, and the morph does not drop it.The morph does not drop or change such an index, also when an older PostgreSQL file lists it as an index on its columns only.
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
uuidcolumn. The old file hasColumn::TYPE_VARCHARwith'size' => 1. - The table has a
CURRENT_TIMESTAMPdefault. The old file has no default, so its run removes the default from the live column. - The table has a MySQL
ON UPDATE CURRENT_TIMESTAMPcolumn. The old file has noonUpdate, 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 nodefaultExpression, 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.
Files from version 5.0.0 or earlier
generate of version 5.0.0 and earlier wrote some tables with wrong data. Generate again the versions that did not run yet in these conditions:
- The PostgreSQL table has an index with the primary key column and other columns, for example
(id, name). The old file has the index without the primary key column,(name). The old file also has no unique index on only the primary key column. - The PostgreSQL table has an index of more than one column. The old file can have the columns in the order of the table, not in the order of the index. A table that the file creates then gets a different index.
- The PostgreSQL table has a text column with
DEFAULT NULL. The old file has'default' => "NULL", so a table that the file creates gets the text default'NULL'. - The SQLite table has a text default with a quote, for example
it's. The old file hasit''s. A quote at the start or at the end of the default is not in the old file.
For these tables, the first generate after the update creates a version, also when no table changed.
The .dat files of version 5.0.0 and earlier are not in a fixed order, and can have a boolean false as an empty field. These files import correctly. The next generate with data writes the rows in the order of the primary key. See Export data.