---
title: "Migration Methods"
description: "The methods of a migration class: drop a table, the helper methods, custom SQL and the data."
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 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.

:::warning[WARNING]
A version has no transaction. If a method fails, the changes to the tables before it stay, and the package does not add the version to the log.
:::

:::info[NOTE]
The package cannot reset the models metadata of your application. After `run`, reset the metadata, for example with `$di->get('modelsMetadata')->reset()`, or delete the metadata cache directory. See [Models Metadata](https://docs.phalcon.io/latest/db-models-metadata).
:::

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

:::warning[WARNING]
The `DELETE` of a table that other tables refer to fails. With `ON DELETE CASCADE`, it also deletes the rows of the other tables. On MySQL and PostgreSQL, `--skip-foreign-checks` turns off the foreign key checks for the run.
:::

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