0

I'm new facing an issue when trying to apply database migration using Yii.

First I'm creating a new migration using this :: ./yiic migrate create tr

This gives me the following output.

Yii Migration Tool v1.0 (based on Yii v1.1.14)

Create new migration '/var/www/html/Trackstar/protected/migrations/m130921_101251_tr.php'? (yes|no) [no]:y New migration created successfully.

Which shows that i've created a new migration.

Now i've added the necessary ddl in up() and the down(). Here is how it looks.

<?php

class m130921_101251_tr extends CDbMigration {

    public function up() {

        //create the issue table
        $this->createTable('tbl_issue', array(
            'id' => 'pk',
            'name' => 'string NOT NULL',
            'description' => 'text',
            'project_id' => 'int(11) DEFAULT NULL',
            'type_id' => 'int(11) DEFAULT NULL',
            'status_id' => 'int(11) DEFAULT NULL',
            'owner_id' => 'int(11) DEFAULT NULL',
            'requester_id' => 'int(11) DEFAULT NULL',
            'create_time' => 'datetime DEFAULT NULL',
            'create_user_id' => 'int(11) DEFAULT NULL',
            'update_time' => 'datetime DEFAULT NULL',
            'update_user_id' => 'int(11) DEFAULT NULL',
                ), 'ENGINE=InnoDB');
//create the user table
        $this->createTable('tbl_user', array(
            'id' => 'pk',
            'username' => 'string NOT NULL',
            'email' => 'string NOT NULL',
            'password' => 'string NOT NULL',
            'last_login_time' => 'datetime DEFAULT NULL',
            'create_time' => 'datetime DEFAULT NULL',
            'create_user_id' => 'int(11) DEFAULT NULL',
            'update_time' => 'datetime DEFAULT NULL',
            'update_user_id' => 'int(11) DEFAULT NULL',
                ), 'ENGINE=InnoDB');



        //create the assignment table that allows for many-to-many
//relationship between projects and users
        $this->createTable('tbl_project_user_assignment', array(
            'project_id' => 'int(11) NOT NULL',
            'user_id' => 'int(11) NOT NULL',
            'PRIMARY KEY (`project_id`,`user_id`)',
                ), 'ENGINE=InnoDB');
//foreign key relationships
//the tbl_issue.project_id is a reference to tbl_project.id
        $this->addForeignKey("fk_issue_project", "tbl_issue", "project_id", "tbl_project", "id", "CASCADE", "RESTRICT");
//the tbl_issue.owner_id is a reference to tbl_user.id
        $this->addForeignKey("fk_issue_owner", "tbl_issue", "owner_id", "tbl_user", "id", "CASCADE", "RESTRICT");
//the tbl_issue.requester_id is a reference to tbl_user.id
        $this->addForeignKey("fk_issue_requester", "tbl_issue", "requester_id", "tbl_user", "id", "CASCADE", "RESTRICT");
//the tbl_project_user_assignment.project_id is a reference to        tbl_project.id
        $this->addForeignKey("fk_project_user", "tbl_project_user_assignment", "project_id", "tbl_project", "id", "CASCADE", "RESTRICT");
//the tbl_project_user_assignment.user_id is a reference to tbl_        user.id
        $this->addForeignKey("fk_user_project", "tbl_project_user_assignment", "user_id", "tbl_user", "id", "CASCADE", "RESTRICT");
    }

    public function down() {
        $this->truncateTable('tbl_project_user_assignment');
        $this->truncateTable('tbl_issue');
        $this->truncateTable('tbl_user');
        $this->dropTable('tbl_project_user_assignment');
        $this->dropTable('tbl_issue');
        $this->dropTable('tbl_user');
    }

    /*
      // Use safeUp/safeDown to do migration with transaction
      public function safeUp()
      {
      }

      public function safeDown()
      {
      }
     */
}

Now the problem is whenever i'm trying to apply this migration using ./yiic migrate, its failing with the same error. Here is the sample output which i'm getting.

[root@localhost protected]# ./yiic migrate

Yii Migration Tool v1.0 (based on Yii v1.1.14)

Total 1 new migration to be applied:
    m130921_101251_tr

Apply the above migration? (yes|no) [no]:y
*** applying m130921_101251_tr
PHP Error[2]: include(m130921_101251_tr.php): failed to open stream: No such file or directory
    in file /var/www/html/yii/framework/YiiBase.php at line 427
#0 /var/www/html/yii/framework/YiiBase.php(427): autoload()
#1 unknown(0): autoload()
#2 /var/www/html/yii/framework/cli/commands/MigrateCommand.php(429): spl_autoload_call()
#3 /var/www/html/yii/framework/cli/commands/MigrateCommand.php(384): MigrateCommand->instantiateMigration()
#4 /var/www/html/yii/framework/cli/commands/MigrateCommand.php(109): MigrateCommand->migrateUp()
#5 unknown(0): MigrateCommand->actionUp()
#6 /var/www/html/yii/framework/console/CConsoleCommand.php(172): ReflectionMethod->invokeArgs()
#7 /var/www/html/yii/framework/console/CConsoleCommandRunner.php(71): MigrateCommand->run()
#8 /var/www/html/yii/framework/console/CConsoleApplication.php(92): CConsoleCommandRunner->run()
#9 /var/www/html/yii/framework/base/CApplication.php(180): CConsoleApplication->processRequest()
#10 /var/www/html/yii/framework/yiic.php(33): CConsoleApplication->run()
#11 /var/www/html/Trackstar/protected/yiic.php(7): require_once()
#12 /var/www/html/Trackstar/protected/yiic(4): require_once()

