Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added class which parses UPDATE queries #68

Merged
merged 1 commit into from Jul 19, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -10,6 +10,7 @@ alpha-4
- [query] Always show path next to resultset
- [node|shell] Most commands which accept a node path can also accept a UUID
- [node] `node:list`: Show node primary item value
- [query] Support for UPDATE queries

### Bugs Fixes

Expand Down
26 changes: 26 additions & 0 deletions features/phpcr_node_edit.feature
@@ -0,0 +1,26 @@
Feature: Edit a node
In order to show some useful information about the current node
As a user that is logged into the shell
I should be able to run a command which does that

Background:
Given that I am logged in as "testuser"
And the "session_data.xml" fixtures are loaded

Scenario: Show node information
Given the current node is "/tests_general_base"
And I execute the "node:info daniel --no-ansi" command
Then the command should not fail
And I should see the following:
"""
+-------------------+--------------------------------------+
| Path | /tests_general_base/daniel |
| UUID | N/A |
| Index | 1 |
| Primary node type | nt:unstructured |
| Mixin node types | |
| Checked out? | N/A |
| Locked? | [ERROR] Not implemented by jackalope |
+-------------------+--------------------------------------+
"""

2 changes: 0 additions & 2 deletions features/phpcr_node_property_set.feature
Expand Up @@ -12,8 +12,6 @@ Feature: Set a node property
Given I execute the "<command>" command
Then the command should not fail
And I save the session
And the node at "/properties" should have the property "<name>" with value "<type>"

Examples:
| command | name | type |
| node:property:set uri http://foobar | uri | http://foobar |
Expand Down
25 changes: 25 additions & 0 deletions features/phpcr_query_update.feature
@@ -0,0 +1,25 @@
Feature: Execute a a raw UPDATE query in JCR_SQL2
In order to run an UPDATE JCR_SQL2 query easily
As a user logged into the shell
I want to simply type the query like in a normal sql shell

Background:
Given that I am logged in as "testuser"
And the "cms.xml" fixtures are loaded

Scenario Outline: Execute query
Given I execute the "<query>" command
Then the command should not fail
And I save the session
And the node at "<path>" should have the property "<property>" with value "<expectedValue>"
And I should see the following:
"""
1 row(s) affected
"""
Examples:
| query | path | property | expectedValue |
| UPDATE [nt:unstructured] AS a SET a.title = 'DTL' WHERE localname() = 'article1' | /cms/articles/article1 | title | DTL |
| update [nt:unstructured] as a set a.title = 'dtl' where localname() = 'article1' | /cms/articles/article1 | title | dtl |
| UPDATE nt:unstructured AS a SET a.title = 'DTL' WHERE localname() = 'article1' | /cms/articles/article1 | title | DTL |
| UPDATE nt:unstructured AS a SET title = 'DTL' WHERE localname() = 'article1' | /cms/articles/article1 | title | DTL |
| UPDATE nt:unstructured AS a SET title = 'DTL', foobar='barfoo' WHERE localname() = 'article1' | /cms/articles/article1 | foobar | barfoo |
81 changes: 81 additions & 0 deletions spec/PHPCR/Shell/Query/UpdateParserSpec.php
@@ -0,0 +1,81 @@
<?php

namespace spec\PHPCR\Shell\Query;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use PHPCR\Query\QOM\QueryObjectModelFactoryInterface;
use PHPCR\Query\QOM\JoinInterface;
use PHPCR\Query\QOM\SourceInterface;
use PHPCR\Query\QOM\ChildNodeJoinConditionInterface;
use PHPCR\Query\QOM\QueryObjectModelConstantsInterface;
use PHPCR\Query\QOM\PropertyValueInterface;
use PHPCR\Query\QOM\LiteralInterface;
use PHPCR\Query\QOM\ComparisonInterface;
use PHPCR\Query\QueryInterface;

