on 11bcbbb help sign in
rel8/src/Rel8/Table/Insert.hs
51 lines 1.9 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(..) )
17import Rel8.Kind.Necessity ( SNecessity( SOptional, SRequired ) )
18import Rel8.Schema.HTable ( hfield, htabulate, hspecs )
19import Rel8.Schema.Insert ( Inserts, Col(..) )
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 'insert'. This will override any columns that have default values to
26-- use exactly what is given. If you want to use default values, you can either
27-- 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 {necessity} -> case hfield exprs field of
32 DB expr -> case necessity of
33 SRequired -> RequiredInsert expr
34 SOptional -> OptionalInsert (Just expr)
37-- | @toInsertDefaults@ converts a 'Table' of 'Expr's into a 'Table' that can
38-- be used with 'insert'. Any columns that have a default value will override
39-- whatever is in the input expression.
40--
41-- One example where this is useful is for any table that has a special @id@
42-- column, which has a default value to draw a new value from a sequence. If we
43-- use 'toInsertDefaults', we can provide a dummy value that will be replaced
44-- with a call to @DEFAULT@.
45toInsertDefaults :: Inserts exprs inserts => exprs -> inserts
46toInsertDefaults (toColumns -> exprs) = fromColumns $ htabulate $ \field ->
47 case hfield hspecs field of
48 SSpec {necessity} -> case hfield exprs field of
49 DB expr -> case necessity of
50 SRequired -> RequiredInsert expr
51 SOptional -> OptionalInsert Nothing