on e15f360 help sign in
rel8/src/Rel8/Table/Insert.hs
49 lines 1.8 kB history raw
1{-# language FlexibleContexts #-}
2{-# language NamedFieldPuns #-}
3{-# language TypeFamilies #-}
4{-# language ViewPatterns #-}
6module Rel8.Table.Insert
7 ( toInsert
8 , toInsertDefaults
9 )
10where
12-- base
13import Prelude
15-- rel8
16import Rel8.Expr ( Col( E ) )
17import Rel8.Kind.Necessity ( SNecessity( SOptional, SRequired ) )
18import Rel8.Schema.HTable ( hfield, htabulate, hspecs )
19import Rel8.Schema.Insert ( Inserts, Col( I ), Create(..) )
20import Rel8.Schema.Spec ( SSpec(..) )
21import Rel8.Table ( fromColumns, toColumns )
24-- | @toInsert@ converts a 'Table' of 'Expr's into a 'Table' that can be used
25-- with 'Rel8.insert'. This will override any columns that have default values
26-- to use exactly what is given. If you want to use default values, you can
27-- either override the result of @toInsert@, or use 'toInsertDefaults'.
28toInsert :: Inserts exprs inserts => exprs -> inserts
29toInsert (toColumns -> exprs) = fromColumns $ htabulate $ \field ->
30 case hfield hspecs field of
31 SSpec {} -> I $ case hfield exprs field of
32 E expr -> Value expr
35-- | @toInsertDefaults@ converts a 'Table' of 'Expr's into a 'Table' that can
36-- be used with 'Rel8.insert'. Any columns that have a default value will
37-- override whatever is in the input expression.
38--
39-- One example where this is useful is for any table that has a special @id@
40-- column, which has a default value to draw a new value from a sequence. If we
41-- use 'toInsertDefaults', we can provide a dummy value that will be replaced
42-- with a call to @DEFAULT@.
43toInsertDefaults :: Inserts exprs inserts => exprs -> inserts
44toInsertDefaults (toColumns -> exprs) = fromColumns $ htabulate $ \field ->
45 case hfield hspecs field of
46 SSpec {necessity} -> case hfield exprs field of
47 E expr -> I $ case necessity of
48 SRequired -> Value expr
49 SOptional -> Default