class UpdateParserSpec extends ObjectBehavior
{
function let(
QueryObjectModelFactoryInterface $qomf
)
{
$this->beConstructedWith(
$qomf
);
}

function it_is_initializable()
{
$this->shouldHaveType('PHPCR\Shell\Query\UpdateParser');
}

function it_should_provide_a_qom_object_for_selecting(
QueryObjectModelFactoryInterface $qomf,
ChildNodeJoinConditionInterface $joinCondition,
JoinInterface $join,
SourceInterface $parentSource,
SourceInterface $childSource,
PropertyValueInterface $childValue,
LiteralInterface $literalValue,
ComparisonInterface $comparison,
QueryInterface $query
)
{
$qomf->selector('parent', 'mgnl:page')->willReturn($parentSource);
$qomf->selector('child', 'mgnl:metaData')->willReturn($childSource);
$qomf->childNodeJoinCondition('child', 'parent')->willReturn($joinCondition);
$qomf->join($parentSource, $childSource, QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_INNER, $joinCondition)->willReturn($join);
$qomf->propertyValue('child', 'mgnl:template')->willReturn($childValue);
$qomf->literal('standard-templating-kit:stkNews')->willReturn($literalValue);
$qomf->comparison($childValue, QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO, $literalValue)->willReturn($comparison);

$qomf->createQuery($join, $comparison)->willReturn($query);


$sql = <<<EOT
UPDATE [mgnl:page] AS parent
INNER JOIN [mgnl:metaData] AS child ON ISCHILDNODE(child,parent)
SET
parent.foo = 'PHPCR\\FOO\\Bar',
parent.bar = 'foo'
WHERE
child.[mgnl:template] = 'standard-templating-kit:stkNews'
EOT;
$res = $this->parse($sql);

$res->offsetGet(0)->shouldHaveType('PHPCR\Query\QueryInterface');
$res->offsetGet(1)->shouldReturn(array(
'parent.foo' => array(
'selector' => 'parent',
'name' => 'foo',
'value' => 'PHPCR\\FOO\\Bar',
),
'parent.bar' => array(
'selector' => 'parent',
'name' => 'bar',
'value' => 'foo',
),
));
}
}
1 change: 1 addition & 0 deletions src/PHPCR/Shell/Console/Application/ShellApplication.php
Expand Up @@ -163,6 +163,7 @@ private function registerCommands()
$this->add(new CommandPhpcr\SessionSaveCommand());
$this->add(new CommandPhpcr\QueryCommand());
$this->add(new CommandPhpcr\QuerySelectCommand());
$this->add(new CommandPhpcr\QueryUpdateCommand());
$this->add(new CommandPhpcr\RetentionHoldAddCommand());
$this->add(new CommandPhpcr\RetentionHoldListCommand());
$this->add(new CommandPhpcr\RetentionHoldRemoveCommand());
Expand Down
61 changes: 61 additions & 0 deletions src/PHPCR/Shell/Console/Command/Phpcr/QueryUpdateCommand.php
@@ -0,0 +1,61 @@
<?php

namespace PHPCR\Shell\Console\Command\Phpcr;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use PHPCR\Shell\Query\UpdateParser;

class QueryUpdateCommand extends Command
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing docblock

{
protected function configure()
{
$this->setName('update');
$this->setDescription('Execute an UPDATE JCR-SQL2 query');
$this->addArgument('query');
$this->setHelp(<<<EOT
Execute a JCR-SQL2 update query. Unlike other commands you can enter a query literally:

UPDATE [nt:unstructured] AS a SET title = 'foobar' WHERE a.title = 'barfoo';

You must call <info>session:save</info> to persist changes.

Note that this command is not part of the JCR-SQL2 language but is implemented specifically
for the PHPCR-Shell.
EOT
);
}

public function execute(InputInterface $input, OutputInterface $output)
{
$sql = $input->getRawCommand();

// trim ";" for people used to MysQL
if (substr($sql, -1) == ';') {
$sql = substr($sql, 0, -1);
}

$session = $this->getHelper('phpcr')->getSession();
$qm = $session->getWorkspace()->getQueryManager();

$updateParser = new UpdateParser($qm->getQOMFactory());
$res = $updateParser->parse($sql);
$query = $res->offsetGet(0);
$updates = $res->offsetGet(1);

$start = microtime(true);
$result = $query->execute();

foreach ($result as $row) {
foreach ($updates as $field => $property) {
$node = $row->getNode($property['selector']);
$node->setProperty($property['name'], $property['value']);
}
}

$elapsed = microtime(true) - $start;

$output->writeln(sprintf('%s row(s) affected in %ss', count($result), number_format($elapsed, 2)));
}
}
13 changes: 8 additions & 5 deletions src/PHPCR/Shell/Console/Input/StringInput.php
Expand Up @@ -14,6 +14,7 @@ class StringInput extends BaseInput
{
protected $rawCommand;
protected $tokens;
protected $isQuery = false;

/**
* {@inheritDoc}
Expand All @@ -24,6 +25,12 @@ public function __construct($command)

if (strpos(strtolower($this->rawCommand), 'select') === 0) {
$command = 'select' . substr($command, 6);
$this->isQuery = true;
}

if (strpos(strtolower($this->rawCommand), 'update') === 0) {
$command = 'update' . substr($command, 6);
$this->isQuery = true;
}

parent::__construct($command);
Expand Down Expand Up @@ -90,10 +97,6 @@ public function getTokens()
*/
protected function isQuery()
{
if (strpos(strtolower($this->rawCommand), 'select') === 0) {
return true;
}

return false;
return $this->isQuery;
}
}
128 changes: 128 additions & 0 deletions src/PHPCR/Shell/Query/UpdateParser.php
@@ -0,0 +1,128 @@
<?php

