Skip to content

Instantly share code, notes, and snippets.

@Stiivi
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Stiivi/7e3f7f41bf4b49081925 to your computer and use it in GitHub Desktop.
Save Stiivi/7e3f7f41bf4b49081925 to your computer and use it in GitHub Desktop.
{-# LANGUAGE MultiParamTypeClasses #-}
import Text.Printf
data SQLLiteral
= SQLFloatLiteral Float
| SQLIntLiteral Integer
| SQLStringLiteral String
deriving (Show, Eq)
data SQLType
= SQLInt
| SQLText
deriving (Show, Eq)
data SQLOperator
= SQLMul
| SQLAdd
| SQLSub
| SQLEql
| SQLNegate
deriving (Show, Eq)
data SQLExpression
= SQLLiteralExpression SQLLiteral
| SQLBinaryExpression SQLOperator SQLExpression SQLExpression
| SQLColumn SQLType String
deriving (Show, Eq)
data Postgres = Postgres
data SQLite = SQLite
class Dialect d ex where
compile :: d -> ex -> String
-- This does not work:
-- compile d (SQLIntLiteral lit) = "defaultlit " ++ (show lit)
instance Dialect SQLite SQLLiteral where
compile SQLite (SQLIntLiteral l) = "sqlitelit " ++ (show l)
compile SQLite (SQLFloatLiteral l) = "sqlitelitf " ++ (show l)
instance Dialect Postgres SQLLiteral where
compile Postgres (SQLIntLiteral l) = "pglit " ++ (show l)
-- compile :: Postgres -> SQLExpression -> String
instance Dialect Postgres SQLExpression where
compile Postgres (SQLLiteralExpression ex) = compile Postgres ex
compile Postgres (SQLBinaryExpression SQLMul left right) = printf "MULTIPLY(%s, %s)" left' right'
where
left' = compile Postgres left
right' = compile Postgres right
compile Postgres (SQLBinaryExpression op left right) = left' ++ op' ++ right'
where
left' = compile Postgres left
right' = compile Postgres right
op' = printf " %s " (show op)
-- (1 + 2) * 3
ex :: SQLExpression
ex = SQLBinaryExpression
SQLMul
(SQLBinaryExpression
SQLAdd
(SQLLiteralExpression (SQLIntLiteral 1))
(SQLLiteralExpression (SQLIntLiteral 2))
)
(SQLLiteralExpression (SQLIntLiteral 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment