@@ -1,7 +1,4 @@
11{-# LANGUAGE ScopedTypeVariables #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE OverloadedStrings #-}
52module ProjectM36.RelationalExpression where
63import ProjectM36.Relation
74import ProjectM36.Tuple
@@ -10,44 +7,32 @@ import ProjectM36.Base
107import qualified Data.UUID as U
118import ProjectM36.Error
129import ProjectM36.AtomType
13−import ProjectM36.Attribute (emptyAttributes, attributesFromList)
10+import ProjectM36.Attribute (emptyAttributes)
1411import ProjectM36.ScriptSession
1512import ProjectM36.DataTypes.Primitive
1613import ProjectM36.AtomFunction
1714import ProjectM36.DatabaseContextFunction
1815import ProjectM36.Arbitrary
19−import ProjectM36.GraphRefRelationalExpr
20−import ProjectM36.Transaction
2116import qualified ProjectM36.Attribute as A
2217import qualified Data.Map as M
2318import qualified Data.HashSet as HS
2419import qualified Data.Set as S
2520import Control.Monad.State hiding (join)
26−import Data.Bifunctor (second)
21+import Control.Exception
2722import Data.Maybe
2823import Data.Either
2924import Data.Char (isUpper)
30−import Data.Time
31−import qualified Data.List.NonEmpty as NE
32−import Data.Functor.Identity
3325import qualified Data.Text as T
3426import qualified Data.Vector as V
3527import qualified ProjectM36.TypeConstructorDef as TCD
36−import qualified Control.Monad.RWS.Strict as RWS
37−import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
38−import Control.Monad.Except hiding (join)
39−import Control.Monad.Trans.Except (except)
40−import Control.Monad.Reader as R hiding (join)
41−import ProjectM36.NormalizeExpr
42−import ProjectM36.WithNameExpr
28+import Control.Monad.Trans.Except
29+import Control.Monad.Trans.Reader
4330import Test.QuickCheck
44−import qualified Data.Functor.Foldable as Fold
45−import Control.Applicative
46−#ifdef PM36_HASKELL_SCRIPTING
47−import GHC hiding (getContext)
48−import Control.Exception
31+import GHC
4932import GHC.Paths
50−#endif
33+import Data.Time.Clock
34+import Data.Time.Calendar
35+import qualified Data.List.NonEmpty as NE
5136
5237data DatabaseContextExprDetails = CountUpdatedTuples
5338
@@ -64,63 +49,50 @@ databaseContextExprDetailsFunc CountUpdatedTuples _ relIn = Relation attrs newTu
6449 Right ts -> ts
6550
6651-- | Used to start a fresh database state for a new database context expression.
67−mkDatabaseContextEvalState :: DatabaseContext -> DatabaseContextEvalState
68−mkDatabaseContextEvalState context = DatabaseContextEvalState {
69− dbc_context = context,
70− dbc_accum = M.empty,
71− dbc_dirty = False
52+freshDatabaseState :: DatabaseContext -> DatabaseStateElems
53+freshDatabaseState context = DatabaseStateElems {
54+ context = context,
55+ accum = M.empty,
56+ dirty = False
7257 } --future work: propagate return accumulator
7358
7459-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
75−data RelationalExprEnv = RelationalExprEnv {
76− re_context :: DatabaseContext,
77− re_graph :: TransactionGraph,
78− re_extra :: Maybe (Either RelationTuple Attributes)
79− }
80−
81−envTuple :: GraphRefRelationalExprEnv -> RelationTuple
82−envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
83−
84−envAttributes :: GraphRefRelationalExprEnv -> Attributes
85−envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
60+data RelationalExprStateElems = RelationalExprStateElems {
61+ elems_context :: DatabaseContext,
62+ elems_graph :: TransactionGraph,
63+ elems_extra :: Maybe (Either RelationTuple Attributes) }
64+
65+stateTuple :: RelationalExprStateElems -> RelationTuple
66+stateTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (elems_extra e))
67+
68+stateAttributes :: RelationalExprStateElems -> Attributes
69+stateAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (elems_extra e))
70+{-
71+data RelationalExprStateElems = RelationalExprStateTupleElems DatabaseContext RelationTuple | -- used when fully evaluating a relexpr
72+ RelationalExprStateAttrsElems DatabaseContext Attributes | --used when evaluating the type of a relexpr
73+ RelationalExprStateElems DatabaseContext --used by default at the top level of evaluation
74+ -}
8675
87−instance Show RelationalExprEnv where
88− show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
76+instance Show RelationalExprStateElems where show e@RelationalExprStateElems{} = "RelationalExprStateElems " ++ show (elems_extra e)
8977
90−--used to eval relationalexpr
91−type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
78+mkRelationalExprState :: DatabaseContext -> TransactionGraph -> RelationalExprStateElems
79+mkRelationalExprState ctx graph = RelationalExprStateElems
80+ { elems_context = ctx,
81+ elems_graph = graph,
82+ elems_extra = Nothing }
9283
93−runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
94−runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
95−
96−reGraph :: RelationalExprM TransactionGraph
97−reGraph = asks re_graph
98−
99−reContext :: RelationalExprM DatabaseContext
100−reContext = asks re_context
101−
102−mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
103−mkRelationalExprEnv ctx graph =
104− RelationalExprEnv
105− { re_context = ctx,
106− re_graph = graph,
107− re_extra = Nothing }
108−
109−askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
110−askEnv = R.ask
111−
112−mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
113−mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
114− env { gre_extra = new_elems }
84+mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprStateElems -> RelationalExprStateElems
85+mergeTuplesIntoRelationalExprState tupIn e@RelationalExprStateElems{} =
86+ e{elems_extra = new_elems }
11587 where
11688 new_elems = Just (Left newTuple)
117− mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
89+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (stateTuple e))
11890 newTuple = mkRelationTupleFromMap mergedTupMap
119−
120−mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
121−mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
91+
92+mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprStateElems -> RelationalExprStateElems
93+mergeAttributesIntoRelationalExprState attrsIn e@RelationalExprStateElems{} = e{elems_extra = newattrs }
12294 where
123− newattrs = Just (Right (A.union attrsIn (envAttributes e)))
95+ newattrs = Just (Right (A.union attrsIn (stateAttributes e)))
12496
12597type ResultAccumName = StringType
12698
@@ -130,403 +102,440 @@ data ResultAccum = ResultAccum { resultAccumFunc :: ResultAccumFunc,
130102 resultAccumResult :: Relation
131103 }
132104
133−data DatabaseContextEvalState = DatabaseContextEvalState {
134− dbc_context :: DatabaseContext, --new, alterable context for a new transaction
135− dbc_accum :: M.Map ResultAccumName ResultAccum,
136− dbc_dirty :: DirtyFlag
105+data DatabaseStateElems = DatabaseStateElems {
106+ context :: DatabaseContext, --new, alterable context for a new transaction
107+ accum :: M.Map ResultAccumName ResultAccum,
108+ dirty :: DirtyFlag
137109 }
138110
139−data DatabaseContextEvalEnv = DatabaseContextEvalEnv
140− { dce_transId :: TransactionId,
141− dce_graph :: TransactionGraph
142− }
143−
144−mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
145−mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
146−
147−type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
148−
149−runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
150−runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
151− where
152− freshEnv = mkDatabaseContextEvalState ctx
153−
154−
155−dbcTransId :: DatabaseContextEvalMonad TransactionId
156−dbcTransId = dce_transId <$> RWS.ask
111+type DatabaseState a = State DatabaseStateElems a
157112
158−dbcGraph :: DatabaseContextEvalMonad TransactionGraph
159−dbcGraph = dce_graph <$> RWS.ask
113+getStateContext :: DatabaseState DatabaseContext
114+getStateContext = context <$> get
160115
161−dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
162−dbcRelationalExprEnv =
163− mkRelationalExprEnv <$> getStateContext <*> dbcGraph
164−
165−getStateContext :: DatabaseContextEvalMonad DatabaseContext
166−getStateContext = gets dbc_context
167−
168−putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
116+putStateContext :: DatabaseContext -> DatabaseState ()
169117putStateContext ctx' = do
170118 s <- get
171− put (s {dbc_context = ctx', dbc_dirty = True})
172−
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)
179− }
119+ put (s {context = ctx'})
180120
181−type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
182−
183−gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
184−gfTransForId tid = do
185− graph <- gfGraph
186− lift $ except $ transactionForId tid graph
187−
188−gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
189−gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
190−gfDatabaseContextForMarker UncommittedContextMarker = do
191− mctx <- gre_context <$> askEnv
192− case mctx of
193− Nothing -> throwError NoUncommittedContextInEvalError
194− Just ctx -> pure ctx
195−
196−runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
197−runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
198−
199−freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
200−freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
201− gre_context = mctx,
202− gre_graph = graph,
203− gre_extra = Nothing
204− }
205−
206−gfGraph :: GraphRefRelationalExprM TransactionGraph
207−gfGraph = asks gre_graph
121+type RelationalExprState a = Reader RelationalExprStateElems a
122+
123+stateElemsContext :: RelationalExprStateElems -> DatabaseContext
124+stateElemsContext = elems_context
125+
126+setStateElemsContext :: RelationalExprStateElems -> DatabaseContext -> RelationalExprStateElems
127+setStateElemsContext e ctx = e { elems_context = ctx }
128+
129+--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
130+evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
131+evalRelationalExpr (RelationVariable name _) = do
132+ relvarTable <- fmap (relationVariables . stateElemsContext) ask
133+ return $ case M.lookup name relvarTable of
134+ Just res -> Right res
135+ Nothing -> Left $ RelVarNotDefinedError name
136+
137+evalRelationalExpr (Project attrNames expr) = do
138+ eAttrNameSet <- evalAttributeNames attrNames expr
139+ case eAttrNameSet of
140+ Left err -> pure (Left err)
141+ Right attrNameSet -> do
142+ rel <- evalRelationalExpr expr
143+ case rel of
144+ Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
145+ Left err -> pure $ Left err
146+
147+evalRelationalExpr (Union exprA exprB) = do
148+ relA <- evalRelationalExpr exprA
149+ relB <- evalRelationalExpr exprB
150+ case relA of
151+ Left err -> return $ Left err
152+ Right relA2 -> case relB of
153+ Left err -> return $ Left err
154+ Right relB2 -> return $ Right (Union relA2 relB2)
155+
156+evalRelationalExpr (Join exprA exprB) = do
157+ relA <- evalRelationalExpr exprA
158+ relB <- evalRelationalExpr exprB
159+ case relA of
160+ Left err -> return $ Left err
161+ Right relA2 -> case relB of
162+ Left err -> return $ Left err
163+ Right relB2 -> return $ Right (Join relA2 relB2)
164+
165+evalRelationalExpr (Difference exprA exprB) = do
166+ relA <- evalRelationalExpr exprA
167+ relB <- evalRelationalExpr exprB
168+ case relA of
169+ Left err -> return $ Left err
170+ Right relA2 -> case relB of
171+ Left err -> return $ Left err
172+ Right relB2 -> return $ Right (Difference relA2 relB2)
173+
174+evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
175+ case mkRelation attributeSet tupleSet of
176+ Right rel -> return $ Right (ExistingRelation rel)
177+ Left err -> return $ Left err
178+
179+evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
180+ currentContext <- fmap stateElemsContext ask
181+ let tConss = typeConstructorMapping currentContext
182+ -- 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
183+ runExceptT $ do
184+ mAttrs <- case mAttrExprs of
185+ Just _ ->
186+ Just . A.attributesFromList <$> mapM (either throwE pure . evalAttrExpr tConss) (fromMaybe [] mAttrExprs)
187+ Nothing -> pure Nothing
188+ tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
189+ let attrs = fromMaybe firstTupleAttrs mAttrs
190+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
191+ expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
192+ pure (ExistingRelation expr)
193+
194+evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
208195
209−envContext :: RelationalExprEnv -> DatabaseContext
210−envContext = re_context
196+evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
197+ evald <- evalRelationalExpr relExpr
198+ case evald of
199+ Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
200+ Left err -> return $ Left err
211201
212−setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
213−setEnvContext e ctx = e { re_context = ctx }
202+evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
203+ eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
204+ case eOldAttrNameSet of
205+ Left err -> pure (Left err)
206+ Right oldAttrNameSet -> do
207+ evald <- evalRelationalExpr relExpr
208+ case evald of
209+ Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
210+ Left err -> return $ Left err
211+
212+evalRelationalExpr (Ungroup attrName relExpr) = do
213+ evald <- evalRelationalExpr relExpr
214+ case evald of
215+ Right expr -> return $ Right (Ungroup attrName expr)
216+ Left err -> return $ Left err
217+
218+evalRelationalExpr (Restrict predicateExpr relExpr) = do
219+ evald <- evalRelationalExpr relExpr
220+ ePred <- processRestrictionPredicateExpr predicateExpr
221+ case evald of
222+ Left err -> return $ Left err
223+ Right expr -> case ePred of
224+ Left err -> pure (Left err)
225+ Right pred -> pure $ Right (Restrict pred expr)
226+
227+evalRelationalExpr (Equals relExprA relExprB) = do
228+ evaldA <- evalRelationalExpr relExprA
229+ evaldB <- evalRelationalExpr relExprB
230+ case evaldA of
231+ Left err -> return $ Left err
232+ Right exprA -> case evaldB of
233+ Left err -> return $ Left err
234+ Right exprB -> return $ Right (Equals exprA exprB)
235+{-
236+evalRelationalExpr (With views mainExpr) = do
237+ rstate <- ask
238+
239+ let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
240+ Left (RelVarAlreadyDefinedError vname)
241+ else
242+ case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
243+ (Left err,_) -> Left err
244+ (Right (), (ctx',_,_)) -> Right ctx'
245+
246+ case foldM addScopedView (stateElemsContext rstate) views of
247+ Left err -> return $ Left err
248+ Right ctx'' -> do
249+ let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprStateElems ctx'')
250+ case evalMainExpr mainExpr of
251+ Left err -> return $ Left err
252+ Right rel -> return $ Right rel
253+-}
254+--warning: copy-pasta from above- refactor
255+evalRelationalExpr (NotEquals relExprA relExprB) = do
256+ evaldA <- evalRelationalExpr relExprA
257+ evaldB <- evalRelationalExpr relExprB
258+ case evaldA of
259+ Left err -> return $ Left err
260+ Right exprA -> case evaldB of
261+ Left err -> return $ Left err
262+ Right exprB -> return $ Right (NotEquals exprA exprB)
263+
264+-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
265+evalRelationalExpr (Extend tupleExpression relExpr) = do
266+ eExpr <- evalRelationalExpr relExpr
267+ case eExpr of
268+ Left err -> pure (Left err)
269+ Right expr -> do
270+ eTupProc <- processExtendTupleExpr tupleExpression
271+ case eTupProc of
272+ Left err -> pure (Left err)
273+ Right tupProc -> pure (Right (Extend tupProc expr))
214274
215275--helper function to process relation variable creation/assignment
216−setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
217−setRelVar relVarName relExpr = do
276+setRelVar :: RelVarName -> GraphRefRelationalExpr -> TransactionId -> TransactionGraph -> DatabaseState (Either RelationalError ())
277+setRelVar relVarName relExpr transId graph = do
218278 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
279+ let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
222280 potentialContext = currentContext { relationVariables = newRelVars }
223− --optimization: if the relexpr is unchanged, skip the update
224− if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
225− pure ()
226− else do
227− --determine when to check constraints
228− graph <- dbcGraph
229− tid <- dbcTransId
230− case checkConstraints potentialContext tid graph of
231− Left err -> dbErr err
232− Right _ -> putStateContext potentialContext
233−
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 ()
281+ --determine when to check constraints
282+
283+ case checkConstraints potentialContext transId graph of
284+ Left err -> pure (Left err)
285+ Right _ -> do
286+ putStateContext potentialContext
287+ return (Right ())
236288
237289-- 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 ()
290+deleteRelVar :: RelVarName -> DatabaseState (Either RelationalError ())
239291deleteRelVar relVarName = do
240292 currContext <- getStateContext
241293 let relVars = relationVariables currContext
242294 if M.notMember relVarName relVars then
243− pure ()
295+ pure (Right ())
244296 else do
245297 let newRelVars = M.delete relVarName relVars
246298 newContext = currContext { relationVariables = newRelVars }
247299 putStateContext newContext
248− pure ()
300+ pure (Right ())
249301
250−evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContextEvalMonad ()
251−evalGraphRefDatabaseContextExpr NoOperation = pure ()
302+evalDatabaseContextExpr :: DatabaseContextExpr -> TransactionId -> TransactionGraph -> DatabaseState (Either RelationalError ())
303+evalDatabaseContextExpr NoOperation _ _ = pure (Right ())
252304
253−evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
254− context <- getStateContext
305+evalDatabaseContextExpr (Define relVarName attrExprs) transId graph = do
255306 relvars <- fmap relationVariables getStateContext
256307 tConss <- fmap typeConstructorMapping getStateContext
257− graph <- dbcGraph
258− let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
259− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
260− case eAttrs of
261− Left err -> dbErr err
262− Right attrsList -> do
263− lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
264− case M.member relVarName relvars of
265− True -> dbErr (RelVarAlreadyDefinedError relVarName)
266− False -> setRelVar relVarName (ExistingRelation emptyRelation)
308+ let eAttrs = map (evalAttrExpr tConss) attrExprs
309+ attrErrs = lefts eAttrs
310+ attrsList = rights eAttrs
311+ if not (null attrErrs) then
312+ pure (Left (someErrors attrErrs))
313+ else do
314+ let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
315+ if not (null atomTypeErrs) then
316+ pure (Left (someErrors atomTypeErrs))
317+ else
318+ case M.member relVarName relvars of
319+ True -> pure (Left (RelVarAlreadyDefinedError relVarName))
320+ False -> setRelVar relVarName (ExistingRelation emptyRelation) transId graph >> pure (Right ())
267321 where
268322 attrs = A.attributesFromList attrsList
269323 emptyRelation = Relation attrs emptyTupleSet
270324
271−evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
325+evalDatabaseContextExpr (Undefine relVarName) _ _ = deleteRelVar relVarName
272326
273−evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
274− graph <- re_graph <$> dbcRelationalExprEnv
327+evalDatabaseContextExpr (Assign relVarName expr) transId graph = do
275328 context <- getStateContext
276329 let existingRelVar = M.lookup relVarName (relationVariables context)
277− reEnv = freshGraphRefRelationalExprEnv (Just context) graph
278− eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
330+ relExprState = mkRelationalExprState context graph
279331 case existingRelVar of
280332 Nothing -> do
281− case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
282− Left err -> dbErr err
283− Right reltype -> do
284− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
285− setRelVar relVarName expr
333+ let ervExpr = runReader (evalRelationalExpr expr) relExprState
334+ case ervExpr of
335+ Left err -> pure (Left err)
336+ Right rvExpr -> setRelVar relVarName rvExpr transId graph
286337 Just existingRel -> do
287− let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
338+ let eExpectedType = typeForGraphRefRelationalExpr existingRel graph
339+ eNewExprType = runReader (typeForRelationalExpr expr transId graph) relExprState
288340 case eExpectedType of
289− Left err -> dbErr err
341+ Left err -> pure (Left err)
290342 Right expectedType ->
291343 case eNewExprType of
292− Left err -> dbErr err
344+ Left err -> pure (Left err)
293345 Right newExprType -> do
294346 if newExprType == expectedType then do
295− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
296− setRelVar relVarName expr
347+ let ervExpr = runReader (evalRelationalExpr expr) relExprState
348+ case ervExpr of
349+ Left err -> pure (Left err)
350+ Right rvExpr -> setRelVar relVarName rvExpr transId graph
297351 else
298− dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
299−
300−evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
301− gfExpr <- relVarByName relVarName
302− let optExpr = applyUnionCollapse (Union
303− relExpr
304− gfExpr)
305− evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
306−
307−evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
308− gfExpr <- relVarByName relVarName
309− let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
310− setRelVar relVarName optExpr
352+ pure (Left (RelationTypeMismatchError (attributes expectedType) (attributes newExprType)))
353+
354+evalDatabaseContextExpr (Insert relVarName relExpr) tid graph =
355+ evalDatabaseContextExpr (Assign relVarName (Union (RelationVariable relVarName ())
356+ relExpr)) tid graph
357+
358+evalDatabaseContextExpr (Delete relVarName predicate) transId graph = do
359+ ctx <- getStateContext
360+ let rv = RelationVariable relVarName transId
361+ rvState = mkRelationalExprState ctx graph
362+ case runReader (processRestrictionPredicateExpr predicate) rvState of
363+ Left err -> pure (Left err)
364+ Right graphRefPredicate ->
365+ setRelVar relVarName (Restrict (NotPredicate graphRefPredicate) rv) transId graph
311366
312367--union of restricted+updated portion and the unrestricted+unupdated portion
313−evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
314− rvExpr <- relVarByName relVarName
315− graph <- re_graph <$> dbcRelationalExprEnv
368+evalDatabaseContextExpr (Update relVarName atomExprMap restrictionPredicateExpr) transId graph = do
316369 context <- getStateContext
317− let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
318− --get the current attributes name in the relvar to ensure that we don't conflict when renaming
319− eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
320− exprType' <- case eExprType of
321− Left err -> throwError err
322− Right t -> pure t
323− let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
324− tmpAttr = tmpAttrC 1
325− tmpAttrC :: Int -> AttributeName -> AttributeName
326− tmpAttrC c attr =
327− let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
328− if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
329− tmpAttrC (c+1) attr
330− else
331− tmpAttrName
332− updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
333− projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
334− restrictedPortion = Restrict pred' rvExpr
335− updated = foldr (\(oldname, atomExpr) accum ->
336− let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
370+ let rvState = mkRelationalExprState context graph
371+ relVarTable = relationVariables context
372+ case runReader (processRestrictionPredicateExpr restrictionPredicateExpr) rvState of
373+ Left err -> pure (Left err)
374+ Right graphRefPredicate ->
375+ case M.lookup relVarName relVarTable of
376+ Nothing -> pure (Left (RelVarNotDefinedError relVarName))
377+ Just existingRvExpr -> do
378+ let unrestrictedPortion = Restrict (NotPredicate graphRefPredicate) rv
379+ rv = RelationVariable relVarName transId
380+ tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
381+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
382+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
383+ restrictedPortion = Restrict graphRefPredicate
384+ updated = foldr (\(oldname, atomExpr) accum ->
385+ let procAtomExpr = processAtomExpr atomExpr transId in
337386 updateAttr oldname procAtomExpr accum
338− ) restrictedPortion (M.toList atomExprMap)
387+ ) rv (M.toList atomExprMap)
339388 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
340− updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
341− setRelVar relVarName (Union unrestrictedPortion updatedPortion)
389+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
390+ setRelVar relVarName (Union unrestrictedPortion updatedPortion) transId graph
342391
343−evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
392+evalDatabaseContextExpr (AddInclusionDependency newDepName newDep) transId graph = do
344393 currContext <- getStateContext
345− transId <- dbcTransId
346− graph <- dbcGraph
347394 let currDeps = inclusionDependencies currContext
348395 newDeps = M.insert newDepName newDep currDeps
349396 if M.member newDepName currDeps then
350− dbErr (InclusionDependencyNameInUseError newDepName)
397+ pure (Left (InclusionDependencyNameInUseError newDepName))
351398 else do
352399 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
355400 case checkConstraints potentialContext transId graph of
356− Left err -> dbErr err
357− Right _ ->
401+ Left err -> pure (Left err)
402+ Right _ -> do
358403 putStateContext potentialContext
404+ return (Right ())
359405
360−evalGraphRefDatabaseContextExpr (RemoveInclusionDependency depName) = do
406+evalDatabaseContextExpr (RemoveInclusionDependency depName) _ _ = do
361407 currContext <- getStateContext
362408 let currDeps = inclusionDependencies currContext
363409 newDeps = M.delete depName currDeps
364410 if M.notMember depName currDeps then
365− dbErr (InclusionDependencyNameNotInUseError depName)
366− else
411+ pure (Left (InclusionDependencyNameNotInUseError depName))
412+ else do
367413 putStateContext $ currContext {inclusionDependencies = newDeps }
414+ return (Right ())
368415
369416-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
370−evalGraphRefDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
417+evalDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) _ _ = do
371418 currentContext <- getStateContext
372419 let nots = notifications currentContext
373420 if M.member notName nots then
374− dbErr (NotificationNameInUseError notName)
421+ pure (Left (NotificationNameInUseError notName))
375422 else do
376423 let newNotifications = M.insert notName newNotification nots
377424 newNotification = Notification { changeExpr = triggerExpr,
378425 reportOldExpr = resultOldExpr,
379426 reportNewExpr = resultNewExpr}
380427 putStateContext $ currentContext { notifications = newNotifications }
428+ return (Right ())
381429
382−evalGraphRefDatabaseContextExpr (RemoveNotification notName) = do
430+evalDatabaseContextExpr (RemoveNotification notName) _ _ = do
383431 currentContext <- getStateContext
384432 let nots = notifications currentContext
385433 if M.notMember notName nots then
386− dbErr (NotificationNameNotInUseError notName)
434+ pure (Left (NotificationNameNotInUseError notName))
387435 else do
388436 let newNotifications = M.delete notName nots
389437 putStateContext $ currentContext { notifications = newNotifications }
390−
438+ pure (Right ())
391439
392440-- | Adds type and data constructors to the database context.
393441-- validate that the type *and* constructor names are unique! not yet implemented!
394−evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
442+evalDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) _ _ = do
395443 currentContext <- getStateContext
396444 let oldTypes = typeConstructorMapping currentContext
397445 tConsName = TCD.name tConsDef
398446 -- validate that the constructor's types exist
399− case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
400− Left err -> throwError err
401− Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
402− | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
447+ case validateTypeConstructorDef tConsDef dConsDefList of
448+ errs@(_:_) -> pure (Left (someErrors errs))
449+ [] | T.null tConsName || not (isUpper (T.head tConsName)) -> pure (Left (InvalidAtomTypeName tConsName))
450+ | isJust (findTypeConstructor tConsName oldTypes) -> pure (Left (AtomTypeNameInUseError tConsName))
403451 | otherwise -> do
404452 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
405453 putStateContext $ currentContext { typeConstructorMapping = newTypes }
454+ pure (Right ())
406455
407456-- | 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
457+evalDatabaseContextExpr (RemoveTypeConstructor tConsName) _ _ = do
409458 currentContext <- getStateContext
410459 let oldTypes = typeConstructorMapping currentContext
411460 if isNothing (findTypeConstructor tConsName oldTypes) then
412− dbErr (AtomTypeNameNotInUseError tConsName)
461+ pure (Left (AtomTypeNameNotInUseError tConsName))
413462 else do
414463 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
415464 putStateContext $ currentContext { typeConstructorMapping = newTypes }
465+ pure (Right ())
416466
417−evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
467+evalDatabaseContextExpr (MultipleExpr exprs) transId graph = do
418468 --the multiple expressions must pass the same context around- not the old unmodified context
419− mapM_ evalGraphRefDatabaseContextExpr exprs
420−
421−evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
469+ evald <- forM exprs (\expr -> evalDatabaseContextExpr expr transId graph)
470+ --some lifting magic needed here
471+ case lefts evald of
472+ [] -> pure (Right ())
473+ errs -> pure (Left (someErrors errs))
474+
475+evalDatabaseContextExpr (RemoveAtomFunction funcName) _ _ = do
422476 currentContext <- getStateContext
423477 let atomFuncs = atomFunctions currentContext
424478 case atomFunctionForName funcName atomFuncs of
425− Left err -> dbErr err
426− Right realFunc ->
427− if isScriptedAtomFunction realFunc then do
428− let updatedFuncs = HS.delete realFunc atomFuncs
429− putStateContext (currentContext {atomFunctions = updatedFuncs })
430− else
431− dbErr (PrecompiledFunctionRemoveError funcName)
479+ Left err -> pure (Left err)
480+ Right realFunc -> if isScriptedAtomFunction realFunc then do
481+ let updatedFuncs = HS.delete realFunc atomFuncs
482+ putStateContext (currentContext {atomFunctions = updatedFuncs })
483+ pure (Right ())
484+ else
485+ pure (Left (PrecompiledFunctionRemoveError funcName))
432486
433−evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
487+evalDatabaseContextExpr (RemoveDatabaseContextFunction funcName) _ _ = do
434488 context <- getStateContext
435489 let dbcFuncs = dbcFunctions context
436490 case databaseContextFunctionForName funcName dbcFuncs of
437− Left err -> dbErr err
438− Right realFunc ->
439− if isScriptedDatabaseContextFunction realFunc then do
440− let updatedFuncs = HS.delete realFunc dbcFuncs
441− putStateContext (context { dbcFunctions = updatedFuncs })
442− else
443− dbErr (PrecompiledFunctionRemoveError funcName)
491+ Left err -> pure (Left err)
492+ Right realFunc -> if isScriptedDatabaseContextFunction realFunc then do
493+ let updatedFuncs = HS.delete realFunc dbcFuncs
494+ putStateContext (context { dbcFunctions = updatedFuncs })
495+ pure (Right ())
496+ else
497+ pure (Left (PrecompiledFunctionRemoveError funcName))
444498
445−evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
499+evalDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) _ graph = do
446500 context <- getStateContext
447− graph <- dbcGraph
448501 --resolve atom arguments
449− let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
502+ let relExprState = mkRelationalExprState context graph
503+ eAtomTypes = map (\atomExpr -> runReader (typeFromAtomExpr emptyAttributes atomExpr) relExprState) atomArgExprs
450504 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
451− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
452505 case eFunc of
453− Left err -> dbErr err
506+ Left err -> pure (Left err)
454507 Right func -> do
455508 let expectedArgCount = length (dbcFuncType func)
456509 actualArgCount = length atomArgExprs
457510 if expectedArgCount /= actualArgCount then
458− dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
511+ pure (Left (FunctionArgumentCountMismatchError expectedArgCount actualArgCount))
459512 else
460513 --check that the atom types are valid
461− case eAtomTypes of
462− Left err -> dbErr err
463− Right atomTypes -> do
464− let mValidTypes = zipWith (\ expType actType
465− -> case atomTypeVerify expType actType of
466− Left err -> Just err
467− Right _ -> Nothing)
468− (dbcFuncType func) atomTypes
514+ case lefts eAtomTypes of
515+ _:_ -> pure (Left (someErrors (lefts eAtomTypes)))
516+ [] -> do
517+ let atomTypes = rights eAtomTypes
518+ let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
519+ Left err -> Just err
520+ Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
469521 typeErrors = catMaybes mValidTypes
470− eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
522+ eAtomArgs = unimplemented
523+ --eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
471524 if length (lefts eAtomArgs) > 1 then
472− dbErr (someErrors (lefts eAtomArgs))
525+ pure (Left (someErrors (lefts eAtomArgs)))
473526 else if not (null typeErrors) then
474− dbErr (someErrors typeErrors)
527+ pure (Left (someErrors typeErrors))
475528 else
476529 case evalDatabaseContextFunction func (rights eAtomArgs) context of
477− Left err -> dbErr err
478− Right newContext -> putStateContext newContext
479−data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
480− { dbcio_transId :: TransactionId,
481− dbcio_graph :: TransactionGraph,
482− dbcio_mScriptSession :: Maybe ScriptSession
483− }
484−
485−type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
486−
487−runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
488−runDatabaseContextIOEvalMonad env ctx m = do
489− res <- runRWST m env freshState
490− case res of
491− (Left err,_,_) -> pure (Left err)
492− (Right (),s,_) -> pure (Right s)
493− where
494− freshState = mkDatabaseContextEvalState ctx
495−
496−requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
497−requireScriptSession = do
498− env <- RWS.ask
499− case dbcio_mScriptSession env of
500− Nothing -> pure $ Left $ ScriptError ScriptCompilationDisabledError
501− Just ss -> pure (Right ss)
502−
503−putDBCIOContext :: DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ())
504−putDBCIOContext ctx = do
505− RWS.modify (\dbstate -> dbstate { dbc_context = ctx})
506− pure (Right ())
507−
508−getDBCIOContext :: DatabaseContextIOEvalMonad DatabaseContext
509−getDBCIOContext = dbc_context <$> RWS.get
510−
511−getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
512−getDBCIORelationalExprEnv = do
513− context <- getDBCIOContext
514− mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
515−
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))
522−#else
523−evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
524− eScriptSession <- requireScriptSession
525− currentContext <- getDBCIOContext
526− case eScriptSession of
527− Left err -> pure (Left err)
528− Right scriptSession -> do
529− res <- liftIO $ try $ runGhc (Just libdir) $ do
530+ Left err -> pure (Left err)
531+ Right newContext -> putStateContext newContext >> pure (Right ())
532+
533+evalDatabaseContextIOExpr :: Maybe ScriptSession -> DatabaseContext -> TransactionId -> TransactionGraph -> DatabaseContextIOExpr -> IO (Either RelationalError DatabaseContext)
534+evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddAtomFunction funcName funcType script) =
535+ case mScriptSession of
536+ Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
537+ Just scriptSession -> do
538+ res <- try $ runGhc (Just libdir) $ do
530539 setSession (hscEnv scriptSession)
531540 let atomFuncs = atomFunctions currentContext
532541 case extractAtomFunctionType funcType of
@@ -552,13 +561,12 @@ evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = d
552561 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
553562 Right eContext -> case eContext of
554563 Left err -> pure (Left err)
555− Right context' -> putDBCIOContext context'
556−evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
557− eScriptSession <- requireScriptSession
558− currentContext <- getDBCIOContext
559− case eScriptSession of
560− Left err -> pure (Left err)
561− Right scriptSession -> do
564+ Right context' -> pure (Right context')
565+
566+evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddDatabaseContextFunction funcName funcType script) =
567+ case mScriptSession of
568+ Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
569+ Just scriptSession -> do
562570 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
563571 let last2Args = reverse (take 2 (reverse funcType))
564572 atomArgs = take (length funcType - 2) funcType
@@ -568,7 +576,7 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
568576 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
569577 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
570578 else do
571− res <- liftIO $ try $ runGhc (Just libdir) $ do
579+ res <- try $ runGhc (Just libdir) $ do
572580 setSession (hscEnv scriptSession)
573581 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
574582 pure $ case eCompiledFunc of
@@ -593,86 +601,79 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
593601 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
594602 Right eContext -> case eContext of
595603 Left err -> pure (Left err)
596− Right context' -> putDBCIOContext context'
597−evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
598− currentContext <- getDBCIOContext
599− eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
604+ Right context' -> pure (Right context')
605+evalDatabaseContextIOExpr _ currentContext _ _ (LoadAtomFunctions modName funcName modPath) = do
606+ eLoadFunc <- loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
600607 case eLoadFunc of
601608 Left LoadSymbolError -> pure (Left LoadFunctionError)
602609 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
603610 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
604− in putDBCIOContext newContext
605−evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName modPath) = do
606− currentContext <- getDBCIOContext
607− eLoadFunc <- liftIO $ loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
611+ in pure (Right newContext)
612+evalDatabaseContextIOExpr _ currentContext _ _ (LoadDatabaseContextFunctions modName funcName modPath) = do
613+ eLoadFunc <- loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
608614 case eLoadFunc of
609615 Left LoadSymbolError -> pure (Left LoadFunctionError)
610616 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
611617 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
612− in putDBCIOContext newContext
613−#endif
614−evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
618+ in pure (Right newContext)
619+
620+evalDatabaseContextIOExpr _ currentContext transId graph (CreateArbitraryRelation relVarName attrExprs range) =
615621 --Define
616− currentContext <- getDBCIOContext
617− env <- RWS.ask
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)
624− Right dbstate -> do
622+ case runState (evalDatabaseContextExpr (Define relVarName attrExprs) transId graph) (freshDatabaseState currentContext) of
623+ (Left err,_) -> pure (Left err)
624+ (Right (), elems) -> do
625625 --Assign
626626 let existingRelVar = M.lookup relVarName relVarTable
627− relVarTable = relationVariables (dbc_context dbstate)
627+ relVarTable = relationVariables (context elems)
628628 case existingRelVar of
629629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
630630 Just existingRel -> do
631− let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
632− case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
631+ case typeForGraphRefRelationalExpr existingRel graph of
633632 Left err -> pure (Left err)
634633 Right relType -> do
635634 let expectedAttributes = attributes relType
636− tcMap = typeConstructorMapping (dbc_context dbstate)
637− eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
635+ tcMap = typeConstructorMapping (context elems)
636+ eitherRel <- generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
638637 case eitherRel of
639638 Left err -> pure $ Left err
640639 Right rel ->
641− case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
642− Left err -> pure (Left err)
643− Right dbstate' -> putDBCIOContext (dbc_context dbstate')
640+ case runState (setRelVar relVarName (ExistingRelation rel) transId graph) elems of
641+ (Left err,_) -> pure (Left err)
642+ (Right (), elems') -> pure $ Right (context elems)
643+
644+updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
645+updateTupleWithAtomExprs exprMap context graph tupIn = do
646+ --resolve all atom exprs
647+ atomsAssoc <- mapM (\(attrName, atomExpr) -> do
648+ let atom = unimplemented
649+ --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
650+ pure (attrName, atom)
651+ ) (M.toList exprMap)
652+ pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
644653
645654--run verification on all constraints
646655checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
647−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
656+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
648657 mapM_ (uncurry checkIncDep) (M.toList deps)
649658 where
650659 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
651660 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
652661 utctDayTime = secondsToDiffTime 0 }
653662 tempSchemas = Schemas context M.empty
654− tempTrans = Transaction U.nil tempTransInfo tempSchemas
655− tempTransInfo = TransactionInfo { parents = transId NE.:| [],
656− stamp = tempStamp,
657− merkleHash = mempty
658− }
663+ tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
659664
660665 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
666+ eval expr = evalReader (evalRelationalExpr expr)
667+ evalReader f = runReader f (mkRelationalExprState context graph)
662668 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
663− let process = runProcessExprM UncommittedContextMarker
664− gfSubsetExpr = process (processRelationalExpr subsetExpr)
665− gfSupersetExpr = process (processRelationalExpr supersetExpr)
669+ let gfSubsetExpr = processRelationalExpr subsetExpr transId
670+ gfSupersetExpr = processRelationalExpr supersetExpr transId
666671 --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
668− runGfRel = runGraphRefRelationalExprM gfEnv
669− typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
670− typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
672+ typeSub <- evalReader (typeForRelationalExpr subsetExpr transId graph)
673+ typeSuper <- evalReader (typeForRelationalExpr supersetExpr transId graph)
671674 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
672675 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
673− gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
674− gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
675− case gfEvald of
676+ case evalGraphRefRelationalExpr checkExpr potentialGraph of
676677 Left err -> Left err
677678 Right resultRel -> if resultRel == relationTrue then
678679 pure ()
@@ -682,81 +683,89 @@ checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
682683-- 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
683684-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
684685
685−typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
686−typeForRelationalExpr expr = do
686+typeForRelationalExpr :: RelationalExpr -> TransactionId -> TransactionGraph -> RelationalExprState (Either RelationalError Relation)
687+typeForRelationalExpr expr transId graph = do
688+ rstate <- ask
689+ let context = stateElemsContext rstate
687690 --replace the relationVariables context element with a cloned set of relation devoid of tuples
688691 --evalRelationalExpr could still return an existing relation with tuples, so strip them
689− graph <- reGraph
690− context <- reContext
691− let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
692− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
693− runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
694− lift $ except runGf
692+ let gfExpr = processRelationalExpr expr transId
693+ pure (typeForGraphRefRelationalExpr gfExpr graph)
694+
695+--returns a database context with all tuples removed
696+--this is useful for type checking and optimization
697+{-
698+contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
699+contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
700+ where
701+ relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
702+-}
695703
696704liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
697705liftE v = do
698706 y <- lift v
699707 case y of
700− Left err -> throwError err
708+ Left err -> throwE err
701709 Right val -> pure val
702710
703711{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
704−predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
705−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
706− expr1v <- predicateRestrictionFilter attrs expr1
707− expr2v <- predicateRestrictionFilter attrs expr2
708− pure (\x -> do
709− ev1 <- expr1v x
710− ev2 <- expr2v x
711− pure (ev1 && ev2))
712−
713−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
714− expr1v <- predicateRestrictionFilter attrs expr1
715− expr2v <- predicateRestrictionFilter attrs expr2
712+predicateRestrictionFilter :: Attributes -> RestrictionPredicateExprBase a -> RelationalExprState (Either RelationalError RestrictionFilter)
713+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
714+ runExceptT $ do
715+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
716+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
717+ pure (\x -> do
718+ ev1 <- expr1v x
719+ ev2 <- expr2v x
720+ pure (ev1 && ev2))
721+
722+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
723+ runExceptT $ do
724+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
725+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
716726 pure (\x -> do
717727 ev1 <- expr1v x
718728 ev2 <- expr2v x
719729 pure (ev1 || ev2))
720730
721−predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
731+predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
722732
723−predicateRestrictionFilter attrs (NotPredicate expr) = do
724− exprv <- predicateRestrictionFilter attrs expr
725− pure (fmap not . exprv)
733+predicateRestrictionFilter attrs (NotPredicate expr) =
734+ runExceptT $ do
735+ exprv <- liftE (predicateRestrictionFilter attrs expr)
736+ pure (fmap not . exprv)
726737
727738--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
739+{-
728740predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
729− renv <- askEnv
730− let eval :: RelationTuple -> Either RelationalError Relation
731− eval tup =
732− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
733− runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
734− pure (\tup -> case eval tup of
741+ rstate <- ask
742+ pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
735743 Left err -> Left err
736744 Right rel -> if arity rel /= 0 then
737745 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
738746 else
739− pure (rel == relationTrue))
747+ pure (rel == relationTrue)))
740748
741749predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
742− env <- askEnv
743− let attrs' = A.union attrs (envAttributes env)
744− ctxtup' = envTuple env
745− atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
746− attr <- lift $ except $ case A.attributeForName attrName attrs of
750+ rstate <- ask
751+ let attrs' = stateAttributes rstate
752+ ctxtup' = stateTuple rstate
753+ runExceptT $ do
754+ atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
755+ attr <- either throwE pure $ case A.attributeForName attrName attrs of
747756 Right attr -> Right attr
748757 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
749758 Right ctxattr -> Right ctxattr
750759 Left err2@(NoSuchAttributeNamesError _) -> Left err2
751760 Left err -> Left err
752761 Left err -> Left err
753− if atomExprType /= A.atomType attr then
754− throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
755− else
762+ if atomExprType /= A.atomType attr then
763+ throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
764+ else
756765 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
757766 Right atomCmp -> atomCmp == atomIn
758767 Left _ -> False
759− atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
768+ atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
760769 in
761770 pure $ case atomForAttributeName attrName tupleIn of
762771 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -767,327 +776,266 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
767776-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
768777predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
769778 --merge attrs into the state attributes
770− renv <- askEnv
771− aType <- typeForGraphRefAtomExpr attrs atomExpr
772− if aType /= BoolAtomType then
773− throwError (AtomTypeMismatchError aType BoolAtomType)
774− else
779+ rstate <- ask
780+ runExceptT $ do
781+ aType <- liftE (typeFromAtomExpr attrs atomExpr)
782+ if aType /= BoolAtomType then
783+ throwE (AtomTypeMismatchError aType BoolAtomType)
784+ else
775785 pure (\tupleIn ->
776− case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
777− Left err -> Left err
778− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
779−
786+ case runReader (evalAtomExpr tupleIn atomExpr) rstate of
787+ Left err -> Left err
788+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
789+-}
780790tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
781791tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
782792 Left (AttributeNameInUseError attrName)
783793 else
784794 Right rel
785795
786−extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
787−extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
788−-- renv <- askEnv
796+extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
797+extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
798+ rstate <- ask
789799 -- check that the attribute name is not in use
790800 case tupleExprCheckNewAttrName newAttrName relIn of
791− Left err -> throwError err
792− Right _ -> do
793− atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
794− atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
801+ Left err -> pure (Left err)
802+ Right _ -> runExceptT $ do
803+ atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
804+ atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
795805 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
796806 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
797− env <- ask
798− pure (newAndOldAttrs, \tup -> do
799− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
800− atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
801− Right (tupleAtomExtend newAttrName atom tup)
807+ pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in
808+ case unimplemented {-runReader (evalAtomExpr tup atomExpr) substate-} of
809+ Left err -> Left err
810+ Right atom -> Right (tupleAtomExtend newAttrName atom tup)
802811 )
803−
804−evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
805−evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
806− case atomForAttributeName attrName tupIn of
807− Right atom -> pure atom
808− Left err@(NoSuchAttributeNamesError _) -> do
809− env <- askEnv
810− case gre_extra env of
811− Nothing -> throwError err
812− Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
813− Just (Right _) -> throwError err
814− Left err -> throwError err
815−evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
816−evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
817− argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
818− context <- gfDatabaseContextForMarker tid
819− let functions = atomFunctions context
820− func <- lift $ except (atomFunctionForName funcName functions)
821− let expectedArgCount = length (atomFuncType func) - 1
822− actualArgCount = length argTypes
823− safeInit [] = [] -- different behavior from normal init
824− safeInit xs = init xs
825− if expectedArgCount /= actualArgCount then
826− throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
827− else do
812+{-
813+evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
814+evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
815+ Right atom -> pure (Right atom)
816+ err@(Left (NoSuchAttributeNamesError _)) -> do
817+ rstate <- ask
818+ let stateTup = stateTuple rstate
819+ pure (atomForAttributeName attrName stateTup)
820+ Left err -> pure (Left err)
821+evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
822+evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
823+ argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
824+ context <- fmap stateElemsContext ask
825+ runExceptT $ do
826+ let functions = atomFunctions context
827+ func <- either throwE pure (atomFunctionForName funcName functions)
828+ let expectedArgCount = length (atomFuncType func) - 1
829+ actualArgCount = length argTypes
830+ safeInit [] = [] -- different behavior from normal init
831+ safeInit xs = init xs
832+ if expectedArgCount /= actualArgCount then
833+ throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
834+ else do
828835 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
829− mapM_ (\(expType, actType) ->
830− lift $ except (atomTypeVerify expType actType)) zippedArgs
831− evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
836+ mapM_ (\(expType, eActType) -> do
837+ actType <- either throwE pure eActType
838+ either throwE pure (atomTypeVerify expType actType)) zippedArgs
839+ evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
832840 case evalAtomFunction func evaldArgs of
833− Left err -> throwError (AtomFunctionUserError err)
841+ Left err -> throwE (AtomFunctionUserError err)
834842 Right result -> do
835843 --validate that the result matches the expected type
836− _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
844+ _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
837845 pure result
838−evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
846+evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
839847 --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
841− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
842− relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
843− pure (RelationAtom relAtom)
844−evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
845− let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
846− aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
847− argAtoms <- local mergeEnv $
848− mapM (evalGraphRefAtomExpr tupIn) dConsArgs
848+ rstate <- ask
849+ runExceptT $ do
850+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
851+ relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
852+ pure (RelationAtom relAtom)
853+evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
854+ rstate <- lift ask
855+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
856+ aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
857+ argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
849858 pure (ConstructedAtom dConsName aType argAtoms)
850−
851−typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
852−typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
853− renv <- askEnv
859+-}
860+typeFromAtomExpr :: Attributes -> AtomExpr -> RelationalExprState (Either RelationalError AtomType)
861+typeFromAtomExpr attrs (AttributeAtomExpr attrName) = do
862+ rstate <- ask
854863 case A.atomTypeForAttributeName attrName attrs of
855− Right aType -> pure aType
864+ Right aType -> pure (Right aType)
856865 Left err@(NoSuchAttributeNamesError _) ->
857− let envTup = envTuple renv
858− envAttrs = envAttributes renv in
859− case A.attributeForName attrName envAttrs of
860− Right attr -> pure (A.atomType attr)
861− Left _ -> case atomForAttributeName attrName envTup of
862− Right atom -> pure (atomTypeForAtom atom)
863− Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
864− throwError err
865− Left err -> throwError err
866−
867−typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
868−typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
869− funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
866+ let stateTup = stateTuple rstate
867+ stateAttrs = stateAttributes rstate in
868+ case A.attributeForName attrName stateAttrs of
869+ Right attr -> pure (Right (A.atomType attr))
870+ Left _ -> case atomForAttributeName attrName stateTup of
871+ Right atom -> pure (Right (atomTypeForAtom atom))
872+ Left _ -> pure (Left err)
873+
874+typeFromAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
875+typeFromAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
876+ context <- fmap stateElemsContext ask
877+ let funcs = atomFunctions context
870878 case atomFunctionForName funcName funcs of
871− Left err -> throwError err
879+ Left err -> pure (Left err)
872880 Right func -> do
873881 let funcRetType = last (atomFuncType func)
874882 funcArgTypes = init (atomFuncType func)
875− argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
876− let eTvMap = resolveTypeVariables funcArgTypes argTypes
877− case eTvMap of
878− Left err -> throwError err
879− Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
880−typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
881− relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
883+ eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
884+ case lefts eArgTypes of
885+ errs@(_:_) -> pure (Left (someErrors errs))
886+ [] -> do
887+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
888+ argTypes = rights eArgTypes
889+ case eTvMap of
890+ Left err -> pure (Left err)
891+ Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
892+typeFromAtomExpr attrs (RelationAtomExpr relExpr) = runExceptT $ do
893+ rstate <- lift ask
894+ relType <- either throwE pure (runReader (typeForRelationalExpr relExpr () (mergeAttributesIntoRelationalExprState attrs rstate))
882895 pure (RelationAtomType (attributes relType))
883896-- grab the type of the data constructor, then validate that the args match the expected types
884−typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
885− do
886− argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
887− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
888− lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
897+typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
898+ runExceptT $ do
899+ argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
900+ context <- fmap stateElemsContext (lift ask)
901+ either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
889902
890903-- | Validate that the type of the AtomExpr matches the expected type.
891−verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
892−verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
893− env <- askEnv
904+verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
905+verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
906+ rstate <- lift ask
894907 case A.atomTypeForAttributeName attrName (attributes relIn) of
895− Right aType -> lift $ except $ atomTypeVerify expectedType aType
908+ Right aType -> either throwE pure (atomTypeVerify expectedType aType)
896909 (Left err@(NoSuchAttributeNamesError _)) ->
897− let attrs' = envAttributes env in
910+ let attrs' = stateAttrs rstate in
898911 if attrs' == emptyAttributes then
899− throwError err
912+ throwE err
900913 else
901− case A.attributeForName attrName attrs' of
902− Left err' -> throwError err'
903− Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
904− Left err -> throwError err
905−
906−verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
907− lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
908−verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
909− context <- gfDatabaseContextForMarker tid
914+ case A.attributeForName attrName attrs of
915+ Left err' -> throwE err'
916+ Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
917+verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
918+verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
919+ rstate <- ask
910920 let functions = atomFunctions context
911− func <- lift $ except $ atomFunctionForName funcName functions
912− let expectedArgTypes = atomFuncType func
913− funcArgVerifier (atomExpr, expectedType2, argCount) = do
914− let handler :: RelationalError -> GraphRefRelationalExprM AtomType
915− handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
916− handler err = throwError err
917− verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
918− funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
919− if length funcArgTypes /= length expectedArgTypes - 1 then
920− throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
921+ context = stateElemsContext rstate
922+ runExceptT $ do
923+ func <- either throwE pure (atomFunctionForName funcName functions)
924+ let expectedArgTypes = atomFuncType func
925+ funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
926+ Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
927+ Left err -> throwE err
928+ Right x -> pure x
929+ ) $ zip3 funcArgExprs expectedArgTypes [1..]
930+ if length funcArgTypes /= length expectedArgTypes - 1 then
931+ throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
921932 else
922− lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
923−verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
924− do
925− let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
926− relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
927− lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
928−verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
929− cType <- typeForGraphRefAtomExpr (attributes rel) cons
930− lift $ except $ atomTypeVerify expectedType cType
933+ either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
934+verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
935+ rstate <- lift ask
936+ relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
937+ either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
938+verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
939+ cType <- liftE (typeFromAtomExpr (attributes rel) cons)
940+ either throwE pure (atomTypeVerify expectedType cType)
931941
932942-- | Look up the type's name and create a new attribute.
933−evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
934−evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
935− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
936− aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
937− lift $ except $ validateAtomType aType tConsMap
938− pure $ Attribute attrName aType
943+evalAttrExpr :: TypeConstructorMapping -> AttributeExpr -> Either RelationalError Attribute
944+evalAttrExpr aTypes (AttributeAndTypeNameExpr attrName tCons ()) = do
945+ aType <- atomTypeForTypeConstructorValidate True tCons aTypes M.empty
946+ validateAtomType aType aTypes
947+ Right (Attribute attrName aType)
948+
949+evalAttrExpr _ (NakedAttributeExpr attr) = Right attr
939950
940−evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
941−
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
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
949− Nothing ->
950− case tuples of
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])
954− let
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
958− pure accAttr
959− else
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
971− pure nextTupleAttrs
972− else
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
986−
987−
988−--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
989−
990−evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
991−evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
951+evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
952+evalTupleExpr mAttrs (TupleExpr tupMap) = do
953+ context <- fmap stateElemsContext ask
954+ runExceptT $ do
992955 -- 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
993956 -- 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
995− resolveOneAtom (attrName, aExpr) =
996− do
997− --provided when the relation header is available
998− let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
999− unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
1000− resolvedType <- case eExpectedAtomType of
957+ let attrs = fromMaybe A.emptyAttributes mAttrs
958+ attrAtoms <- mapM (\(attrName, aExpr) -> do
959+ --provided when the relation header is available
960+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
961+ unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
962+ resolvedType <- case eExpectedAtomType of
1001963 Left _ -> pure unresolvedType
1002− Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
964+ Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
1003965 --resolve atom typevars based on resolvedType?
1004− newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
1005− pure (attrName, newAtom, resolvedType)
1006− attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
1007− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1008− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1009− tup = mkRelationTuple tupAttrs atoms
1010− finalAttrs = fromMaybe tupAttrs mAttrs
966+ newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
967+ pure (attrName, newAtom, resolvedType)
968+ ) (M.toList tupMap)
969+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
970+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
971+ tup = mkRelationTuple tupAttrs atoms
972+ tConss = typeConstructorMapping context
973+ finalAttrs = fromMaybe tupAttrs mAttrs
1011974 --verify that the attributes match
1012− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (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))
1015− let tup' = reorderTuple finalAttrs tup
1016− --TODO: restore type resolution
1017−-- _ <- lift $ except (validateTuple tup' tConss)
1018− pure tup'
1019−
1020−--temporary implementation until we have a proper planner+executor
1021−evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1022−evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1023− mAttrs <- case mAttrExprs of
1024− Just _ ->
1025− Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1026− Nothing -> pure Nothing
1027− tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1028− let attrs = fromMaybe firstTupleAttrs mAttrs
1029− firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1030− lift $ except $ mkRelation attrs (RelationTupleSet tuples)
1031−evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
1032− lift $ except $ mkRelation attributeSet tupleSet
1033−evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1034−evalGraphRefRelationalExpr (RelationVariable name tid) = do
1035− ctx <- gfDatabaseContextForMarker tid
975+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
976+ tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
977+ _ <- either throwE pure (validateTuple tup' tConss)
978+ pure tup'
979+
980+evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
981+evalAttributeNames attrNames expr = do
982+ eExprType <- typeForRelationalExpr expr
983+ case eExprType of
984+ Left err -> pure (Left err)
985+ Right exprTyp -> do
986+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
987+ case attrNames of
988+ AttributeNames names ->
989+ case A.projectionAttributesForNames names (attributes exprTyp) of
990+ Left err -> pure (Left err)
991+ Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
992+
993+ InvertedAttributeNames names -> do
994+ let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
995+ if not (S.null nonExistentAttributeNames) then
996+ pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
997+ else
998+ pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
999+
1000+ UnionAttributeNames namesA namesB -> do
1001+ eNameSetA <- evalAttributeNames namesA expr
1002+ case eNameSetA of
1003+ Left err -> pure (Left err)
1004+ Right nameSetA -> do
1005+ eNameSetB <- evalAttributeNames namesB expr
1006+ case eNameSetB of
1007+ Left err -> pure (Left err)
1008+ Right nameSetB ->
1009+ pure (Right (S.union nameSetA nameSetB))
1010+
1011+ IntersectAttributeNames namesA namesB -> do
1012+ eNameSetA <- evalAttributeNames namesA expr
1013+ case eNameSetA of
1014+ Left err -> pure (Left err)
1015+ Right nameSetA -> do
1016+ eNameSetB <- evalAttributeNames namesB expr
1017+ case eNameSetB of
1018+ Left err -> pure (Left err)
1019+ Right nameSetB ->
1020+ pure (Right (S.intersection nameSetA nameSetB))
1021+
1022+ RelationalExprAttributeNames attrExpr -> do
1023+ eAttrExprType <- typeForRelationalExpr attrExpr
1024+ case eAttrExprType of
1025+ Left err -> pure (Left err)
1026+ Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1027+
1028+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError Relation
1029+evalGraphRefRelationalExpr (RelationVariable name tid) graph = do
1030+ ctx <- dbContextForTransId tid graph
10361031 case M.lookup name (relationVariables ctx) of
1037− Nothing -> throwError (RelVarNotDefinedError name)
1038− Just rv -> evalGraphRefRelationalExpr rv
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)
1032+ Nothing -> Left (RelVarNotDefinedError name)
1033+ Just rv -> evalGraphRefRelationalExpr rv graph
10861034
10871035dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
10881036dbContextForTransId tid graph = do
10891037 trans <- transactionForId tid graph
1090− pure (concreteDatabaseContext trans)
1038+ pure (concreteDatabaseContext ctx)
10911039
10921040transactionForId :: TransactionId -> TransactionGraph -> Either RelationalError Transaction
10931041transactionForId tid graph
@@ -1100,293 +1048,113 @@ transactionForId tid graph
11001048 where
11011049 matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
11021050
1103−typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1104−typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1105−typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1106−typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1107− mAttrs <- case mAttrExprs of
1108− Just attrExprs -> do
1109− attrs <- mapM evalGraphRefAttributeExpr attrExprs
1110− pure (Just (attributesFromList 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
1117−
1118−typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1119− relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1051+processRestrictionPredicateExpr :: RestrictionPredicateExpr -> RelationalExprState (Either RelationalError GraphRefRestrictionPredicateExpr)
1052+processRestrictionPredicateExpr TruePredicate = TruePredicate
1053+processRestrictionPredicateExpr (AndPredicate a b) = pure $ AndPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
1054+processRestrictionPredicateExpr (OrPredicate a b) = OrPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
1055+processRestrictionPredicateExpr (NotPredicate a) = pure $ NotPredicate <$> processRestrictionPredicateExpr a
1056+processRestrictionPredicateExpr (RelationalExprPredicate expr) = pure $ RelationalExprPredicate <$> evalRelationalExpr expr
1057+processRestrictionPredicateExpr (AtomExprPredicate expr) = AtomExprPredicate <$> evalAtomExpr expr
1058+processRestrictionPredicateExpr (AttributeEqualityPredicate nam expr) = AttributeEqualityPredicate nam <$> evalAtomExpr expr
1059+
1060+processExtendTupleExpr :: ExtendTupleExpr -> RelationalExprState (Either RelationalError (ExtendTupleExprBase a))
1061+processExtendTupleExpr (AttributeExtendTupleExpr nam atomExpr) = do
1062+ eExpr <- evalAtomExpr atomExpr
1063+ case eExpr of
1064+ Left err -> pure (Left err)
1065+ Right expr -> pure (Right (AttributeExtendTupleExpr nam expr))
1066+
1067+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError Relation
1068+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) _ = mkRelation attrs emptyTupleSet
1069+typeForGraphRefRelationalExpr (ExistingRelation rel) _ = pure (emptyRelationWithAttrs (attributes rel))
1070+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) graph =
1071+ case mAttrExprs of
1072+ Just attrExprs -> do
1073+ attrs <- mapM (\e -> evalGraphRefAttributeExpr e graph) attrExprs
1074+ pure (emptyRelationWithAttrs attrs)
1075+typeForGraphRefRelationalExpr (RelationVariable rvName tid) graph = do
1076+ trans <- transactionForId tid graph
1077+ let relVars = relationVariables (concreteDatabaseContext trans)
11201078 case M.lookup rvName relVars of
1121− Nothing -> throwError (RelVarNotDefinedError rvName)
1122− Just rvExpr ->
1123− typeForGraphRefRelationalExpr rvExpr
1124−typeForGraphRefRelationalExpr (Project attrNames expr) = do
1125− exprType' <- typeForGraphRefRelationalExpr expr
1126− projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1127− lift $ except $ project projectionAttrs exprType'
1128−typeForGraphRefRelationalExpr (Union exprA exprB) = do
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{} =
1155− pure relationFalse
1156−typeForGraphRefRelationalExpr NotEquals{} =
1157− pure relationFalse
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
1167− Nothing -> pure ()
1168− mapM_ (checkMacroName . fst) withs
1169− typeForGraphRefRelationalExpr expr'
1170−
1171−evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1172−evalGraphRefAttributeNames attrNames expr = do
1173− exprType' <- typeForGraphRefRelationalExpr expr
1174− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1079+ Nothing -> Left $ RelVarNotDefinedError name
1080+ Just rvExpr -> typeForGraphRefRelationalExpr rvExpr graph
1081+typeForGraphRefRelationalExpr (Project attrNames expr) graph = do
1082+ exprType <- typeForGraphRefRelationalExpr expr graph
1083+ projectionAttrs <- evalGraphRefAttributeNames attrNames expr graph
1084+ project projectionAttrs exprType
1085+
1086+evalGraphRefAttributeNames :: AttributeNames -> GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError (S.Set AttributeName)
1087+evalGraphRefAttributeNames attrNames expr graph = do
1088+ exprTyp <- typeForGraphRefRelationalExpr expr graph
1089+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
11751090 case attrNames of
1176− AttributeNames names ->
1177− case A.projectionAttributesForNames names (attributes exprType') of
1178− Left err -> throwError err
1179− Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1091+ AttributeNames names ->
1092+ case A.projectionAttributesForNames names (attributes exprTyp) of
1093+ Left err -> pure (Left err)
1094+ Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
11801095
1181− InvertedAttributeNames names -> do
1096+ InvertedAttributeNames names -> do
11821097 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
11831098 if not (S.null nonExistentAttributeNames) then
1184− throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1099+ pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
11851100 else
1186− pure (A.nonMatchingAttributeNameSet names typeNameSet)
1101+ pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
11871102
1188− UnionAttributeNames namesA namesB -> do
1189− nameSetA <- evalGraphRefAttributeNames namesA expr
1190− nameSetB <- evalGraphRefAttributeNames namesB expr
1191− pure (S.union nameSetA nameSetB)
1103+ UnionAttributeNames namesA namesB -> do
1104+ eNameSetA <- evalAttributeNames namesA expr
1105+ case eNameSetA of
1106+ Left err -> pure (Left err)
1107+ Right nameSetA -> do
1108+ eNameSetB <- evalAttributeNames namesB expr
1109+ case eNameSetB of
1110+ Left err -> pure (Left err)
1111+ Right nameSetB ->
1112+ pure (Right (S.union nameSetA nameSetB))
11921113
1193− IntersectAttributeNames namesA namesB -> do
1194− nameSetA <- evalGraphRefAttributeNames namesA expr
1195− nameSetB <- evalGraphRefAttributeNames namesB expr
1196− pure (S.intersection nameSetA nameSetB)
1114+ IntersectAttributeNames namesA namesB -> do
1115+ eNameSetA <- evalAttributeNames namesA expr
1116+ case eNameSetA of
1117+ Left err -> pure (Left err)
1118+ Right nameSetA -> do
1119+ eNameSetB <- evalAttributeNames namesB expr
1120+ case eNameSetB of
1121+ Left err -> pure (Left err)
1122+ Right nameSetB ->
1123+ pure (Right (S.intersection nameSetA nameSetB))
1124+
1125+ RelationalExprAttributeNames attrExpr -> do
1126+ eAttrExprType <- typeForRelationalExpr attrExpr
1127+ case eAttrExprType of
1128+ Left err -> pure (Left err)
1129+ Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
11971130
1198− RelationalExprAttributeNames attrExpr -> do
1199− attrExprType <- typeForGraphRefRelationalExpr attrExpr
1200− pure (A.attributeNameSet (attributes attrExprType))
1201−
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
1207− Right aType -> do
1208− case validateAtomType aType tConsMap of
1209− Left err -> throwError err
1210− Right _ -> pure (Attribute attrName aType)
1211−evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1212−
1213−mkEmptyRelVars :: RelationVariables -> RelationVariables
1214−mkEmptyRelVars = M.map mkEmptyRelVar
1215− where
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)
1232−
1233−
1234−dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1235−dbErr err = lift (except (Left err))
1236−
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
1256−
1257−-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1258−evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1259−evalRelationalExpr expr = do
1260− graph <- reGraph
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
1267−
1268−class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1269− getContext :: m DatabaseContext
1270−
1271−instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1272− getContext = gfDatabaseContextForMarker UncommittedContextMarker
12731131
1274−instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1275− getContext = getStateContext
1276−
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
12831132
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
1287−
1288−-- s := s union t
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
1312−
1313−instance ResolveGraphRefTransactionMarker GraphRefTupleExprs where
1314− resolve (TupleExprs marker tupleExprs) =
1315− TupleExprs marker <$> mapM resolve tupleExprs
1316−
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'))
1321−
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
1328−
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
1337−
1338−instance ResolveGraphRefTransactionMarker GraphRefExtendTupleExpr where
1339− resolve (AttributeExtendTupleExpr nam atomExpr) = AttributeExtendTupleExpr nam <$> resolve atomExpr
1340−
1341−instance ResolveGraphRefTransactionMarker GraphRefWithNameExpr where
1342− resolve orig@WithNameExpr{} = pure orig -- match uncommitted marker?
1343−
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
1352−
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')
1356−
1357−--MakeRelationFromExprs Nothing (TupleExprs UncommittedContextMarker [TupleExpr (fromList [("name", NakedAtomExpr (TextAtom "steve"))])])
1358−
1359−applyUnionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1360−applyUnionCollapse = Fold.cata opt
1361− where
1362− opt :: RelationalExprBaseF GraphRefTransactionMarker GraphRefRelationalExpr -> GraphRefRelationalExpr
1363− opt (UnionF exprA exprB) | exprA == exprB = exprA
1364− opt (UnionF
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
1372−
1373−
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)
1376−-- =>
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)
1379−
1380−--strategy: try to collapse the top-level update (union (restrict pred MakeRelationFromExpr) expr) if it contains the same predicate and resultant relation
1381−
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) =
1387− case expr of
1388− orig'@(Restrict npred'@(NotPredicate _) _) | npred == npred' -> orig'
1389− _ -> orig
1390−applyRestrictionCollapse expr = expr
1391−
1392−
1133+
1134+processAtomExpr :: AtomExpr -> TransactionId -> GraphRefAtomExpr
1135+processAtomExpr (AttributeAtomExpr nam) _ = AttributeAtomExpr nam
1136+processAtomExpr (NakedAtomExpr atom) _ = NakedAtomExpr atom
1137+processAtomExpr (FunctionAtomExpr fName atomExprs ()) tid = FunctionAtomExpr fName (fmap processAtomExpr tid) tid
1138+processAtomExpr (RelationAtomExpr expr) tid = RelationAtomExpr (processRelationalExpr expr tid)
1139+processAtomExpr (ConstructedAtomExpr dConsName atomExprs) = ConstructedAtomExpr dConsName (fmap processAtomExpr tid) tid
1140+
1141+processTupleExpr :: TupleExpr -> TransactionId -> GraphRefTupleExpr
1142+processTupleExpr (TupleExpr tMap) tid = TupleExpr (M.map (processAtomExpr tid) tMap)
1143+
1144+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> TransactionGraph -> Either RelationalError Attribute
1145+evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) graph = do
1146+ trans <- transactionForId tid graph
1147+ let tConsMap = typeConstructorMapping (concreteDatabaseContext trans)
1148+ aType <- atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
1149+ validateAtomType aType tConsMap
1150+ pure (Attribute attrName aType)
1151+
1152+--convert AttributeExpr to GraphRefAttributeExpr
1153+processAttributeExpr :: AttributeExpr -> TransactionId -> GraphRefAttributeExpr
1154+processAttributeExpr (AttributeAndTypeNameExpr nam tCons ()) tid = AttributeAndTypeNameExpr nam tCons tid
1155+processAttributeExpr (NakedAttributeExpr attr) = NakedAttributeExpr attr
1156+
1157+-- convert a RelationalExpr into a GraphRefRelationalExpr
1158+processRelationalExpr :: RelationalExpr -> TransactionId -> GraphRefRelationalExpr
1159+processRelationalExpr (MakeRelationFromExprs mAttrs tupleExprs) =
1160+ MakeRelationFromExprs (fmap (fmap processAttributeExpr) mAttrs) (processTupleExprs tupleExprs)