POST to insert row.
This commit is contained in:
+19
-2
@@ -4,10 +4,13 @@
|
||||
|
||||
module PgQuery where
|
||||
|
||||
import Data.Text (Text)
|
||||
import Data.Functor ( (<$>) )
|
||||
import Data.Maybe (fromMaybe)
|
||||
import Data.List (intersperse, intercalate)
|
||||
import Data.Monoid ((<>), mconcat)
|
||||
import Data.HashMap.Strict (fromList)
|
||||
import qualified Data.Aeson as JSON
|
||||
|
||||
import qualified RangeQuery as R
|
||||
import qualified Data.ByteString.Char8 as BS
|
||||
@@ -18,6 +21,8 @@ import Database.HDBC.PostgreSQL
|
||||
|
||||
import qualified Network.HTTP.Types.URI as Net
|
||||
|
||||
import Types (SqlRow, getRow)
|
||||
|
||||
-- }}}
|
||||
|
||||
data RangedResult = RangedResult {
|
||||
@@ -56,7 +61,6 @@ whereClause qs =
|
||||
where
|
||||
conjunction = mconcat $ intersperse (" and ", []) (map wherePred qs)
|
||||
|
||||
|
||||
wherePred :: Net.QueryItem -> QuotedSql
|
||||
wherePred (column, predicate) =
|
||||
("%I " <> op <> "%L", map toSql [column, value])
|
||||
@@ -73,7 +77,6 @@ wherePred (column, predicate) =
|
||||
"neq" -> "<>"
|
||||
_ -> "="
|
||||
|
||||
|
||||
limitClause :: Maybe R.NonnegRange -> QuotedSql
|
||||
limitClause range =
|
||||
(" LIMIT %s OFFSET %s ", [toSql limit, toSql offset])
|
||||
@@ -101,6 +104,20 @@ jsonArrayRows :: QuotedSql -> QuotedSql
|
||||
jsonArrayRows q =
|
||||
("array_to_json(array_agg(row_to_json(t))) from (", []) <> q <> (") t", [])
|
||||
|
||||
insert :: Text -> Text -> SqlRow -> Connection -> IO BL.ByteString
|
||||
insert schema table row conn = do
|
||||
query <- populateSql conn ("insert into %I.%I ("++colIds++")", map toSql $ schema:table:cols)
|
||||
stmt <- prepare conn (query ++ " values ("++phs++") returning *")
|
||||
_ <- execute stmt values
|
||||
keys <- getColumnNames stmt
|
||||
Just vals <- fetchRow stmt
|
||||
let rowMap = fromList $ zip keys vals
|
||||
return $ JSON.encode rowMap
|
||||
where
|
||||
(cols, values) = unzip . getRow $ row
|
||||
colIds = intercalate ", " $ map (const "%I") cols
|
||||
phs = intercalate ", " $ map (const "?") values
|
||||
|
||||
populateSql :: Connection -> QuotedSql -> IO String
|
||||
populateSql conn sql = do
|
||||
[[escaped]] <- quickQuery conn q (snd sql)
|
||||
|
||||
Reference in New Issue
Block a user