Skip to content

Instantly share code, notes, and snippets.

@balibali
Created January 29, 2014 07:36
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 balibali/8683401 to your computer and use it in GitHub Desktop.
Save balibali/8683401 to your computer and use it in GitHub Desktop.
<?php
class openpneTruncateTablesTask extends sfBaseTask
{
protected function configure()
{
$this->addOptions(array(
new sfCommandOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', true),
new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
new sfCommandOption('no-confirmation', null, sfCommandOption::PARAMETER_NONE, 'Whether to force dropping of the database')
));
$this->namespace = 'openpne';
$this->name = 'truncate-tables';
$this->briefDescription = 'Truncates all tables (for MySQL)';
}
protected function execute($arguments = array(), $options = array())
{
if (!$options['no-confirmation'] && !$this->askTruncateConfirmation())
{
$this->logSection('openpne', 'task aborted');
return 1;
}
new sfDatabaseManager($this->configuration);
$pdo = opDoctrineQuery::getMasterConnectionDirect()->getDbh();
$tables = $pdo->query('SHOW TABLES', PDO::FETCH_COLUMN, 0);
if ($table = $tables->fetch())
{
$pdo->exec('SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0');
do
{
$this->logSection('truncate', $table);
$pdo->exec('TRUNCATE '.$table);
}
while (false !== ($table = $tables->fetch()));
$pdo->exec('SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS');
}
else
{
throw new sfException('No tables found');
}
}
protected function askTruncateConfirmation()
{
return $this->askConfirmation(
array(
'This command will remove all data.',
'Are you sure you want to proceed? (y/N)',
),
'QUESTION_LARGE',
false
);
}
}
@balibali
Copy link
Author

test/bootstrap/database.php

<?php

$configuration = ProjectConfiguration::getApplicationConfiguration('pc_frontend', 'test', true);

new sfDatabaseManager($configuration);

try
{
  $task = new openpneTruncateTablesTask($configuration->getEventDispatcher(), new sfFormatter());
  $task->setConfiguration($configuration);
  $task->run(array(), array(
    'no-confirmation' => true,
  ));
}
catch (Exception $e)
{
  $task = new sfDoctrineBuildTask($configuration->getEventDispatcher(), new sfFormatter());
  $task->setConfiguration($configuration);
  $task->run(array(), array(
    'no-confirmation' => true,
    'db'              => true,
  ));
}

$task = new sfDoctrineDataLoadTask($configuration->getEventDispatcher(), new sfFormatter());
$task->setConfiguration($configuration);
$task->run(array(dirname(__FILE__).'/../fixtures'));

Doctrine_Manager::connection()->clear();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment