You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by ta...@apache.org on 2019/02/16 01:20:51 UTC
[impala] 01/11: IMPALA-2195: Improper handling of comments in
queries
This is an automated email from the ASF dual-hosted git repository.
tarmstrong pushed a commit to branch 2.x
in repository https://gitbox.apache.org/repos/asf/impala.git
commit 4fe01b280e1dcf0b6e99578ddc581f230444d1ad
Author: Fredy Wijaya <fw...@cloudera.com>
AuthorDate: Wed Apr 4 19:09:14 2018 -0700
IMPALA-2195: Improper handling of comments in queries
This patch fixes an issue where parseline is unable to deduce the
correct command when a statement has a leading comment.
Before:
> -- comment
> insert into table t values(100);
Fetched 1 row(s) in 0.01s
After:
> -- comment
> insert into table t values(100);
Modified 1 row(s) in 0.01s
Before (FE syntax error):
> /*comment*/ help;
After (show help correctly):
> /*comment*/ help;
Testing:
- Added shell tests
- Ran end-to-end shell tests on Python 2.6 and Python 2.7
Change-Id: I7ac7cb5a30e6dda73ebe761d9f0eb9ba038e14a7
Reviewed-on: http://gerrit.cloudera.org:8080/9933
Tested-by: Impala Public Jenkins <im...@cloudera.com>
Reviewed-by: Bharath Vissapragada <bh...@cloudera.com>
---
shell/impala_shell.py | 82 ++++++++++++++++++++++++---
tests/shell/test_shell_interactive.py | 103 ++++++++++++++++++++++++++++++++--
2 files changed, 173 insertions(+), 12 deletions(-)
diff --git a/shell/impala_shell.py b/shell/impala_shell.py
index 8cb1442..841457e 100755
--- a/shell/impala_shell.py
+++ b/shell/impala_shell.py
@@ -312,11 +312,15 @@ class ImpalaShell(object, cmd.Cmd):
command = self.orig_cmd
self.orig_cmd = None
if not command:
- print_to_stderr("Unexpected error: Failed to execute query due to command "\
+ print_to_stderr("Unexpected error: Failed to execute query due to command "
"is missing")
sys.exit(1)
- return self.imp_client.create_beeswax_query("%s %s" % (command, args),
- self.set_query_options)
+ # In order to deduce the correct cmd, parseline stripped the leading comment.
+ # To preserve the original query, the leading comment (if exists) will be
+ # prepended when constructing the query sent to the Impala front-end.
+ return self.imp_client.create_beeswax_query("%s%s %s" % (self.leading_comment or "",
+ command, args),
+ self.set_query_options)
def do_shell(self, args):
"""Run a command on the shell
@@ -582,7 +586,7 @@ class ImpalaShell(object, cmd.Cmd):
# is necessary to find a proper function and here is a right place
# because the lowering command in front of the finding can avoid a
# side effect.
- command, arg, line = self.parseline(line)
+ command, arg, line, leading_comment = self.parseline(line)
if not line:
return self.emptyline()
if command is None:
@@ -596,6 +600,7 @@ class ImpalaShell(object, cmd.Cmd):
try:
func = getattr(self, 'do_' + command.lower())
self.orig_cmd = command
+ self.leading_comment = leading_comment
except AttributeError:
return self.default(line)
return func(arg)
@@ -1281,17 +1286,78 @@ class ImpalaShell(object, cmd.Cmd):
def parseline(self, line):
"""Parse the line into a command name and a string containing
- the arguments. Returns a tuple containing (command, args, line).
+ the arguments. Returns a tuple containing (command, args, line, leading comment).
'command' and 'args' may be None if the line couldn't be parsed.
'line' in return tuple is the rewritten original line, with leading
and trailing space removed and special characters transformed into
- their aliases.
+ their aliases. If the line contains a leading comment, the leading
+ comment will be removed in order to deduce a 'command' correctly.
+ The 'command' is used to determine which 'do_<command>' function to invoke.
+ The 'do_<command>' implementation can decide whether to retain or ignore the
+ leading comment.
+
+ Examples:
+
+ > /*comment*/ help connect;
+ line: help connect
+ args: connect
+ command: help
+ leading comment: /*comment*/
+
+ > /*comment*/ ? connect;
+ line: help connect
+ args: connect
+ command: help
+ leading comment: /*comment*/
+
+ > /*first comment*/ select /*second comment*/ 1;
+ line: select /*second comment*/ 1
+ args: /*second comment*/ 1
+ command: select
+ leading comment: /*first comment*/
"""
- line = line.strip()
+ leading_comment, line = ImpalaShell.strip_leading_comment(line.strip())
+ line = line.encode('utf-8')
if line and line[0] == '@':
line = 'rerun ' + line[1:]
- return super(ImpalaShell, self).parseline(line)
+ return super(ImpalaShell, self).parseline(line) + (leading_comment,)
+ @staticmethod
+ def strip_leading_comment(sql):
+ """
+ Filter a leading comment in the SQL statement. This function returns a tuple
+ containing (leading comment, line without the leading comment).
+ """
+ class StripLeadingCommentFilter:
+ def __init__(self):
+ self.comment = None
+
+ def _process(self, tlist):
+ token = tlist.token_first()
+ if self._is_comment(token):
+ self.comment = token.value
+ tidx = tlist.token_index(token)
+ tlist.tokens.pop(tidx)
+
+ def _is_comment(self, token):
+ if isinstance(token, sqlparse.sql.Comment):
+ return True
+ for comment in sqlparse.tokens.Comment:
+ if token.ttype == comment:
+ return True
+ return False
+
+ def process(self, stack, stmt):
+ [self.process(stack, sgroup) for sgroup in stmt.get_sublists()]
+ self._process(stmt)
+
+ stack = sqlparse.engine.FilterStack()
+ stack.enable_grouping()
+ strip_leading_comment_filter = StripLeadingCommentFilter()
+ stack.stmtprocess.append(strip_leading_comment_filter)
+ stack.postprocess.append(sqlparse.filters.SerializerUnicode())
+ stripped_line = ''.join(stack.run(sql, 'utf-8'))
+ return strip_leading_comment_filter.comment, stripped_line
def _replace_history_delimiters(self, src_delim, tgt_delim):
"""Replaces source_delim with target_delim for all items in history.
diff --git a/tests/shell/test_shell_interactive.py b/tests/shell/test_shell_interactive.py
index fe41e36..d0308d8 100755
--- a/tests/shell/test_shell_interactive.py
+++ b/tests/shell/test_shell_interactive.py
@@ -367,12 +367,9 @@ class TestImpalaShellInteractive(object):
@pytest.mark.execute_serially
def test_zero_row_fetch(self):
# IMPALA-4418: DROP and USE are generally exceptional statements where
- # the client does not fetch. However, when preceded by a comment, the
- # Impala shell treats them like any other statement and will try to
- # fetch - receiving 0 rows. For statements returning 0 rows we do not
+ # the client does not fetch. For statements returning 0 rows we do not
# want an empty line in stdout.
result = run_impala_shell_interactive("-- foo \n use default;")
- assert "Fetched 0 row(s)" in result.stderr
assert re.search('> \[', result.stdout)
result = run_impala_shell_interactive("select * from functional.alltypes limit 0;")
assert "Fetched 0 row(s)" in result.stderr
@@ -459,6 +456,55 @@ class TestImpalaShellInteractive(object):
os.chdir(cwd)
@pytest.mark.execute_serially
+ def test_line_with_leading_comment(self):
+ # IMPALA-2195: A line with a comment produces incorrect command.
+ try:
+ run_impala_shell_interactive('drop table if exists leading_comment;')
+ run_impala_shell_interactive('create table leading_comment (i int);')
+ result = run_impala_shell_interactive('-- comment\n'
+ 'insert into leading_comment values(1);')
+ assert 'Modified 1 row(s)' in result.stderr
+ result = run_impala_shell_interactive('-- comment\n'
+ 'select * from leading_comment;')
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive('/* comment */\n'
+ 'select * from leading_comment;')
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive('/* comment1 */\n'
+ '-- comment2\n'
+ 'select * from leading_comment;')
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive('/* comment1\n'
+ 'comment2 */ select * from leading_comment;')
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive('/* select * from leading_comment */ '
+ 'select * from leading_comment;')
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive('/* comment */ help use')
+ assert 'Executes a USE... query' in result.stdout
+
+ result = run_impala_shell_interactive('-- comment\n'
+ ' help use;')
+ assert 'Executes a USE... query' in result.stdout
+
+ result = run_impala_shell_interactive('/* comment1 */\n'
+ '-- comment2\n'
+ 'desc leading_comment;')
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive('/* comment1 */\n'
+ '-- comment2\n'
+ 'help use;')
+ assert 'Executes a USE... query' in result.stdout
+ finally:
+ run_impala_shell_interactive('drop table if exists leading_comment;')
+
+ @pytest.mark.execute_serially
def test_line_ends_with_comment(self):
# IMPALA-5269: Test lines that end with a comment.
queries = ['select 1 + 1; --comment',
@@ -558,6 +604,55 @@ class TestImpalaShellInteractive(object):
self._expect_with_cmd(proc, "use functional", (), 'functional')
self._expect_with_cmd(proc, "use foo", (), 'functional')
+ def test_strip_leading_comment(self):
+ """Test stripping leading comments from SQL statements"""
+ assert ('--delete\n', 'select 1') == \
+ ImpalaShellClass.strip_leading_comment('--delete\nselect 1')
+ assert ('--delete\n', 'select --do not delete\n1') == \
+ ImpalaShellClass.strip_leading_comment('--delete\nselect --do not delete\n1')
+ assert (None, 'select --do not delete\n1') == \
+ ImpalaShellClass.strip_leading_comment('select --do not delete\n1')
+
+ assert ('/*delete*/\n', 'select 1') == \
+ ImpalaShellClass.strip_leading_comment('/*delete*/\nselect 1')
+ assert ('/*delete\nme*/\n', 'select 1') == \
+ ImpalaShellClass.strip_leading_comment('/*delete\nme*/\nselect 1')
+ assert ('/*delete\nme*/\n', 'select 1') == \
+ ImpalaShellClass.strip_leading_comment('/*delete\nme*/\nselect 1')
+ assert ('/*delete*/', 'select 1') == \
+ ImpalaShellClass.strip_leading_comment('/*delete*/select 1')
+ assert ('/*delete*/ ', 'select /*do not delete*/ 1') == \
+ ImpalaShellClass.strip_leading_comment('/*delete*/ select /*do not delete*/ 1')
+ assert ('/*delete1*/ \n/*delete2*/ \n--delete3 \n', 'select /*do not delete*/ 1') == \
+ ImpalaShellClass.strip_leading_comment('/*delete1*/ \n'
+ '/*delete2*/ \n'
+ '--delete3 \n'
+ 'select /*do not delete*/ 1')
+ assert (None, 'select /*do not delete*/ 1') == \
+ ImpalaShellClass.strip_leading_comment('select /*do not delete*/ 1')
+ assert ('/*delete*/\n', 'select c1 from\n'
+ 'a\n'
+ 'join -- +SHUFFLE\n'
+ 'b') == \
+ ImpalaShellClass.strip_leading_comment('/*delete*/\n'
+ 'select c1 from\n'
+ 'a\n'
+ 'join -- +SHUFFLE\n'
+ 'b')
+ assert ('/*delete*/\n', 'select c1 from\n'
+ 'a\n'
+ 'join /* +SHUFFLE */\n'
+ 'b') == \
+ ImpalaShellClass.strip_leading_comment('/*delete*/\n'
+ 'select c1 from\n'
+ 'a\n'
+ 'join /* +SHUFFLE */\n'
+ 'b')
+
+ assert (None, 'select 1') == \
+ ImpalaShellClass.strip_leading_comment('select 1')
+
+
def run_impala_shell_interactive(input_lines, shell_args=None):
"""Runs a command in the Impala shell interactively."""
# if argument "input_lines" is a string, makes it into a list