Created
July 4, 2015 16:07
-
-
Save kyanny/52d9cc04d9c28df94497 to your computer and use it in GitHub Desktop.
Parslet SQL parser practice
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
require 'parslet' | |
require 'pp' | |
require 'yaml' | |
class P < Parslet::Parser | |
root(:table_definition) | |
rule(:space) { match('\s') } | |
rule(:space?) { space.maybe } | |
rule(:spaces) { space.repeat(1) } | |
rule(:spaces?) { spaces.maybe } | |
rule(:comma) { str(',') } | |
rule(:table_definition) do | |
create_table >> | |
spaces? >> | |
str('(') >> | |
spaces? >> | |
column_definitions >> | |
spaces? >> | |
table_constraints | |
end | |
rule(:create_table) do | |
spaces? >> | |
str('CREATE TABLE') >> | |
spaces? >> | |
table_name | |
end | |
rule(:table_name) do | |
identifier >> | |
str('.') >> | |
identifier | |
end | |
rule(:column_definitions) do | |
column_definition.repeat | |
end | |
rule(:column_definition) do | |
spaces? >> | |
identifier >> | |
spaces? >> | |
type >> | |
spaces? >> | |
column_constraints.repeat >> | |
comma >> | |
spaces? | |
end | |
rule(:identifier) do | |
str('"') >> | |
match('[^"]').repeat(1) >> | |
str('"') >> | |
spaces? | |
end | |
rule(:type) do | |
type_varchar2 | date | number | char | |
end | |
rule(:type_varchar2) do | |
str("VARCHAR2") >> | |
str('(') >> | |
match(['[0-9]']).repeat(1) >> | |
str(')') | |
end | |
rule(:date) do | |
str('DATE') | |
end | |
rule(:number) do | |
str('NUMBER') >> | |
str('(') >> | |
match('[0-9]').repeat(1) >> | |
str(',') >> | |
match('[0-9]').repeat(1) >> | |
str(')') | |
end | |
rule(:char) do | |
str("CHAR") >> | |
str('(') >> | |
match('[0-9]').repeat(1) >> | |
str(')') | |
end | |
# 列制約 | |
rule(:column_constraints) do | |
( | |
column_constraint_not_null | column_constraint_enable | column_constraint_default_zero | |
) >> spaces? | |
end | |
rule(:column_constraint_not_null) do | |
str('NOT NULL') | |
end | |
rule(:column_constraint_enable) do | |
str('ENABLE') | |
end | |
rule(:column_constraint_default_zero) do | |
str('DEFAULT 0') | |
end | |
# 表制約 | |
rule(:table_constraints) do | |
spaces? >> | |
str('CONSTRAINT') >> | |
spaces? >> | |
identifier >> | |
spaces? >> | |
table_constraint_primary_key | |
end | |
rule(:table_constraint_primary_key) do | |
str('PRIMARY KEY') >> | |
spaces? >> | |
str('(') >> | |
comma_separated_identifiers >> | |
str(')') | |
end | |
rule(:comma_separated_identifiers) do | |
(identifier >> spaces? >> comma.maybe >> spaces?).repeat | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment