@@ -1,7 +1,4 @@
1{-# LANGUAGE ScopedTypeVariables #-}
1{-# LANGUAGE ScopedTypeVariables #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE OverloadedStrings #-}
5module ProjectM36.RelationalExpression where
2module ProjectM36.RelationalExpression where
6import ProjectM36.Relation
3import ProjectM36.Relation
7import ProjectM36.Tuple
4import ProjectM36.Tuple
@@ -10,44 +7,32 @@ import ProjectM36.Base
10import qualified Data.UUID as U
7import qualified Data.UUID as U
11import ProjectM36.Error
8import ProjectM36.Error
12import ProjectM36.AtomType
9import ProjectM36.AtomType
13−import ProjectM36.Attribute (emptyAttributes, attributesFromList)
10+import ProjectM36.Attribute (emptyAttributes)
14import ProjectM36.ScriptSession
11import ProjectM36.ScriptSession
15import ProjectM36.DataTypes.Primitive
12import ProjectM36.DataTypes.Primitive
16import ProjectM36.AtomFunction
13import ProjectM36.AtomFunction
17import ProjectM36.DatabaseContextFunction
14import ProjectM36.DatabaseContextFunction
18import ProjectM36.Arbitrary
15import ProjectM36.Arbitrary
19−import ProjectM36.GraphRefRelationalExpr
20−import ProjectM36.Transaction
21import qualified ProjectM36.Attribute as A
16import qualified ProjectM36.Attribute as A
22import qualified Data.Map as M
17import qualified Data.Map as M
23import qualified Data.HashSet as HS
18import qualified Data.HashSet as HS
24import qualified Data.Set as S
19import qualified Data.Set as S
25import Control.Monad.State hiding (join)
20import Control.Monad.State hiding (join)
26−import Data.Bifunctor (second)
21+import Control.Exception
27import Data.Maybe
22import Data.Maybe
28import Data.Either
23import Data.Either
29import Data.Char (isUpper)
24import Data.Char (isUpper)
31−import qualified Data.List.NonEmpty as NE
32−import Data.Functor.Identity
33import qualified Data.Text as T
25import qualified Data.Text as T
34import qualified Data.Vector as V
26import qualified Data.Vector as V
35import qualified ProjectM36.TypeConstructorDef as TCD
27import qualified ProjectM36.TypeConstructorDef as TCD
36−import qualified Control.Monad.RWS.Strict as RWS
28+import Control.Monad.Trans.Except
37−import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
38−import Control.Monad.Except hiding (join)
39−import Control.Monad.Trans.Except (except)
29+import Control.Monad.Trans.Reader
40−import Control.Monad.Reader as R hiding (join)
41−import ProjectM36.NormalizeExpr
42−import ProjectM36.WithNameExpr
43import Test.QuickCheck
30import Test.QuickCheck
44−import qualified Data.Functor.Foldable as Fold
31+import GHC
45−import Control.Applicative
46−#ifdef PM36_HASKELL_SCRIPTING
47−import GHC hiding (getContext)
48−import Control.Exception
49import GHC.Paths
32import GHC.Paths
50−#endif
33+import Data.Time.Clock
34+import Data.Time.Calendar
35+import qualified Data.List.NonEmpty as NE
52data DatabaseContextExprDetails = CountUpdatedTuples
37data DatabaseContextExprDetails = CountUpdatedTuples
@@ -64,63 +49,41 @@ databaseContextExprDetailsFunc CountUpdatedTuples _ relIn = Relation attrs newTu
64 Right ts -> ts
49 Right ts -> ts
66-- | Used to start a fresh database state for a new database context expression.
51-- | Used to start a fresh database state for a new database context expression.
67−mkDatabaseContextEvalState :: DatabaseContext -> DatabaseContextEvalState
52+freshDatabaseState :: DatabaseContext -> DatabaseStateElems
68−mkDatabaseContextEvalState context = DatabaseContextEvalState {
53+freshDatabaseState context = DatabaseStateElems {
69− dbc_context = context,
54+ context = context,
70− dbc_accum = M.empty,
55+ accum = M.empty,
71− dbc_dirty = False
56+ dirty = False
72 } --future work: propagate return accumulator
57 } --future work: propagate return accumulator
74-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
59-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
75−data RelationalExprEnv = RelationalExprEnv {
60+data RelationalExprStateElems = RelationalExprStateTupleElems
76− re_context :: DatabaseContext,
61+ DatabaseContext
77− re_graph :: TransactionGraph,
62+ TransactionGraph
78− re_extra :: Maybe (Either RelationTuple Attributes)
63+ Maybe (Either RelationTuple Attributes)
80−
65+data RelationalExprStateElems = RelationalExprStateTupleElems DatabaseContext RelationTuple | -- used when fully evaluating a relexpr
81−envTuple :: GraphRefRelationalExprEnv -> RelationTuple
66+ RelationalExprStateAttrsElems DatabaseContext Attributes | --used when evaluating the type of a relexpr
82−envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
67+ RelationalExprStateElems DatabaseContext --used by default at the top level of evaluation
84−envAttributes :: GraphRefRelationalExprEnv -> Attributes
69+instance Show RelationalExprStateElems where
85−envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
70+ show (RelationalExprStateTupleElems _ tup) = "RelationalExprStateTupleElems " ++ show tup
71+ show (RelationalExprStateAttrsElems _ attrs) = "RelationalExprStateAttrsElems" ++ show attrs
72+ show (RelationalExprStateElems _) = "RelationalExprStateElems"
74+mkRelationalExprState :: DatabaseContext -> RelationalExprStateElems
75+mkRelationalExprState = RelationalExprStateElems
77+mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprStateElems -> RelationalExprStateElems
78+mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateElems ctx) = RelationalExprStateTupleElems ctx tupIn
79+mergeTuplesIntoRelationalExprState _ st@(RelationalExprStateAttrsElems _ _) = st
80+mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateTupleElems ctx existingTuple) = let mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap existingTuple) in
81+ RelationalExprStateTupleElems ctx (mkRelationTupleFromMap mergedTupMap)
87−instance Show RelationalExprEnv where
83+mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprStateElems -> RelationalExprStateElems
88− show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
84+mergeAttributesIntoRelationalExprState attrs (RelationalExprStateElems ctx) = RelationalExprStateAttrsElems ctx attrs
89−
85+mergeAttributesIntoRelationalExprState _ st@(RelationalExprStateTupleElems _ _) = st
90−--used to eval relationalexpr
86+mergeAttributesIntoRelationalExprState attrsIn (RelationalExprStateAttrsElems ctx attrs) = RelationalExprStateAttrsElems ctx (A.union attrsIn attrs)
91−type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
93−runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
94−runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
96−reGraph :: RelationalExprM TransactionGraph
97−reGraph = asks re_graph
99−reContext :: RelationalExprM DatabaseContext
100−reContext = asks re_context
102−mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
103−mkRelationalExprEnv ctx graph =
107− re_extra = Nothing }
109−askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
112−mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
113−mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
114− env { gre_extra = new_elems }
116− new_elems = Just (Left newTuple)
117− mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
118− newTuple = mkRelationTupleFromMap mergedTupMap
120−mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
121−mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
123− newattrs = Just (Right (A.union attrsIn (envAttributes e)))
125type ResultAccumName = StringType
88type ResultAccumName = StringType
@@ -130,403 +93,443 @@ data ResultAccum = ResultAccum { resultAccumFunc :: ResultAccumFunc,
130 resultAccumResult :: Relation
93 resultAccumResult :: Relation
133−data DatabaseContextEvalState = DatabaseContextEvalState {
96+data DatabaseStateElems = DatabaseStateElems {
134− dbc_context :: DatabaseContext, --new, alterable context for a new transaction
97+ context :: DatabaseContext, --new, alterable context for a new transaction
135− dbc_accum :: M.Map ResultAccumName ResultAccum,
98+ accum :: M.Map ResultAccumName ResultAccum,
136− dbc_dirty :: DirtyFlag
99+ dirty :: DirtyFlag
139−data DatabaseContextEvalEnv = DatabaseContextEvalEnv
102+type DatabaseState a = State DatabaseStateElems a
140− { dce_transId :: TransactionId,
141− dce_graph :: TransactionGraph
144−mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
145−mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
147−type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
149−runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
104+getStateContext :: DatabaseState DatabaseContext
150−runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
105+getStateContext = context <$> get
152− freshEnv = mkDatabaseContextEvalState ctx
155−dbcTransId :: DatabaseContextEvalMonad TransactionId
156−dbcTransId = dce_transId <$> RWS.ask
158−dbcGraph :: DatabaseContextEvalMonad TransactionGraph
159−dbcGraph = dce_graph <$> RWS.ask
161−dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
162−dbcRelationalExprEnv =
163− mkRelationalExprEnv <$> getStateContext <*> dbcGraph
165−getStateContext :: DatabaseContextEvalMonad DatabaseContext
166−getStateContext = gets dbc_context
168−putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
107+putStateContext :: DatabaseContext -> DatabaseState ()
169putStateContext ctx' = do
108putStateContext ctx' = do
171− put (s {dbc_context = ctx', dbc_dirty = True})
110+ put (s {context = ctx'})
173−-- | The context is optionally passed down along in cases where the current context is uncommitted.
174−data GraphRefRelationalExprEnv =
175− GraphRefRelationalExprEnv {
176− gre_context :: Maybe DatabaseContext,
177− gre_graph :: TransactionGraph,
178− gre_extra :: Maybe (Either RelationTuple Attributes)
181−type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
112+type RelationalExprState a = Reader RelationalExprStateElems a
183−gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
114+stateElemsContext :: RelationalExprStateElems -> DatabaseContext
184−gfTransForId tid = do
115+stateElemsContext (RelationalExprStateTupleElems ctx _) = ctx
185− graph <- gfGraph
116+stateElemsContext (RelationalExprStateElems ctx) = ctx
186− lift $ except $ transactionForId tid graph
117+stateElemsContext (RelationalExprStateAttrsElems ctx _) = ctx
188−gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
119+setStateElemsContext :: RelationalExprStateElems -> DatabaseContext -> RelationalExprStateElems
189−gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
120+setStateElemsContext (RelationalExprStateTupleElems _ tup) ctx = RelationalExprStateTupleElems ctx tup
190−gfDatabaseContextForMarker UncommittedContextMarker = do
121+setStateElemsContext (RelationalExprStateElems _) ctx = RelationalExprStateElems ctx
191− mctx <- gre_context <$> askEnv
122+setStateElemsContext (RelationalExprStateAttrsElems _ attrs) ctx = RelationalExprStateAttrsElems ctx attrs
193− Nothing -> throwError NoUncommittedContextInEvalError
124+--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
194− Just ctx -> pure ctx
125+evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
195−
126+evalRelationalExpr (RelationVariable name _) = do
196−runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
127+ relvarTable <- fmap (relationVariables . stateElemsContext) ask
197−runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
128+ return $ case M.lookup name relvarTable of
198−
129+ Just res -> Right res
199−freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
130+ Nothing -> Left $ RelVarNotDefinedError name
200−freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
131+
201− gre_context = mctx,
132+evalRelationalExpr (Project attrNames expr) = do
202− gre_graph = graph,
133+ eAttrNameSet <- evalAttributeNames attrNames expr
203− gre_extra = Nothing
134+ case eAttrNameSet of
204− }
135+ Left err -> pure (Left err)
205−
136+ Right attrNameSet -> do
206−gfGraph :: GraphRefRelationalExprM TransactionGraph
137+ rel <- evalRelationalExpr expr
207−gfGraph = asks gre_graph
138+ case rel of
139+ Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
140+ Left err -> pure $ Left err
142+evalRelationalExpr (Union exprA exprB) = do
143+ relA <- evalRelationalExpr exprA
144+ relB <- evalRelationalExpr exprB
146+ Left err -> return $ Left err
147+ Right relA2 -> case relB of
148+ Left err -> return $ Left err
149+ Right relB2 -> return $ Right (Union relA2 relB2)
151+evalRelationalExpr (Join exprA exprB) = do
152+ relA <- evalRelationalExpr exprA
153+ relB <- evalRelationalExpr exprB
155+ Left err -> return $ Left err
156+ Right relA2 -> case relB of
157+ Left err -> return $ Left err
158+ Right relB2 -> return $ Right (Join relA2 relB2)
160+evalRelationalExpr (Difference exprA exprB) = do
161+ relA <- evalRelationalExpr exprA
162+ relB <- evalRelationalExpr exprB
164+ Left err -> return $ Left err
165+ Right relA2 -> case relB of
166+ Left err -> return $ Left err
167+ Right relB2 -> return $ Right (Difference relA2 relB2)
169+evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
170+ case mkRelation attributeSet tupleSet of
171+ Right rel -> return $ Right (ExistingRelation rel)
172+ Left err -> return $ Left err
174+evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
175+ currentContext <- fmap stateElemsContext ask
176+ let tConss = typeConstructorMapping currentContext
177+ -- if the mAttrExprs is Nothing, then we should attempt to infer the tuple attributes from the first tuple itself- note that this is not always possible
179+ mAttrs <- case mAttrExprs of
181+ Just . A.attributesFromList <$> mapM (either throwE pure . evalAttrExpr tConss) (fromMaybe [] mAttrExprs)
182+ Nothing -> pure Nothing
183+ tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
184+ let attrs = fromMaybe firstTupleAttrs mAttrs
185+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
186+ expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
187+ pure (ExistingRelation expr)
189+evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
209−envContext :: RelationalExprEnv -> DatabaseContext
191+evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
210−envContext = re_context
192+ evald <- evalRelationalExpr relExpr
194+ Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
195+ Left err -> return $ Left err
212−setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
197+evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
213−setEnvContext e ctx = e { re_context = ctx }
198+ eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
199+ case eOldAttrNameSet of
200+ Left err -> pure (Left err)
201+ Right oldAttrNameSet -> do
202+ evald <- evalRelationalExpr relExpr
204+ Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
205+ Left err -> return $ Left err
207+evalRelationalExpr (Ungroup attrName relExpr) = do
208+ evald <- evalRelationalExpr relExpr
210+ Right expr -> return $ Right (Ungroup attrName expr)
211+ Left err -> return $ Left err
213+evalRelationalExpr (Restrict predicateExpr relExpr) = do
214+ evald <- evalRelationalExpr relExpr
215+ ePred <- processRestrictionPredicateExpr predicateExpr
217+ Left err -> return $ Left err
218+ Right expr -> case ePred of
219+ Left err -> pure (Left err)
220+ Right pred -> pure $ Right (Restrict pred expr)
222+evalRelationalExpr (Equals relExprA relExprB) = do
223+ evaldA <- evalRelationalExpr relExprA
224+ evaldB <- evalRelationalExpr relExprB
226+ Left err -> return $ Left err
227+ Right exprA -> case evaldB of
228+ Left err -> return $ Left err
229+ Right exprB -> return $ Right (Equals exprA exprB)
231+evalRelationalExpr (With views mainExpr) = do
234+ let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
235+ Left (RelVarAlreadyDefinedError vname)
237+ case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
238+ (Left err,_) -> Left err
239+ (Right (), (ctx',_,_)) -> Right ctx'
241+ case foldM addScopedView (stateElemsContext rstate) views of
242+ Left err -> return $ Left err
244+ let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprStateElems ctx'')
245+ case evalMainExpr mainExpr of
246+ Left err -> return $ Left err
247+ Right rel -> return $ Right rel
249+--warning: copy-pasta from above- refactor
250+evalRelationalExpr (NotEquals relExprA relExprB) = do
251+ evaldA <- evalRelationalExpr relExprA
252+ evaldB <- evalRelationalExpr relExprB
254+ Left err -> return $ Left err
255+ Right exprA -> case evaldB of
256+ Left err -> return $ Left err
257+ Right exprB -> return $ Right (NotEquals exprA exprB)
259+-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
260+evalRelationalExpr (Extend tupleExpression relExpr) = do
261+ eExpr <- evalRelationalExpr relExpr
263+ Left err -> pure (Left err)
265+ eTupProc <- processExtendTupleExpr tupleExpression
267+ Left err -> pure (Left err)
268+ Right tupProc -> pure (Right (Extend tupProc expr))
215--helper function to process relation variable creation/assignment
270--helper function to process relation variable creation/assignment
216−setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
271+setRelVar :: RelVarName -> GraphRefRelationalExpr -> TransactionId -> TransactionGraph -> DatabaseState (Either RelationalError ())
217−setRelVar relVarName relExpr = do
272+setRelVar relVarName relExpr transId graph = do
218 currentContext <- getStateContext
273 currentContext <- getStateContext
219− --prevent recursive relvar definition by resolving references to relvars in previous states
220− relExpr' <- resolve relExpr
221− let newRelVars = M.insert relVarName relExpr' $ relationVariables currentContext
274+ let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
222 potentialContext = currentContext { relationVariables = newRelVars }
275 potentialContext = currentContext { relationVariables = newRelVars }
223− --optimization: if the relexpr is unchanged, skip the update
224− if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
227− --determine when to check constraints
276+ --determine when to check constraints
228− graph <- dbcGraph
277+
230− case checkConstraints potentialContext tid graph of
278+ case checkConstraints potentialContext transId graph of
231− Left err -> dbErr err
279+ Left err -> pure (Left err)
232− Right _ -> putStateContext potentialContext
281+ putStateContext potentialContext
233−
282+ return (Right ())
234−--fast-path insertion- we already know that the previous relvar validated correctly, so we can validate just the relation that is being inserted for attribute matches- without this, even a single tuple relation inserted causes the entire relation to be re-validated unnecessarily
235−--insertIntoRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
237-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
284-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
238−deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
285+deleteRelVar :: RelVarName -> DatabaseState (Either RelationalError ())
239deleteRelVar relVarName = do
286deleteRelVar relVarName = do
240 currContext <- getStateContext
287 currContext <- getStateContext
241 let relVars = relationVariables currContext
288 let relVars = relationVariables currContext
242 if M.notMember relVarName relVars then
289 if M.notMember relVarName relVars then
243− pure ()
290+ pure (Right ())
245 let newRelVars = M.delete relVarName relVars
292 let newRelVars = M.delete relVarName relVars
246 newContext = currContext { relationVariables = newRelVars }
293 newContext = currContext { relationVariables = newRelVars }
247 putStateContext newContext
294 putStateContext newContext
248− pure ()
295+ pure (Right ())
250−evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContextEvalMonad ()
297+evalDatabaseContextExpr :: DatabaseContextExpr -> TransactionId -> TransactionGraph -> DatabaseState (Either RelationalError ())
251−evalGraphRefDatabaseContextExpr NoOperation = pure ()
298+evalDatabaseContextExpr NoOperation _ _ = pure (Right ())
253−evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
300+evalDatabaseContextExpr (Define relVarName attrExprs) transId graph = do
254− context <- getStateContext
255 relvars <- fmap relationVariables getStateContext
301 relvars <- fmap relationVariables getStateContext
256 tConss <- fmap typeConstructorMapping getStateContext
302 tConss <- fmap typeConstructorMapping getStateContext
257− graph <- dbcGraph
303+ let eAttrs = map (evalAttrExpr tConss) attrExprs
258− let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
304+ attrErrs = lefts eAttrs
259− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
305+ attrsList = rights eAttrs
260− case eAttrs of
306+ if not (null attrErrs) then
261− Left err -> dbErr err
307+ pure (Left (someErrors attrErrs))
262− Right attrsList -> do
308+ else do
263− lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
309+ let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
310+ if not (null atomTypeErrs) then
311+ pure (Left (someErrors atomTypeErrs))
264− case M.member relVarName relvars of
313+ case M.member relVarName relvars of
265− True -> dbErr (RelVarAlreadyDefinedError relVarName)
314+ True -> pure (Left (RelVarAlreadyDefinedError relVarName))
266− False -> setRelVar relVarName (ExistingRelation emptyRelation)
315+ False -> setRelVar relVarName (ExistingRelation emptyRelation) transId graph >> pure (Right ())
268 attrs = A.attributesFromList attrsList
317 attrs = A.attributesFromList attrsList
269 emptyRelation = Relation attrs emptyTupleSet
318 emptyRelation = Relation attrs emptyTupleSet
271−evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
320+evalDatabaseContextExpr (Undefine relVarName) _ _ = deleteRelVar relVarName
273−evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
322+evalDatabaseContextExpr (Assign relVarName expr) transId graph = do
274− graph <- re_graph <$> dbcRelationalExprEnv
275 context <- getStateContext
323 context <- getStateContext
276 let existingRelVar = M.lookup relVarName (relationVariables context)
324 let existingRelVar = M.lookup relVarName (relationVariables context)
277− reEnv = freshGraphRefRelationalExprEnv (Just context) graph
325+ relExprState = mkRelationalExprState context
278− eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
279 case existingRelVar of
326 case existingRelVar of
280 Nothing -> do
327 Nothing -> do
281− case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
328+ let ervExpr = runReader (evalRelationalExpr expr) relExprState
282− Left err -> dbErr err
330+ Left err -> pure (Left err)
284− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
285− setRelVar relVarName expr
331+ Right rvExpr -> setRelVar relVarName rvExpr transId graph
286 Just existingRel -> do
332 Just existingRel -> do
287− let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
333+ let eExpectedType = typeForGraphRefRelationalExpr existingRel graph
334+ eNewExprType = runReader (typeForRelationalExpr expr transId graph) relExprState
288 case eExpectedType of
335 case eExpectedType of
289− Left err -> dbErr err
336+ Left err -> pure (Left err)
290 Right expectedType ->
337 Right expectedType ->
291 case eNewExprType of
338 case eNewExprType of
292− Left err -> dbErr err
339+ Left err -> pure (Left err)
293 Right newExprType -> do
340 Right newExprType -> do
294 if newExprType == expectedType then do
341 if newExprType == expectedType then do
295− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
342+ let ervExpr = runReader (evalRelationalExpr expr) relExprState
344+ Left err -> pure (Left err)
296− setRelVar relVarName expr
345+ Right rvExpr -> setRelVar relVarName rvExpr transId graph
298− dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
347+ pure (Left (RelationTypeMismatchError (attributes expectedType) (attributes newExprType)))
300−evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
349+evalDatabaseContextExpr (Insert relVarName relExpr) tid graph =
301− gfExpr <- relVarByName relVarName
350+ evalDatabaseContextExpr (Assign relVarName (Union (RelationVariable relVarName ())
302− let optExpr = applyUnionCollapse (Union
351+ relExpr)) tid graph
305− evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
307−evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
353+evalDatabaseContextExpr (Delete relVarName predicate) transId graph = do
308− gfExpr <- relVarByName relVarName
354+ ctx <- getStateContext
309− let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
355+ let rv = RelationVariable relVarName transId
310− setRelVar relVarName optExpr
356+ rvState = mkRelationalExprState ctx
357+ case runReader (processRestrictionPredicateExpr predicate) rvState of
358+ Left err -> pure (Left err)
359+ Right graphRefPredicate ->
360+ setRelVar relVarName (Restrict (NotPredicate graphRefPredicate) rv) transId graph
312--union of restricted+updated portion and the unrestricted+unupdated portion
362--union of restricted+updated portion and the unrestricted+unupdated portion
313−evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
363+evalDatabaseContextExpr (Update relVarName atomExprMap restrictionPredicateExpr) transId graph = do
314− rvExpr <- relVarByName relVarName
315− graph <- re_graph <$> dbcRelationalExprEnv
316 context <- getStateContext
364 context <- getStateContext
317− let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
365+ let rvState = mkRelationalExprState context
318− --get the current attributes name in the relvar to ensure that we don't conflict when renaming
366+ relVarTable = relationVariables context
319− eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
367+ case runReader (processRestrictionPredicateExpr restrictionPredicateExpr) rvState of
320− exprType' <- case eExprType of
368+ Left err -> pure (Left err)
321− Left err -> throwError err
369+ Right graphRefPredicate ->
322− Right t -> pure t
370+ case M.lookup relVarName relVarTable of
323− let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
371+ Nothing -> pure (Left (RelVarNotDefinedError relVarName))
324− tmpAttr = tmpAttrC 1
372+ Just existingRvExpr -> do
325− tmpAttrC :: Int -> AttributeName -> AttributeName
373+ let unrestrictedPortion = Restrict (NotPredicate graphRefPredicate) rv
326− tmpAttrC c attr =
374+ rv = RelationVariable relVarName transId
327− let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
375+ tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
328− if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
332− updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
376+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
333− projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
377+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
334− restrictedPortion = Restrict pred' rvExpr
378+ restrictedPortion = Restrict graphRefPredicate
335− updated = foldr (\(oldname, atomExpr) accum ->
379+ updated = foldr (\(oldname, atomExpr) accum ->
336− let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
380+ let procAtomExpr = processAtomExpr atomExpr transId in
337 updateAttr oldname procAtomExpr accum
381 updateAttr oldname procAtomExpr accum
338− ) restrictedPortion (M.toList atomExprMap)
382+ ) rv (M.toList atomExprMap)
339 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
383 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
340− updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
384+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
341− setRelVar relVarName (Union unrestrictedPortion updatedPortion)
385+ setRelVar relVarName (Union unrestrictedPortion updatedPortion) transId graph
343−evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
387+evalDatabaseContextExpr (AddInclusionDependency newDepName newDep) transId graph = do
344 currContext <- getStateContext
388 currContext <- getStateContext
345− transId <- dbcTransId
347 let currDeps = inclusionDependencies currContext
389 let currDeps = inclusionDependencies currContext
348 newDeps = M.insert newDepName newDep currDeps
390 newDeps = M.insert newDepName newDep currDeps
349 if M.member newDepName currDeps then
391 if M.member newDepName currDeps then
350− dbErr (InclusionDependencyNameInUseError newDepName)
392+ pure (Left (InclusionDependencyNameInUseError newDepName))
352 let potentialContext = currContext { inclusionDependencies = newDeps }
394 let potentialContext = currContext { inclusionDependencies = newDeps }
353− -- if the potential context passes all constraints, then save it
354− -- potential optimization: validate only the new constraint- all old constraints must already hold
355 case checkConstraints potentialContext transId graph of
395 case checkConstraints potentialContext transId graph of
356− Left err -> dbErr err
396+ Left err -> pure (Left err)
357− Right _ ->
397+ Right _ -> do
358 putStateContext potentialContext
398 putStateContext potentialContext
360−evalGraphRefDatabaseContextExpr (RemoveInclusionDependency depName) = do
401+evalDatabaseContextExpr (RemoveInclusionDependency depName) _ _ = do
361 currContext <- getStateContext
402 currContext <- getStateContext
362 let currDeps = inclusionDependencies currContext
403 let currDeps = inclusionDependencies currContext
363 newDeps = M.delete depName currDeps
404 newDeps = M.delete depName currDeps
364 if M.notMember depName currDeps then
405 if M.notMember depName currDeps then
365− dbErr (InclusionDependencyNameNotInUseError depName)
406+ pure (Left (InclusionDependencyNameNotInUseError depName))
367 putStateContext $ currContext {inclusionDependencies = newDeps }
408 putStateContext $ currContext {inclusionDependencies = newDeps }
369-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
411-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
370−evalGraphRefDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
412+evalDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) _ _ = do
371 currentContext <- getStateContext
413 currentContext <- getStateContext
372 let nots = notifications currentContext
414 let nots = notifications currentContext
373 if M.member notName nots then
415 if M.member notName nots then
374− dbErr (NotificationNameInUseError notName)
416+ pure (Left (NotificationNameInUseError notName))
376 let newNotifications = M.insert notName newNotification nots
418 let newNotifications = M.insert notName newNotification nots
377 newNotification = Notification { changeExpr = triggerExpr,
419 newNotification = Notification { changeExpr = triggerExpr,
378 reportOldExpr = resultOldExpr,
420 reportOldExpr = resultOldExpr,
379 reportNewExpr = resultNewExpr}
421 reportNewExpr = resultNewExpr}
380 putStateContext $ currentContext { notifications = newNotifications }
422 putStateContext $ currentContext { notifications = newNotifications }
382−evalGraphRefDatabaseContextExpr (RemoveNotification notName) = do
425+evalDatabaseContextExpr (RemoveNotification notName) _ _ = do
383 currentContext <- getStateContext
426 currentContext <- getStateContext
384 let nots = notifications currentContext
427 let nots = notifications currentContext
385 if M.notMember notName nots then
428 if M.notMember notName nots then
386− dbErr (NotificationNameNotInUseError notName)
429+ pure (Left (NotificationNameNotInUseError notName))
388 let newNotifications = M.delete notName nots
431 let newNotifications = M.delete notName nots
389 putStateContext $ currentContext { notifications = newNotifications }
432 putStateContext $ currentContext { notifications = newNotifications }
392-- | Adds type and data constructors to the database context.
435-- | Adds type and data constructors to the database context.
393-- validate that the type *and* constructor names are unique! not yet implemented!
436-- validate that the type *and* constructor names are unique! not yet implemented!
394−evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
437+evalDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) _ _ = do
395 currentContext <- getStateContext
438 currentContext <- getStateContext
396 let oldTypes = typeConstructorMapping currentContext
439 let oldTypes = typeConstructorMapping currentContext
397 tConsName = TCD.name tConsDef
440 tConsName = TCD.name tConsDef
398 -- validate that the constructor's types exist
441 -- validate that the constructor's types exist
399− case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
442+ case validateTypeConstructorDef tConsDef dConsDefList of
400− Left err -> throwError err
443+ errs@(_:_) -> pure (Left (someErrors errs))
401− Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
444+ [] | T.null tConsName || not (isUpper (T.head tConsName)) -> pure (Left (InvalidAtomTypeName tConsName))
402− | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
445+ | isJust (findTypeConstructor tConsName oldTypes) -> pure (Left (AtomTypeNameInUseError tConsName))
403 | otherwise -> do
446 | otherwise -> do
404 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
447 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
405 putStateContext $ currentContext { typeConstructorMapping = newTypes }
448 putStateContext $ currentContext { typeConstructorMapping = newTypes }
407-- | Removing the atom constructor prevents new atoms of the type from being created. Existing atoms of the type remain. Thus, the atomTypes list in the DatabaseContext need not be all-inclusive.
451-- | Removing the atom constructor prevents new atoms of the type from being created. Existing atoms of the type remain. Thus, the atomTypes list in the DatabaseContext need not be all-inclusive.
408−evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
452+evalDatabaseContextExpr (RemoveTypeConstructor tConsName) _ _ = do
409 currentContext <- getStateContext
453 currentContext <- getStateContext
410 let oldTypes = typeConstructorMapping currentContext
454 let oldTypes = typeConstructorMapping currentContext
411 if isNothing (findTypeConstructor tConsName oldTypes) then
455 if isNothing (findTypeConstructor tConsName oldTypes) then
412− dbErr (AtomTypeNameNotInUseError tConsName)
456+ pure (Left (AtomTypeNameNotInUseError tConsName))
414 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
458 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
415 putStateContext $ currentContext { typeConstructorMapping = newTypes }
459 putStateContext $ currentContext { typeConstructorMapping = newTypes }
417−evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
462+evalDatabaseContextExpr (MultipleExpr exprs) transId graph = do
418 --the multiple expressions must pass the same context around- not the old unmodified context
463 --the multiple expressions must pass the same context around- not the old unmodified context
419− mapM_ evalGraphRefDatabaseContextExpr exprs
464+ evald <- forM exprs (\expr -> evalDatabaseContextExpr expr transId graph)
420−
465+ --some lifting magic needed here
467+ [] -> pure (Right ())
468+ errs -> pure (Left (someErrors errs))
421−evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
470+evalDatabaseContextExpr (RemoveAtomFunction funcName) _ _ = do
422 currentContext <- getStateContext
471 currentContext <- getStateContext
423 let atomFuncs = atomFunctions currentContext
472 let atomFuncs = atomFunctions currentContext
424 case atomFunctionForName funcName atomFuncs of
473 case atomFunctionForName funcName atomFuncs of
425− Left err -> dbErr err
474+ Left err -> pure (Left err)
427− if isScriptedAtomFunction realFunc then do
475+ Right realFunc -> if isScriptedAtomFunction realFunc then do
428− let updatedFuncs = HS.delete realFunc atomFuncs
476+ let updatedFuncs = HS.delete realFunc atomFuncs
429− putStateContext (currentContext {atomFunctions = updatedFuncs })
477+ putStateContext (currentContext {atomFunctions = updatedFuncs })
431− dbErr (PrecompiledFunctionRemoveError funcName)
480+ pure (Left (PrecompiledFunctionRemoveError funcName))
433−evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
482+evalDatabaseContextExpr (RemoveDatabaseContextFunction funcName) _ _ = do
434 context <- getStateContext
483 context <- getStateContext
435 let dbcFuncs = dbcFunctions context
484 let dbcFuncs = dbcFunctions context
436 case databaseContextFunctionForName funcName dbcFuncs of
485 case databaseContextFunctionForName funcName dbcFuncs of
437− Left err -> dbErr err
486+ Left err -> pure (Left err)
439− if isScriptedDatabaseContextFunction realFunc then do
487+ Right realFunc -> if isScriptedDatabaseContextFunction realFunc then do
440− let updatedFuncs = HS.delete realFunc dbcFuncs
488+ let updatedFuncs = HS.delete realFunc dbcFuncs
441− putStateContext (context { dbcFunctions = updatedFuncs })
489+ putStateContext (context { dbcFunctions = updatedFuncs })
443− dbErr (PrecompiledFunctionRemoveError funcName)
492+ pure (Left (PrecompiledFunctionRemoveError funcName))
445−evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
494+evalDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) _ _ = do
446 context <- getStateContext
495 context <- getStateContext
448 --resolve atom arguments
496 --resolve atom arguments
449− let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
497+ let relExprState = mkRelationalExprState context
498+ eAtomTypes = map (\atomExpr -> runReader (typeFromAtomExpr emptyAttributes atomExpr) relExprState) atomArgExprs
450 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
499 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
451− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
452 case eFunc of
500 case eFunc of
453− Left err -> dbErr err
501+ Left err -> pure (Left err)
454 Right func -> do
502 Right func -> do
455 let expectedArgCount = length (dbcFuncType func)
503 let expectedArgCount = length (dbcFuncType func)
456 actualArgCount = length atomArgExprs
504 actualArgCount = length atomArgExprs
457 if expectedArgCount /= actualArgCount then
505 if expectedArgCount /= actualArgCount then
458− dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
506+ pure (Left (FunctionArgumentCountMismatchError expectedArgCount actualArgCount))
460 --check that the atom types are valid
508 --check that the atom types are valid
461− case eAtomTypes of
509+ case lefts eAtomTypes of
462− Left err -> dbErr err
510+ _:_ -> pure (Left (someErrors (lefts eAtomTypes)))
463− Right atomTypes -> do
511+ [] -> do
464− let mValidTypes = zipWith (\ expType actType
512+ let atomTypes = rights eAtomTypes
465− -> case atomTypeVerify expType actType of
513+ let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
466− Left err -> Just err
514+ Left err -> Just err
468− (dbcFuncType func) atomTypes
515+ Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
469− typeErrors = catMaybes mValidTypes
516+ typeErrors = catMaybes mValidTypes
470− eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
517+ eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
471 if length (lefts eAtomArgs) > 1 then
518 if length (lefts eAtomArgs) > 1 then
472− dbErr (someErrors (lefts eAtomArgs))
519+ pure (Left (someErrors (lefts eAtomArgs)))
473 else if not (null typeErrors) then
520 else if not (null typeErrors) then
474− dbErr (someErrors typeErrors)
521+ pure (Left (someErrors typeErrors))
476 case evalDatabaseContextFunction func (rights eAtomArgs) context of
523 case evalDatabaseContextFunction func (rights eAtomArgs) context of
477− Left err -> dbErr err
524+ Left err -> pure (Left err)
478− Right newContext -> putStateContext newContext
525+ Right newContext -> putStateContext newContext >> pure (Right ())
479−data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
526+
480− { dbcio_transId :: TransactionId,
527+evalDatabaseContextIOExpr :: Maybe ScriptSession -> DatabaseContext -> TransactionId -> TransactionGraph -> DatabaseContextIOExpr -> IO (Either RelationalError DatabaseContext)
481− dbcio_graph :: TransactionGraph,
482− dbcio_mScriptSession :: Maybe ScriptSession
485−type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
487−runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
488−runDatabaseContextIOEvalMonad env ctx m = do
489− res <- runRWST m env freshState
491− (Left err,_,_) -> pure (Left err)
492− (Right (),s,_) -> pure (Right s)
494− freshState = mkDatabaseContextEvalState ctx
496−requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
497−requireScriptSession = do
499− case dbcio_mScriptSession env of
500− Nothing -> pure $ Left $ ScriptError ScriptCompilationDisabledError
501− Just ss -> pure (Right ss)
503−putDBCIOContext :: DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ())
504−putDBCIOContext ctx = do
505− RWS.modify (\dbstate -> dbstate { dbc_context = ctx})
508−getDBCIOContext :: DatabaseContextIOEvalMonad DatabaseContext
509−getDBCIOContext = dbc_context <$> RWS.get
511−getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
512−getDBCIORelationalExprEnv = do
513− context <- getDBCIOContext
514− mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
516−evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
517−#if !defined(PM36_HASKELL_SCRIPTING)
518−evalGraphRefDatabaseContextIOExpr AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
519−evalGraphRefDatabaseContextIOExpr AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
520−evalGraphRefDatabaseContextIOExpr LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
521−evalGraphRefDatabaseContextIOExpr LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
523−evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
528+evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddAtomFunction funcName funcType script) =
524− eScriptSession <- requireScriptSession
529+ case mScriptSession of
525− currentContext <- getDBCIOContext
530+ Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
526− case eScriptSession of
527− Left err -> pure (Left err)
528− Right scriptSession -> do
531+ Just scriptSession -> do
529− res <- liftIO $ try $ runGhc (Just libdir) $ do
532+ res <- try $ runGhc (Just libdir) $ do
530 setSession (hscEnv scriptSession)
533 setSession (hscEnv scriptSession)
531 let atomFuncs = atomFunctions currentContext
534 let atomFuncs = atomFunctions currentContext
532 case extractAtomFunctionType funcType of
535 case extractAtomFunctionType funcType of
@@ -552,13 +555,12 @@ evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = d
552 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
555 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
553 Right eContext -> case eContext of
556 Right eContext -> case eContext of
554 Left err -> pure (Left err)
557 Left err -> pure (Left err)
555− Right context' -> putDBCIOContext context'
558+ Right context' -> pure (Right context')
556−evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
560+evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddDatabaseContextFunction funcName funcType script) =
557− eScriptSession <- requireScriptSession
561+ case mScriptSession of
558− currentContext <- getDBCIOContext
562+ Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
559− case eScriptSession of
560− Left err -> pure (Left err)
561− Right scriptSession -> do
563+ Just scriptSession -> do
562 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
564 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
563 let last2Args = reverse (take 2 (reverse funcType))
565 let last2Args = reverse (take 2 (reverse funcType))
564 atomArgs = take (length funcType - 2) funcType
566 atomArgs = take (length funcType - 2) funcType
@@ -568,7 +570,7 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
568 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
570 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
569 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
571 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
571− res <- liftIO $ try $ runGhc (Just libdir) $ do
573+ res <- try $ runGhc (Just libdir) $ do
572 setSession (hscEnv scriptSession)
574 setSession (hscEnv scriptSession)
573 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
575 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
574 pure $ case eCompiledFunc of
576 pure $ case eCompiledFunc of
@@ -593,86 +595,78 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
593 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
595 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
594 Right eContext -> case eContext of
596 Right eContext -> case eContext of
595 Left err -> pure (Left err)
597 Left err -> pure (Left err)
596− Right context' -> putDBCIOContext context'
598+ Right context' -> pure (Right context')
597−evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
599+evalDatabaseContextIOExpr _ currentContext _ _ (LoadAtomFunctions modName funcName modPath) = do
598− currentContext <- getDBCIOContext
599− eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
600+ eLoadFunc <- loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
600 case eLoadFunc of
601 case eLoadFunc of
601 Left LoadSymbolError -> pure (Left LoadFunctionError)
602 Left LoadSymbolError -> pure (Left LoadFunctionError)
602 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
603 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
603 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
604 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
604− in putDBCIOContext newContext
605+ in pure (Right newContext)
605−evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName modPath) = do
606+evalDatabaseContextIOExpr _ currentContext _ _ (LoadDatabaseContextFunctions modName funcName modPath) = do
606− currentContext <- getDBCIOContext
607− eLoadFunc <- liftIO $ loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
607+ eLoadFunc <- loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
608 case eLoadFunc of
608 case eLoadFunc of
609 Left LoadSymbolError -> pure (Left LoadFunctionError)
609 Left LoadSymbolError -> pure (Left LoadFunctionError)
610 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
610 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
611 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
611 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
612− in putDBCIOContext newContext
612+ in pure (Right newContext)
614−evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
614+evalDatabaseContextIOExpr _ currentContext transId graph (CreateArbitraryRelation relVarName attrExprs range) =
616− currentContext <- getDBCIOContext
616+ case runState (evalDatabaseContextExpr (Define relVarName attrExprs) transId graph) (freshDatabaseState currentContext) of
618− --create graph ref expr
619− let gfExpr = Define relVarName attrExprs
620− evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
621− graph = dbcio_graph env
622− case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
623− Left err -> pure (Left err)
617+ (Left err,_) -> pure (Left err)
624− Right dbstate -> do
618+ (Right (), elems) -> do
626 let existingRelVar = M.lookup relVarName relVarTable
620 let existingRelVar = M.lookup relVarName relVarTable
627− relVarTable = relationVariables (dbc_context dbstate)
621+ relVarTable = relationVariables (context elems)
628 case existingRelVar of
622 case existingRelVar of
629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
623 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
630 Just existingRel -> do
624 Just existingRel -> do
631− let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
632− case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
625+ case typeForGraphRefRelationalExpr existingRel graph of
633 Left err -> pure (Left err)
626 Left err -> pure (Left err)
634 Right relType -> do
627 Right relType -> do
635 let expectedAttributes = attributes relType
628 let expectedAttributes = attributes relType
636− tcMap = typeConstructorMapping (dbc_context dbstate)
629+ tcMap = typeConstructorMapping (context elems)
637− eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
630+ eitherRel <- generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
638 case eitherRel of
631 case eitherRel of
639 Left err -> pure $ Left err
632 Left err -> pure $ Left err
640 Right rel ->
633 Right rel ->
641− case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
634+ case runState (setRelVar relVarName (ExistingRelation rel) transId graph) elems of
642− Left err -> pure (Left err)
635+ (Left err,_) -> pure (Left err)
643− Right dbstate' -> putDBCIOContext (dbc_context dbstate')
636+ (Right (), elems') -> pure $ Right (context elems)
638+updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> RelationTuple -> Either RelationalError RelationTuple
639+updateTupleWithAtomExprs exprMap context tupIn = do
640+ --resolve all atom exprs
641+ atomsAssoc <- mapM (\(attrName, atomExpr) -> do
642+ atom <- runReader (evalAtomExpr tupIn atomExpr) (RelationalExprStateElems context)
643+ pure (attrName, atom)
644+ ) (M.toList exprMap)
645+ pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
645--run verification on all constraints
647--run verification on all constraints
646checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
648checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
647−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
649+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
648 mapM_ (uncurry checkIncDep) (M.toList deps)
650 mapM_ (uncurry checkIncDep) (M.toList deps)
650 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
652 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
651 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
653 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
652 utctDayTime = secondsToDiffTime 0 }
654 utctDayTime = secondsToDiffTime 0 }
653 tempSchemas = Schemas context M.empty
655 tempSchemas = Schemas context M.empty
654− tempTrans = Transaction U.nil tempTransInfo tempSchemas
655− tempTransInfo = TransactionInfo { parents = transId NE.:| [],
656+ tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
660 deps = inclusionDependencies context
658 deps = inclusionDependencies context
661− -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
659+ eval expr = evalReader (evalRelationalExpr expr)
660+ evalReader f = runReader f (RelationalExprStateElems context)
662 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
661 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
663− let process = runProcessExprM UncommittedContextMarker
664− gfSubsetExpr = process (processRelationalExpr subsetExpr)
662+ let gfSubsetExpr = processRelationalExpr subsetExpr transId
665− gfSupersetExpr = process (processRelationalExpr supersetExpr)
663+ gfSupersetExpr = processRelationalExpr supersetExpr transId
666 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
664 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
667− let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
665+ typeSub <- evalReader (typeForRelationalExpr subsetExpr transId graph)
668− runGfRel = runGraphRefRelationalExprM gfEnv
666+ typeSuper <- evalReader (typeForRelationalExpr supersetExpr transId graph)
669− typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
670− typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
671 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
667 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
672 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
668 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
673− gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
669+ case evalGraphRefRelationalExpr checkExpr potentialGraph of
674− gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
676 Left err -> Left err
670 Left err -> Left err
677 Right resultRel -> if resultRel == relationTrue then
671 Right resultRel -> if resultRel == relationTrue then
@@ -682,81 +676,90 @@ checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
682-- the type of a relational expression is equal to the relation attribute set returned from executing the relational expression; therefore, the type can be cheaply derived by evaluating a relational expression and ignoring and tuple processing
676-- the type of a relational expression is equal to the relation attribute set returned from executing the relational expression; therefore, the type can be cheaply derived by evaluating a relational expression and ignoring and tuple processing
683-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
677-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
685−typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
679+typeForRelationalExpr :: RelationalExpr -> TransactionId -> TransactionGraph -> RelationalExprState (Either RelationalError Relation)
686−typeForRelationalExpr expr = do
680+typeForRelationalExpr expr transId graph = do
682+ let context = stateElemsContext rstate
687 --replace the relationVariables context element with a cloned set of relation devoid of tuples
683 --replace the relationVariables context element with a cloned set of relation devoid of tuples
688 --evalRelationalExpr could still return an existing relation with tuples, so strip them
684 --evalRelationalExpr could still return an existing relation with tuples, so strip them
690− context <- reContext
691− let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
685+ let gfExpr = processRelationalExpr expr transId
692− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
693− runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
686+ pure (typeForGraphRefRelationalExpr gfExpr graph)
694− lift $ except runGf
687+
688+--returns a database context with all tuples removed
689+--this is useful for type checking and optimization
691+contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
692+contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
694+ relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
696liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
697liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
697liftE v = do
698liftE v = do
698 y <- lift v
699 y <- lift v
699 case y of
700 case y of
700− Left err -> throwError err
701+ Left err -> throwE err
701 Right val -> pure val
702 Right val -> pure val
703{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
704{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
704−predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
705+predicateRestrictionFilter :: Attributes -> RestrictionPredicateExprBase a -> RelationalExprState (Either RelationalError RestrictionFilter)
705−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
706+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
706− expr1v <- predicateRestrictionFilter attrs expr1
708+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
707− expr2v <- predicateRestrictionFilter attrs expr2
709+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
708− pure (\x -> do
710+ pure (\x -> do
709− ev1 <- expr1v x
711+ ev1 <- expr1v x
710− ev2 <- expr2v x
712+ ev2 <- expr2v x
711− pure (ev1 && ev2))
713+ pure (ev1 && ev2))
713−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
715+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
714− expr1v <- predicateRestrictionFilter attrs expr1
717+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
715− expr2v <- predicateRestrictionFilter attrs expr2
718+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
716 pure (\x -> do
719 pure (\x -> do
717 ev1 <- expr1v x
720 ev1 <- expr1v x
718 ev2 <- expr2v x
721 ev2 <- expr2v x
719 pure (ev1 || ev2))
722 pure (ev1 || ev2))
721−predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
724+predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
723−predicateRestrictionFilter attrs (NotPredicate expr) = do
726+predicateRestrictionFilter attrs (NotPredicate expr) =
724− exprv <- predicateRestrictionFilter attrs expr
728+ exprv <- liftE (predicateRestrictionFilter attrs expr)
725− pure (fmap not . exprv)
729+ pure (fmap not . exprv)
727--optimization opportunity: if the subexpression does not reference attributes in the top-level expression, then it need only be evaluated once, statically, outside the tuple filter- see historical implementation here
731--optimization opportunity: if the subexpression does not reference attributes in the top-level expression, then it need only be evaluated once, statically, outside the tuple filter- see historical implementation here
728predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
732predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
729− renv <- askEnv
733+ rstate <- ask
730− let eval :: RelationTuple -> Either RelationalError Relation
734+ pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
732− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
733− runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
734− pure (\tup -> case eval tup of
735 Left err -> Left err
735 Left err -> Left err
736 Right rel -> if arity rel /= 0 then
736 Right rel -> if arity rel /= 0 then
737 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
737 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
739− pure (rel == relationTrue))
739+ pure (rel == relationTrue)))
741predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
741predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
742− env <- askEnv
742+ rstate <- ask
743− let attrs' = A.union attrs (envAttributes env)
743+ let (attrs', ctxtup') = case rstate of
744− ctxtup' = envTuple env
744+ RelationalExprStateElems _ -> (attrs, emptyTuple)
745+ RelationalExprStateAttrsElems _ _ -> (attrs, emptyTuple)
746+ RelationalExprStateTupleElems _ ctxtup -> (A.union attrs (tupleAttributes ctxtup), ctxtup)
745− atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
748+ atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
746− attr <- lift $ except $ case A.attributeForName attrName attrs of
749+ attr <- either throwE pure $ case A.attributeForName attrName attrs of
747 Right attr -> Right attr
750 Right attr -> Right attr
748 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
751 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
749 Right ctxattr -> Right ctxattr
752 Right ctxattr -> Right ctxattr
750 Left err2@(NoSuchAttributeNamesError _) -> Left err2
753 Left err2@(NoSuchAttributeNamesError _) -> Left err2
751 Left err -> Left err
754 Left err -> Left err
752 Left err -> Left err
755 Left err -> Left err
753− if atomExprType /= A.atomType attr then
756+ if atomExprType /= A.atomType attr then
754− throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
757+ throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
756 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
759 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
757 Right atomCmp -> atomCmp == atomIn
760 Right atomCmp -> atomCmp == atomIn
758 Left _ -> False
761 Left _ -> False
759− atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
762+ atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
761 pure $ case atomForAttributeName attrName tupleIn of
764 pure $ case atomForAttributeName attrName tupleIn of
762 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
765 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -767,15 +770,16 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
767-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
770-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
768predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
771predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
769 --merge attrs into the state attributes
772 --merge attrs into the state attributes
770− renv <- askEnv
773+ rstate <- ask
771− aType <- typeForGraphRefAtomExpr attrs atomExpr
775+ aType <- liftE (typeFromAtomExpr attrs atomExpr)
772− if aType /= BoolAtomType then
776+ if aType /= BoolAtomType then
773− throwError (AtomTypeMismatchError aType BoolAtomType)
777+ throwE (AtomTypeMismatchError aType BoolAtomType)
775 pure (\tupleIn ->
779 pure (\tupleIn ->
776− case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
780+ case runReader (evalAtomExpr tupleIn atomExpr) rstate of
777− Left err -> Left err
781+ Left err -> Left err
778− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
782+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
780tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
784tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
781tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
785tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
@@ -783,311 +787,249 @@ tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName r
784 Right rel
788 Right rel
786−extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
790+extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
787−extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
791+extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
788−-- renv <- askEnv
792+ rstate <- ask
789 -- check that the attribute name is not in use
793 -- check that the attribute name is not in use
790 case tupleExprCheckNewAttrName newAttrName relIn of
794 case tupleExprCheckNewAttrName newAttrName relIn of
791− Left err -> throwError err
795+ Left err -> pure (Left err)
792− Right _ -> do
796+ Right _ -> runExceptT $ do
793− atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
797+ atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
794− atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
798+ atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
795 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
799 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
796 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
800 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
797− env <- ask
801+ pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in case runReader (evalAtomExpr tup atomExpr) substate of
798− pure (newAndOldAttrs, \tup -> do
802+ Left err -> Left err
799− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
800− atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
801− Right (tupleAtomExtend newAttrName atom tup)
803+ Right atom -> Right (tupleAtomExtend newAttrName atom tup)
804−evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
806+evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
805−evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
806− case atomForAttributeName attrName tupIn of
807+evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
807− Right atom -> pure atom
808+ Right atom -> pure (Right atom)
808− Left err@(NoSuchAttributeNamesError _) -> do
809+ err@(Left (NoSuchAttributeNamesError _)) -> do
809− env <- askEnv
810+ rstate <- ask
810− case gre_extra env of
811+ case rstate of
811− Nothing -> throwError err
812+ RelationalExprStateElems _ -> pure err
813+ RelationalExprStateAttrsElems _ _ -> pure err
812− Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
814+ RelationalExprStateTupleElems _ ctxtup -> pure (atomForAttributeName attrName ctxtup)
813− Just (Right _) -> throwError err
814− Left err -> throwError err
815+ Left err -> pure (Left err)
815−evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
816+evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
816−evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
817+evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
817− argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
818+ argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
818− context <- gfDatabaseContextForMarker tid
819+ context <- fmap stateElemsContext ask
819− let functions = atomFunctions context
821+ let functions = atomFunctions context
820− func <- lift $ except (atomFunctionForName funcName functions)
822+ func <- either throwE pure (atomFunctionForName funcName functions)
821− let expectedArgCount = length (atomFuncType func) - 1
823+ let expectedArgCount = length (atomFuncType func) - 1
822− actualArgCount = length argTypes
824+ actualArgCount = length argTypes
823− safeInit [] = [] -- different behavior from normal init
825+ safeInit [] = [] -- different behavior from normal init
824− safeInit xs = init xs
826+ safeInit xs = init xs
825− if expectedArgCount /= actualArgCount then
827+ if expectedArgCount /= actualArgCount then
826− throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
828+ throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
828 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
830 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
829− mapM_ (\(expType, actType) ->
831+ mapM_ (\(expType, eActType) -> do
832+ actType <- either throwE pure eActType
830− lift $ except (atomTypeVerify expType actType)) zippedArgs
833+ either throwE pure (atomTypeVerify expType actType)) zippedArgs
831− evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
834+ evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
832 case evalAtomFunction func evaldArgs of
835 case evalAtomFunction func evaldArgs of
833− Left err -> throwError (AtomFunctionUserError err)
836+ Left err -> throwE (AtomFunctionUserError err)
834 Right result -> do
837 Right result -> do
835 --validate that the result matches the expected type
838 --validate that the result matches the expected type
836− _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
839+ _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
837 pure result
840 pure result
838−evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
841+evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
839 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
842 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
840− env <- ask
843+ rstate <- ask
841− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
844+ runExceptT $ do
842− relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
845+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
846+ relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
843− pure (RelationAtom relAtom)
847+ pure (RelationAtom relAtom)
844−evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
848+evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
845− let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
849+ rstate <- lift ask
850+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
846− aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
851+ aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
847− argAtoms <- local mergeEnv $
852+ argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
848− mapM (evalGraphRefAtomExpr tupIn) dConsArgs
849 pure (ConstructedAtom dConsName aType argAtoms)
853 pure (ConstructedAtom dConsName aType argAtoms)
851−typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
855+typeFromAtomExpr :: Attributes -> AtomExpr -> RelationalExprState (Either RelationalError AtomType)
852−typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
856+typeFromAtomExpr attrs (AttributeAtomExpr attrName) = do
853− renv <- askEnv
857+ rstate <- ask
854 case A.atomTypeForAttributeName attrName attrs of
858 case A.atomTypeForAttributeName attrName attrs of
855− Right aType -> pure aType
859+ Right aType -> pure (Right aType)
856− Left err@(NoSuchAttributeNamesError _) ->
860+ Left err@(NoSuchAttributeNamesError _) -> case rstate of
857− let envTup = envTuple renv
858− envAttrs = envAttributes renv in
859− case A.attributeForName attrName envAttrs of
861+ RelationalExprStateAttrsElems _ attrs' -> case A.attributeForName attrName attrs' of
862+ Left err' -> pure (Left err')
860− Right attr -> pure (A.atomType attr)
863+ Right attr -> pure (Right (A.atomType attr))
864+ RelationalExprStateElems _ -> pure (Left err)
861− Left _ -> case atomForAttributeName attrName envTup of
865+ RelationalExprStateTupleElems _ tup -> case atomForAttributeName attrName tup of
862− Right atom -> pure (atomTypeForAtom atom)
866+ Left err' -> pure (Left err')
863− Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
867+ Right atom -> pure (Right (atomTypeForAtom atom))
865− Left err -> throwError err
868+ Left err -> pure (Left err)
867−typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
869+typeFromAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
868−typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
870+typeFromAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
871+ context <- fmap stateElemsContext ask
869− funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
872+ let funcs = atomFunctions context
870 case atomFunctionForName funcName funcs of
873 case atomFunctionForName funcName funcs of
871− Left err -> throwError err
874+ Left err -> pure (Left err)
872 Right func -> do
875 Right func -> do
873 let funcRetType = last (atomFuncType func)
876 let funcRetType = last (atomFuncType func)
874 funcArgTypes = init (atomFuncType func)
877 funcArgTypes = init (atomFuncType func)
875− argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
878+ eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
879+ case lefts eArgTypes of
880+ errs@(_:_) -> pure (Left (someErrors errs))
876− let eTvMap = resolveTypeVariables funcArgTypes argTypes
882+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
883+ argTypes = rights eArgTypes
877− case eTvMap of
884+ case eTvMap of
878− Left err -> throwError err
885+ Left err -> pure (Left err)
879− Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
886+ Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
880−typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
887+typeFromAtomExpr attrs (RelationAtomExpr relExpr) = runExceptT $ do
881− relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
888+ rstate <- lift ask
889+ relType <- either throwE pure (runReader (typeForRelationalExpr relExpr) (mergeAttributesIntoRelationalExprState attrs rstate))
882 pure (RelationAtomType (attributes relType))
890 pure (RelationAtomType (attributes relType))
883-- grab the type of the data constructor, then validate that the args match the expected types
891-- grab the type of the data constructor, then validate that the args match the expected types
884−typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
892+typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
885− do
893+ runExceptT $ do
886− argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
894+ argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
887− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
895+ context <- fmap stateElemsContext (lift ask)
888− lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
896+ either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
890-- | Validate that the type of the AtomExpr matches the expected type.
898-- | Validate that the type of the AtomExpr matches the expected type.
891−verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
899+verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
892−verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
900+verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
893− env <- askEnv
901+ rstate <- lift ask
894 case A.atomTypeForAttributeName attrName (attributes relIn) of
902 case A.atomTypeForAttributeName attrName (attributes relIn) of
895− Right aType -> lift $ except $ atomTypeVerify expectedType aType
903+ Right aType -> either throwE pure (atomTypeVerify expectedType aType)
896− (Left err@(NoSuchAttributeNamesError _)) ->
904+ (Left err@(NoSuchAttributeNamesError _)) -> case rstate of
897− let attrs' = envAttributes env in
905+ RelationalExprStateTupleElems _ _ -> throwE err
898− if attrs' == emptyAttributes then
906+ RelationalExprStateElems _ -> throwE err
901− case A.attributeForName attrName attrs' of
907+ RelationalExprStateAttrsElems _ attrs -> case A.attributeForName attrName attrs of
902− Left err' -> throwError err'
908+ Left err' -> throwE err'
903− Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
909+ Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
904− Left err -> throwError err
910+ Left err -> throwE err
906−verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
907− lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
911+verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
908−verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
912+verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
909− context <- gfDatabaseContextForMarker tid
913+ rstate <- ask
910 let functions = atomFunctions context
914 let functions = atomFunctions context
915+ context = stateElemsContext rstate
911− func <- lift $ except $ atomFunctionForName funcName functions
917+ func <- either throwE pure (atomFunctionForName funcName functions)
912− let expectedArgTypes = atomFuncType func
918+ let expectedArgTypes = atomFuncType func
913− funcArgVerifier (atomExpr, expectedType2, argCount) = do
919+ funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
914− let handler :: RelationalError -> GraphRefRelationalExprM AtomType
915− handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
920+ Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
916− handler err = throwError err
921+ Left err -> throwE err
917− verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
922+ Right x -> pure x
918− funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
923+ ) $ zip3 funcArgExprs expectedArgTypes [1..]
919− if length funcArgTypes /= length expectedArgTypes - 1 then
924+ if length funcArgTypes /= length expectedArgTypes - 1 then
920− throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
925+ throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
922− lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
927+ either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
923−verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
928+verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
924− do
929+ rstate <- lift ask
925− let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
930+ relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
926− relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
927− lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
931+ either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
928−verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
932+verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
929− cType <- typeForGraphRefAtomExpr (attributes rel) cons
933+ cType <- liftE (typeFromAtomExpr (attributes rel) cons)
930− lift $ except $ atomTypeVerify expectedType cType
934+ either throwE pure (atomTypeVerify expectedType cType)
932-- | Look up the type's name and create a new attribute.
936-- | Look up the type's name and create a new attribute.
933−evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
937+evalAttrExpr :: TypeConstructorMapping -> AttributeExpr -> Either RelationalError Attribute
934−evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
938+evalAttrExpr aTypes (AttributeAndTypeNameExpr attrName tCons ()) = do
935− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
936− aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
939+ aType <- atomTypeForTypeConstructorValidate True tCons aTypes M.empty
937− lift $ except $ validateAtomType aType tConsMap
940+ validateAtomType aType aTypes
938− pure $ Attribute attrName aType
941+ Right (Attribute attrName aType)
940−evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
943+evalAttrExpr _ (NakedAttributeExpr attr) = Right attr
942−-- for tuple type concrete resolution (Nothing ==> Maybe Int) when the attributes hint is Nothing, we need to first process all the tuples, then extract the concrete types on a per-attribute basis, then reprocess the tuples to include the concrete types
945+evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
943−evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
944−evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
945−evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
946− tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
947− finalAttrs <- case mAttrs of
948− Just attrs -> pure attrs
951− [] -> pure emptyAttributes
952− (headTuple:tailTuples) -> do
953− --gather up resolved atom types or throw an error if an attribute cannot be made concrete from the inferred types- this could still fail if the type cannot be inferred (e.g. from [Nothing, Nothing])
955− processTupleAttrs (tupAttr, accAttr) =
956− --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
957− if isResolvedAttribute accAttr && tupAttr == accAttr then
960− lift $ except $ resolveAttributes accAttr tupAttr
961− mostResolvedTypes <-
962− foldM (\acc tup -> do
963− let zipped = zip (V.toList . attributesVec $ tupleAttributes tup) acc
964− accNames = S.fromList $ map A.attributeName acc
965− tupNames = A.attributeNameSet (tupleAttributes tup)
966− attrNamesDiff = S.union (S.difference accNames tupNames) (S.difference tupNames accNames)
967− unless (null attrNamesDiff) (throwError (AttributeNamesMismatchError attrNamesDiff))
968− nextTupleAttrs <- mapM processTupleAttrs zipped
969− let diff = A.attributesDifference (A.attributesFromList nextTupleAttrs) (A.attributesFromList acc)
970− if diff == A.emptyAttributes then
973− throwError (TupleAttributeTypeMismatchError diff)
974− ) (V.toList . attributesVec $ tupleAttributes headTuple) tailTuples
975− pure (A.attributesFromList mostResolvedTypes)
976− --strategy: if all the tuple expr transaction markers refer to one location, then we can pass the type constructor mapping from that location, otherwise, we cannot assume that the types are the same
977− tConsMap <- case singularTransactions tupleExprL of
978− SingularTransactionRef commonTransId ->
979− typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
980− NoTransactionsRef ->
981− typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
982− -- if there are multiple transaction markers in the TupleExprs, then we can't assume a single type constructor mapping- this could be improved in the future, but if all the tuples are fully resolved, then we don't need further resolution
983− _ -> throwError TupleExprsReferenceMultipleMarkersError
984− lift $ except $ validateAttributes tConsMap finalAttrs
985− mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
988−--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
990−evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
991−evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
946+evalTupleExpr mAttrs (TupleExpr tupMap) = do
947+ context <- fmap stateElemsContext ask
992 -- it's not possible for AtomExprs in tuple constructors to reference other Attributes' atoms due to the necessary order-of-operations (need a tuple to pass to evalAtomExpr)- it may be possible with some refactoring of type usage or delayed evaluation- needs more thought, but not a priority
949 -- it's not possible for AtomExprs in tuple constructors to reference other Attributes' atoms due to the necessary order-of-operations (need a tuple to pass to evalAtomExpr)- it may be possible with some refactoring of type usage or delayed evaluation- needs more thought, but not a priority
993 -- I could adjust this logic so that when the attributes are not specified (Nothing), then I can attempt to extract the attributes from the tuple- the type resolution will blow up if an ambiguous data constructor is used (Left 4) and this should allow simple cases to "relation{tuple{a 4}}" to be processed
950 -- I could adjust this logic so that when the attributes are not specified (Nothing), then I can attempt to extract the attributes from the tuple- the type resolution will blow up if an ambiguous data constructor is used (Left 4) and this should allow simple cases to "relation{tuple{a 4}}" to be processed
994− let attrs = fromMaybe A.emptyAttributes mAttrs
951+ let attrs = fromMaybe A.emptyAttributes mAttrs
995− resolveOneAtom (attrName, aExpr) =
952+ attrAtoms <- mapM (\(attrName, aExpr) -> do
997− --provided when the relation header is available
953+ --provided when the relation header is available
998− let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
954+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
999− unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
955+ unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
1000− resolvedType <- case eExpectedAtomType of
956+ resolvedType <- case eExpectedAtomType of
1001 Left _ -> pure unresolvedType
957 Left _ -> pure unresolvedType
1002− Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
958+ Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
1003 --resolve atom typevars based on resolvedType?
959 --resolve atom typevars based on resolvedType?
1004− newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
960+ newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
1005− pure (attrName, newAtom, resolvedType)
961+ pure (attrName, newAtom, resolvedType)
1006− attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
962+ ) (M.toList tupMap)
1007− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
963+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1008− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
964+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1009− tup = mkRelationTuple tupAttrs atoms
965+ tup = mkRelationTuple tupAttrs atoms
966+ tConss = typeConstructorMapping context
1010− finalAttrs = fromMaybe tupAttrs mAttrs
967+ finalAttrs = fromMaybe tupAttrs mAttrs
1011 --verify that the attributes match
968 --verify that the attributes match
1012− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
969+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
1013− --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1014− --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
970+ tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1015− let tup' = reorderTuple finalAttrs tup
1016− --TODO: restore type resolution
1017−-- _ <- lift $ except (validateTuple tup' tConss)
971+ _ <- either throwE pure (validateTuple tup' tConss)
1018− pure tup'
972+ pure tup'
1020−--temporary implementation until we have a proper planner+executor
974+evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
1021−evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
975+evalAttributeNames attrNames expr = do
1022−evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
976+ eExprType <- typeForRelationalExpr expr
1023− mAttrs <- case mAttrExprs of
977+ case eExprType of
1024− Just _ ->
978+ Left err -> pure (Left err)
1025− Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
979+ Right exprTyp -> do
1026− Nothing -> pure Nothing
980+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1027− tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
981+ case attrNames of
1028− let attrs = fromMaybe firstTupleAttrs mAttrs
982+ AttributeNames names ->
1029− firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
983+ case A.projectionAttributesForNames names (attributes exprTyp) of
1030− lift $ except $ mkRelation attrs (RelationTupleSet tuples)
984+ Left err -> pure (Left err)
1031−evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
985+ Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1032− lift $ except $ mkRelation attributeSet tupleSet
986+
1033−evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
987+ InvertedAttributeNames names -> do
988+ let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
989+ if not (S.null nonExistentAttributeNames) then
990+ pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
992+ pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
994+ UnionAttributeNames namesA namesB -> do
995+ eNameSetA <- evalAttributeNames namesA expr
997+ Left err -> pure (Left err)
998+ Right nameSetA -> do
999+ eNameSetB <- evalAttributeNames namesB expr
1001+ Left err -> pure (Left err)
1003+ pure (Right (S.union nameSetA nameSetB))
1005+ IntersectAttributeNames namesA namesB -> do
1006+ eNameSetA <- evalAttributeNames namesA expr
1008+ Left err -> pure (Left err)
1009+ Right nameSetA -> do
1010+ eNameSetB <- evalAttributeNames namesB expr
1012+ Left err -> pure (Left err)
1014+ pure (Right (S.intersection nameSetA nameSetB))
1016+ RelationalExprAttributeNames attrExpr -> do
1017+ eAttrExprType <- typeForRelationalExpr attrExpr
1018+ case eAttrExprType of
1019+ Left err -> pure (Left err)
1020+ Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1022+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError Relation
1034−evalGraphRefRelationalExpr (RelationVariable name tid) = do
1023+evalGraphRefRelationalExpr (RelationVariable name tid) graph = do
1035− ctx <- gfDatabaseContextForMarker tid
1024+ ctx <- dbContextForTransId tid graph
1036 case M.lookup name (relationVariables ctx) of
1025 case M.lookup name (relationVariables ctx) of
1037− Nothing -> throwError (RelVarNotDefinedError name)
1026+ Nothing -> Left (RelVarNotDefinedError name)
1038− Just rv -> evalGraphRefRelationalExpr rv
1027+ Just rv -> evalGraphRefRelationalExpr rv graph
1039−evalGraphRefRelationalExpr (Project attrNames expr) = do
1040− attrNameSet <- evalGraphRefAttributeNames attrNames expr
1041− rel <- evalGraphRefRelationalExpr expr
1042− lift $ except $ project attrNameSet rel
1043−evalGraphRefRelationalExpr (Union exprA exprB) = do
1044− relA <- evalGraphRefRelationalExpr exprA
1045− relB <- evalGraphRefRelationalExpr exprB
1046− lift $ except $ union relA relB
1047−evalGraphRefRelationalExpr (Join exprA exprB) = do
1048− relA <- evalGraphRefRelationalExpr exprA
1049− relB <- evalGraphRefRelationalExpr exprB
1050− lift $ except $ join relA relB
1051−evalGraphRefRelationalExpr (Rename oldName newName expr) = do
1052− rel <- evalGraphRefRelationalExpr expr
1053− lift $ except $ rename oldName newName rel
1054−evalGraphRefRelationalExpr (Difference exprA exprB) = do
1055− relA <- evalGraphRefRelationalExpr exprA
1056− relB <- evalGraphRefRelationalExpr exprB
1057− lift $ except $ difference relA relB
1058−evalGraphRefRelationalExpr (Group groupAttrNames newAttrName expr) = do
1059− groupNames <- evalGraphRefAttributeNames groupAttrNames expr
1060− rel <- evalGraphRefRelationalExpr expr
1061− lift $ except $ group groupNames newAttrName rel
1062−evalGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1063− rel <- evalGraphRefRelationalExpr expr
1064− lift $ except $ ungroup groupAttrName rel
1065−evalGraphRefRelationalExpr (Restrict predExpr expr) = do
1066− rel <- evalGraphRefRelationalExpr expr
1067− filt <- predicateRestrictionFilter (attributes rel) predExpr
1068− lift $ except $ restrict filt rel
1069−evalGraphRefRelationalExpr (Equals exprA exprB) = do
1070− relA <- evalGraphRefRelationalExpr exprA
1071− relB <- evalGraphRefRelationalExpr exprB
1072− pure $ if relA == relB then relationTrue else relationFalse
1073−evalGraphRefRelationalExpr (NotEquals exprA exprB) = do
1074− relA <- evalGraphRefRelationalExpr exprA
1075− relB <- evalGraphRefRelationalExpr exprB
1076− pure $ if relA == relB then relationFalse else relationTrue
1077−evalGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1078− rel <- evalGraphRefRelationalExpr expr
1079− (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1080− lift $ except $ relMogrify tupProc newAttrs rel
1081−evalGraphRefRelationalExpr expr@With{} =
1082− --strategy A: add relation variables to the contexts in the graph
1083− --strategy B: drop in macros in place (easier programmatically)
1084− --strategy B implementation
1085− evalGraphRefRelationalExpr (substituteWithNameMacros [] expr)
1087dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1029dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1088dbContextForTransId tid graph = do
1030dbContextForTransId tid graph = do
1089 trans <- transactionForId tid graph
1031 trans <- transactionForId tid graph
1090− pure (concreteDatabaseContext trans)
1032+ pure (concreteDatabaseContext ctx)
1092transactionForId :: TransactionId -> TransactionGraph -> Either RelationalError Transaction
1034transactionForId :: TransactionId -> TransactionGraph -> Either RelationalError Transaction
1093transactionForId tid graph
1035transactionForId tid graph
@@ -1100,293 +1042,113 @@ transactionForId tid graph
1101 matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
1043 matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
1045+processRestrictionPredicateExpr :: RestrictionPredicateExpr -> RelationalExprState (Either RelationalError GraphRefRestrictionPredicateExpr)
1046+processRestrictionPredicateExpr TruePredicate = TruePredicate
1047+processRestrictionPredicateExpr (AndPredicate a b) = pure $ AndPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
1048+processRestrictionPredicateExpr (OrPredicate a b) = OrPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
1049+processRestrictionPredicateExpr (NotPredicate a) = pure $ NotPredicate <$> processRestrictionPredicateExpr a
1050+processRestrictionPredicateExpr (RelationalExprPredicate expr) = pure $ RelationalExprPredicate <$> evalRelationalExpr expr
1051+processRestrictionPredicateExpr (AtomExprPredicate expr) = AtomExprPredicate <$> evalAtomExpr expr
1052+processRestrictionPredicateExpr (AttributeEqualityPredicate nam expr) = AttributeEqualityPredicate nam <$> evalAtomExpr expr
1054+processExtendTupleExpr :: ExtendTupleExpr -> RelationalExprState (Either RelationalError (ExtendTupleExprBase a))
1055+processExtendTupleExpr (AttributeExtendTupleExpr nam atomExpr) = do
1056+ eExpr <- evalAtomExpr atomExpr
1058+ Left err -> pure (Left err)
1059+ Right expr -> pure (Right (AttributeExtendTupleExpr nam expr))
1103−typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1061+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError Relation
1104−typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1062+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) _ = mkRelation attrs emptyTupleSet
1105−typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1063+typeForGraphRefRelationalExpr (ExistingRelation rel) _ = pure (emptyRelationWithAttrs (attributes rel))
1106−typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1064+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) graph =
1107− mAttrs <- case mAttrExprs of
1065+ case mAttrExprs of
1108− Just attrExprs -> do
1066+ Just attrExprs -> do
1109− attrs <- mapM evalGraphRefAttributeExpr attrExprs
1067+ attrs <- mapM (\e -> evalGraphRefAttributeExpr e graph) attrExprs
1110− pure (Just (attributesFromList attrs))
1068+ pure (emptyRelationWithAttrs attrs)
1111− Nothing -> pure Nothing
1112− tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1113− let retAttrs = case tuples of
1114− (tup:_) -> tupleAttributes tup
1115− [] -> fromMaybe A.emptyAttributes mAttrs
1116− pure $ emptyRelationWithAttrs retAttrs
1118−typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1069+typeForGraphRefRelationalExpr (RelationVariable rvName tid) graph = do
1070+ trans <- transactionForId tid graph
1119− relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1071+ let relVars = relationVariables (concreteDatabaseContext trans)
1120 case M.lookup rvName relVars of
1072 case M.lookup rvName relVars of
1121− Nothing -> throwError (RelVarNotDefinedError rvName)
1073+ Nothing -> Left $ RelVarNotDefinedError name
1123− typeForGraphRefRelationalExpr rvExpr
1074+ Just rvExpr -> typeForGraphRefRelationalExpr rvExpr graph
1124−typeForGraphRefRelationalExpr (Project attrNames expr) = do
1075+typeForGraphRefRelationalExpr (Project attrNames expr) graph = do
1125− exprType' <- typeForGraphRefRelationalExpr expr
1076+ exprType <- typeForGraphRefRelationalExpr expr graph
1126− projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1077+ projectionAttrs <- evalGraphRefAttributeNames attrNames expr graph
1127− lift $ except $ project projectionAttrs exprType'
1078+ project projectionAttrs exprType
1128−typeForGraphRefRelationalExpr (Union exprA exprB) = do
1079+
1129− exprA' <- typeForGraphRefRelationalExpr exprA
1130− exprB' <- typeForGraphRefRelationalExpr exprB
1131− lift $ except $ union exprA' exprB'
1132−typeForGraphRefRelationalExpr (Join exprA exprB) = do
1133− exprA' <- typeForGraphRefRelationalExpr exprA
1134− exprB' <- typeForGraphRefRelationalExpr exprB
1135− lift $ except $ join exprA' exprB'
1136−typeForGraphRefRelationalExpr (Rename oldAttr newAttr expr) = do
1137− expr' <- typeForGraphRefRelationalExpr expr
1138− lift $ except $ rename oldAttr newAttr expr'
1139−typeForGraphRefRelationalExpr (Difference exprA exprB) = do
1140− exprA' <- typeForGraphRefRelationalExpr exprA
1141− exprB' <- typeForGraphRefRelationalExpr exprB
1142− lift $ except $ difference exprA' exprB'
1143−typeForGraphRefRelationalExpr (Group groupNames attrName expr) = do
1144− expr' <- typeForGraphRefRelationalExpr expr
1145− groupNames' <- evalGraphRefAttributeNames groupNames expr
1146− lift $ except $ group groupNames' attrName expr'
1147−typeForGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1148− expr' <- typeForGraphRefRelationalExpr expr
1149− lift $ except $ ungroup groupAttrName expr'
1150−typeForGraphRefRelationalExpr (Restrict pred' expr) = do
1151− expr' <- typeForGraphRefRelationalExpr expr
1152− filt <- predicateRestrictionFilter (attributes expr') pred'
1153− lift $ except $ restrict filt expr'
1154−typeForGraphRefRelationalExpr Equals{} =
1156−typeForGraphRefRelationalExpr NotEquals{} =
1158−typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1159− rel <- typeForGraphRefRelationalExpr expr
1160− evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1161−typeForGraphRefRelationalExpr expr@(With withs _) = do
1162− let expr' = substituteWithNameMacros [] expr
1163− checkMacroName (WithNameExpr macroName tid) = do
1164− rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1165− case M.lookup macroName rvs of
1166− Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1168− mapM_ (checkMacroName . fst) withs
1169− typeForGraphRefRelationalExpr expr'
1171−evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1080+evalGraphRefAttributeNames :: AttributeNames -> GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError (S.Set AttributeName)
1172−evalGraphRefAttributeNames attrNames expr = do
1081+evalGraphRefAttributeNames attrNames expr graph = do
1173− exprType' <- typeForGraphRefRelationalExpr expr
1082+ exprTyp <- typeForGraphRefRelationalExpr expr graph
1174− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1083+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1175 case attrNames of
1084 case attrNames of
1176− AttributeNames names ->
1085+ AttributeNames names ->
1177− case A.projectionAttributesForNames names (attributes exprType') of
1086+ case A.projectionAttributesForNames names (attributes exprTyp) of
1178− Left err -> throwError err
1087+ Left err -> pure (Left err)
1179− Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1088+ Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1181− InvertedAttributeNames names -> do
1090+ InvertedAttributeNames names -> do
1182 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1091 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1183 if not (S.null nonExistentAttributeNames) then
1092 if not (S.null nonExistentAttributeNames) then
1184− throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1093+ pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1186− pure (A.nonMatchingAttributeNameSet names typeNameSet)
1095+ pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
1188− UnionAttributeNames namesA namesB -> do
1097+ UnionAttributeNames namesA namesB -> do
1189− nameSetA <- evalGraphRefAttributeNames namesA expr
1098+ eNameSetA <- evalAttributeNames namesA expr
1190− nameSetB <- evalGraphRefAttributeNames namesB expr
1099+ case eNameSetA of
1100+ Left err -> pure (Left err)
1101+ Right nameSetA -> do
1102+ eNameSetB <- evalAttributeNames namesB expr
1104+ Left err -> pure (Left err)
1191− pure (S.union nameSetA nameSetB)
1106+ pure (Right (S.union nameSetA nameSetB))
1193− IntersectAttributeNames namesA namesB -> do
1108+ IntersectAttributeNames namesA namesB -> do
1194− nameSetA <- evalGraphRefAttributeNames namesA expr
1109+ eNameSetA <- evalAttributeNames namesA expr
1195− nameSetB <- evalGraphRefAttributeNames namesB expr
1110+ case eNameSetA of
1111+ Left err -> pure (Left err)
1112+ Right nameSetA -> do
1113+ eNameSetB <- evalAttributeNames namesB expr
1115+ Left err -> pure (Left err)
1196− pure (S.intersection nameSetA nameSetB)
1117+ pure (Right (S.intersection nameSetA nameSetB))
1119+ RelationalExprAttributeNames attrExpr -> do
1120+ eAttrExprType <- typeForRelationalExpr attrExpr
1121+ case eAttrExprType of
1122+ Left err -> pure (Left err)
1123+ Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1198− RelationalExprAttributeNames attrExpr -> do
1199− attrExprType <- typeForGraphRefRelationalExpr attrExpr
1200− pure (A.attributeNameSet (attributes attrExprType))
1202−evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1203−evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1204− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1205− case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1206− Left err -> throwError err
1208− case validateAtomType aType tConsMap of
1209− Left err -> throwError err
1210− Right _ -> pure (Attribute attrName aType)
1211−evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1213−mkEmptyRelVars :: RelationVariables -> RelationVariables
1214−mkEmptyRelVars = M.map mkEmptyRelVar
1216− mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1217− mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1218− mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1219− mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
1220− mkEmptyRelVar (Project attrNames expr) = Project attrNames (mkEmptyRelVar expr)
1221− mkEmptyRelVar (Union exprA exprB) = Union (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1222− mkEmptyRelVar (Join exprA exprB) = Join (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1223− mkEmptyRelVar (Rename nameA nameB expr) = Rename nameA nameB (mkEmptyRelVar expr)
1224− mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1225− mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1226− mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1227− mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1228− mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1229− mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1230− mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1231− mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1234−dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1235−dbErr err = lift (except (Left err))
1237−-- | Return a Relation describing the relation variables.
1238−relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1239−relationVariablesAsRelation ctx graph = do
1240− let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1241− attrs = A.attributesFromList [Attribute "name" TextAtomType,
1242− Attribute "attributes" (RelationAtomType subrelAttrs)]
1243− relVars = relationVariables ctx
1244− mkRvDesc (rvName, gfExpr) = do
1245− let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1246− gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1247− pure (rvName, gfType)
1248− relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributesVec (attributes rel))]
1249− attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1250− attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1251− Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1252− Right rel -> RelationAtom rel
1253− rvs <- mapM mkRvDesc (M.toList relVars)
1254− let tups = map relVarToAtomList rvs
1255− mkRelationFromList attrs tups
1257−-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1258−evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1259−evalRelationalExpr expr = do
1261− context <- reContext
1262− let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1263− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1264− case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1265− Left err -> throwError err
1266− Right rel -> pure rel
1268−class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1269− getContext :: m DatabaseContext
1271−instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1272− getContext = gfDatabaseContextForMarker UncommittedContextMarker
1274−instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1275− getContext = getStateContext
1277−relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1278−relVarByName rvName = do
1279− relvars <- relationVariables <$> getContext
1280− case M.lookup rvName relvars of
1281− Nothing -> throwError (RelVarNotDefinedError rvName)
1282− Just gfexpr -> pure gfexpr
1284−-- | resolve UncommittedTransactionMarker whenever possible- this is important in the DatabaseContext in order to mitigate self-referencing loops for updates
1285−class ResolveGraphRefTransactionMarker a where
1286− resolve :: a -> DatabaseContextEvalMonad a
1289−instance ResolveGraphRefTransactionMarker GraphRefRelationalExpr where
1290− resolve (MakeRelationFromExprs mAttrs tupleExprs) =
1291− MakeRelationFromExprs mAttrs <$> resolve tupleExprs
1292− resolve orig@MakeStaticRelation{} = pure orig
1293− resolve orig@ExistingRelation{} = pure orig
1294− resolve orig@(RelationVariable rvName UncommittedContextMarker) = do
1295− rvMap <- relationVariables <$> getStateContext
1296− case M.lookup rvName rvMap of
1297− Nothing -> pure orig
1298− Just resolvedRv -> resolve resolvedRv
1299− resolve orig@RelationVariable{} = pure orig
1300− resolve (Project attrNames relExpr) = Project <$> resolve attrNames <*> resolve relExpr
1301− resolve (Union exprA exprB) = Union <$> resolve exprA <*> resolve exprB
1302− resolve (Join exprA exprB) = Join <$> resolve exprA <*> resolve exprB
1303− resolve (Rename attrA attrB expr) = Rename attrA attrB <$> resolve expr
1304− resolve (Difference exprA exprB) = Difference <$> resolve exprA <*> resolve exprB
1305− resolve (Group namesA nameB expr) = Group <$> resolve namesA <*> pure nameB <*> resolve expr
1306− resolve (Ungroup nameA expr) = Ungroup nameA <$> resolve expr
1307− resolve (Restrict restrictExpr relExpr) = Restrict <$> resolve restrictExpr <*> resolve relExpr
1308− resolve (Equals exprA exprB) = Equals <$> resolve exprA <*> resolve exprB
1309− resolve (NotEquals exprA exprB) = NotEquals <$> resolve exprA <*> resolve exprB
1310− resolve (Extend extendExpr relExpr) = Extend <$> resolve extendExpr <*> resolve relExpr
1311− resolve (With withExprs relExpr) = With <$> mapM (\(nam, expr) -> (,) <$> resolve nam <*> resolve expr) withExprs <*> resolve relExpr
1313−instance ResolveGraphRefTransactionMarker GraphRefTupleExprs where
1314− resolve (TupleExprs marker tupleExprs) =
1315− TupleExprs marker <$> mapM resolve tupleExprs
1317−instance ResolveGraphRefTransactionMarker GraphRefTupleExpr where
1318− resolve (TupleExpr tupMap) = do
1319− tupMap' <- mapM (\(attrName, expr) -> (,) attrName <$> resolve expr ) (M.toList tupMap)
1320− pure (TupleExpr (M.fromList tupMap'))
1322−instance ResolveGraphRefTransactionMarker GraphRefAttributeNames where
1323− resolve orig@AttributeNames{} = pure orig
1324− resolve orig@InvertedAttributeNames{} = pure orig
1325− resolve (UnionAttributeNames namesA namesB) = UnionAttributeNames <$> resolve namesA <*> resolve namesB
1326− resolve (IntersectAttributeNames namesA namesB) = IntersectAttributeNames <$> resolve namesA <*> resolve namesB
1327− resolve (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> resolve expr
1329−instance ResolveGraphRefTransactionMarker GraphRefRestrictionPredicateExpr where
1330− resolve TruePredicate = pure TruePredicate
1331− resolve (AndPredicate exprA exprB) = AndPredicate <$> resolve exprA <*> resolve exprB
1332− resolve (OrPredicate exprA exprB) = OrPredicate <$> resolve exprA <*> resolve exprB
1333− resolve (NotPredicate expr) = NotPredicate <$> resolve expr
1334− resolve (RelationalExprPredicate expr) = RelationalExprPredicate <$> resolve expr
1335− resolve (AtomExprPredicate expr) = AtomExprPredicate <$> resolve expr
1336− resolve (AttributeEqualityPredicate nam expr)= AttributeEqualityPredicate nam <$> resolve expr
1338−instance ResolveGraphRefTransactionMarker GraphRefExtendTupleExpr where
1339− resolve (AttributeExtendTupleExpr nam atomExpr) = AttributeExtendTupleExpr nam <$> resolve atomExpr
1341−instance ResolveGraphRefTransactionMarker GraphRefWithNameExpr where
1342− resolve orig@WithNameExpr{} = pure orig -- match uncommitted marker?
1344−instance ResolveGraphRefTransactionMarker GraphRefAtomExpr where
1345− resolve orig@AttributeAtomExpr{} = pure orig
1346− resolve orig@NakedAtomExpr{} = pure orig
1347− resolve (FunctionAtomExpr nam atomExprs marker) =
1348− FunctionAtomExpr nam <$> mapM resolve atomExprs <*> pure marker
1349− resolve (RelationAtomExpr expr) = RelationAtomExpr <$> resolve expr
1350− resolve (ConstructedAtomExpr dConsName atomExprs marker) =
1351− ConstructedAtomExpr dConsName <$> mapM resolve atomExprs <*> pure marker
1353−--convert series of simple Union queries into MakeStaticRelation
1354−-- this is especially useful for long, nested applications of Union with simple tuples
1355−-- Union (MakeRelation x y) (MakeRelation x y') -> MakeRelation x (y + y')
1357−--MakeRelationFromExprs Nothing (TupleExprs UncommittedContextMarker [TupleExpr (fromList [("name", NakedAtomExpr (TextAtom "steve"))])])
1359−applyUnionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1360−applyUnionCollapse = Fold.cata opt
1362− opt :: RelationalExprBaseF GraphRefTransactionMarker GraphRefRelationalExpr -> GraphRefRelationalExpr
1363− opt (UnionF exprA exprB) | exprA == exprB = exprA
1365− exprA@(MakeRelationFromExprs mAttrs1 tupExprs1)
1366− exprB@(MakeRelationFromExprs mAttrs2 tupExprs2)) | tupExprs1 == tupExprs2 = MakeRelationFromExprs (mAttrs1 <|> mAttrs2) tupExprs1
1367− | tupExprsNull tupExprs1 = exprB
1368− | tupExprsNull tupExprs2 = exprA
1369− opt x = Fold.embed x
1370− tupExprsNull (TupleExprs _ []) = True
1371− tupExprsNull _ = False
1374−--UPDATE optimization- find matching where clause in "lower" levels of renaming
1375−--update x where y=1 set (x:=5,z:=10); update x where y=1 set(x:=6,z:=11)
1377−-- update x where y=1 set (x:=6,z:=11)
1378−-- future opt: match individual attributes update x where y=1 set (x:=5); update x where y=1 set (z:=11) => update x where y=1 set (x:=5,z:=11)
1380−--strategy: try to collapse the top-level update (union (restrict pred MakeRelationFromExpr) expr) if it contains the same predicate and resultant relation
1382−--DELETE optimization
1383−-- if a restriction matches a previous restriction, combine them
1384−-- O(1) since it only scans at the top level, critical in benchmarks generating redundant deletions
1385−applyRestrictionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1386−applyRestrictionCollapse orig@(Restrict npred@(NotPredicate _) expr) =
1388− orig'@(Restrict npred'@(NotPredicate _) _) | npred == npred' -> orig'
1390−applyRestrictionCollapse expr = expr
1392−
1128+processAtomExpr :: AtomExpr -> TransactionId -> GraphRefAtomExpr
1129+processAtomExpr (AttributeAtomExpr nam) _ = AttributeAtomExpr nam
1130+processAtomExpr (NakedAtomExpr atom) _ = NakedAtomExpr atom
1131+processAtomExpr (FunctionAtomExpr fName atomExprs ()) tid = FunctionAtomExpr fName (fmap processAtomExpr tid) tid
1132+processAtomExpr (RelationAtomExpr expr) tid = RelationAtomExpr (processRelationalExpr expr tid)
1133+processAtomExpr (ConstructedAtomExpr dConsName atomExprs) = ConstructedAtomExpr dConsName (fmap processAtomExpr tid) tid
1135+processTupleExpr :: TupleExpr -> TransactionId -> GraphRefTupleExpr
1136+processTupleExpr (TupleExpr tMap) tid = TupleExpr (M.map (processAtomExpr tid) tMap)
1138+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> TransactionGraph -> Either RelationalError Attribute
1139+evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) graph = do
1140+ trans <- transactionForId tid graph
1141+ let tConsMap = typeConstructorMapping (concreteDatabaseContext trans)
1142+ aType <- atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
1143+ validateAtomType aType tConsMap
1144+ pure (Attribute attrName aType)
1146+--convert AttributeExpr to GraphRefAttributeExpr
1147+processAttributeExpr :: AttributeExpr -> TransactionId -> GraphRefAttributeExpr
1148+processAttributeExpr (AttributeAndTypeNameExpr nam tCons ()) tid = AttributeAndTypeNameExpr nam tCons tid
1149+processAttributeExpr (NakedAttributeExpr attr) = NakedAttributeExpr attr
1151+-- convert a RelationalExpr into a GraphRefRelationalExpr
1152+processRelationalExpr :: RelationalExpr -> TransactionId -> GraphRefRelationalExpr
1153+processRelationalExpr (MakeRelationFromExprs mAttrs tupleExprs) =
1154+ MakeRelationFromExprs (fmap (fmap processAttributeExpr) mAttrs) (processTupleExprs tupleExprs)