---
title: "Migration Files"
description: "The format of the migration files: the columns, the indexes, the foreign keys and the table options."
version: "5.0"
---

> Documentation Index
> Fetch the complete documentation index at: https://migrations.phalcon.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 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
<?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).

:::info[NOTE]
Since version 4.0.0, migration files use the `Phalcon\Migrations\Db\Column`, `Phalcon\Migrations\Db\Index` and `Phalcon\Migrations\Db\Reference` classes. The `Column::TYPE_*` constants of `Phalcon\Migrations\Db\Column` are strings, for example `Column::TYPE_INTEGER` is `'integer'`. To update files from earlier versions, see [Upgrade from 3.x to 4.0](/5.0/upgrade#upgrade-from-3x-to-40).
:::

## 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](#column-types)                                                                                                           |
| `size`              | `int`    | None                   | Size of the column, for example `255` for `VARCHAR(255)`. See [Column types](#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)                                                                                       |

:::warning[WARNING]
The default of `notNull` is `true`. A column with no `notNull` option is `NOT NULL`. To accept `NULL`, set `'notNull' => false`.
:::

```php
<?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:

```sql
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
<?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
<?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](https://docs.phalcon.io/latest/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
<?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
<?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
<?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:

```sql
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](/5.0/introduction#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.

Source: https://migrations.phalcon.io/5.0/migration-files/index.mdx
