@@ -1,4 +1,7 @@
1{-# LANGUAGE ScopedTypeVariables #-}
1{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE OverloadedStrings #-}
2module ProjectM36.RelationalExpression where
5module ProjectM36.RelationalExpression where
3import ProjectM36.Relation
6import ProjectM36.Relation
4import ProjectM36.Tuple
7import ProjectM36.Tuple
@@ -13,35 +16,37 @@ import ProjectM36.DataTypes.Primitive
13import ProjectM36.AtomFunction
16import ProjectM36.AtomFunction
14import ProjectM36.DatabaseContextFunction
17import ProjectM36.DatabaseContextFunction
15import ProjectM36.Arbitrary
18import ProjectM36.Arbitrary
19+import ProjectM36.GraphRefRelationalExpr
16import ProjectM36.Transaction
20import ProjectM36.Transaction
17import qualified ProjectM36.Attribute as A
21import qualified ProjectM36.Attribute as A
18import qualified Data.Map as M
22import qualified Data.Map as M
19import qualified Data.HashSet as HS
23import qualified Data.HashSet as HS
20import qualified Data.Set as S
24import qualified Data.Set as S
21−import Control.Monad.RWS.Strict as RWS
25+import Control.Monad.State hiding (join)
22−import Control.Monad.Trans.Class (lift)
26+import Data.Bifunctor (second)
23−import Control.Exception
24import Data.Maybe
27import Data.Maybe
25import Data.Either
28import Data.Either
26import Data.Char (isUpper)
29import Data.Char (isUpper)
31+import qualified Data.List.NonEmpty as NE
32+import Data.Functor.Identity
27import qualified Data.Text as T
33import qualified Data.Text as T
28import qualified Data.Vector as V
34import qualified Data.Vector as V
29import qualified ProjectM36.TypeConstructorDef as TCD
35import qualified ProjectM36.TypeConstructorDef as TCD
36+import qualified Control.Monad.RWS.Strict as RWS
37+import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
30−import Control.Monad.Except
38+import Control.Monad.Except hiding (join)
31import Control.Monad.Trans.Except (except)
39import Control.Monad.Trans.Except (except)
32−import Control.Monad.Reader as R
40+import Control.Monad.Reader as R hiding (join)
33import ProjectM36.NormalizeExpr
41import ProjectM36.NormalizeExpr
42+import ProjectM36.WithNameExpr
34import Test.QuickCheck
43import Test.QuickCheck
35−import GHC
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
36import GHC.Paths
49import GHC.Paths
37−import Data.Time.Clock
38−import Data.Time.Calendar
39−import qualified Data.List.NonEmpty as NE
40−import Data.Functor.Identity
42−import Control.Monad.IO.Class
43−#if __GLASGOW_HASKELL__ <= 802
47data DatabaseContextExprDetails = CountUpdatedTuples
52data DatabaseContextExprDetails = CountUpdatedTuples
@@ -70,7 +75,6 @@ mkDatabaseContextEvalState context = DatabaseContextEvalState {
70data RelationalExprEnv = RelationalExprEnv {
75data RelationalExprEnv = RelationalExprEnv {
71 re_context :: DatabaseContext,
76 re_context :: DatabaseContext,
72 re_graph :: TransactionGraph,
77 re_graph :: TransactionGraph,
73− re_currentTransId :: TransactionId,
74 re_extra :: Maybe (Either RelationTuple Attributes)
78 re_extra :: Maybe (Either RelationTuple Attributes)
@@ -86,42 +90,33 @@ instance Show RelationalExprEnv where
86--used to eval relationalexpr
90--used to eval relationalexpr
87type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
91type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
89−reGraph :: RelationalExprM TransactionGraph
93+runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
90−reGraph = re_graph <$> R.ask
94+runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
92−gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
96+reGraph :: RelationalExprM TransactionGraph
95− lift $ except $ transactionForId tid graph
97−currentTrans :: RelationalExprM Transaction
99− tid <- re_currentTransId <$> R.ask
100− graph <- re_graph <$> R.ask
97+reGraph = asks re_graph
101− lift $ except $ transactionForId tid graph
103−reTransId :: RelationalExprM TransactionId
99+reContext :: RelationalExprM DatabaseContext
104−reTransId = re_currentTransId <$> R.ask
100+reContext = asks re_context
106−mkRelationalExprEnv :: DatabaseContext -> TransactionId -> TransactionGraph -> RelationalExprEnv
102+mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
107−mkRelationalExprEnv ctx currentTransId graph =
103+mkRelationalExprEnv ctx graph =
108 RelationalExprEnv
104 RelationalExprEnv
109 { re_context = ctx,
105 { re_context = ctx,
110 re_graph = graph,
106 re_graph = graph,
111− re_currentTransId = currentTransId,
112 re_extra = Nothing }
107 re_extra = Nothing }
114askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
109askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
115askEnv = R.ask
110askEnv = R.ask
117mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
112mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
118−mergeTuplesIntoGraphRefRelationalExprEnv tupIn e =
113+mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
119− e{ gre_extra = new_elems }
114+ env { gre_extra = new_elems }
121 new_elems = Just (Left newTuple)
116 new_elems = Just (Left newTuple)
122− mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple e))
117+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
123 newTuple = mkRelationTupleFromMap mergedTupMap
118 newTuple = mkRelationTupleFromMap mergedTupMap
125mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
120mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
126mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
121mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
@@ -147,12 +142,12 @@ data DatabaseContextEvalEnv = DatabaseContextEvalEnv
149mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
144mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
150−mkDatabaseContextEvalEnv tid graph = DatabaseContextEvalEnv tid graph
145+mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
152type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
147type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
154runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
149runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
155−runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> (execRWST m env freshEnv)))
150+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
157 freshEnv = mkDatabaseContextEvalState ctx
152 freshEnv = mkDatabaseContextEvalState ctx
@@ -165,35 +160,51 @@ dbcGraph = dce_graph <$> RWS.ask
166dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
161dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
167dbcRelationalExprEnv =
162dbcRelationalExprEnv =
168− mkRelationalExprEnv <$> getStateContext <*> dbcTransId <*> dbcGraph
163+ mkRelationalExprEnv <$> getStateContext <*> dbcGraph
170getStateContext :: DatabaseContextEvalMonad DatabaseContext
165getStateContext :: DatabaseContextEvalMonad DatabaseContext
171−getStateContext = dbc_context <$> get
166+getStateContext = gets dbc_context
173putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
168putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
174putStateContext ctx' = do
169putStateContext ctx' = do
176− put (s {dbc_context = ctx'})
171+ put (s {dbc_context = ctx', dbc_dirty = True})
173+-- | The context is optionally passed down along in cases where the current context is uncommitted.
178data GraphRefRelationalExprEnv =
174data GraphRefRelationalExprEnv =
179 GraphRefRelationalExprEnv {
175 GraphRefRelationalExprEnv {
176+ gre_context :: Maybe DatabaseContext,
180 gre_graph :: TransactionGraph,
177 gre_graph :: TransactionGraph,
181 gre_extra :: Maybe (Either RelationTuple Attributes)
178 gre_extra :: Maybe (Either RelationTuple Attributes)
184type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
181type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
183+gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
184+gfTransForId tid = do
186+ lift $ except $ transactionForId tid graph
188+gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
189+gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
190+gfDatabaseContextForMarker UncommittedContextMarker = do
191+ mctx <- gre_context <$> askEnv
193+ Nothing -> throwError NoUncommittedContextInEvalError
194+ Just ctx -> pure ctx
186runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
196runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
187runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
197runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
189−freshGraphRefRelationalExprEnv :: TransactionGraph -> GraphRefRelationalExprEnv
199+freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
190−freshGraphRefRelationalExprEnv graph = GraphRefRelationalExprEnv {
200+freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
191 gre_graph = graph,
202 gre_graph = graph,
192 gre_extra = Nothing
203 gre_extra = Nothing
195gfGraph :: GraphRefRelationalExprM TransactionGraph
206gfGraph :: GraphRefRelationalExprM TransactionGraph
196−gfGraph = gre_graph <$> R.ask
207+gfGraph = asks gre_graph
198envContext :: RelationalExprEnv -> DatabaseContext
209envContext :: RelationalExprEnv -> DatabaseContext
199envContext = re_context
210envContext = re_context
@@ -201,173 +212,27 @@ envContext = re_context
201setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
212setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
202setEnvContext e ctx = e { re_context = ctx }
213setEnvContext e ctx = e { re_context = ctx }
205−--full evaluation down the graph
206−eval :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
209− eGfExpr <- processRelationalExpr expr
211− Left err -> pure (Left err)
212− Right gfExpr -> pure $ evalGraphRefRelationalExpr gfExpr (re_graph env)
215−--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
216−evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
217−evalRelationalExpr (RelationVariable name _) = do
218− relvarTable <- fmap (relationVariables . envContext) askEnv
219− return $ case M.lookup name relvarTable of
220− Just res -> Right res
221− Nothing -> Left $ RelVarNotDefinedError name
223−evalRelationalExpr (Project attrNames expr) = do
224− eAttrNameSet <- evalAttributeNames attrNames expr
225− case eAttrNameSet of
226− Left err -> pure (Left err)
227− Right attrNameSet -> do
228− rel <- evalRelationalExpr expr
230− Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
231− Left err -> pure $ Left err
233−evalRelationalExpr (Union exprA exprB) = do
234− relA <- evalRelationalExpr exprA
235− relB <- evalRelationalExpr exprB
237− Left err -> return $ Left err
238− Right relA2 -> case relB of
239− Left err -> return $ Left err
240− Right relB2 -> return $ Right (Union relA2 relB2)
242−evalRelationalExpr (Join exprA exprB) = do
243− relA <- evalRelationalExpr exprA
244− relB <- evalRelationalExpr exprB
246− Left err -> return $ Left err
247− Right relA2 -> case relB of
248− Left err -> return $ Left err
249− Right relB2 -> return $ Right (Join relA2 relB2)
251−evalRelationalExpr (Difference exprA exprB) = do
252− relA <- evalRelationalExpr exprA
253− relB <- evalRelationalExpr exprB
255− Left err -> return $ Left err
256− Right relA2 -> case relB of
257− Left err -> return $ Left err
258− Right relB2 -> return $ Right (Difference relA2 relB2)
260−evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
261− case mkRelation attributeSet tupleSet of
262− Right rel -> return $ Right (ExistingRelation rel)
263− Left err -> return $ Left err
265−evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
266− currentContext <- fmap envContext askEnv
267− let tConss = typeConstructorMapping currentContext
268− -- 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
270− mAttrs <- case mAttrExprs of
272− Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
273− Nothing -> pure Nothing
274− tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
275− let attrs = fromMaybe firstTupleAttrs mAttrs
276− firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
277− expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
278− pure (ExistingRelation expr)
280−evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
282−evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
283− evald <- evalRelationalExpr relExpr
285− Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
286− Left err -> return $ Left err
288−evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
289− eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
290− case eOldAttrNameSet of
291− Left err -> pure (Left err)
292− Right oldAttrNameSet -> do
293− evald <- evalRelationalExpr relExpr
295− Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
296− Left err -> return $ Left err
298−evalRelationalExpr (Ungroup attrName relExpr) = do
299− evald <- evalRelationalExpr relExpr
301− Right expr -> return $ Right (Ungroup attrName expr)
302− Left err -> return $ Left err
304−evalRelationalExpr (Restrict predicateExpr relExpr) = do
305− evald <- evalRelationalExpr relExpr
306− pred <- processRestrictionPredicateExpr predicateExpr
308− Left err -> return $ Left err
310− pure $ Right (Restrict pred expr)
312−evalRelationalExpr (Equals relExprA relExprB) = do
313− evaldA <- evalRelationalExpr relExprA
314− evaldB <- evalRelationalExpr relExprB
316− Left err -> return $ Left err
317− Right exprA -> case evaldB of
318− Left err -> return $ Left err
319− Right exprB -> return $ Right (Equals exprA exprB)
321−evalRelationalExpr (With views mainExpr) = do
324− let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
325− Left (RelVarAlreadyDefinedError vname)
327− case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
328− (Left err,_) -> Left err
329− (Right (), (ctx',_,_)) -> Right ctx'
331− case foldM addScopedView (stateElemsContext rstate) views of
332− Left err -> return $ Left err
334− let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprEnv ctx'')
335− case evalMainExpr mainExpr of
336− Left err -> return $ Left err
337− Right rel -> return $ Right rel
339−--warning: copy-pasta from above- refactor
340−evalRelationalExpr (NotEquals relExprA relExprB) = do
341− evaldA <- evalRelationalExpr relExprA
342− evaldB <- evalRelationalExpr relExprB
344− Left err -> return $ Left err
345− Right exprA -> case evaldB of
346− Left err -> return $ Left err
347− Right exprB -> return $ Right (NotEquals exprA exprB)
349−-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
350−evalRelationalExpr (Extend tupleExpression relExpr) = do
351− eExpr <- evalRelationalExpr relExpr
353− Left err -> pure (Left err)
355− tupProc <- processExtendTupleExpr tupleExpression
356− pure (Right (Extend tupProc expr))
358--helper function to process relation variable creation/assignment
215--helper function to process relation variable creation/assignment
359setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
216setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
360setRelVar relVarName relExpr = do
217setRelVar relVarName relExpr = do
362 currentContext <- getStateContext
218 currentContext <- getStateContext
219+ --prevent recursive relvar definition by resolving references to relvars in previous states
220+ relExpr' <- resolve relExpr
363− let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
221+ let newRelVars = M.insert relVarName relExpr' $ relationVariables currentContext
364 potentialContext = currentContext { relationVariables = newRelVars }
222 potentialContext = currentContext { relationVariables = newRelVars }
223+ --optimization: if the relexpr is unchanged, skip the update
224+ if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
365− --determine when to check constraints
227+ --determine when to check constraints
366− graph <- dbcGraph
228+ graph <- dbcGraph
367− tid <- dbcTransId
229+ tid <- dbcTransId
368− case checkConstraints potentialContext tid graph of
230+ case checkConstraints potentialContext tid graph of
369− Left err -> dbErr err
231+ Left err -> dbErr err
370− Right _ -> putStateContext potentialContext
232+ Right _ -> putStateContext potentialContext
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 ()
372-- 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
237-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
373deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
238deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
@@ -386,20 +251,17 @@ evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContex
386evalGraphRefDatabaseContextExpr NoOperation = pure ()
251evalGraphRefDatabaseContextExpr NoOperation = pure ()
388evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
253evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
254+ context <- getStateContext
389 relvars <- fmap relationVariables getStateContext
255 relvars <- fmap relationVariables getStateContext
390 tConss <- fmap typeConstructorMapping getStateContext
256 tConss <- fmap typeConstructorMapping getStateContext
391− relEnv <- dbcRelationalExprEnv
392 graph <- dbcGraph
257 graph <- dbcGraph
393 let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
258 let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
394− gfEnv = freshGraphRefRelationalExprEnv graph
259+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
395 case eAttrs of
260 case eAttrs of
396− Left err -> dbErr err
261+ Left err -> dbErr err
397 Right attrsList -> do
262 Right attrsList -> do
398− let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
263+ lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
399− if not (null atomTypeErrs) then
400− dbErr (someErrors atomTypeErrs)
402− case M.member relVarName relvars of
264+ case M.member relVarName relvars of
403 True -> dbErr (RelVarAlreadyDefinedError relVarName)
265 True -> dbErr (RelVarAlreadyDefinedError relVarName)
404 False -> setRelVar relVarName (ExistingRelation emptyRelation)
266 False -> setRelVar relVarName (ExistingRelation emptyRelation)
@@ -412,13 +274,17 @@ evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
412 graph <- re_graph <$> dbcRelationalExprEnv
274 graph <- re_graph <$> dbcRelationalExprEnv
413 context <- getStateContext
275 context <- getStateContext
414 let existingRelVar = M.lookup relVarName (relationVariables context)
276 let existingRelVar = M.lookup relVarName (relationVariables context)
277+ reEnv = freshGraphRefRelationalExprEnv (Just context) graph
278+ eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
415 case existingRelVar of
279 case existingRelVar of
416 Nothing -> do
280 Nothing -> do
281+ case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
282+ Left err -> dbErr err
284+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
417− setRelVar relVarName expr
285+ setRelVar relVarName expr
418 Just existingRel -> do
286 Just existingRel -> do
419 let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
287 let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
420− eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
421− reEnv = freshGraphRefRelationalExprEnv graph
422 case eExpectedType of
288 case eExpectedType of
423 Left err -> dbErr err
289 Left err -> dbErr err
424 Right expectedType ->
290 Right expectedType ->
@@ -426,44 +292,53 @@ evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
426 Left err -> dbErr err
292 Left err -> dbErr err
427 Right newExprType -> do
293 Right newExprType -> do
428 if newExprType == expectedType then do
294 if newExprType == expectedType then do
295+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
429 setRelVar relVarName expr
296 setRelVar relVarName expr
431 dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
298 dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
433evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
300evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
434− transId <- dbcTransId
301+ gfExpr <- relVarByName relVarName
435− evalGraphRefDatabaseContextExpr (Assign relVarName
302+ let optExpr = applyUnionCollapse (Union
437− (RelationVariable relVarName transId)
438− relExpr))
303+ relExpr
305+ evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
440evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
307evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
441− transId <- dbcTransId
308+ gfExpr <- relVarByName relVarName
442− let rv = RelationVariable relVarName transId
443− setRelVar relVarName (Restrict (NotPredicate predicate) rv)
309+ let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
310+ setRelVar relVarName optExpr
445--union of restricted+updated portion and the unrestricted+unupdated portion
312--union of restricted+updated portion and the unrestricted+unupdated portion
446evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
313evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
314+ rvExpr <- relVarByName relVarName
315+ graph <- re_graph <$> dbcRelationalExprEnv
447 context <- getStateContext
316 context <- getStateContext
448− transId <- dbcTransId
317+ let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
449− graph <- dbcGraph
318+ --get the current attributes name in the relvar to ensure that we don't conflict when renaming
450− let relVarMap = relationVariables context
319+ eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
451− case M.lookup relVarName relVarMap of
320+ exprType' <- case eExprType of
452− Nothing -> dbErr (RelVarNotDefinedError relVarName)
321+ Left err -> throwError err
453− Just _ -> do
322+ Right t -> pure t
454− let unrestrictedPortion = Restrict (NotPredicate pred') rv
323+ let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
455− rv = RelationVariable relVarName transId
324+ tmpAttr = tmpAttrC 1
456− tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
325+ tmpAttrC :: Int -> AttributeName -> AttributeName
327+ let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
328+ if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
457− updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
332+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
458− projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
333+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
459− restrictedPortion = Restrict pred'
334+ restrictedPortion = Restrict pred' rvExpr
460− updated = foldr (\(oldname, atomExpr) accum ->
335+ updated = foldr (\(oldname, atomExpr) accum ->
461− let procAtomExpr = runProcessExprM transId graph (processAtomExpr atomExpr) in
336+ let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
462 updateAttr oldname procAtomExpr accum
337 updateAttr oldname procAtomExpr accum
463− ) rv (M.toList atomExprMap)
338+ ) restrictedPortion (M.toList atomExprMap)
464 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
339 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
465− updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
340+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
466− setRelVar relVarName (Union unrestrictedPortion updatedPortion)
341+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
468evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
343evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
469 currContext <- getStateContext
344 currContext <- getStateContext
@@ -475,6 +350,8 @@ evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
475 dbErr (InclusionDependencyNameInUseError newDepName)
350 dbErr (InclusionDependencyNameInUseError newDepName)
477 let potentialContext = currContext { inclusionDependencies = newDeps }
352 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
478 case checkConstraints potentialContext transId graph of
355 case checkConstraints potentialContext transId graph of
479 Left err -> dbErr err
356 Left err -> dbErr err
480 Right _ ->
357 Right _ ->
@@ -519,9 +396,9 @@ evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
519 let oldTypes = typeConstructorMapping currentContext
396 let oldTypes = typeConstructorMapping currentContext
520 tConsName = TCD.name tConsDef
397 tConsName = TCD.name tConsDef
521 -- validate that the constructor's types exist
398 -- validate that the constructor's types exist
522− case validateTypeConstructorDef tConsDef dConsDefList of
399+ case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
523− errs@(_:_) -> dbErr (someErrors errs)
400+ Left err -> throwError err
524− [] | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
401+ Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
525 | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
402 | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
526 | otherwise -> do
403 | otherwise -> do
527 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
404 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
@@ -537,15 +414,10 @@ evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
537 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
414 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
538 putStateContext $ currentContext { typeConstructorMapping = newTypes }
415 putStateContext $ currentContext { typeConstructorMapping = newTypes }
540−evalGraphRefDatabaseContextExpr (MultipleExpr _) = do
417+evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
541 --the multiple expressions must pass the same context around- not the old unmodified context
418 --the multiple expressions must pass the same context around- not the old unmodified context
543−{- evald <- forM exprs (\expr -> evalGraphRefDatabaseContextExpr expr)
419+ mapM_ evalGraphRefDatabaseContextExpr exprs
544− --some lifting magic needed here
420+
547− errs -> dbErr (someErrors errs)
549evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
421evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
550 currentContext <- getStateContext
422 currentContext <- getStateContext
551 let atomFuncs = atomFunctions currentContext
423 let atomFuncs = atomFunctions currentContext
@@ -572,12 +444,11 @@ evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
573evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
445evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
574 context <- getStateContext
446 context <- getStateContext
575− relExprEnv <- dbcRelationalExprEnv
576 graph <- dbcGraph
447 graph <- dbcGraph
577 --resolve atom arguments
448 --resolve atom arguments
578− let eAtomTypes = mapM (\atomExpr -> runGraphRefRelationalExprM gfEnv (typeForGraphRefAtomExpr emptyAttributes atomExpr)) atomArgExprs
449+ let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
579 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
450 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
580− gfEnv = freshGraphRefRelationalExprEnv graph
451+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
581 case eFunc of
452 case eFunc of
582 Left err -> dbErr err
453 Left err -> dbErr err
583 Right func -> do
454 Right func -> do
@@ -590,12 +461,13 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
590 case eAtomTypes of
461 case eAtomTypes of
591 Left err -> dbErr err
462 Left err -> dbErr err
592 Right atomTypes -> do
463 Right atomTypes -> do
464+ let mValidTypes = zipWith (\ expType actType
593− let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
465+ -> case atomTypeVerify expType actType of
594− Left err -> Just err
466+ Left err -> Just err
595− Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
468+ (dbcFuncType func) atomTypes
596 typeErrors = catMaybes mValidTypes
469 typeErrors = catMaybes mValidTypes
597− eAtomArgs = unimplemented
470+ eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
598− --eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
599 if length (lefts eAtomArgs) > 1 then
471 if length (lefts eAtomArgs) > 1 then
600 dbErr (someErrors (lefts eAtomArgs))
472 dbErr (someErrors (lefts eAtomArgs))
601 else if not (null typeErrors) then
473 else if not (null typeErrors) then
@@ -604,7 +476,6 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
604 case evalDatabaseContextFunction func (rights eAtomArgs) context of
476 case evalDatabaseContextFunction func (rights eAtomArgs) context of
605 Left err -> dbErr err
477 Left err -> dbErr err
606 Right newContext -> putStateContext newContext
478 Right newContext -> putStateContext newContext
608data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
479data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
609 { dbcio_transId :: TransactionId,
480 { dbcio_transId :: TransactionId,
610 dbcio_graph :: TransactionGraph,
481 dbcio_graph :: TransactionGraph,
@@ -640,10 +511,15 @@ getDBCIOContext = dbc_context <$> RWS.get
640getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
511getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
641getDBCIORelationalExprEnv = do
512getDBCIORelationalExprEnv = do
642 context <- getDBCIOContext
513 context <- getDBCIOContext
644− pure $ mkRelationalExprEnv context (dbcio_transId env) (dbcio_graph env)
514+ mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
646evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
516evalGraphRefDatabaseContextIOExpr :: 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))
647evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
523evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
648 eScriptSession <- requireScriptSession
524 eScriptSession <- requireScriptSession
649 currentContext <- getDBCIOContext
525 currentContext <- getDBCIOContext
@@ -677,7 +553,6 @@ evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = d
677 Right eContext -> case eContext of
553 Right eContext -> case eContext of
678 Left err -> pure (Left err)
554 Left err -> pure (Left err)
679 Right context' -> putDBCIOContext context'
555 Right context' -> putDBCIOContext context'
681evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
556evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
682 eScriptSession <- requireScriptSession
557 eScriptSession <- requireScriptSession
683 currentContext <- getDBCIOContext
558 currentContext <- getDBCIOContext
@@ -719,7 +594,6 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
719 Right eContext -> case eContext of
594 Right eContext -> case eContext of
720 Left err -> pure (Left err)
595 Left err -> pure (Left err)
721 Right context' -> putDBCIOContext context'
596 Right context' -> putDBCIOContext context'
723evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
597evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
724 currentContext <- getDBCIOContext
598 currentContext <- getDBCIOContext
725 eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
599 eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
@@ -736,7 +610,7 @@ evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName
736 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
610 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
737 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
611 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
738 in putDBCIOContext newContext
612 in putDBCIOContext newContext
740evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
614evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
742 currentContext <- getDBCIOContext
616 currentContext <- getDBCIOContext
@@ -744,7 +618,6 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
744 --create graph ref expr
618 --create graph ref expr
745 let gfExpr = Define relVarName attrExprs
619 let gfExpr = Define relVarName attrExprs
746 evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
620 evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
747− transId = dbcio_transId env
748 graph = dbcio_graph env
621 graph = dbcio_graph env
749 case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
622 case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
750 Left err -> pure (Left err)
623 Left err -> pure (Left err)
@@ -755,8 +628,8 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
755 case existingRelVar of
628 case existingRelVar of
756 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
757 Just existingRel -> do
630 Just existingRel -> do
758− let env = freshGraphRefRelationalExprEnv graph
631+ let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
759− case runGraphRefRelationalExprM env (typeForGraphRefRelationalExpr existingRel) of
632+ case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
760 Left err -> pure (Left err)
633 Left err -> pure (Left err)
761 Right relType -> do
634 Right relType -> do
762 let expectedAttributes = attributes relType
635 let expectedAttributes = attributes relType
@@ -769,45 +642,36 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
769 Left err -> pure (Left err)
642 Left err -> pure (Left err)
770 Right dbstate' -> putDBCIOContext (dbc_context dbstate')
643 Right dbstate' -> putDBCIOContext (dbc_context dbstate')
773−updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
774−updateTupleWithAtomExprs exprMap context graph tupIn = do
775− --resolve all atom exprs
777− atomsAssoc <- mapM (\(attrName, atomExpr) -> do
778− let atom = unimplemented
779− --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
780− pure (attrName, atom)
781− ) (M.toList exprMap)
782− pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
784--run verification on all constraints
645--run verification on all constraints
785checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
646checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
786−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
647+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
787 mapM_ (uncurry checkIncDep) (M.toList deps)
648 mapM_ (uncurry checkIncDep) (M.toList deps)
789 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
650 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
790 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
651 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
791 utctDayTime = secondsToDiffTime 0 }
652 utctDayTime = secondsToDiffTime 0 }
792 tempSchemas = Schemas context M.empty
653 tempSchemas = Schemas context M.empty
654+ tempTrans = Transaction U.nil tempTransInfo tempSchemas
793− tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
655+ tempTransInfo = TransactionInfo { parents = transId NE.:| [],
795 deps = inclusionDependencies context
660 deps = inclusionDependencies context
796− reEnv = mkRelationalExprEnv context transId graph
797 -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
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
798 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
662 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
799− let process = runProcessExprM transId graph
663+ let process = runProcessExprM UncommittedContextMarker
800 gfSubsetExpr = process (processRelationalExpr subsetExpr)
664 gfSubsetExpr = process (processRelationalExpr subsetExpr)
801 gfSupersetExpr = process (processRelationalExpr supersetExpr)
665 gfSupersetExpr = process (processRelationalExpr supersetExpr)
802 --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.
666 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
803− let gfEnv = freshGraphRefRelationalExprEnv graph
667+ let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
804 runGfRel = runGraphRefRelationalExprM gfEnv
668 runGfRel = runGraphRefRelationalExprM gfEnv
805 typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
669 typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
806 typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
670 typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
807 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
671 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
808 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
672 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
809− gfEvald = runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr checkExpr)
673+ gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
810− gfEnv = freshGraphRefRelationalExprEnv potentialGraph
674+ gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
811 case gfEvald of
675 case gfEvald of
812 Left err -> Left err
676 Left err -> Left err
813 Right resultRel -> if resultRel == relationTrue then
677 Right resultRel -> if resultRel == relationTrue then
@@ -823,20 +687,11 @@ typeForRelationalExpr expr = do
823 --replace the relationVariables context element with a cloned set of relation devoid of tuples
687 --replace the relationVariables context element with a cloned set of relation devoid of tuples
824 --evalRelationalExpr could still return an existing relation with tuples, so strip them
688 --evalRelationalExpr could still return an existing relation with tuples, so strip them
825 graph <- reGraph
689 graph <- reGraph
826− transId <- reTransId
690+ context <- reContext
827− let gfExpr = runProcessExprM transId graph (processRelationalExpr expr)
691+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
828− gfEnv = freshGraphRefRelationalExprEnv graph
692+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
829 runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
693 runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
830− lift $ except $ runGf
694+ lift $ except runGf
832−--returns a database context with all tuples removed
833−--this is useful for type checking and optimization
835−contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
836−contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
838− relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
841liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
696liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
842liftE v = do
697liftE v = do
@@ -885,7 +740,7 @@ predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
886predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
741predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
887 env <- askEnv
742 env <- askEnv
888− let attrs' = envAttributes env
743+ let attrs' = A.union attrs (envAttributes env)
889 ctxtup' = envTuple env
744 ctxtup' = envTuple env
890 atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
745 atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
891 attr <- lift $ except $ case A.attributeForName attrName attrs of
746 attr <- lift $ except $ case A.attributeForName attrName attrs of
@@ -929,8 +784,8 @@ tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName r
929 Right rel
784 Right rel
931extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
786extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
932−extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
787+extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
933− renv <- askEnv
788+-- renv <- askEnv
934 -- check that the attribute name is not in use
789 -- check that the attribute name is not in use
935 case tupleExprCheckNewAttrName newAttrName relIn of
790 case tupleExprCheckNewAttrName newAttrName relIn of
936 Left err -> throwError err
791 Left err -> throwError err
@@ -939,65 +794,60 @@ extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrNa
939 atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
794 atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
940 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
795 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
941 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
796 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
798+ pure (newAndOldAttrs, \tup -> do
942− pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
799+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
943− case unimplemented {-runReader (evalAtomExpr tup atomExpr) substate-} of
800+ atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
944− Left err -> Left err
945− Right atom -> Right (tupleAtomExtend newAttrName atom tup)
801+ Right (tupleAtomExtend newAttrName atom tup)
948evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
804evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
949−evalGraphRefAtomExpr = unimplemented
805+evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
951−evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprM Atom
952−evalAtomExpr = unimplemented
955−evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
806+ case atomForAttributeName attrName tupIn of
956− Right atom -> pure (Right atom)
807+ Right atom -> pure atom
957− err@(Left (NoSuchAttributeNamesError _)) -> do
808+ Left err@(NoSuchAttributeNamesError _) -> do
958− rstate <- ask
809+ env <- askEnv
959− let stateTup = stateTuple rstate
810+ case gre_extra env of
811+ Nothing -> throwError err
960− pure (atomForAttributeName attrName stateTup)
812+ Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
813+ Just (Right _) -> throwError err
961− Left err -> pure (Left err)
814+ Left err -> throwError err
962−evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
815+evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
963−evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
816+evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
964− argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
817+ argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
965− context <- fmap stateElemsContext ask
818+ context <- gfDatabaseContextForMarker tid
967− let functions = atomFunctions context
819+ let functions = atomFunctions context
968− func <- either throwE pure (atomFunctionForName funcName functions)
820+ func <- lift $ except (atomFunctionForName funcName functions)
969− let expectedArgCount = length (atomFuncType func) - 1
821+ let expectedArgCount = length (atomFuncType func) - 1
970− actualArgCount = length argTypes
822+ actualArgCount = length argTypes
971− safeInit [] = [] -- different behavior from normal init
823+ safeInit [] = [] -- different behavior from normal init
972− safeInit xs = init xs
824+ safeInit xs = init xs
973− if expectedArgCount /= actualArgCount then
825+ if expectedArgCount /= actualArgCount then
974− throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
826+ throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
976 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
828 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
977− mapM_ (\(expType, eActType) -> do
829+ mapM_ (\(expType, actType) ->
978− actType <- either throwE pure eActType
979− either throwE pure (atomTypeVerify expType actType)) zippedArgs
830+ lift $ except (atomTypeVerify expType actType)) zippedArgs
980− evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
831+ evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
981 case evalAtomFunction func evaldArgs of
832 case evalAtomFunction func evaldArgs of
982− Left err -> throwE (AtomFunctionUserError err)
833+ Left err -> throwError (AtomFunctionUserError err)
983 Right result -> do
834 Right result -> do
984 --validate that the result matches the expected type
835 --validate that the result matches the expected type
985− _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
836+ _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
986 pure result
837 pure result
987−evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
838+evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
988 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
839 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
989− rstate <- ask
840+ env <- ask
990− runExceptT $ do
841+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
991− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
842+ relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
992− relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
993− pure (RelationAtom relAtom)
843+ pure (RelationAtom relAtom)
994−evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
844+evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
995− rstate <- lift ask
845+ let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
996− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
997− aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
846+ aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
998− argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
847+ argAtoms <- local mergeEnv $
848+ mapM (evalGraphRefAtomExpr tupIn) dConsArgs
999 pure (ConstructedAtom dConsName aType argAtoms)
849 pure (ConstructedAtom dConsName aType argAtoms)
1001typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
851typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
1002typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
852typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
1003 renv <- askEnv
853 renv <- askEnv
@@ -1010,11 +860,13 @@ typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
1010 Right attr -> pure (A.atomType attr)
860 Right attr -> pure (A.atomType attr)
1011 Left _ -> case atomForAttributeName attrName envTup of
861 Left _ -> case atomForAttributeName attrName envTup of
1012 Right atom -> pure (atomTypeForAtom atom)
862 Right atom -> pure (atomTypeForAtom atom)
863+ Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
1013− Left _ -> throwError err
865+ Left err -> throwError err
1015typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
867typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
1016typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
868typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
1017− funcs <- atomFunctions . concreteDatabaseContext <$> gfTransForId transId
869+ funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
1018 case atomFunctionForName funcName funcs of
870 case atomFunctionForName funcName funcs of
1019 Left err -> throwError err
871 Left err -> throwError err
1020 Right func -> do
872 Right func -> do
@@ -1032,7 +884,7 @@ typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
1032typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
884typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
1034 argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
886 argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
1035− tConsMap <- typeConstructorMapping . concreteDatabaseContext <$> gfTransForId tid
887+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1036 lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
888 lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
1038-- | Validate that the type of the AtomExpr matches the expected type.
890-- | Validate that the type of the AtomExpr matches the expected type.
@@ -1049,10 +901,12 @@ verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
1049 case A.attributeForName attrName attrs' of
901 case A.attributeForName attrName attrs' of
1050 Left err' -> throwError err'
902 Left err' -> throwError err'
1051 Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
903 Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
904+ Left err -> throwError err
1052verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
906verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
1053 lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
907 lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
1054verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
908verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
1055− context <- concreteDatabaseContext <$> gfTransForId tid
909+ context <- gfDatabaseContextForMarker tid
1056 let functions = atomFunctions context
910 let functions = atomFunctions context
1057 func <- lift $ except $ atomFunctionForName funcName functions
911 func <- lift $ except $ atomFunctionForName funcName functions
1058 let expectedArgTypes = atomFuncType func
912 let expectedArgTypes = atomFuncType func
@@ -1060,7 +914,7 @@ verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) e
1060 let handler :: RelationalError -> GraphRefRelationalExprM AtomType
914 let handler :: RelationalError -> GraphRefRelationalExprM AtomType
1061 handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
915 handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
1062 handler err = throwError err
916 handler err = throwError err
1063− verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
917+ verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
1064 funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
918 funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
1065 if length funcArgTypes /= length expectedArgTypes - 1 then
919 if length funcArgTypes /= length expectedArgTypes - 1 then
1066 throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
920 throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
@@ -1078,13 +932,61 @@ verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
1078-- | Look up the type's name and create a new attribute.
932-- | Look up the type's name and create a new attribute.
1079evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
933evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1080evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
934evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
1081− tConsMap <- typeConstructorMapping . concreteDatabaseContext <$> gfTransForId transId
935+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
1082 aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
936 aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
1083 lift $ except $ validateAtomType aType tConsMap
937 lift $ except $ validateAtomType aType tConsMap
1084 pure $ Attribute attrName aType
938 pure $ Attribute attrName aType
1086evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
940evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
942+-- for tuple type concrete resolution (Nothing ==> Maybe Int) when the attributes hint is Nothing, we need to first process all the tuples, then extract the concrete types on a per-attribute basis, then reprocess the tuples to include the concrete types
943+evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
944+evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
945+evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
946+ tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
947+ finalAttrs <- case mAttrs of
948+ Just attrs -> pure attrs
951+ [] -> pure emptyAttributes
952+ (headTuple:tailTuples) -> do
953+ --gather up resolved atom types or throw an error if an attribute cannot be made concrete from the inferred types- this could still fail if the type cannot be inferred (e.g. from [Nothing, Nothing])
955+ processTupleAttrs (tupAttr, accAttr) =
956+ --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
957+ if isResolvedAttribute accAttr && tupAttr == accAttr then
960+ lift $ except $ resolveAttributes accAttr tupAttr
961+ mostResolvedTypes <-
962+ foldM (\acc tup -> do
963+ let zipped = zip (V.toList . attributesVec $ tupleAttributes tup) acc
964+ accNames = S.fromList $ map A.attributeName acc
965+ tupNames = A.attributeNameSet (tupleAttributes tup)
966+ attrNamesDiff = S.union (S.difference accNames tupNames) (S.difference tupNames accNames)
967+ unless (null attrNamesDiff) (throwError (AttributeNamesMismatchError attrNamesDiff))
968+ nextTupleAttrs <- mapM processTupleAttrs zipped
969+ let diff = A.attributesDifference (A.attributesFromList nextTupleAttrs) (A.attributesFromList acc)
970+ if diff == A.emptyAttributes then
973+ throwError (TupleAttributeTypeMismatchError diff)
974+ ) (V.toList . attributesVec $ tupleAttributes headTuple) tailTuples
975+ pure (A.attributesFromList mostResolvedTypes)
976+ --strategy: if all the tuple expr transaction markers refer to one location, then we can pass the type constructor mapping from that location, otherwise, we cannot assume that the types are the same
977+ tConsMap <- case singularTransactions tupleExprL of
978+ SingularTransactionRef commonTransId ->
979+ typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
980+ NoTransactionsRef ->
981+ typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
982+ -- if there are multiple transaction markers in the TupleExprs, then we can't assume a single type constructor mapping- this could be improved in the future, but if all the tuples are fully resolved, then we don't need further resolution
983+ _ -> throwError TupleExprsReferenceMultipleMarkersError
984+ lift $ except $ validateAttributes tConsMap finalAttrs
985+ mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
988+--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
1088evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
990evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
1089evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
991evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
1090 -- 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
992 -- it's not possible for AtomExprs in tuple constructors to reference other Attributes' atoms due to the necessary order-of-operations (need a tuple to pass to evalAtomExpr)- it may be possible with some refactoring of type usage or delayed evaluation- needs more thought, but not a priority
@@ -1109,70 +1011,78 @@ evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
1109 --verify that the attributes match
1011 --verify that the attributes match
1110 when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1012 when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1111 --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1013 --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1112−-- tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1014+ --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1113 let tup' = reorderTuple finalAttrs tup
1015 let tup' = reorderTuple finalAttrs tup
1114 --TODO: restore type resolution
1016 --TODO: restore type resolution
1115-- _ <- lift $ except (validateTuple tup' tConss)
1017-- _ <- lift $ except (validateTuple tup' tConss)
1116 pure tup'
1018 pure tup'
1118−{-
1020+--temporary implementation until we have a proper planner+executor
1119−evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprM (Either RelationalError (S.Set AttributeName))
1120−evalAttributeNames attrNames expr = do
1121− eExprType <- typeForRelationalExpr expr
1123− Left err -> throwError err
1124− Right exprTyp -> do
1125− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1127− AttributeNames names ->
1128− case A.projectionAttributesForNames names (attributes exprTyp) of
1129− Left err -> pure (Left err)
1130− Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1132− InvertedAttributeNames names -> do
1133− let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1134− if not (S.null nonExistentAttributeNames) then
1135− pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1137− pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
1139− UnionAttributeNames namesA namesB -> do
1140− eNameSetA <- evalAttributeNames namesA expr
1142− Left err -> pure (Left err)
1143− Right nameSetA -> do
1144− eNameSetB <- evalAttributeNames namesB expr
1146− Left err -> pure (Left err)
1148− pure (Right (S.union nameSetA nameSetB))
1150− IntersectAttributeNames namesA namesB -> do
1151− eNameSetA <- evalAttributeNames namesA expr
1153− Left err -> pure (Left err)
1154− Right nameSetA -> do
1155− eNameSetB <- evalAttributeNames namesB expr
1157− Left err -> pure (Left err)
1159− pure (Right (S.intersection nameSetA nameSetB))
1161− RelationalExprAttributeNames attrExpr -> do
1162− eAttrExprType <- typeForRelationalExpr attrExpr
1163− case eAttrExprType of
1164− Left err -> pure (Left err)
1165− Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1168evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1021evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1169−--evalGraphRefRelationalExpr (MakeRelationaFromExprs
1022+evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1023+ mAttrs <- case mAttrExprs of
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
1170evalGraphRefRelationalExpr (RelationVariable name tid) = do
1034evalGraphRefRelationalExpr (RelationVariable name tid) = do
1171− ctx <- concreteDatabaseContext <$> gfTransForId tid
1035+ ctx <- gfDatabaseContextForMarker tid
1172 case M.lookup name (relationVariables ctx) of
1036 case M.lookup name (relationVariables ctx) of
1173 Nothing -> throwError (RelVarNotDefinedError name)
1037 Nothing -> throwError (RelVarNotDefinedError name)
1174 Just rv -> evalGraphRefRelationalExpr rv
1038 Just rv -> evalGraphRefRelationalExpr rv
1175−
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)
1177dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1087dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1178dbContextForTransId tid graph = do
1088dbContextForTransId tid graph = do
@@ -1193,35 +1103,85 @@ transactionForId tid graph
1193typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1103typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1194typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1104typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1195typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1105typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1196−typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) =
1106+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1197− case mAttrExprs of
1107+ mAttrs <- case mAttrExprs of
1198− Just attrExprs -> do
1108+ Just attrExprs -> do
1199− attrs <- mapM (\e -> evalGraphRefAttributeExpr e) attrExprs
1109+ attrs <- mapM evalGraphRefAttributeExpr attrExprs
1200− pure (emptyRelationWithAttrs (attributesFromList attrs))
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
1201typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1118typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1202− relVars <- relationVariables . concreteDatabaseContext <$> gfTransForId tid
1119+ relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1203 case M.lookup rvName relVars of
1120 case M.lookup rvName relVars of
1204 Nothing -> throwError (RelVarNotDefinedError rvName)
1121 Nothing -> throwError (RelVarNotDefinedError rvName)
1205− Just rvExpr -> typeForGraphRefRelationalExpr rvExpr
1123+ typeForGraphRefRelationalExpr rvExpr
1206typeForGraphRefRelationalExpr (Project attrNames expr) = do
1124typeForGraphRefRelationalExpr (Project attrNames expr) = do
1207− exprType <- typeForGraphRefRelationalExpr expr
1125+ exprType' <- typeForGraphRefRelationalExpr expr
1208 projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1126 projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1209− lift $ except $ project projectionAttrs exprType
1127+ lift $ except $ project projectionAttrs exprType'
1210−
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{} =
1156+typeForGraphRefRelationalExpr NotEquals{} =
1158+typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1159+ rel <- typeForGraphRefRelationalExpr expr
1160+ evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1161+typeForGraphRefRelationalExpr expr@(With withs _) = do
1162+ let expr' = substituteWithNameMacros [] expr
1163+ checkMacroName (WithNameExpr macroName tid) = do
1164+ rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1165+ case M.lookup macroName rvs of
1166+ Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1168+ mapM_ (checkMacroName . fst) withs
1169+ typeForGraphRefRelationalExpr expr'
1211evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1171evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1212evalGraphRefAttributeNames attrNames expr = do
1172evalGraphRefAttributeNames attrNames expr = do
1213− exprType <- typeForGraphRefRelationalExpr expr
1173+ exprType' <- typeForGraphRefRelationalExpr expr
1214− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType)))
1174+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1215 case attrNames of
1175 case attrNames of
1216 AttributeNames names ->
1176 AttributeNames names ->
1217− case A.projectionAttributesForNames names (attributes exprType) of
1177+ case A.projectionAttributesForNames names (attributes exprType') of
1218 Left err -> throwError err
1178 Left err -> throwError err
1219 Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1179 Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1221 InvertedAttributeNames names -> do
1181 InvertedAttributeNames names -> do
1222 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1182 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1223 if not (S.null nonExistentAttributeNames) then
1183 if not (S.null nonExistentAttributeNames) then
1224− throwError (AttributeNamesMismatchError nonExistentAttributeNames)
1184+ throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1226 pure (A.nonMatchingAttributeNameSet names typeNameSet)
1186 pure (A.nonMatchingAttributeNameSet names typeNameSet)
@@ -1241,18 +1201,19 @@ evalGraphRefAttributeNames attrNames expr = do
1242evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1202evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1243evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1203evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1244− tConsMap <- typeConstructorMapping . concreteDatabaseContext <$> gfTransForId tid
1204+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1245 case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1205 case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1246 Left err -> throwError err
1206 Left err -> throwError err
1247 Right aType -> do
1207 Right aType -> do
1248 case validateAtomType aType tConsMap of
1208 case validateAtomType aType tConsMap of
1249 Left err -> throwError err
1209 Left err -> throwError err
1250 Right _ -> pure (Attribute attrName aType)
1210 Right _ -> pure (Attribute attrName aType)
1211+evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1252mkEmptyRelVars :: RelationVariables -> RelationVariables
1213mkEmptyRelVars :: RelationVariables -> RelationVariables
1253−mkEmptyRelVars rvMap = M.map mkEmptyRelVar rvMap
1214+mkEmptyRelVars = M.map mkEmptyRelVar
1255− mkEmptyRelVar (MakeRelationFromExprs mAttrs _) = MakeRelationFromExprs mAttrs []
1216+ mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1256 mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1217 mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1257 mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1218 mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1258 mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
1219 mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
@@ -1263,32 +1224,169 @@ mkEmptyRelVars rvMap = M.map mkEmptyRelVar rvMap
1263 mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1224 mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1264 mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1225 mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1265 mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1226 mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1266− mkEmptyRelVar (Restrict pred expr) = Restrict pred (mkEmptyRelVar expr)
1227+ mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1267 mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1228 mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1268 mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1229 mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1269 mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1230 mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1270− mkEmptyRelVar (With macros expr) = With (map (\(rv, expr) -> (rv, mkEmptyRelVar expr)) macros) (mkEmptyRelVar expr)
1231+ mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1273dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1234dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1274dbErr err = lift (except (Left err))
1235dbErr err = lift (except (Left err))
1276-- | Return a Relation describing the relation variables.
1237-- | Return a Relation describing the relation variables.
1277−relationVariablesAsRelation :: RelationVariables -> TransactionGraph -> Either RelationalError Relation
1238+relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1278−relationVariablesAsRelation relVarMap graph = do
1239+relationVariablesAsRelation ctx graph = do
1279 let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1240 let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1280 attrs = A.attributesFromList [Attribute "name" TextAtomType,
1241 attrs = A.attributesFromList [Attribute "name" TextAtomType,
1281 Attribute "attributes" (RelationAtomType subrelAttrs)]
1242 Attribute "attributes" (RelationAtomType subrelAttrs)]
1243+ relVars = relationVariables ctx
1282 mkRvDesc (rvName, gfExpr) = do
1244 mkRvDesc (rvName, gfExpr) = do
1283− let gfEnv = freshGraphRefRelationalExprEnv graph
1245+ let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1284 gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1246 gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1285 pure (rvName, gfType)
1247 pure (rvName, gfType)
1286− relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributes rel)]
1248+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributesVec (attributes rel))]
1287 attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1249 attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1288 attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1250 attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1289 Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1251 Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1290 Right rel -> RelationAtom rel
1252 Right rel -> RelationAtom rel
1291− rvs <- mapM mkRvDesc (M.toList relVarMap)
1253+ rvs <- mapM mkRvDesc (M.toList relVars)
1292 let tups = map relVarToAtomList rvs
1254 let tups = map relVarToAtomList rvs
1293 mkRelationFromList attrs tups
1255 mkRelationFromList attrs tups
1257+-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1258+evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1259+evalRelationalExpr expr = do
1261+ context <- reContext
1262+ let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1263+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1264+ case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1265+ Left err -> throwError err
1266+ Right rel -> pure rel
1268+class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1269+ getContext :: m DatabaseContext
1271+instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1272+ getContext = gfDatabaseContextForMarker UncommittedContextMarker
1274+instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1275+ getContext = getStateContext
1277+relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1278+relVarByName rvName = do
1279+ relvars <- relationVariables <$> getContext
1280+ case M.lookup rvName relvars of
1281+ Nothing -> throwError (RelVarNotDefinedError rvName)
1282+ Just gfexpr -> pure gfexpr
1284+-- | resolve UncommittedTransactionMarker whenever possible- this is important in the DatabaseContext in order to mitigate self-referencing loops for updates
1285+class ResolveGraphRefTransactionMarker a where
1286+ resolve :: a -> DatabaseContextEvalMonad a
1289+instance ResolveGraphRefTransactionMarker GraphRefRelationalExpr where
1290+ resolve (MakeRelationFromExprs mAttrs tupleExprs) =
1291+ MakeRelationFromExprs mAttrs <$> resolve tupleExprs
1292+ resolve orig@MakeStaticRelation{} = pure orig
1293+ resolve orig@ExistingRelation{} = pure orig
1294+ resolve orig@(RelationVariable rvName UncommittedContextMarker) = do
1295+ rvMap <- relationVariables <$> getStateContext
1296+ case M.lookup rvName rvMap of
1297+ Nothing -> pure orig
1298+ Just resolvedRv -> resolve resolvedRv
1299+ resolve orig@RelationVariable{} = pure orig
1300+ resolve (Project attrNames relExpr) = Project <$> resolve attrNames <*> resolve relExpr
1301+ resolve (Union exprA exprB) = Union <$> resolve exprA <*> resolve exprB
1302+ resolve (Join exprA exprB) = Join <$> resolve exprA <*> resolve exprB
1303+ resolve (Rename attrA attrB expr) = Rename attrA attrB <$> resolve expr
1304+ resolve (Difference exprA exprB) = Difference <$> resolve exprA <*> resolve exprB
1305+ resolve (Group namesA nameB expr) = Group <$> resolve namesA <*> pure nameB <*> resolve expr
1306+ resolve (Ungroup nameA expr) = Ungroup nameA <$> resolve expr
1307+ resolve (Restrict restrictExpr relExpr) = Restrict <$> resolve restrictExpr <*> resolve relExpr
1308+ resolve (Equals exprA exprB) = Equals <$> resolve exprA <*> resolve exprB
1309+ resolve (NotEquals exprA exprB) = NotEquals <$> resolve exprA <*> resolve exprB
1310+ resolve (Extend extendExpr relExpr) = Extend <$> resolve extendExpr <*> resolve relExpr
1311+ resolve (With withExprs relExpr) = With <$> mapM (\(nam, expr) -> (,) <$> resolve nam <*> resolve expr) withExprs <*> resolve relExpr
1313+instance ResolveGraphRefTransactionMarker GraphRefTupleExprs where
1314+ resolve (TupleExprs marker tupleExprs) =
1315+ TupleExprs marker <$> mapM resolve tupleExprs
1317+instance ResolveGraphRefTransactionMarker GraphRefTupleExpr where
1318+ resolve (TupleExpr tupMap) = do
1319+ tupMap' <- mapM (\(attrName, expr) -> (,) attrName <$> resolve expr ) (M.toList tupMap)
1320+ pure (TupleExpr (M.fromList tupMap'))
1322+instance ResolveGraphRefTransactionMarker GraphRefAttributeNames where
1323+ resolve orig@AttributeNames{} = pure orig
1324+ resolve orig@InvertedAttributeNames{} = pure orig
1325+ resolve (UnionAttributeNames namesA namesB) = UnionAttributeNames <$> resolve namesA <*> resolve namesB
1326+ resolve (IntersectAttributeNames namesA namesB) = IntersectAttributeNames <$> resolve namesA <*> resolve namesB
1327+ resolve (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> resolve expr
1329+instance ResolveGraphRefTransactionMarker GraphRefRestrictionPredicateExpr where
1330+ resolve TruePredicate = pure TruePredicate
1331+ resolve (AndPredicate exprA exprB) = AndPredicate <$> resolve exprA <*> resolve exprB
1332+ resolve (OrPredicate exprA exprB) = OrPredicate <$> resolve exprA <*> resolve exprB
1333+ resolve (NotPredicate expr) = NotPredicate <$> resolve expr
1334+ resolve (RelationalExprPredicate expr) = RelationalExprPredicate <$> resolve expr
1335+ resolve (AtomExprPredicate expr) = AtomExprPredicate <$> resolve expr
1336+ resolve (AttributeEqualityPredicate nam expr)= AttributeEqualityPredicate nam <$> resolve expr
1338+instance ResolveGraphRefTransactionMarker GraphRefExtendTupleExpr where
1339+ resolve (AttributeExtendTupleExpr nam atomExpr) = AttributeExtendTupleExpr nam <$> resolve atomExpr
1341+instance ResolveGraphRefTransactionMarker GraphRefWithNameExpr where
1342+ resolve orig@WithNameExpr{} = pure orig -- match uncommitted marker?
1344+instance ResolveGraphRefTransactionMarker GraphRefAtomExpr where
1345+ resolve orig@AttributeAtomExpr{} = pure orig
1346+ resolve orig@NakedAtomExpr{} = pure orig
1347+ resolve (FunctionAtomExpr nam atomExprs marker) =
1348+ FunctionAtomExpr nam <$> mapM resolve atomExprs <*> pure marker
1349+ resolve (RelationAtomExpr expr) = RelationAtomExpr <$> resolve expr
1350+ resolve (ConstructedAtomExpr dConsName atomExprs marker) =
1351+ ConstructedAtomExpr dConsName <$> mapM resolve atomExprs <*> pure marker
1353+--convert series of simple Union queries into MakeStaticRelation
1354+-- this is especially useful for long, nested applications of Union with simple tuples
1355+-- Union (MakeRelation x y) (MakeRelation x y') -> MakeRelation x (y + y')
1357+--MakeRelationFromExprs Nothing (TupleExprs UncommittedContextMarker [TupleExpr (fromList [("name", NakedAtomExpr (TextAtom "steve"))])])
1359+applyUnionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1360+applyUnionCollapse = Fold.cata opt
1362+ opt :: RelationalExprBaseF GraphRefTransactionMarker GraphRefRelationalExpr -> GraphRefRelationalExpr
1363+ opt (UnionF exprA exprB) | exprA == exprB = exprA
1365+ exprA@(MakeRelationFromExprs mAttrs1 tupExprs1)
1366+ exprB@(MakeRelationFromExprs mAttrs2 tupExprs2)) | tupExprs1 == tupExprs2 = MakeRelationFromExprs (mAttrs1 <|> mAttrs2) tupExprs1
1367+ | tupExprsNull tupExprs1 = exprB
1368+ | tupExprsNull tupExprs2 = exprA
1369+ opt x = Fold.embed x
1370+ tupExprsNull (TupleExprs _ []) = True
1371+ tupExprsNull _ = False
1374+--UPDATE optimization- find matching where clause in "lower" levels of renaming
1375+--update x where y=1 set (x:=5,z:=10); update x where y=1 set(x:=6,z:=11)
1377+-- update x where y=1 set (x:=6,z:=11)
1378+-- future opt: match individual attributes update x where y=1 set (x:=5); update x where y=1 set (z:=11) => update x where y=1 set (x:=5,z:=11)
1380+--strategy: try to collapse the top-level update (union (restrict pred MakeRelationFromExpr) expr) if it contains the same predicate and resultant relation
1382+--DELETE optimization
1383+-- if a restriction matches a previous restriction, combine them
1384+-- O(1) since it only scans at the top level, critical in benchmarks generating redundant deletions
1385+applyRestrictionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1386+applyRestrictionCollapse orig@(Restrict npred@(NotPredicate _) expr) =
1388+ orig'@(Restrict npred'@(NotPredicate _) _) | npred == npred' -> orig'
1390+applyRestrictionCollapse expr = expr