module Database.Relational.Internal.Literal (
  stringExpr,
  bool, integral, timestamp,
  ) where
import Data.Monoid ((<>))
import Data.Time (FormatTime, formatTime)
import Data.Time.Locale.Compat (defaultTimeLocale)
import Language.SQL.Keyword (Keyword)
import Database.Relational.Internal.String (StringSQL, stringSQL)
escapeStringToSqlExpr :: String -> String
escapeStringToSqlExpr = rec where
  rec ""        = ""
  rec ('\'':cs) = '\'' : '\'' : rec cs
  rec (c:cs)    = c : rec cs
stringExpr :: String -> StringSQL
stringExpr = stringSQL . ('\'' :) . (++ "'") . escapeStringToSqlExpr
bool :: Bool -> StringSQL
bool =
    stringSQL . d
  where
    d True  = "(0=0)"
    d False = "(0=1)"
integral :: (Show a, Integral a) => a -> StringSQL
integral = stringSQL . show
timestamp :: FormatTime t => Keyword -> String -> t -> StringSQL
timestamp kw fmt t = kw <> stringExpr (formatTime defaultTimeLocale fmt t)