Reputation: 400
I want to integrate Codeigniter's migration class to my project's build process. Can i use the migration class to create databases, or it's only purpose to keep up to date the database structure?
My migration class looks like this:
class Migration_base extends CI_Migration {
public function up()
{
$this->dbforge->create_database('my_db');
}
public function down()
{
$this->dbforge->drop_database('my_db');
}
}
When i run this code:
class Migrate extends CI_Controller
{
public function index()
{
$this->load->library('migration');
if ($this->migration->current() === FALSE)
{
show_error($this->migration->error_string());
}
}
}
I get this message:
Database error: A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: path_to_codeigniter/codeigniter/framework/system/database/DB_driver.php
Line Number: 436
It seems the database must already exist before I can use migration class. Am I correct and need to write a wrapper around migration class where i create the database first?
Upvotes: 1
Views: 1978
Reputation: 8964
Your suspicion that a workaround will be needed in order to create a database as part of a migration seems to be true. I don't know if it could be called a bug or missing feature but it will not do it as written.
The big issue is that the _migration_table
that the class creates needs to be in the database being migrated. A classic "chicken or egg" problem.
Another possible issue, something the documentation assumes and doesn't address, is that the database to be migrated is the one that should be "loaded".
I think the following version of your Migrate
controller will handle both of those issues.
class Migrate extends CI_Controller
{
public function index()
{
if( ! isset($this->db))
{
throw new RuntimeException("Must have a database loaded to run a migration");
}
// Are we connected to 'my_db' ?
if( ! $this->db->database !== 'my_db')
{
//find out if that db even exists
$this->load->dbutil();
if( ! $this->dbutil->database_exists('my_db'))
{
// try to create 'my_db'
$this->load->dbforge();
if( ! $this->dbforge->create_database('my_db'))
{
throw new RuntimeException("Could not create the database 'my_db");
}
}
// Connection data for 'my_db' must be available
// in /config/database.php for this to work.
if(($db = $this->load->database('my_db', TRUE)) === TRUE)
{
$this->db = $db; //replace the previously loaded database
}
else
{
throw new RuntimeException("Could not load 'my_db' database");
}
}
$this->load->library('migration');
if($this->migration->current() === FALSE)
{
show_error($this->migration->error_string());
}
}
}
Please know I have not tested this code. There may be syntax, logic or other errors. If nothing else, hopefully, it gives you a good starting place
Upvotes: 3