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