[Symfony] Load an sql dump within a task

I recently had a problem when loading fixtures in my symfony project. I was loading cities, about 37 000 of them, and the doctrine:data-load was extremly slow (about 5 minutes). I finally found a solution to load an sql dump wihtin a task, using the doctrine/default connection.

With this solution, I reduced the time from minutes to 2 secondes.

<?php
 
class loadALotOfDataTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));
 
    $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'),
      // add your own options here
    ));
 
    $this->namespace        = '';
    $this->name             = 'loadALotOfData';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [loadALotOfData|INFO] task does things.
Call it with:
 
  [php symfony loadALotOfData|INFO]|>
EOF;
  }
 
  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
 
    // add your code here
    $file = '../data/dump.sql';
    if(!file_exists($file)) {
        $this->logSection('File', sprintf('File %s does not exists', $file));
        return;
    }
    // loading the file in the memory. In my case, the file was 
    $data = file_get_contents($file);
    // passing queries to the orm
    $statement = $connection->prepare($data);
    // executing
    $statement->execute();
  }
}

Haut de page