-
-
Save ymnk/123081 to your computer and use it in GitHub Desktop.
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
import scala.util.parsing.combinator._ | |
/** | |
* expr :: CREATE TABLE tbl_name ( create_definition,...) | |
* | |
* create_definition: | |
* col_name column_definition | |
* | |
* column_definition: | |
* data_type | |
* | |
* data_type: string | |
*/ | |
class CreateParser extends JavaTokenParsers { | |
def colOption:Parser[Number] = | |
"(" ~ decimalNumber ~ ")" ^^ { case _~num~_ => num.toInt } | |
def column:Parser[Column] = ident ~ ident ~ opt( colOption ) ^^ { | |
case name~stype~o => Column(name,stype,o) | |
} | |
def columns:Parser[ List[Column] ] = | |
"(" ~> repsep(column,",") <~ ")" ~ ";" ^^ { case l => l } | |
def create:Parser[Create] = "create" ~ "table" ~ ident ~ columns ^^ { | |
case _~_~name~cs => Create(name,cs) | |
} | |
case class Create( name:String, cols:List[Column] ) { | |
def gen:String = name +"->"+ cols.map( _.gen ) | |
} | |
case class Column( name:String, sql_type:String, option:Option[Any] ) { | |
def gen:String = name + ":" + sql_type | |
} | |
} | |
object CreateTest extends CreateParser { | |
def main(args:Array[String]) { | |
p(""" | |
CREATE table simple ( | |
id integer(10), | |
name varchar(255) | |
) ; | |
""") | |
} | |
def p( sql:String ) { | |
val s = sql.toLowerCase | |
println( parseAll(create, s) ) | |
println( parseAll(create, s).get.gen ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment