Skip to content

Instantly share code, notes, and snippets.

@HParker
Created December 22, 2018 02:44
Show Gist options
  • Save HParker/6b3eaf0f1b682179c762059b1d53c0ec to your computer and use it in GitHub Desktop.
Save HParker/6b3eaf0f1b682179c762059b1d53c0ec to your computer and use it in GitHub Desktop.
module SqlParser exposing (..)
import Parser exposing ((|.), (|=), Parser, Trailing(..), float, keyword, spaces, succeed, symbol)
import Set
type alias Query =
{ select : List SelectField
, from : String
}
type alias SelectField =
{ table : Maybe String
, fieldName : String
}
sql : Parser Query
sql =
succeed Query
|. spaces
|= select
|. spaces
|= tableName
|. spaces
|. symbol ";"
select : Parser (List SelectField)
select =
Parser.sequence
{ start = "select"
, separator = ","
, end = "from"
, spaces = spaces
, item = selectField
, trailing = Forbidden
}
selectField : Parser SelectField
selectField =
Parser.oneOf
[ Parser.backtrackable
(succeed SelectField
|= (succeed Just |= sqlVariable)
|. symbol "."
|= sqlVariable
)
, succeed SelectField
|= succeed Nothing
|= sqlVariable
]
sqlVariable : Parser String
sqlVariable =
Parser.variable
{ start = \c -> Char.isLower c || c == '*'
, inner = \c -> Char.isAlphaNum c || c == '*' || c == '_'
, reserved = Set.fromList [ "select", "from", "where", "joins" ]
}
tableName : Parser String
tableName =
Parser.variable
{ start = Char.isLower
, inner = \c -> Char.isAlphaNum c || c == '_'
, reserved = Set.fromList [ "select", "from", "where", "joins" ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment