|
| 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\Input\InputOption; |
| 8 | +use Symfony\Component\Console\Output\OutputInterface; |
| 9 | + |
| 10 | +class QueryCommand extends Command |
| 11 | +{ |
| 12 | + protected function configure() |
| 13 | + { |
| 14 | + $this->setName('query'); |
| 15 | + $this->setDescription('Execute a query '); |
| 16 | + $this->addArgument('query'); |
| 17 | + $this->addOption('language', 'l', InputOption::VALUE_OPTIONAL, 'The query language (e.g. jcr-sql2', 'JCR-SQL2'); |
| 18 | + $this->addOption('limit', null, InputOption::VALUE_OPTIONAL, 'The query limit', 0); |
| 19 | + $this->addOption('offset', null, InputOption::VALUE_OPTIONAL, 'The query offset', 0); |
| 20 | + $this->setHelp(<<<EOT |
| 21 | +Execute an SQL query. This command differs from <info>select</info> in that it |
| 22 | +is executed conventionally and not literally. The advantage is that you can |
| 23 | +specify a specific query language and additional options: |
| 24 | +
|
| 25 | + <info>query "SELECT * FROM [nt:unstructured]" --language=JCR_SQL2 --limit=5 --offset=4</info> |
| 26 | +EOT |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + public function execute(InputInterface $input, OutputInterface $output) |
| 31 | + { |
| 32 | + $language = $input->getOption('language'); |
| 33 | + $limit = $input->getOption('limit'); |
| 34 | + $offset = $input->getOption('offset'); |
| 35 | + $query = $input->getArgument('query'); |
| 36 | + |
| 37 | + $session = $this->getHelper('phpcr')->getSession(); |
| 38 | + $workspace = $session->getWorkspace();; |
| 39 | + $supportedQueryLanguages = $workspace->getQueryManager()->getSupportedQueryLanguages(); |
| 40 | + |
| 41 | + if (!in_array($language, $supportedQueryLanguages)) { |
| 42 | + throw new \InvalidArgumentException(sprintf( |
| 43 | + '"%s" is an invalid query language, valid query languages are:%s', |
| 44 | + $language, |
| 45 | + PHP_EOL . ' -' . implode(PHP_EOL . ' - ', $supportedQueryLanguages) |
| 46 | + )); |
| 47 | + } |
| 48 | + |
| 49 | + $qm = $session->getWorkspace()->getQueryManager(); |
| 50 | + $query = $qm->createQuery($query, $language); |
| 51 | + |
| 52 | + if ($limit) { |
| 53 | + $query->setLimit($limit); |
| 54 | + } |
| 55 | + |
| 56 | + if ($offset) { |
| 57 | + $query->setOffset($offset); |
| 58 | + } |
| 59 | + |
| 60 | + $start = microtime(true); |
| 61 | + $result = $query->execute(); |
| 62 | + $elapsed = microtime(true) - $start; |
| 63 | + |
| 64 | + $this->getHelper('result_formatter')->formatQueryResult($result, $output, $elapsed); |
| 65 | + } |
| 66 | +} |
0 commit comments