RunSqlCommand.php 2.2 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Tools\Console\Command;

5
use Doctrine\DBAL\Tools\Dumper;
6 7
use LogicException;
use RuntimeException;
Benjamin Morel's avatar
Benjamin Morel committed
8 9 10 11
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Output\OutputInterface;
Sergei Morozov's avatar
Sergei Morozov committed
13
use function assert;
14
use function is_bool;
15
use function is_numeric;
Sergei Morozov's avatar
Sergei Morozov committed
16
use function is_string;
17
use function stripos;
18 19 20 21 22

/**
 * Task for executing arbitrary SQL that can come from a file or directly from
 * the command line.
 */
Benjamin Morel's avatar
Benjamin Morel committed
23
class RunSqlCommand extends Command
24
{
25
    /** @return void */
26 27 28 29 30
    protected function configure()
    {
        $this
        ->setName('dbal:run-sql')
        ->setDescription('Executes arbitrary SQL directly from the command line.')
31
        ->setDefinition([
32
            new InputArgument('sql', InputArgument::REQUIRED, 'The SQL statement to execute.'),
33
            new InputOption('depth', null, InputOption::VALUE_REQUIRED, 'Dumping depth of result set.', 7),
34
            new InputOption('force-fetch', null, InputOption::VALUE_NONE, 'Forces fetching the result.'),
35
        ])
36 37 38 39 40 41 42
        ->setHelp(<<<EOT
Executes arbitrary SQL directly from the command line.
EOT
        );
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
43
     * {@inheritdoc}
44
     */
Benjamin Morel's avatar
Benjamin Morel committed
45
    protected function execute(InputInterface $input, OutputInterface $output)
46 47 48
    {
        $conn = $this->getHelper('db')->getConnection();

49 50 51
        $sql = $input->getArgument('sql');

        if ($sql === null) {
52
            throw new RuntimeException("Argument 'SQL' is required in order to execute this command correctly.");
53 54
        }

Sergei Morozov's avatar
Sergei Morozov committed
55 56
        assert(is_string($sql));

57 58
        $depth = $input->getOption('depth');

59 60
        if (! is_numeric($depth)) {
            throw new LogicException("Option 'depth' must contains an integer value");
61
        }
62

63 64 65 66
        $forceFetch = $input->getOption('force-fetch');
        assert(is_bool($forceFetch));

        if (stripos($sql, 'select') === 0 || $forceFetch) {
Tobias Schultze's avatar
Tobias Schultze committed
67
            $resultSet = $conn->fetchAll($sql);
68
        } else {
69
            $resultSet = $conn->executeUpdate($sql);
70 71
        }

72
        $output->write(Dumper::dump($resultSet, (int) $depth));
73 74

        return 0;
75
    }
76
}