I can't seem to find a solution for the above problem. I've been searching on google, stackoverflow, and yii forums, for relevant answers, but i haven't found one. Please provide any help on how to solve this. I'm new to Yii so i'm still learning, and i'm loving it. But being stuck in the first steps is a real setback. Any sort of help would be much appreciated.

Thanks, Maxx

For more clarification. I'm posting the config/console.php and config/main.php

-------------config/console.php-------------------------

<?php

// This is the configuration for yiic console application.
// Any writable CConsoleApplication properties can be configured here.
return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'My Console Application',

    // preloading 'log' component
    'preload'=>array('log'),

    // application components
    'components'=>array(

        // uncomment the following to use a MySQL database

        'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=trackstar',
            'emulatePrepare' => true,
            'username' => 'user1',
            'password' => 'mydb389',
            'charset' => 'utf8',
        ),

        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error, warning',
                ),
            ),
        ),
    ),
);

---------------------end of console.php----------------------

------------------------config/main.php----------------------

<?php

// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');

// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'My Web Application',

    // preloading 'log' component
    'preload'=>array('log'),

    // autoloading model and component classes
    'import'=>array(
        'application.models.*',
        'application.components.*',
    ),

    'modules'=>array(
        // uncomment the following to enable the Gii tool
        /*
        'gii'=>array(
            'class'=>'system.gii.GiiModule',
            'password'=>'Enter Your Password Here',
            // If removed, Gii defaults to localhost only. Edit carefully to taste.
            'ipFilters'=>array('127.0.0.1','::1'),
        ),
        */
    ),

    // application components
    'components'=>array(
        'user'=>array(
            // enable cookie-based authentication
            'allowAutoLogin'=>true,
        ),
        // uncomment the following to enable URLs in path-format
        /*
        'urlManager'=>array(
            'urlFormat'=>'path',
            'rules'=>array(
                '<controller:\w+>/<id:\d+>'=>'<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
            ),
        ),
        */
        // uncomment the following to use a MySQL database
        'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=trackstar',
            'emulatePrepare' => true,
            'username' => 'user1',
            'password' => 'mydb389',
            'charset' => 'utf8',
        ),
        'errorHandler'=>array(
            // use 'site/error' action to display errors
            'errorAction'=>'site/error',
        ),
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error, warning',
                ),
                // uncomment the following to show log messages on web pages
                /*
                array(
                    'class'=>'CWebLogRoute',
                ),
                */
            ),
        ),
    ),

    // application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
    'params'=>array(
        // this is used in contact page
        'adminEmail'=>'webmaster@example.com',
    ),
);

-----------------------------end of config/main.php----------------------

mysql> show tables
-> ;



+-------------------------+
| Tables_in_trackStar |
+-------------------------+
| tbl_migration           |
+-------------------------+
1 row in set (0.00 sec)

mysql> desc tbl_migration;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| version    | varchar(255) | NO   | PRI | NULL    |       |
| apply_time | int(11)      | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Maxx
  • 592
  • 18
  • 42
  • found your problem.. you cannot rename migration files classes *after creating* migrations! – Manquer Sep 21 '13 at 05:45
  • see my updated answer below on the correct class name you should use change your migration file accordingly – Manquer Sep 21 '13 at 05:52
  • sorry i posted the wrong code above. I haven't renamed the migration class name. I'm using the one created by default. – Maxx Sep 21 '13 at 05:59
  • is the filename also m130921_101251_tr.php in protected/migrations ?, the only way i am getting this error is when both don't match – Manquer Sep 21 '13 at 06:09
  • the config string DB name and your DB name in your sql query seem to be different, i was not able to catch it before because your sql output was not code formatted.. is that correct DB your are using? – Manquer Sep 21 '13 at 07:01
  • sorry forgot to edit it. now its updated and reflects my current configuration. I have changed main.php and console.php to match the db i'm using, before i created any migrations. So, the error must be caused by something else which i'm not getting. – Maxx Sep 21 '13 at 07:28

2 Answers2

3

EDIT: You should not rename your migration files classes, as the filename is linked to to the tbl_migrations in your database. So rename your migration file as class as

<?php

