Welcome Guest, Not a member yet? Register   Sign In
Check whether database exists (using dbforge)
#1

[eluser]aidehua[/eluser]
I am using the CodeIgniter Database Forge class to create a database, like this:

Code:
$this->load->dbforge();
$this->dbforge->create_database('some_database');

It works fine - but returns an error if the database already exists (using MySQL).

So I want to add an "IF NOT EXISTS" check. I notice this is easy to do when creating tables with dbforge:

Code:
$this->dbforge->create_table('table_name', TRUE);
// gives CREATE TABLE IF NOT EXISTS table_name

But this option to add a second parameter of TRUE to add an IF NOT EXISTS clause does not seem to exist for the create_database function.

Anyone have any ready-made solutions?

(Otherwise I suppose it's a case of tweaking the create_database($db_name) function in /system/database/DB_forge.php and the _create_database($name) function in /system/database/mysql/mysql_forge.php?)
#2

[eluser]aidehua[/eluser]
This tweak seems to do the job - but it might not be the best way to do it:

In /system/database/DB_forge.php, I've changed the create_database function to the following:


Code:
/**
     * Create database
     *
     * @access    public
     * @param    string    the database name
     * @param    bool    insert "if not exists" clause
     * @return    bool
     */
    function create_database($db_name, $ifnotexists = false)
    {
        if($ifnotexists){
            $db_name = "IF NOT EXISTS " . $db_name;
        }
        $sql = $this->_create_database($db_name);
        
        if (is_bool($sql))
        {
            return $sql;
        }
    
        return $this->db->query($sql);
    }

(The original un-altered function looked like thisSmile

Code:
/**
     * Create database
     *
     * @access    public
     * @param    string    the database name
     * @return    bool
     */
    function create_database($db_name)
    {
        $sql = $this->_create_database($db_name);
        
        if (is_bool($sql))
        {
            return $sql;
        }
    
        return $this->db->query($sql);
    }

Any other/better suggestions would be welcome. (As I understand it, it is not possible to extend the DB_forge class in the way you can extend other CI classes by creating a MY_class_name class in the application directory.)
#3

[eluser]Unknown[/eluser]
try $this->dbutil->list_databases() -> http://ellislab.com/codeigniter/user-gui....html#list




Theme © iAndrew 2016 - Forum software by © MyBB