开发者

Check for table existence before dropping?

I'm trying to check for the existence of a table before dropp开发者_开发技巧ing it. I've read through the API documentation for Doctrine_Table and I can't seem to find anything like this. Is there something I'm missing?

I've got code that looks like:

$table = new Doctrine_Table('model_name', $conn);

$export = new Doctrine_Export();

$export->dropTable($table->getTableName());

And the error I get when a table doesn't exist is:

Fatal error: Uncaught exception 'Doctrine_Connection_Mysql_Exception' with message 'SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table

Thanks in advance,

Casey


Doctrine2 method is:

$schemaManager = $this->getDoctrine()->getConnection()->getSchemaManager();
if ($schemaManager->tablesExist(array('users')) == true) {
      // table exists! ...
}


If you just want to return true/false if the table exists, this is what I did:

public function checkTable($table)
{
    $conn = Doctrine_Manager::connection();
    try { $conn->execute("DESC $table"); }
    catch (Exception $e) { return false; }
    return true;
}


Here's what I wound up using... any suggestions for improvement are welcome:

public static function isInstalled()
{
    $installed = true;

    $q = Doctrine_Query::create($conn);
    $q->select('t.id');
    $q->from('Table t'); //the table to check

    try {
        $q->execute();
    } catch (Doctrine_Connection_Exception $e) {
        // we only want to silence 'no such table' errors
        if ($e->getPortableCode() !== Doctrine_Core::ERR_NOSUCHTABLE) {
            throw new Doctrine_Export_Exception($e->getMessage());
        }

        $installed = false;
    }

    return $installed;
}


Try this for table exist check:

 public function up(Schema $schema): void
{
    $schema->hasTable('table_name');
}

For columns check:

$schema->getTable('supply')->hasColumn('contracts')

Full example with skip:

$this->skipIf($schema->getTable('supply')->hasColumn('contracts'), 'Table order_statuses already exist');


I haven't tested portability, but in native SQL you can do:

DROP TABLE IF EXISTS ...

You can run native SQL queries with Doctrine as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