on da76712 help sign in
78 lines 2.2 kB history raw
1{-# language FlexibleContexts #-}
2{-# language MonoLocalBinds #-}
4module Rel8.Statement.View
5 ( createView
6 , createOrReplaceView
7 )
8where
10-- base
11import Prelude
13-- hasql
14import qualified Hasql.Decoders as Hasql
15import qualified Hasql.Encoders as Hasql
16import qualified Hasql.Statement as Hasql
18-- rel8
19import Rel8.Query ( Query )
20import Rel8.Schema.Name ( Selects )
21import Rel8.Schema.Table ( TableSchema )
22import Rel8.Statement.Insert ( ppInto )
23import Rel8.Statement.Select ( ppSelect )
25-- pretty
26import Text.PrettyPrint ( Doc, (<+>), ($$), text )
28-- text
29import qualified Data.Text as Text
30import Data.Text.Encoding ( encodeUtf8 )
33data CreateView = Create | CreateOrReplace
36-- | Given a 'TableSchema' and 'Query', @createView@ runs a @CREATE VIEW@
37-- statement that will save the given query as a view. This can be useful if
38-- you want to share Rel8 queries with other applications.
39createView :: Selects names exprs
40 => TableSchema names -> Query exprs -> Hasql.Statement () ()
41createView =
42 createViewGeneric Create
45-- | Given a 'TableSchema' and 'Query', @createOrReplaceView@ runs a
46-- @CREATE OR REPLACE VIEW@ statement that will save the given query
47-- as a view, replacing the current view definition if it exists and
48-- adheres to the restrictions in place for replacing a view in
49-- PostgreSQL.
50createOrReplaceView :: Selects names exprs
51 => TableSchema names -> Query exprs -> Hasql.Statement () ()
52createOrReplaceView =
53 createViewGeneric CreateOrReplace
56createViewGeneric :: Selects names exprs
57 => CreateView -> TableSchema names -> Query exprs -> Hasql.Statement () ()
58createViewGeneric replace schema query =
59 Hasql.Statement bytes params decode prepare
60 where
61 bytes = encodeUtf8 (Text.pack sql)
62 params = Hasql.noParams
63 decode = Hasql.noResult
64 prepare = False
65 sql = show doc
66 doc = ppCreateView schema query replace
69ppCreateView :: Selects names exprs
70 => TableSchema names -> Query exprs -> CreateView -> Doc
71ppCreateView schema query replace =
72 createOrReplace replace <+>
73 ppInto schema $$
74 text "AS" <+>
75 ppSelect query
76 where
77 createOrReplace Create = text "CREATE VIEW"
78 createOrReplace CreateOrReplace = text "CREATE OR REPLACE VIEW"