简体   繁体   中英

Yii2 set MySQL user for first time migration table creation?

My issue has to do with the automated creation of the migration history table when first executing yii migrate/up --interactive=0 .
I was able to override the database access credentials for the migrations themselves. (see example below)

For my web application, I have a user default that has the following GRANT s: SELECT, INSERT For migrations, I want to use my admin user who has additional GRANT s for DDL .

When executing the migration Yii2 wants to create a migration table with the default user which leads to a permission denied error.

How can I set the database user for the migration table creation?

My migration script:

<?php

use yii\db\Migration;

/**
 * Handles adding columns to table `{{%Tablename}}`.
 */
class m210907_145507_add_json_column_to_Tablename_table extends Migration
{
    public function init()
    {
        $this->db = new \yii\db\Connection([
            'dsn' => 'mysql:host=mysql;dbname=dbname',
            'username' => 'admin',
            'password' => 'itasecrettoeverybody',
            'charset' => 'utf8',
            'enableSchemaCache' => true,
            'schemaCacheDuration' => 60,
            'schemaCache' => 'cache',
        ]);
        parent::init();
    }
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->addColumn('{{%Tablename}}', 'json', $this->json());
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropColumn('{{%Tablename}}', 'json');
    }
}

The error:

Yii Migration Tool (based on Yii v2.0.43)

Creating migration history table "migration"...
Exception 'yii\db\Exception' with message 'SQLSTATE[42000]: Syntax error or access violation: 1142 CREATE command denied to user 'default'@'172.27.0.4' for table 'migration'
The SQL being executed was: CREATE TABLE `migration` (
        `version` varchar(180) NOT NULL PRIMARY KEY,
        `apply_time` int(11)
)'

in /app/vendor/yiisoft/yii2/db/Schema.php:678

Error Info:
Array
(
    [0] => 42000
    [1] => 1142
    [2] => CREATE command denied to user 'default'@'172.27.0.4' for table 'migration'
)

Caused by: Exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1142 CREATE command denied to user 'default'@'172.27.0.4' for table 'migration''

in /app/vendor/yiisoft/yii2/db/Command.php:1302

Stack trace:
#0 /app/vendor/yiisoft/yii2/db/Command.php(1302): PDOStatement->execute()
#1 /app/vendor/yiisoft/yii2/db/Command.php(1102): yii\db\Command->internalExecute()
#2 /app/vendor/yiisoft/yii2/console/controllers/MigrateController.php(273): yii\db\Command->execute()
#3 /app/vendor/yiisoft/yii2/console/controllers/MigrateController.php(212): yii\console\controllers\MigrateController->createMigrationHistoryTable()
#4 /app/vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(908): yii\console\controllers\MigrateController->getMigrationHistory()
#5 /app/vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(183): yii\console\controllers\BaseMigrateController->getNewMigrations()
#6 [internal function]: yii\console\controllers\BaseMigrateController->actionUp()
#7 /app/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array()
#8 /app/vendor/yiisoft/yii2/base/Controller.php(181): yii\base\InlineAction->runWithParams()
#9 /app/vendor/yiisoft/yii2/console/Controller.php(184): yii\base\Controller->runAction()
#10 /app/vendor/yiisoft/yii2/base/Module.php(534): yii\console\Controller->runAction()
#11 /app/vendor/yiisoft/yii2/console/Application.php(181): yii\base\Module->runAction()
#12 /app/vendor/yiisoft/yii2/console/Application.php(148): yii\console\Application->runAction()
#13 /app/vendor/yiisoft/yii2/base/Application.php(392): yii\console\Application->handleRequest()
#14 /app/yii(20): yii\base\Application->run()
#15 {main}

Migrations are run from console.

That means, the console.php config file is loaded instead of your main.php config. So one way, that would also affect any other console commands you might have, would be to change the db configuration in the components section of the console config.

config\\console.php :

<?php

$config = [
    // ...
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => [], // PLACE HERE CUSTOM ADMIN CREDENTIALS
        // ...
    ],
    
];

Now your migrations will be run with the credentials defined in the console config.

If by chance you have other console commands that modify data in the database and you don't want to change their user too, then you could add another DB component and call it "dbAdmin" with the admin credentials.

<?php

$config = [
    // ...
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => [], // REGULAR DB connection
        'dbAdmin' => [], // PLACE HERE CUSTOM ADMIN CREDENTIALS
        // ...
    ],
    
];

And then check:

https://www.yiiframework.com/doc/guide/2.0/en/db-migrations#using-command-line-options

To specify what db connection to use when running the migrations.

yii migrate --db=dbAdmin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM