|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace PHPCR\Shell\Console\Command\Phpcr; |
| 4 | + |
| 5 | +use Symfony\Component\Console\Command\Command; |
| 6 | +use Symfony\Component\Console\Input\InputInterface; |
| 7 | +use Symfony\Component\Console\Output\OutputInterface; |
| 8 | +use PHPCR\Util\QOM\Sql2ToQomQueryConverter; |
| 9 | + |
| 10 | +class QueryDeleteCommand extends Command |
| 11 | +{ |
| 12 | + protected function configure() |
| 13 | + { |
| 14 | + $this->setName('delete'); |
| 15 | + $this->setDescription('Execute a literal JCR-SQL2 query'); |
| 16 | + $this->addArgument('query'); |
| 17 | + $this->setHelp(<<<EOT |
| 18 | +Execute a JCR-SQL2 query. Unlike other commands you can enter a query literally: |
| 19 | +
|
| 20 | + DELETE FROM [nt:unstructured] WHERE title = 'foo'; |
| 21 | +
|
| 22 | +You must call <info>session:save</info> to persist changes. |
| 23 | +
|
| 24 | +Note that this command is not part of the JCR-SQL2 language but is implemented specifically |
| 25 | +for the PHPCR-Shell. |
| 26 | +EOT |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + public function execute(InputInterface $input, OutputInterface $output) |
| 31 | + { |
| 32 | + $sql = $input->getRawCommand(); |
| 33 | + |
| 34 | + // trim ";" for people used to MysQL |
| 35 | + if (substr($sql, -1) == ';') { |
| 36 | + $sql = substr($sql, 0, -1); |
| 37 | + } |
| 38 | + |
| 39 | + $session = $this->getHelper('phpcr')->getSession(); |
| 40 | + $qm = $session->getWorkspace()->getQueryManager(); |
| 41 | + |
| 42 | + if (!preg_match('{^delete from}', strtolower($sql))) { |
| 43 | + throw new \PHPCR\Query\InvalidQueryException(sprintf( |
| 44 | + '"FROM" not specified in DELETE query: "%s"', $sql |
| 45 | + )); |
| 46 | + } |
| 47 | + |
| 48 | + $sql = 'SELECT * FROM' . substr($sql, 11); |
| 49 | + |
| 50 | + $selectParser = new Sql2ToQomQueryConverter($qm->getQOMFactory()); |
| 51 | + $query = $selectParser->parse($sql); |
| 52 | + |
| 53 | + $start = microtime(true); |
| 54 | + $result = $query->execute(); |
| 55 | + |
| 56 | + foreach ($result as $row) { |
| 57 | + $node = $row->getNode(); |
| 58 | + $node->remove(); |
| 59 | + } |
| 60 | + |
| 61 | + $elapsed = microtime(true) - $start; |
| 62 | + $output->writeln(sprintf('%s row(s) affected in %ss', count($result), number_format($elapsed, 2))); |
| 63 | + } |
| 64 | +} |
0 commit comments