2

Is possible to dump in a file the SQL of the executed migration(s)? (or before executing? like a dry-run)

I took a look into the sources and if I'm not wrong the current implementation doesn't handle it, but probably wouldn't be too complicate to add the option, or I'm missing something?

2 Answers 2

2

It's not easy right now but still possible.

You would have to override yii\db\Command::execute() to return raw SQL instead of executing it.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for pointing me in this direction, to me currently the complex task seems to be to find how/where to inject the overriding class. Right now have no time to try it, but hopefully I will soon, then I'll get back here to confirm
@Alex you can do it i.e. by using a classmap, override the class there right before the extraction. I'm doing the same thing in my migration extension.
Thanks, perhaps that's the way but my yii knowledge is still too limited, I've extended the migrate controller and in its init() placed the classMap to my MigrationSql but seems like isn't working (if I modify the migration extending to my MigrationSql instead of Migration of course it works)
Actually got it working, ugly as easy, nothing fancy but a start, thanks again.
2

You can execute raw SQL inside Migrations, since yii\db\Migration class has an execute($sql, $params = []) method, like

<?php

use yii\db\Migration;

/**
 * Handles the creation of table `{{%users}}`.
 */
class m220914_163215_create_users_table extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->execute("
            CREATE TABLE `users` (
                `user_id` int(11) NOT NULL AUTO_INCREMENT,
                `username` varchar(255) NOT NULL,
                `updated_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `created_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (`user_id`),
                UNIQUE KEY `username` (`username`),
                UNIQUE KEY `user_id` (`user_id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=5705 DEFAULT CHARSET=latin1;
        ");
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropTable('{{%users}}');
    }
}

Then just run php yii migrate and your table must be created.

1 Comment

Thanks @victorf, I'm no longer using Yii but sometimes I still use migrations, it took me a while to understand what you mean, I knew you could use raw SQL, I never thought about using only those in migrations, very interesting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.