on b0e47ec help sign in
59 lines 1.6 kB history raw
1{-# language FlexibleContexts #-}
2{-# language MonoLocalBinds #-}
4module Rel8.Statement.View
5 ( createView
6 )
7where
9-- base
10import Control.Exception ( throwIO )
11import Prelude
13-- hasql
14import Hasql.Connection ( Connection )
15import qualified Hasql.Decoders as Hasql
16import qualified Hasql.Encoders as Hasql
17import qualified Hasql.Session as Hasql
18import qualified Hasql.Statement as Hasql
20-- rel8
21import Rel8.Query ( Query )
22import Rel8.Schema.Name ( Selects )
23import Rel8.Schema.Table ( TableSchema )
24import Rel8.Statement.Insert ( ppInto )
25import Rel8.Statement.Select ( ppSelect )
27-- pretty
28import Text.PrettyPrint ( Doc, (<+>), ($$), text )
30-- text
31import qualified Data.Text as Text
32import Data.Text.Encoding ( encodeUtf8 )
35-- | Given a 'TableSchema' and 'Query', @createView@ runs a @CREATE VIEW@
36-- statement that will save the given query as a view. This can be useful if
37-- you want to share Rel8 queries with other applications.
38createView :: Selects names exprs
39 => Connection -> TableSchema names -> Query exprs -> IO ()
40createView connection schema query =
41 Hasql.run session connection >>= either throwIO pure
42 where
43 session = Hasql.statement () statement
44 statement = Hasql.Statement bytes params decode prepare
45 bytes = encodeUtf8 (Text.pack sql)
46 params = Hasql.noParams
47 decode = Hasql.noResult
48 prepare = False
49 sql = show doc
50 doc = ppCreateView schema query
53ppCreateView :: Selects names exprs
54 => TableSchema names -> Query exprs -> Doc
55ppCreateView schema query =
56 text "CREATE VIEW" <+>
57 ppInto schema $$
58 text "AS" <+>
59 ppSelect query