-
Notifications
You must be signed in to change notification settings - Fork 29k
[SPARK-5009][SQL][Bug FIx] allCaseVersions leads to stackoverflow. #3909
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
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2357d02
initial lowercase version
OopsOutOfMemory 42be742
refine code
OopsOutOfMemory b6f916d
refine code
OopsOutOfMemory 2512990
not affect indentifier
OopsOutOfMemory 0387472
add test suit
OopsOutOfMemory ce67cd2
code style format
OopsOutOfMemory File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
316 changes: 316 additions & 0 deletions
316
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/parser/KeyWordParserSuit.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,316 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
|
|
||
| import scala.language.implicitConversions | ||
| import scala.util.parsing.combinator.syntactical.StandardTokenParsers | ||
| import scala.util.parsing.combinator.PackratParsers | ||
| import scala.util.parsing.input.CharArrayReader.EofCh | ||
| import scala.util.parsing.combinator.lexical._ | ||
| import org.scalatest.FunSuite | ||
|
|
||
| class KeyWordParserSuit extends FunSuite { | ||
|
|
||
| val testDDL = s""" | ||
| |creAtE TEMPORARY TABLE hbase_people | ||
| |USING com.shengli.spark.hbase | ||
| |OPTIONS ( | ||
| | sparksql_table_schema '(row_key string, name string, age int, job string)', | ||
| | hbase_table_name 'people', | ||
| | hbase_table_schema '(:key , profile:name , profile:age , career:job )' | ||
| |) | ||
| |sERDEPRopERTIES ( | ||
| | path 'temp_path' | ||
| |) | ||
| |TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST( | ||
| | test 'test_keyword' | ||
| )""".stripMargin | ||
|
|
||
| val allCaseVersionsParser = new AllCaseVersionsParser() | ||
| val lowerCaseKeyWordParser = new LowerCaseParser() | ||
| var ret = "" | ||
|
|
||
| test("SPARK-5009 reproduce the stackoverflow exception") { | ||
| try { | ||
| val rs =allCaseVersionsParser(testDDL) | ||
| } | ||
| catch { | ||
| case e: java.lang.StackOverflowError => | ||
| ret = "stackoverflow" | ||
| println("stackoverflow when keyword using all case versions") | ||
| } | ||
| assert(ret=="stackoverflow") | ||
| } | ||
|
|
||
| test("SPARK-5009 fix the stackoverflow exception with keyword lower case way") { | ||
| try { | ||
| val rs =lowerCaseKeyWordParser(testDDL) | ||
| ret = rs.get | ||
| } | ||
| catch { | ||
| case e: java.lang.StackOverflowError => | ||
| ret = "stackoverflow" | ||
| } | ||
| assert(ret=="parse success") | ||
| } | ||
| } | ||
|
|
||
|
|
||
| class AllCaseVersionsParser extends StandardTokenParsers with PackratParsers { | ||
| def apply(input: String): Option[String] = { | ||
| phrase(ddl)(new lexical.Scanner(input)) match { | ||
| case Success(r, x) => Some(r) | ||
| case x => | ||
| None | ||
| } | ||
| } | ||
| protected case class Keyword(str: String) | ||
|
|
||
| protected implicit def asParser(k: Keyword): Parser[String] = | ||
| lexical.allCaseVersions(k.str).map(x => x : Parser[String]).reduce(_ | _) | ||
|
|
||
| protected val AS = Keyword("AS") | ||
| protected val CREATE = Keyword("CREATE") | ||
| protected val TEMPORARY = Keyword("TEMPORARY") | ||
| protected val TABLE = Keyword("TABLE") | ||
| protected val USING = Keyword("USING") | ||
| protected val OPTIONS = Keyword("OPTIONS") | ||
| protected val SERDEPROPERTIES = Keyword("SERDEPROPERTIES") | ||
| protected val TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST = | ||
| Keyword("TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST") | ||
|
|
||
| // Use reflection to find the reserved words defined in this class. | ||
| protected val reservedWords = this.getClass.getMethods.filter(_.getReturnType == classOf[Keyword]) | ||
| .map(_.invoke(this).asInstanceOf[Keyword].str) | ||
|
|
||
| override val lexical = new LowerCaseSqlLexical(reservedWords) | ||
|
|
||
| protected lazy val ddl: Parser[String] = createTable | ||
|
|
||
| /** | ||
| * CREATE FOREIGN TEMPORARY TABLE avroTable | ||
| * USING org.apache.spark.sql.avro | ||
| * OPTIONS (path "../hive/src/test/resources/data/files/episodes.avro") | ||
| */ | ||
| protected lazy val createTable: Parser[String] = | ||
| CREATE ~ TEMPORARY ~ TABLE ~> ident ~ (USING ~> className) ~ (OPTIONS ~> options) ~ | ||
| (SERDEPROPERTIES~>serde) ~ (TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST ~> test).? ^^ { | ||
| case tableName ~ provider ~ opts ~ sd ~ tst => | ||
| "parse success" | ||
| } | ||
|
|
||
| protected lazy val test: Parser[Map[String, String]] = | ||
| "(" ~> repsep(pair, ",") <~ ")" ^^ { case s: Seq[(String, String)] => s.toMap } | ||
|
|
||
| protected lazy val serde: Parser[Map[String, String]] = | ||
| "(" ~> repsep(pair, ",") <~ ")" ^^ { case s: Seq[(String, String)] => s.toMap } | ||
|
|
||
| protected lazy val options: Parser[Map[String, String]] = | ||
| "(" ~> repsep(pair, ",") <~ ")" ^^ { case s: Seq[(String, String)] => s.toMap } | ||
|
|
||
| protected lazy val className: Parser[String] = repsep(ident, ".") ^^ { case s => s.mkString(".")} | ||
|
|
||
| protected lazy val pair: Parser[(String, String)] = ident ~ stringLit ^^ { case k ~ v => (k,v) } | ||
|
|
||
| } | ||
|
|
||
|
|
||
|
|
||
|
|
||
| class LowerCaseParser extends StandardTokenParsers with PackratParsers { | ||
| def apply(input: String): Option[String] = { | ||
| phrase(ddl)(new lexical.Scanner(input)) match { | ||
| case Success(r, x) => Some(r) | ||
| case x => | ||
| None | ||
| } | ||
| } | ||
| protected case class Keyword(str: String) | ||
|
|
||
| protected implicit def asParser(k: Keyword): Parser[String] = k.str.toLowerCase | ||
|
|
||
| protected val AS = Keyword("AS") | ||
| protected val CREATE = Keyword("CREATE") | ||
| protected val TEMPORARY = Keyword("TEMPORARY") | ||
| protected val TABLE = Keyword("TABLE") | ||
| protected val USING = Keyword("USING") | ||
| protected val OPTIONS = Keyword("OPTIONS") | ||
| protected val SERDEPROPERTIES = Keyword("SERDEPROPERTIES") | ||
| protected val TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST = | ||
| Keyword("TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST") | ||
|
|
||
| // Use reflection to find the reserved words defined in this class. | ||
| protected val reservedWords = | ||
| this.getClass.getMethods.filter(_.getReturnType == classOf[Keyword]) | ||
| .map(_.invoke(this).asInstanceOf[Keyword].str) | ||
|
|
||
| override val lexical = new LowerCaseSqlLexical(reservedWords) | ||
|
|
||
| protected lazy val ddl: Parser[String] = createTable | ||
|
|
||
| /** | ||
| * CREATE FOREIGN TEMPORARY TABLE avroTable | ||
| * USING org.apache.spark.sql.avro | ||
| * OPTIONS (path "../hive/src/test/resources/data/files/episodes.avro") | ||
| */ | ||
| protected lazy val createTable: Parser[String] = | ||
| CREATE ~ TEMPORARY ~ TABLE ~> ident ~ (USING ~> className) ~ (OPTIONS ~> options) ~ | ||
| (SERDEPROPERTIES~>serde) ~ (TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST ~> test).? ^^ { | ||
| case tableName ~ provider ~ opts ~ sd ~ tst => | ||
| "parse success" | ||
| } | ||
|
|
||
| protected lazy val test: Parser[Map[String, String]] = | ||
| "(" ~> repsep(pair, ",") <~ ")" ^^ { case s: Seq[(String, String)] => s.toMap } | ||
|
|
||
| protected lazy val serde: Parser[Map[String, String]] = | ||
| "(" ~> repsep(pair, ",") <~ ")" ^^ { case s: Seq[(String, String)] => s.toMap } | ||
|
|
||
| protected lazy val options: Parser[Map[String, String]] = | ||
| "(" ~> repsep(pair, ",") <~ ")" ^^ { case s: Seq[(String, String)] => s.toMap } | ||
|
|
||
| protected lazy val className: Parser[String] = repsep(ident, ".") ^^ { case s => s.mkString(".")} | ||
|
|
||
| protected lazy val pair: Parser[(String, String)] = ident ~ stringLit ^^ { case k ~ v => (k,v) } | ||
|
|
||
| } | ||
|
|
||
| /* | ||
| * This class demonstrate the all case versions , if keyword is long, the allCaseVersions generate a long Stream. | ||
| * In Parser, when called `asParser` method, the reduce(_|_) will cause stackoverflow exception | ||
| */ | ||
| class AllCaseVersionsSqlLexical(val keywords: Seq[String]) extends StdLexical { | ||
| case class FloatLit(chars: String) extends Token { | ||
| override def toString = chars | ||
| } | ||
|
|
||
| reserved ++= keywords.flatMap(w => allCaseVersions(w) ) | ||
|
|
||
| delimiters += ( | ||
| "@", "*", "+", "-", "<", "=", "<>", "!=", "<=", ">=", ">", "/", "(", ")", | ||
| ",", ";", "%", "{", "}", ":", "[", "]", ".", "&", "|", "^", "~" | ||
| ) | ||
|
|
||
|
|
||
| override lazy val token: Parser[Token] = | ||
| ( identChar ~ (identChar | digit).* ^^ | ||
| { case first ~ rest => processIdent((first :: rest).mkString) } | ||
| | rep1(digit) ~ ('.' ~> digit.*).? ^^ { | ||
| case i ~ None => NumericLit(i.mkString) | ||
| case i ~ Some(d) => FloatLit(i.mkString + "." + d.mkString) | ||
| } | ||
| | '\'' ~> chrExcept('\'', '\n', EofCh).* <~ '\'' ^^ | ||
| { case chars => StringLit(chars mkString "") } | ||
| | '"' ~> chrExcept('"', '\n', EofCh).* <~ '"' ^^ | ||
| { case chars => StringLit(chars mkString "") } | ||
| | '`' ~> chrExcept('`', '\n', EofCh).* <~ '`' ^^ | ||
| { case chars => Identifier(chars mkString "") } | ||
| | EofCh ^^^ EOF | ||
| | '\'' ~> failure("unclosed string literal") | ||
| | '"' ~> failure("unclosed string literal") | ||
| | delim | ||
| | failure("illegal character") | ||
| ) | ||
|
|
||
| override def identChar = letter | elem('_') | ||
|
|
||
| override def whitespace: Parser[Any] = | ||
| ( whitespaceChar | ||
| | '/' ~ '*' ~ comment | ||
| | '/' ~ '/' ~ chrExcept(EofCh, '\n').* | ||
| | '#' ~ chrExcept(EofCh, '\n').* | ||
| | '-' ~ '-' ~ chrExcept(EofCh, '\n').* | ||
| | '/' ~ '*' ~ failure("unclosed comment") | ||
| ).* | ||
|
|
||
| /** Generate all variations of upper and lower case of a given string */ | ||
| def allCaseVersions(s: String, prefix: String = ""): Stream[String] = { | ||
| if (s == "") { | ||
| Stream(prefix) | ||
| } else { | ||
| allCaseVersions(s.tail, prefix + s.head.toLower) ++ | ||
| allCaseVersions(s.tail, prefix + s.head.toUpper) | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| /* | ||
| * This class demonstrate the lower case keyword matching strategy | ||
| * Will not cause stackoverflow exception and speed up keyword matching | ||
| */ | ||
| class LowerCaseSqlLexical(val keywords: Seq[String]) extends StdLexical { | ||
| case class FloatLit(chars: String) extends Token { | ||
| override def toString = chars | ||
| } | ||
|
|
||
| reserved ++= keywords.flatMap(w => Stream(w.toLowerCase()) ) | ||
|
|
||
| delimiters += ( | ||
| "@", "*", "+", "-", "<", "=", "<>", "!=", "<=", ">=", ">", "/", "(", ")", | ||
| ",", ";", "%", "{", "}", ":", "[", "]", ".", "&", "|", "^", "~" | ||
| ) | ||
|
|
||
|
|
||
| override lazy val token: Parser[Token] = | ||
| ( identChar ~ (identChar | digit).* ^^ | ||
| { | ||
| case first ~ rest => | ||
| val rsIdent = processIdent((first :: rest).mkString.toLowerCase()) | ||
| if(rsIdent.getClass.getCanonicalName.contains("StdTokens.Keyword")) | ||
| Keyword(rsIdent.chars.toLowerCase()) | ||
| else | ||
| processIdent((first :: rest).mkString) | ||
| } | ||
| | rep1(digit) ~ ('.' ~> digit.*).? ^^ { | ||
| case i ~ None => NumericLit(i.mkString) | ||
| case i ~ Some(d) => FloatLit(i.mkString + "." + d.mkString) | ||
| } | ||
| | '\'' ~> chrExcept('\'', '\n', EofCh).* <~ '\'' ^^ | ||
| { case chars => StringLit(chars mkString "") } | ||
| | '"' ~> chrExcept('"', '\n', EofCh).* <~ '"' ^^ | ||
| { case chars => StringLit(chars mkString "") } | ||
| | '`' ~> chrExcept('`', '\n', EofCh).* <~ '`' ^^ | ||
| { case chars => Identifier(chars mkString "") } | ||
| | EofCh ^^^ EOF | ||
| | '\'' ~> failure("unclosed string literal") | ||
| | '"' ~> failure("unclosed string literal") | ||
| | delim | ||
| | failure("illegal character") | ||
| ) | ||
|
|
||
| override def identChar = letter | elem('_') | ||
|
|
||
| override def whitespace: Parser[Any] = | ||
| ( whitespaceChar | ||
| | '/' ~ '*' ~ comment | ||
| | '/' ~ '/' ~ chrExcept(EofCh, '\n').* | ||
| | '#' ~ chrExcept(EofCh, '\n').* | ||
| | '-' ~ '-' ~ chrExcept(EofCh, '\n').* | ||
| | '/' ~ '*' ~ failure("unclosed comment") | ||
| ).* | ||
|
|
||
| /** Generate all variations of upper and lower case of a given string */ | ||
| def allCaseVersions(s: String, prefix: String = ""): Stream[String] = { | ||
| if (s == "") { | ||
| Stream(prefix) | ||
| } else { | ||
| allCaseVersions(s.tail, prefix + s.head.toLower) ++ | ||
| allCaseVersions(s.tail, prefix + s.head.toUpper) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
toLowerCaseprobably causes some other issue, can you add a unit test for this?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@chenghao-intel
Since Keyword is a
constantand it's usage is to parsing matching and identify others, we don't need them after parsing correctly, so here I only makeKeywordlower case is doesn't matter and will not cause other issues.