Quasi-quote the SQL

Fixes #1
This commit is contained in:
Joe Nelson
2014-06-23 12:37:10 -07:00
parent e28c875502
commit 293d5f6581
+19 -14
View File
@@ -1,4 +1,4 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module PgStructure where
@@ -14,7 +14,7 @@ import qualified Data.Aeson as JSON
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.Types
import Database.PostgreSQL.Simple.FromRow
--import Database.PostgreSQL.Simple.Arrays (esc)
import Database.PostgreSQL.Simple.SqlQQ
import Data.Aeson ((.=))
@@ -67,18 +67,20 @@ instance JSON.ToJSON Column where
tables :: String -> Connection -> IO [Table]
tables s conn = query conn q $ Only s
where q = "select table_schema, table_name,\
\ is_insertable_into \
\ from information_schema.tables\
\ where table_schema = ?"
where q = [sql|
select table_schema, table_name,\
is_insertable_into \
from information_schema.tables\
where table_schema = ? |]
columns :: T.Text -> Connection -> IO [Column]
columns t conn = query conn q $ Only t
where q = "select table_schema, table_name, column_name, ordinal_position,\
\ is_nullable, data_type, is_updatable,\
\ character_maximum_length, numeric_precision\
\ from information_schema.columns\
\ where table_name = ?"
where q = [sql|
select table_schema, table_name, column_name, ordinal_position,
is_nullable, data_type, is_updatable,
character_maximum_length, numeric_precision
from information_schema.columns
where table_name = ? |]
namedColumnHash :: [Column] -> HashMap String Column
namedColumnHash = fromList . (Prelude.zip =<< Prelude.map colName)
@@ -90,6 +92,9 @@ printColumns :: T.Text -> Connection -> IO BL.ByteString
printColumns table conn = JSON.encode . namedColumnHash <$> columns table conn
selectAll :: T.Text -> Connection -> IO JSON.Value
selectAll table conn = fromOnly <$> Prelude.head <$> query conn sql (Only $ QualifiedIdentifier (Just "base") table)
where sql = "select array_to_json(array_agg(row_to_json(t)))\
\ from (select * from ?) t;"
selectAll table conn = fromOnly <$> Prelude.head <$> query conn q (Only safeName)
where
q = [sql|
select array_to_json(array_agg(row_to_json(t)))
from (select * from ?) t; |]
safeName = QualifiedIdentifier (Just "base") table