class m130921_101251_tr extends CDbMigration { 

EDIT2: also ensure that your filename is protected/migrations/m130921_101251_tr.php

EDIT3: Below is logical flow of how Yii migrations work, perhaps that will help


Yii Migration Tool v1.0 (based on Yii v1.1.14)

Coming to this point means that the framework got included and your yiic.php settings is correct

Total 1 new migration to be applied:
    m130921_101251_tr

This couple of lines means yiic was able to scan your migrations directory and also connect with your database and check of all the files in your migrations folder, and see if there exists a row in tbl_migrations of the same name. The files which don't have a row or listed as new migrations

Apply the above migration? (yes|no) [no]:y
   *** applying m130921_101251_tr

This line of output means that yiic is now trying to apply the migration, to do so it will try to find a class of the same which extents CDbMigration framework class. If yiic fails to find this class you will get this error.

PHP Error[2]: include(m130921_101251_tr.php): failed to open stream: No such file or directory in file /var/www/html/yii/framework/YiiBase.php at line 427

The way Yii works it always looks up for classnames same as the filename using namspaces which is only available in PHP 5.3 and above From Yii docs

Namespaced Classes A namespaced class refers to a class declared within a non-global namespace. For example, the application\components\GoogleMap class is declared within the namespace application\components. Using namespaced classes requires PHP 5.3.0 or above.

Starting from version 1.1.5, it is possible to use a namespaced class without including it explicitly. For example, we can create a new instance of application\components\GoogleMap without including the corresponding class file explicitly. This is made possible with the enhanced Yii class autoloading mechanism.

The only cases where i was able to simulate your error is when not using Php 5.3 or above or the class name is not matching the file

Manquer
  • 7,390
  • 8
  • 42
  • 69
  • yes i have already modified config/console.php before applying the migration. – Maxx Sep 21 '13 at 05:09
  • return array( 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 'name'=>'My Console Application', // preloading 'log' component 'preload'=>array('log'), // application components – Maxx Sep 21 '13 at 05:10
  • 'components'=>array( // uncomment the following to use a MySQL database 'db'=>array( 'connectionString' => 'mysql:host=localhost;dbname=trackstar', 'emulatePrepare' => true, 'username' => 'user1', 'password' => 'mydb389', 'charset' => 'utf8', ), – Maxx Sep 21 '13 at 05:13
  • 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), ), ), – Maxx Sep 21 '13 at 05:15
  • Thats the current code in protected/config/console.php. Sorry, had to break it up, StackOverflow won't allow me to post very long comments. Also config/main.php is configured similarly to config/console.php. – Maxx Sep 21 '13 at 05:17
  • is it file permission issue? you seem to be using root.. can you just chmod 777 and test and see? – Manquer Sep 21 '13 at 05:25
  • Yeah i've done chmod -R 777 * from parent html directory. But its still giving the same error – Maxx Sep 21 '13 at 05:32
  • is tbl_migrations being created in your db? Have you granted CREATE ON privileges for user1? – Manquer Sep 21 '13 at 05:41
  • yes tbl_migration is showing successfully under the database. – Maxx Sep 21 '13 at 05:59
  • check out the updated answers. And i have given full privileges to user1. Still not working. – Maxx Sep 21 '13 at 06:01
  • also i've updated Yii to the latest release hoping that it would get rid of the error. But it still throws the same error no matter what. – Maxx Sep 21 '13 at 06:02
  • Yep.. i've checked it the filename is set to protected/migrations/m130921_101251_tr.php... Still the error is coming up.. :-( – Maxx Sep 21 '13 at 06:17
  • what version of php are you using ?? there *may* be some problems with versions of php 5.3 below due to namespaces not being a feature before then – Manquer Sep 21 '13 at 06:47
  • I have broken your console output into steps see answer update, php version and file classname mismatch are my last guesses, 5.2 is really old so that is really a long shot. If all of it checks out and still getting error, as a last trial suggest you delete this migration and create a new one and try fresh again. – Manquer Sep 21 '13 at 06:52
  • No i'm pretty sure i have php 5.4 installed. I even created the project using Netbeans, where i choose php 5.4. All this options are set by default on my machine. Thanks for all your effort, but the error doesn't seem to go away. :-( – Maxx Sep 21 '13 at 07:31
  • also the only i have change to my php/apache/mysql environment, is that i installed mysql workbench, a few days ago and also updated pcre, pcre-devel, libpcre. Suprisingly ./yiic migrate ran well before that.. – Maxx Sep 21 '13 at 09:51
  • no problem.. actually pcre could cause the kind of problem you are having, if you see YiiBase.php in the framework, line 427 where you are getting stuck uses string_replace which uses pcre. I am not aware of any bugs being caused by latest versions of pcre in string_replace or Yii, you can check the issues in github or perhaps file one if it is not there :) – Manquer Sep 21 '13 at 09:58
  • yes i thought so.. Here is the version of the update pcre and pcre-devel Package pcre-8.21-7.fc17.x86_64 already installed and latest version Package pcre-devel-8.21-7.fc17.x86_64 already installed and latest version – Maxx Sep 21 '13 at 10:59
0

The file is not not properly included.

include(m130921_101251_tr.php);

that's why it is unable to find your class.

Try giving a proper path for your file in your include construct.

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126