on db148ff help sign in
rel8/src/Rel8/Statement/Insert.hs
89 lines 2.8 kB history raw
1{-# language GADTs #-}
2{-# language NamedFieldPuns #-}
3{-# language ScopedTypeVariables #-}
4{-# language TypeApplications #-}
6module Rel8.Statement.Insert
7 ( Insert(..)
8 , OnConflict(..)
9 , insert
10 )
11where
13-- base
14import Control.Exception ( throwIO )
15import Data.List.NonEmpty ( NonEmpty( (:|) ) )
16import Prelude
18-- hasql
19import Hasql.Connection ( Connection )
20import qualified Hasql.Decoders as Hasql
21import qualified Hasql.Encoders as Hasql
22import qualified Hasql.Session as Hasql
23import qualified Hasql.Statement as Hasql
25-- opaleye
26import qualified Opaleye.Internal.Manipulation as Opaleye
27import qualified Opaleye.Manipulation as Opaleye
29-- rel8
30import Rel8.Schema.Insert ( Insert(..), OnConflict(..) )
31import Rel8.Statement.Returning ( Returning( Projection, NumberOfRowsAffected ) )
32import Rel8.Table ( fromColumns, toColumns )
33import Rel8.Table.Opaleye ( castTable, table, unpackspec )
34import Rel8.Table.Serialize ( Serializable, parse )
36-- text
37import qualified Data.Text as Text ( pack )
38import Data.Text.Encoding ( encodeUtf8 )
41-- | Run an @INSERT@ statement
42insert :: Connection -> Insert a -> IO a
43insert c Insert {into, rows, onConflict, returning} =
44 case (rows, returning) of
45 ([], NumberOfRowsAffected) -> pure 0
46 ([], Projection _) -> pure []
48 (x:xs, NumberOfRowsAffected) -> Hasql.run session c >>= either throwIO pure
49 where
50 session = Hasql.statement () statement
51 statement = Hasql.Statement bytes params decode prepare
52 bytes = encodeUtf8 $ Text.pack sql
53 params = Hasql.noParams
54 decode = Hasql.rowsAffected
55 prepare = False
56 sql = Opaleye.arrangeInsertManySql into' rows' onConflict'
57 where
58 into' = table $ toColumns <$> into
59 rows' = toColumns <$> x :| xs
61 (x:xs, Projection project) -> Hasql.run session c >>= either throwIO pure
62 where
63 session = Hasql.statement () statement
64 statement = Hasql.Statement bytes params decode prepare
65 bytes = encodeUtf8 $ Text.pack sql
66 params = Hasql.noParams
67 decode = decoder project
68 prepare = False
69 sql =
70 Opaleye.arrangeInsertManyReturningSql
71 unpackspec
72 into'
73 rows'
74 project'
75 onConflict'
76 where
77 into' = table $ toColumns <$> into
78 rows' = toColumns <$> x :| xs
79 project' = castTable . toColumns . project . fromColumns
81 where
82 onConflict' =
83 case onConflict of
84 DoNothing -> Just Opaleye.DoNothing
85 Abort -> Nothing
87 decoder :: forall exprs projection a. Serializable projection a
88 => (exprs -> projection) -> Hasql.Result [a]
89 decoder _ = Hasql.rowList (parse @projection @a)