4.6. Migration examples

License

All code in this article is licensed under CC0 1.0. You are free to use, modify, and distribute the code for any purpose, including commercial use, without asking for permission.

The code is provided "as is", without warranty of any kind, express or implied.

For more visit https://creativecommons.org/publicdomain/zero/1.0/.

Yii2 Migration Generator Script

This script is designed to generate migration files for Yii2 framework based on changes in a database schema. The generated migration file includes methods for applying (safeUp()) and reverting (safeDown()) database changes.

Overview

This Python script reads an XML file containing database schema changes (e.g., create, alter, drop tables, etc.) and generates a Yii2 migration class file. It supports various operations, including:

  • Creating new tables
  • Dropping tables
  • Adding, changing, and dropping columns
  • Creating foreign key relationships
  • Adding indexes and primary keys

The script outputs a migration class in PHP, which can be used in Yii2 to modify the database schema.

Features

  • Create Table: Generates a createTable migration for new tables, including the table's columns, primary keys, indexes, and foreign keys.
  • Alter Table: Generates migrations for adding, altering, or dropping columns in existing tables.
  • Drop Table: Generates a migration for dropping tables.
  • Foreign Keys: Handles the addition and removal of foreign keys with configurable options for onDelete and onUpdate.
  • Indexes: Supports the creation of indexes for columns.
  • Comments: Supports adding comments to tables and columns.

Script Configuration

At the beginning of the script, you can configure the following settings:

INDENT = "    "
NEWLINE = "\r\n"

Script Workflow

The script processes an XML input representing schema changes and generates a PHP migration file with the appropriate Yii2 migration syntax.

  • Parse the XML: The script starts by parsing the XML file provided as input. Each schema change (CreateTable, DropTable, AlterTable) is processed individually.
  • Generate Migration Code: Based on the parsed XML, the script generates the corresponding migration code for each schema change.
  • Create Migration Class: The generated migration code is wrapped inside a migration class extending yii\db\Migration, with safeUp() and safeDown() methods.
  • Output: The migration class is saved to a file in the directory Yii2-Migrations/.

Example of Generated Migration Class

Here is an example of what the generated PHP migration class might look like:

class m250514_182637_create_test_table extends Migration
{
    public function safeUp()
    {
        $this->createTable("test", [
            $table->int('id')->notNull()->autoIncrement(),
            $table->text('name')->notNull(),
            $table->int('favorite_movie')
        ]);
        $this->addPrimaryKey('pk_test', 'test', 'id');
        $this->addForeignKey('FK_favorite_movie_film_film_id',
            'test',
            'favorite_movie',
            'film',
            'film_id');
    }

    public function safeDown()
    {
        $this->dropForeignKey('FK_favorite_movie_film_film_id', 'test');
        $this->dropTable("test");
    }
}

Functions

The script includes several functions to handle the migration generation process:

  • parse_column_list(s): Converts a comma-separated list of columns into a Python list format.
  • parse_column_element(column_element): Converts a column XML element into a Yii2 migration column definition.
  • handle_create_table(diff): Handles CreateTable elements in the XML, generating createTable migration code.
  • handle_alter_table(diff): Handles AlterTable elements, generating migrations for adding, altering, or dropping columns.
  • handle_drop_table(diff): Handles DropTable elements, generating a migration to drop the specified table.
  • handle_foreign_key(table_name, foreign_key): Handles the creation of foreign keys in the migration.
  • get_class_name(): Generates a migration class name based on the current timestamp.
  • get_class(): Generates the full migration class code.

Direct link to download the script - yii2-migration.py or view online.

Laravel Migration Generator Script

This script is designed to generate migration files for the Laravel framework based on changes in a database schema. The generated migration file includes methods for applying (up()) and reverting (down()) database changes.

Overview

This Python script reads an XML file containing database schema changes (e.g., create, alter, drop tables, etc.) and generates a Laravel migration class file. It supports various operations, including:

  • Creating new tables
  • Dropping tables
  • Adding, changing, and dropping columns
  • Creating foreign key relationships
  • Adding indexes and primary keys

The script outputs a migration class in PHP, which can be used in Laravel to modify the database schema.

Features

  • Create Table: Generates a create migration for new tables, including the table's columns, primary keys, indexes, and foreign keys.
  • Alter Table: Generates migrations for adding, altering, or dropping columns in existing tables.
  • Drop Table: Generates a migration for dropping tables.
  • Foreign Keys: Handles the addition and removal of foreign keys with configurable options for onDelete and onUpdate.
  • Indexes: Supports the creation of indexes for columns.
  • Comments: Supports adding comments to tables and columns.

Script Configuration

At the beginning of the script, you can configure the following settings:

INDENT = "    "
NEWLINE = "\n"

Script Workflow

The script processes an XML input representing schema changes and generates a PHP migration file with the appropriate Laravel migration syntax.

  • Parse the XML: The script starts by parsing the XML file provided as input. Each schema change (CreateTable, DropTable, AlterTable) is processed individually.
  • Generate Migration Code: Based on the parsed XML, the script generates the corresponding migration code for each schema change.
  • Create Migration Class: The generated migration code is wrapped inside a migration class extending Migration, with up() and down() methods.
  • Output: The migration class is saved to a file in the directory Laravel-Migrations/.

Functions

The script includes several functions to handle the migration generation process:

  • parse_column_list(s): Converts a comma-separated list of columns into a Python list format.
  • parse_column_element(column_element): Converts a column XML element into a Laravel migration column definition.
  • handle_create_table(diff): Handles CreateTable elements in the XML, generating Schema::create migration code.
  • handle_alter_table(diff): Handles AlterTable elements, generating migrations for adding, altering, or dropping columns.
  • handle_drop_table(diff): Handles DropTable elements, generating a migration to drop the specified table.
  • handle_foreign_key_inline(fk): Handles the creation of foreign keys in the migration using inline definitions.
  • get_filename(): Generates a migration filename based on the current timestamp and action (create, alter, drop).
  • generate_class(): Generates the full migration class code, including the up() and down() methods.

Script Output

The migration file will be saved in the directory Laravel-Migrations/, and the filename will be based on the current timestamp, for example: 2025_05_14_182637_create_test_table.php.

Here is an example of what the generated PHP migration class might look like:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up(): void
    {
        Schema::create('test', function (Blueprint $table) {
            $table->int('id')->increments();
            $table->text('name');
            $table->int('favorite_movie')->nullable(true);
            $table->primary(['id'], 'pk_test');
            $table->foreign('favorite_movie')->references('film_id')->on('film')->name('FK_favorite_movie_film_film_id');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('test');
    }
};

Direct link to download the script - laravel-migration.py or view online.