Skip to content

Instantly share code, notes, and snippets.

@flevour
Created August 18, 2011 16:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flevour/1154458 to your computer and use it in GitHub Desktop.
Save flevour/1154458 to your computer and use it in GitHub Desktop.
Truncate all tables of a Doctrine Connection
<?php
class doctrineClearDbTask extends sfBaseTask
{
protected function configure()
{
$this->addOptions(array(
new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name', 'frontend'),
new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
));
$this->namespace = 'doctrine';
$this->name = 'clearDb';
$this->briefDescription = 'truncate all tables in the db';
$this->detailedDescription = <<<EOF
The [clearDb|INFO] truncates all tables in the db connected to the current connection.
[php symfony clearDb|INFO]
EOF;
}
protected function execute($arguments = array(), $options = array())
{
// initialize the database connection
$databaseManager = new sfDatabaseManager($this->configuration);
$connection = Doctrine_Manager::getInstance()->getCurrentConnection();
$this->dbh = $connection->getDbh();
$this->dbh->query(sprintf('SET FOREIGN_KEY_CHECKS = 0;'));
$tables = $connection->import->listTables();
foreach ($tables as $table)
{
$this->truncateTable($table);
}
$this->dbh->query(sprintf('SET FOREIGN_KEY_CHECKS = 1;'));
unset($this->dbh);
}
protected function truncateTable($tableName)
{
$sql = sprintf('TRUNCATE TABLE %s', $tableName);
$this->dbh->query($sql);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment