Created
June 2, 2009 08:34
This file contains 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 { | |
val string = """[_a-zA-Z0-9]+""".r | |
val number = """[0-9]+""".r | |
def colOption:Parser[Number] = "(" ~ number ~ ")" ^^ { case a~num~b => num.toInt } | |
def column:Parser[Column] = | |
string ~ string ~ 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" ~ string ~ columns ^^ { case literal~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