on master help sign in
Allow for view creation or the replacing of an existing views (#209)
commit38cbebc7d053561caf63d1b339f28ea016b2a842 authorGary Pamparà <gpampara@gmail.com> dateTue 18 Oct 2022, 20:35 (4 years ago) parentd2f05bd
1 file changed+30−5
src/Rel8/Statement/View.hs+30−5
src/Rel8/Statement/View.hs+30−5
@@ -3,6 +3,7 @@
33
44module Rel8.Statement.View
55 ( createView
6+ , createOrReplaceView
67 )
78where
89
@@ -29,25 +30,49 @@ import qualified Data.Text as Text
2930import Data.Text.Encoding ( encodeUtf8 )
3031
3132
33+data CreateView = Create | CreateOrReplace
34+
35+
3236-- | Given a 'TableSchema' and 'Query', @createView@ runs a @CREATE VIEW@
3337-- statement that will save the given query as a view. This can be useful if
3438-- you want to share Rel8 queries with other applications.
3539createView :: Selects names exprs
3640 => TableSchema names -> Query exprs -> Hasql.Statement () ()
37−createView schema query = Hasql.Statement bytes params decode prepare
41+createView =
42+ createViewGeneric Create
43+
44+
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.
50+createOrReplaceView :: Selects names exprs
51+ => TableSchema names -> Query exprs -> Hasql.Statement () ()
52+createOrReplaceView =
53+ createViewGeneric CreateOrReplace
54+
55+
56+createViewGeneric :: Selects names exprs
57+ => CreateView -> TableSchema names -> Query exprs -> Hasql.Statement () ()
58+createViewGeneric replace schema query =
59+ Hasql.Statement bytes params decode prepare
3860 where
3961 bytes = encodeUtf8 (Text.pack sql)
4062 params = Hasql.noParams
4163 decode = Hasql.noResult
4264 prepare = False
4365 sql = show doc
44− doc = ppCreateView schema query
66+ doc = ppCreateView schema query replace
4567
4668
4769ppCreateView :: Selects names exprs
48− => TableSchema names -> Query exprs -> Doc
49−ppCreateView schema query =
50− text "CREATE VIEW" <+>
70+ => TableSchema names -> Query exprs -> CreateView -> Doc
71+ppCreateView schema query replace =
72+ createOrReplace replace <+>
5173 ppInto schema $$
5274 text "AS" <+>
5375 ppSelect query
76+ where
77+ createOrReplace Create = text "CREATE VIEW"
78+ createOrReplace CreateOrReplace = text "CREATE OR REPLACE VIEW"