namespace PHPCR\Shell\Query;

use PHPCR\Util\ValueConverter;
use PHPCR\Util\QOM\Sql2Scanner;
use PHPCR\Util\QOM\Sql2ToQomQueryConverter;
use PHPCR\Query\InvalidQueryException;
use PHPCR\Query\QOM\SourceInterface;

/**
* Parse "UPDATE" queries.
*
* This class extends the Sql2ToQomQueryConverter class and adapts it
* to parse UPDATE queries.
*
* @author Daniel Leech <daniel@dantleech.com>
*/
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing doc block

class UpdateParser extends Sql2ToQomQueryConverter
{
/**
* Parse an "SQL2" UPDATE statement and construct a query builder
* for selecting the rows and build a field => value mapping for the
* update.
*
* @param string $sql2
*
* @return array($query, $updates)
*/
public function parse($sql2)
{
$this->implicitSelectorName = null;
$this->sql2 = $sql2;
$this->scanner = new Sql2Scanner($sql2);
$source = null;
$constraint = null;

while ($this->scanner->lookupNextToken() !== '') {
switch (strtoupper($this->scanner->lookupNextToken())) {
case 'UPDATE':
$this->scanner->expectToken('UPDATE');
$source = $this->parseSource();
break;
case 'SET':
$this->scanner->expectToken('SET');
$updates = $this->parseUpdates();
break;
case 'WHERE':
$this->scanner->expectToken('WHERE');
$constraint = $this->parseConstraint();
break;
default:
throw new InvalidQueryException('Expected end of query, got "' . $this->scanner->lookupNextToken() . '" in ' . $this->sql2);
}
}

if (!$source instanceof SourceInterface) {
throw new InvalidQueryException('Invalid query, source could not be determined: '.$sql2);
}

$query = $this->factory->createQuery($source, $constraint);

$res = new \ArrayObject(array($query, $updates));

return $res;
}

/**
* Parse the SET section of the query, returning
* an array containing the property names (<selectorName.propertyName)
* as keys and an array
*
* array(
* 'selector' => <selector>,
* 'name' => <name>,
* '<value>' => <property value>,
* )
*
* @return array
*/
protected function parseUpdates()
{
$updates = array();

while (true) {
$selectorName = $this->scanner->fetchNextToken();
$delimiter = $this->scanner->fetchNextToken();

if ($delimiter !== '.') {
$property = array(
'selector' => null,
'name' => $selectorName
);
$equals = $delimiter;
} else {
$property = array(
'selector' => $selectorName,
'name' => $this->scanner->fetchNextToken()
);
$equals = $this->scanner->fetchNextToken();
}


if ($equals !== '=') {
throw new InvalidQueryException(sprintf(
'Expected "=" after property name in UPDATE query, got "%s"',
$equals,
$this->sql2
));
}

$value = $this->parseLiteralValue();
$property['value'] = $value;

$updates[$property['selector'] . '.' . $property['name']] = $property;

$next = $this->scanner->lookupNextToken();

if ($next == ',') {
$next = $this->scanner->fetchNextToken();
} elseif (strtolower($next) == 'where' || !$next) {
break;
}
}

return $updates;
}
}