Skip to content

Commit

Permalink
Add Support for CASE ... END AS alias
Browse files Browse the repository at this point in the history
  • Loading branch information
mostertb committed Oct 13, 2018
1 parent 20ed994 commit 1a18d1c
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/Components/CaseExpression.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
namespace PhpMyAdmin\SqlParser\Components;

use PhpMyAdmin\SqlParser\Component;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;
Expand Down Expand Up @@ -55,6 +56,13 @@ class CaseExpression extends Component
*/
public $else_result;

/**
* The alias of this CASE statement
*
* @var string
*/
public $alias;

/**
* The sub-expression.
*
Expand Down Expand Up @@ -94,6 +102,13 @@ public static function parse(Parser $parser, TokensList $list, array $options =
*/
$type = 0;

/**
* Whether an alias is expected
*
* @bool
*/
$alias = false;

++$list->idx; // Skip 'CASE'

for (; $list->idx < $list->count; ++$list->idx) {
Expand Down Expand Up @@ -201,6 +216,56 @@ public static function parse(Parser $parser, TokensList $list, array $options =
$list->tokens[$list->idx - 1]
);
} else {

// Parse alias for CASE statement
for (; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];

// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE)
|| ($token->type === Token::TYPE_COMMENT)
) {
continue;
}

//
if($token->type === Token::TYPE_KEYWORD
&& $token->keyword === 'AS'){

if ($alias) {
$parser->error(
'An alias was expected.',
$token
);
break;
}
$alias = true;
continue;
}

if ($alias){

// An alias is expected (the keyword `AS` was previously found).
if (!empty($ret->alias)) {
$parser->error('An alias was previously found.', $token);
break;
}
$ret->alias = $token->value;
$alias = false;

continue;
}

break;
}
if ($alias) {
$parser->error(
'An alias was expected.',
$list->tokens[$list->idx - 1]
);
}


$ret->expr = self::build($ret);
}

Expand Down Expand Up @@ -241,6 +306,10 @@ public static function build($component, array $options = array())
}
$ret .= 'END';

if ($component->alias) {
$ret .= ' AS ' . Context::escape($component->alias);
}

return $ret;
}
}

0 comments on commit 1a18d1c

Please sign in to comment.