@@ -1,7 +1,4 @@
1{-# LANGUAGE ScopedTypeVariables #-}
1{-# LANGUAGE ScopedTypeVariables #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE OverloadedStrings #-}
5module ProjectM36.RelationalExpression where
2module ProjectM36.RelationalExpression where
6import ProjectM36.Relation
3import ProjectM36.Relation
7import ProjectM36.Tuple
4import ProjectM36.Tuple
@@ -16,37 +13,35 @@ import ProjectM36.DataTypes.Primitive
16import ProjectM36.AtomFunction
13import ProjectM36.AtomFunction
17import ProjectM36.DatabaseContextFunction
14import ProjectM36.DatabaseContextFunction
18import ProjectM36.Arbitrary
15import ProjectM36.Arbitrary
19−import ProjectM36.GraphRefRelationalExpr
20import ProjectM36.Transaction
16import ProjectM36.Transaction
21import qualified ProjectM36.Attribute as A
17import qualified ProjectM36.Attribute as A
22import qualified Data.Map as M
18import qualified Data.Map as M
23import qualified Data.HashSet as HS
19import qualified Data.HashSet as HS
24import qualified Data.Set as S
20import qualified Data.Set as S
25−import Control.Monad.State hiding (join)
21+import Control.Monad.RWS.Strict as RWS
26−import Data.Bifunctor (second)
22+import Control.Monad.Trans.Class (lift)
23+import Control.Exception
27import Data.Maybe
24import Data.Maybe
28import Data.Either
25import Data.Either
29import Data.Char (isUpper)
26import Data.Char (isUpper)
31−import qualified Data.List.NonEmpty as NE
32−import Data.Functor.Identity
33import qualified Data.Text as T
27import qualified Data.Text as T
34import qualified Data.Vector as V
28import qualified Data.Vector as V
35import qualified ProjectM36.TypeConstructorDef as TCD
29import 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)
30+import Control.Monad.Except
39import Control.Monad.Trans.Except (except)
31import Control.Monad.Trans.Except (except)
40−import Control.Monad.Reader as R hiding (join)
32+import Control.Monad.Reader as R
41import ProjectM36.NormalizeExpr
33import ProjectM36.NormalizeExpr
42−import ProjectM36.WithNameExpr
43import Test.QuickCheck
34import Test.QuickCheck
44−import qualified Data.Functor.Foldable as Fold
35+import GHC
45−import Control.Applicative
46−#ifdef PM36_HASKELL_SCRIPTING
47−import GHC hiding (getContext)
48−import Control.Exception
49import GHC.Paths
36import 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
52data DatabaseContextExprDetails = CountUpdatedTuples
47data DatabaseContextExprDetails = CountUpdatedTuples
@@ -75,6 +70,7 @@ mkDatabaseContextEvalState context = DatabaseContextEvalState {
75data RelationalExprEnv = RelationalExprEnv {
70data RelationalExprEnv = RelationalExprEnv {
76 re_context :: DatabaseContext,
71 re_context :: DatabaseContext,
77 re_graph :: TransactionGraph,
72 re_graph :: TransactionGraph,
73+ re_currentTransId :: TransactionId,
78 re_extra :: Maybe (Either RelationTuple Attributes)
74 re_extra :: Maybe (Either RelationTuple Attributes)
@@ -90,33 +86,42 @@ instance Show RelationalExprEnv where
90--used to eval relationalexpr
86--used to eval relationalexpr
91type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
87type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
93−runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
94−runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
96reGraph :: RelationalExprM TransactionGraph
89reGraph :: RelationalExprM TransactionGraph
97−reGraph = asks re_graph
90+reGraph = re_graph <$> R.ask
99−reContext :: RelationalExprM DatabaseContext
92+gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
100−reContext = asks re_context
93+gfTransForId tid = do
95+ lift $ except $ transactionForId tid graph
97+currentTrans :: RelationalExprM Transaction
99+ tid <- re_currentTransId <$> R.ask
100+ graph <- re_graph <$> R.ask
101+ lift $ except $ transactionForId tid graph
103+reTransId :: RelationalExprM TransactionId
104+reTransId = re_currentTransId <$> R.ask
102−mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
106+mkRelationalExprEnv :: DatabaseContext -> TransactionId -> TransactionGraph -> RelationalExprEnv
103−mkRelationalExprEnv ctx graph =
107+mkRelationalExprEnv ctx currentTransId graph =
104 RelationalExprEnv
108 RelationalExprEnv
105 { re_context = ctx,
109 { re_context = ctx,
106 re_graph = graph,
110 re_graph = graph,
111+ re_currentTransId = currentTransId,
107 re_extra = Nothing }
112 re_extra = Nothing }
109askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
114askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
110askEnv = R.ask
115askEnv = R.ask
112mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
117mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
113−mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
118+mergeTuplesIntoGraphRefRelationalExprEnv tupIn e =
114− env { gre_extra = new_elems }
119+ e{ gre_extra = new_elems }
116 new_elems = Just (Left newTuple)
121 new_elems = Just (Left newTuple)
117− mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
122+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple e))
118 newTuple = mkRelationTupleFromMap mergedTupMap
123 newTuple = mkRelationTupleFromMap mergedTupMap
120mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
125mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
121mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
126mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
@@ -142,12 +147,12 @@ data DatabaseContextEvalEnv = DatabaseContextEvalEnv
144mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
149mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
145−mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
150+mkDatabaseContextEvalEnv tid graph = DatabaseContextEvalEnv tid graph
147type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
152type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
149runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
154runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
150−runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
155+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> (execRWST m env freshEnv)))
152 freshEnv = mkDatabaseContextEvalState ctx
157 freshEnv = mkDatabaseContextEvalState ctx
@@ -160,51 +165,35 @@ dbcGraph = dce_graph <$> RWS.ask
161dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
166dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
162dbcRelationalExprEnv =
167dbcRelationalExprEnv =
163− mkRelationalExprEnv <$> getStateContext <*> dbcGraph
168+ mkRelationalExprEnv <$> getStateContext <*> dbcTransId <*> dbcGraph
165getStateContext :: DatabaseContextEvalMonad DatabaseContext
170getStateContext :: DatabaseContextEvalMonad DatabaseContext
166−getStateContext = gets dbc_context
171+getStateContext = dbc_context <$> get
168putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
173putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
169putStateContext ctx' = do
174putStateContext ctx' = do
171− put (s {dbc_context = ctx', dbc_dirty = True})
176+ put (s {dbc_context = ctx'})
173−-- | The context is optionally passed down along in cases where the current context is uncommitted.
174data GraphRefRelationalExprEnv =
178data GraphRefRelationalExprEnv =
175 GraphRefRelationalExprEnv {
179 GraphRefRelationalExprEnv {
176− gre_context :: Maybe DatabaseContext,
177 gre_graph :: TransactionGraph,
180 gre_graph :: TransactionGraph,
178 gre_extra :: Maybe (Either RelationTuple Attributes)
181 gre_extra :: Maybe (Either RelationTuple Attributes)
181type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
184type 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
196runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
186runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
197runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
187runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
199−freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
189+freshGraphRefRelationalExprEnv :: TransactionGraph -> GraphRefRelationalExprEnv
200−freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
190+freshGraphRefRelationalExprEnv graph = GraphRefRelationalExprEnv {
202 gre_graph = graph,
191 gre_graph = graph,
203 gre_extra = Nothing
192 gre_extra = Nothing
206gfGraph :: GraphRefRelationalExprM TransactionGraph
195gfGraph :: GraphRefRelationalExprM TransactionGraph
207−gfGraph = asks gre_graph
196+gfGraph = gre_graph <$> R.ask
209envContext :: RelationalExprEnv -> DatabaseContext
198envContext :: RelationalExprEnv -> DatabaseContext
210envContext = re_context
199envContext = re_context
@@ -212,27 +201,173 @@ envContext = re_context
212setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
201setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
213setEnvContext e ctx = e { re_context = ctx }
202setEnvContext 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))
215--helper function to process relation variable creation/assignment
358--helper function to process relation variable creation/assignment
216setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
359setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
217setRelVar relVarName relExpr = do
360setRelVar relVarName relExpr = do
218 currentContext <- getStateContext
362 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
363+ let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
222 potentialContext = currentContext { relationVariables = newRelVars }
364 potentialContext = currentContext { relationVariables = newRelVars }
223− --optimization: if the relexpr is unchanged, skip the update
224− if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
227− --determine when to check constraints
365+ --determine when to check constraints
228− graph <- dbcGraph
366+ graph <- dbcGraph
229− tid <- dbcTransId
367+ tid <- dbcTransId
230− case checkConstraints potentialContext tid graph of
368+ case checkConstraints potentialContext tid graph of
231− Left err -> dbErr err
369+ Left err -> dbErr err
232− Right _ -> putStateContext potentialContext
370+ 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 ()
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
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
238deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
373deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
@@ -251,17 +386,20 @@ evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContex
251evalGraphRefDatabaseContextExpr NoOperation = pure ()
386evalGraphRefDatabaseContextExpr NoOperation = pure ()
253evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
388evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
254− context <- getStateContext
255 relvars <- fmap relationVariables getStateContext
389 relvars <- fmap relationVariables getStateContext
256 tConss <- fmap typeConstructorMapping getStateContext
390 tConss <- fmap typeConstructorMapping getStateContext
391+ relEnv <- dbcRelationalExprEnv
257 graph <- dbcGraph
392 graph <- dbcGraph
258 let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
393 let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
259− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
394+ gfEnv = freshGraphRefRelationalExprEnv graph
260 case eAttrs of
395 case eAttrs of
261− Left err -> dbErr err
396+ Left err -> dbErr err
262 Right attrsList -> do
397 Right attrsList -> do
263− lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
398+ let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
399+ if not (null atomTypeErrs) then
400+ dbErr (someErrors atomTypeErrs)
264− case M.member relVarName relvars of
402+ case M.member relVarName relvars of
265 True -> dbErr (RelVarAlreadyDefinedError relVarName)
403 True -> dbErr (RelVarAlreadyDefinedError relVarName)
266 False -> setRelVar relVarName (ExistingRelation emptyRelation)
404 False -> setRelVar relVarName (ExistingRelation emptyRelation)
@@ -274,17 +412,13 @@ evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
274 graph <- re_graph <$> dbcRelationalExprEnv
412 graph <- re_graph <$> dbcRelationalExprEnv
275 context <- getStateContext
413 context <- getStateContext
276 let existingRelVar = M.lookup relVarName (relationVariables context)
414 let existingRelVar = M.lookup relVarName (relationVariables context)
277− reEnv = freshGraphRefRelationalExprEnv (Just context) graph
278− eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
279 case existingRelVar of
415 case existingRelVar of
280 Nothing -> do
416 Nothing -> do
281− case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
282− Left err -> dbErr err
284− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
285− setRelVar relVarName expr
417+ setRelVar relVarName expr
286 Just existingRel -> do
418 Just existingRel -> do
287 let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
419 let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
420+ eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
421+ reEnv = freshGraphRefRelationalExprEnv graph
288 case eExpectedType of
422 case eExpectedType of
289 Left err -> dbErr err
423 Left err -> dbErr err
290 Right expectedType ->
424 Right expectedType ->
@@ -292,53 +426,44 @@ evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
292 Left err -> dbErr err
426 Left err -> dbErr err
293 Right newExprType -> do
427 Right newExprType -> do
294 if newExprType == expectedType then do
428 if newExprType == expectedType then do
295− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
296 setRelVar relVarName expr
429 setRelVar relVarName expr
298 dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
431 dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
300evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
433evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
301− gfExpr <- relVarByName relVarName
434+ transId <- dbcTransId
302− let optExpr = applyUnionCollapse (Union
305− evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
435+ evalGraphRefDatabaseContextExpr (Assign relVarName
437+ (RelationVariable relVarName transId)
307evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
440evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
308− gfExpr <- relVarByName relVarName
441+ transId <- dbcTransId
442+ let rv = RelationVariable relVarName transId
309− let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
443+ setRelVar relVarName (Restrict (NotPredicate predicate) rv)
310− setRelVar relVarName optExpr
312--union of restricted+updated portion and the unrestricted+unupdated portion
445--union of restricted+updated portion and the unrestricted+unupdated portion
313evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
446evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
314− rvExpr <- relVarByName relVarName
315− graph <- re_graph <$> dbcRelationalExprEnv
316 context <- getStateContext
447 context <- getStateContext
317− let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
448+ transId <- dbcTransId
318− --get the current attributes name in the relvar to ensure that we don't conflict when renaming
449+ graph <- dbcGraph
319− eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
450+ let relVarMap = relationVariables context
320− exprType' <- case eExprType of
451+ case M.lookup relVarName relVarMap of
321− Left err -> throwError err
452+ Nothing -> dbErr (RelVarNotDefinedError relVarName)
322− Right t -> pure t
453+ Just _ -> do
323− let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
454+ let unrestrictedPortion = Restrict (NotPredicate pred') rv
324− tmpAttr = tmpAttrC 1
455+ rv = RelationVariable relVarName transId
325− tmpAttrC :: Int -> AttributeName -> AttributeName
456+ tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
327− let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
328− if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
332− updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
457+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
333− projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
458+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
334− restrictedPortion = Restrict pred' rvExpr
459+ restrictedPortion = Restrict pred'
335− updated = foldr (\(oldname, atomExpr) accum ->
460+ updated = foldr (\(oldname, atomExpr) accum ->
336− let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
461+ let procAtomExpr = runProcessExprM transId graph (processAtomExpr atomExpr) in
337 updateAttr oldname procAtomExpr accum
462 updateAttr oldname procAtomExpr accum
338− ) restrictedPortion (M.toList atomExprMap)
463+ ) rv (M.toList atomExprMap)
339 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
464 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
340− updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
465+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
341− setRelVar relVarName (Union unrestrictedPortion updatedPortion)
466+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
343evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
468evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
344 currContext <- getStateContext
469 currContext <- getStateContext
@@ -350,8 +475,6 @@ evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
350 dbErr (InclusionDependencyNameInUseError newDepName)
475 dbErr (InclusionDependencyNameInUseError newDepName)
352 let potentialContext = currContext { inclusionDependencies = newDeps }
477 let potentialContext = currContext { inclusionDependencies = newDeps }
353− -- if the potential context passes all constraints, then save it
354− -- potential optimization: validate only the new constraint- all old constraints must already hold
355 case checkConstraints potentialContext transId graph of
478 case checkConstraints potentialContext transId graph of
356 Left err -> dbErr err
479 Left err -> dbErr err
357 Right _ ->
480 Right _ ->
@@ -396,9 +519,9 @@ evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
396 let oldTypes = typeConstructorMapping currentContext
519 let oldTypes = typeConstructorMapping currentContext
397 tConsName = TCD.name tConsDef
520 tConsName = TCD.name tConsDef
398 -- validate that the constructor's types exist
521 -- validate that the constructor's types exist
399− case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
522+ case validateTypeConstructorDef tConsDef dConsDefList of
400− Left err -> throwError err
523+ errs@(_:_) -> dbErr (someErrors errs)
401− Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
524+ [] | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
402 | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
525 | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
403 | otherwise -> do
526 | otherwise -> do
404 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
527 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
@@ -414,10 +537,15 @@ evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
414 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
537 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
415 putStateContext $ currentContext { typeConstructorMapping = newTypes }
538 putStateContext $ currentContext { typeConstructorMapping = newTypes }
417−evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
540+evalGraphRefDatabaseContextExpr (MultipleExpr _) = do
418 --the multiple expressions must pass the same context around- not the old unmodified context
541 --the multiple expressions must pass the same context around- not the old unmodified context
419− mapM_ evalGraphRefDatabaseContextExpr exprs
543+{- evald <- forM exprs (\expr -> evalGraphRefDatabaseContextExpr expr)
420−
544+ --some lifting magic needed here
547+ errs -> dbErr (someErrors errs)
421evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
549evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
422 currentContext <- getStateContext
550 currentContext <- getStateContext
423 let atomFuncs = atomFunctions currentContext
551 let atomFuncs = atomFunctions currentContext
@@ -444,11 +572,12 @@ evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
445evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
573evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
446 context <- getStateContext
574 context <- getStateContext
575+ relExprEnv <- dbcRelationalExprEnv
447 graph <- dbcGraph
576 graph <- dbcGraph
448 --resolve atom arguments
577 --resolve atom arguments
449− let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
578+ let eAtomTypes = mapM (\atomExpr -> runGraphRefRelationalExprM gfEnv (typeForGraphRefAtomExpr emptyAttributes atomExpr)) atomArgExprs
450 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
579 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
451− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
580+ gfEnv = freshGraphRefRelationalExprEnv graph
452 case eFunc of
581 case eFunc of
453 Left err -> dbErr err
582 Left err -> dbErr err
454 Right func -> do
583 Right func -> do
@@ -461,13 +590,12 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
461 case eAtomTypes of
590 case eAtomTypes of
462 Left err -> dbErr err
591 Left err -> dbErr err
463 Right atomTypes -> do
592 Right atomTypes -> do
464− let mValidTypes = zipWith (\ expType actType
465− -> case atomTypeVerify expType actType of
593+ let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
466− Left err -> Just err
594+ Left err -> Just err
468− (dbcFuncType func) atomTypes
595+ Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
469 typeErrors = catMaybes mValidTypes
596 typeErrors = catMaybes mValidTypes
470− eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
597+ eAtomArgs = unimplemented
598+ --eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
471 if length (lefts eAtomArgs) > 1 then
599 if length (lefts eAtomArgs) > 1 then
472 dbErr (someErrors (lefts eAtomArgs))
600 dbErr (someErrors (lefts eAtomArgs))
473 else if not (null typeErrors) then
601 else if not (null typeErrors) then
@@ -476,6 +604,7 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
476 case evalDatabaseContextFunction func (rights eAtomArgs) context of
604 case evalDatabaseContextFunction func (rights eAtomArgs) context of
477 Left err -> dbErr err
605 Left err -> dbErr err
478 Right newContext -> putStateContext newContext
606 Right newContext -> putStateContext newContext
479data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
608data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
480 { dbcio_transId :: TransactionId,
609 { dbcio_transId :: TransactionId,
481 dbcio_graph :: TransactionGraph,
610 dbcio_graph :: TransactionGraph,
@@ -511,15 +640,10 @@ getDBCIOContext = dbc_context <$> RWS.get
511getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
640getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
512getDBCIORelationalExprEnv = do
641getDBCIORelationalExprEnv = do
513 context <- getDBCIOContext
642 context <- getDBCIOContext
514− mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
644+ pure $ mkRelationalExprEnv context (dbcio_transId env) (dbcio_graph env)
516evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
646evalGraphRefDatabaseContextIOExpr :: 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))
523evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
647evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
524 eScriptSession <- requireScriptSession
648 eScriptSession <- requireScriptSession
525 currentContext <- getDBCIOContext
649 currentContext <- getDBCIOContext
@@ -553,6 +677,7 @@ evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = d
553 Right eContext -> case eContext of
677 Right eContext -> case eContext of
554 Left err -> pure (Left err)
678 Left err -> pure (Left err)
555 Right context' -> putDBCIOContext context'
679 Right context' -> putDBCIOContext context'
556evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
681evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
557 eScriptSession <- requireScriptSession
682 eScriptSession <- requireScriptSession
558 currentContext <- getDBCIOContext
683 currentContext <- getDBCIOContext
@@ -594,6 +719,7 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
594 Right eContext -> case eContext of
719 Right eContext -> case eContext of
595 Left err -> pure (Left err)
720 Left err -> pure (Left err)
596 Right context' -> putDBCIOContext context'
721 Right context' -> putDBCIOContext context'
597evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
723evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
598 currentContext <- getDBCIOContext
724 currentContext <- getDBCIOContext
599 eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
725 eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
@@ -610,7 +736,7 @@ evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName
610 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
736 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
611 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
737 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
612 in putDBCIOContext newContext
738 in putDBCIOContext newContext
614evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
740evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
616 currentContext <- getDBCIOContext
742 currentContext <- getDBCIOContext
@@ -618,6 +744,7 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
618 --create graph ref expr
744 --create graph ref expr
619 let gfExpr = Define relVarName attrExprs
745 let gfExpr = Define relVarName attrExprs
620 evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
746 evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
747+ transId = dbcio_transId env
621 graph = dbcio_graph env
748 graph = dbcio_graph env
622 case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
749 case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
623 Left err -> pure (Left err)
750 Left err -> pure (Left err)
@@ -628,8 +755,8 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
628 case existingRelVar of
755 case existingRelVar of
629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
756 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
630 Just existingRel -> do
757 Just existingRel -> do
631− let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
758+ let env = freshGraphRefRelationalExprEnv graph
632− case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
759+ case runGraphRefRelationalExprM env (typeForGraphRefRelationalExpr existingRel) of
633 Left err -> pure (Left err)
760 Left err -> pure (Left err)
634 Right relType -> do
761 Right relType -> do
635 let expectedAttributes = attributes relType
762 let expectedAttributes = attributes relType
@@ -642,36 +769,45 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
642 Left err -> pure (Left err)
769 Left err -> pure (Left err)
643 Right dbstate' -> putDBCIOContext (dbc_context dbstate')
770 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)
645--run verification on all constraints
784--run verification on all constraints
646checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
785checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
647−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
786+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
648 mapM_ (uncurry checkIncDep) (M.toList deps)
787 mapM_ (uncurry checkIncDep) (M.toList deps)
650 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
789 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
651 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
790 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
652 utctDayTime = secondsToDiffTime 0 }
791 utctDayTime = secondsToDiffTime 0 }
653 tempSchemas = Schemas context M.empty
792 tempSchemas = Schemas context M.empty
654− tempTrans = Transaction U.nil tempTransInfo tempSchemas
655− tempTransInfo = TransactionInfo { parents = transId NE.:| [],
793+ tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
660 deps = inclusionDependencies context
795 deps = inclusionDependencies context
796+ reEnv = mkRelationalExprEnv context transId graph
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
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
662 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
798 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
663− let process = runProcessExprM UncommittedContextMarker
799+ let process = runProcessExprM transId graph
664 gfSubsetExpr = process (processRelationalExpr subsetExpr)
800 gfSubsetExpr = process (processRelationalExpr subsetExpr)
665 gfSupersetExpr = process (processRelationalExpr supersetExpr)
801 gfSupersetExpr = process (processRelationalExpr supersetExpr)
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.
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.
667− let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
803+ let gfEnv = freshGraphRefRelationalExprEnv graph
668 runGfRel = runGraphRefRelationalExprM gfEnv
804 runGfRel = runGraphRefRelationalExprM gfEnv
669 typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
805 typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
670 typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
806 typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
671 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
807 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
672 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
808 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
673− gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
809+ gfEvald = runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr checkExpr)
674− gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
810+ gfEnv = freshGraphRefRelationalExprEnv potentialGraph
675 case gfEvald of
811 case gfEvald of
676 Left err -> Left err
812 Left err -> Left err
677 Right resultRel -> if resultRel == relationTrue then
813 Right resultRel -> if resultRel == relationTrue then
@@ -687,11 +823,20 @@ typeForRelationalExpr expr = do
687 --replace the relationVariables context element with a cloned set of relation devoid of tuples
823 --replace the relationVariables context element with a cloned set of relation devoid of tuples
688 --evalRelationalExpr could still return an existing relation with tuples, so strip them
824 --evalRelationalExpr could still return an existing relation with tuples, so strip them
689 graph <- reGraph
825 graph <- reGraph
690− context <- reContext
826+ transId <- reTransId
691− let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
827+ let gfExpr = runProcessExprM transId graph (processRelationalExpr expr)
692− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
828+ gfEnv = freshGraphRefRelationalExprEnv graph
693 runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
829 runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
694− lift $ except runGf
830+ 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)
696liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
841liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
697liftE v = do
842liftE v = do
@@ -740,7 +885,7 @@ predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
741predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
886predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
742 env <- askEnv
887 env <- askEnv
743− let attrs' = A.union attrs (envAttributes env)
888+ let attrs' = envAttributes env
744 ctxtup' = envTuple env
889 ctxtup' = envTuple env
745 atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
890 atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
746 attr <- lift $ except $ case A.attributeForName attrName attrs of
891 attr <- lift $ except $ case A.attributeForName attrName attrs of
@@ -784,8 +929,8 @@ tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName r
784 Right rel
929 Right rel
786extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
931extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
787−extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
932+extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
788−-- renv <- askEnv
933+ renv <- askEnv
789 -- check that the attribute name is not in use
934 -- check that the attribute name is not in use
790 case tupleExprCheckNewAttrName newAttrName relIn of
935 case tupleExprCheckNewAttrName newAttrName relIn of
791 Left err -> throwError err
936 Left err -> throwError err
@@ -794,60 +939,65 @@ extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrNa
794 atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
939 atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
795 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
940 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
796 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
941 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
798− pure (newAndOldAttrs, \tup -> do
799− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
942+ pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
800− atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
943+ case unimplemented {-runReader (evalAtomExpr tup atomExpr) substate-} of
944+ Left err -> Left err
801− Right (tupleAtomExtend newAttrName atom tup)
945+ Right atom -> Right (tupleAtomExtend newAttrName atom tup)
804evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
948evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
805−evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
949+evalGraphRefAtomExpr = unimplemented
951+evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprM Atom
952+evalAtomExpr = unimplemented
806− case atomForAttributeName attrName tupIn of
955+evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
807− Right atom -> pure atom
956+ Right atom -> pure (Right atom)
808− Left err@(NoSuchAttributeNamesError _) -> do
957+ err@(Left (NoSuchAttributeNamesError _)) -> do
809− env <- askEnv
958+ rstate <- ask
810− case gre_extra env of
959+ let stateTup = stateTuple rstate
811− Nothing -> throwError err
812− Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
960+ pure (atomForAttributeName attrName stateTup)
813− Just (Right _) -> throwError err
814− Left err -> throwError err
961+ Left err -> pure (Left err)
815−evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
962+evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
816−evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
963+evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
817− argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
964+ argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
818− context <- gfDatabaseContextForMarker tid
965+ context <- fmap stateElemsContext ask
819− let functions = atomFunctions context
967+ let functions = atomFunctions context
820− func <- lift $ except (atomFunctionForName funcName functions)
968+ func <- either throwE pure (atomFunctionForName funcName functions)
821− let expectedArgCount = length (atomFuncType func) - 1
969+ let expectedArgCount = length (atomFuncType func) - 1
822− actualArgCount = length argTypes
970+ actualArgCount = length argTypes
823− safeInit [] = [] -- different behavior from normal init
971+ safeInit [] = [] -- different behavior from normal init
824− safeInit xs = init xs
972+ safeInit xs = init xs
825− if expectedArgCount /= actualArgCount then
973+ if expectedArgCount /= actualArgCount then
826− throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
974+ throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
828 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
976 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
829− mapM_ (\(expType, actType) ->
977+ mapM_ (\(expType, eActType) -> do
978+ actType <- either throwE pure eActType
830− lift $ except (atomTypeVerify expType actType)) zippedArgs
979+ either throwE pure (atomTypeVerify expType actType)) zippedArgs
831− evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
980+ evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
832 case evalAtomFunction func evaldArgs of
981 case evalAtomFunction func evaldArgs of
833− Left err -> throwError (AtomFunctionUserError err)
982+ Left err -> throwE (AtomFunctionUserError err)
834 Right result -> do
983 Right result -> do
835 --validate that the result matches the expected type
984 --validate that the result matches the expected type
836− _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
985+ _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
837 pure result
986 pure result
838−evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
987+evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
839 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
988 --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
989+ rstate <- ask
841− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
990+ runExceptT $ do
842− relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
991+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
992+ relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
843− pure (RelationAtom relAtom)
993+ pure (RelationAtom relAtom)
844−evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
994+evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
845− let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
995+ rstate <- lift ask
996+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
846− aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
997+ aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
847− argAtoms <- local mergeEnv $
998+ argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
848− mapM (evalGraphRefAtomExpr tupIn) dConsArgs
849 pure (ConstructedAtom dConsName aType argAtoms)
999 pure (ConstructedAtom dConsName aType argAtoms)
851typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
1001typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
852typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
1002typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
853 renv <- askEnv
1003 renv <- askEnv
@@ -860,13 +1010,11 @@ typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
860 Right attr -> pure (A.atomType attr)
1010 Right attr -> pure (A.atomType attr)
861 Left _ -> case atomForAttributeName attrName envTup of
1011 Left _ -> case atomForAttributeName attrName envTup of
862 Right atom -> pure (atomTypeForAtom atom)
1012 Right atom -> pure (atomTypeForAtom atom)
863− Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
865− Left err -> throwError err
1013+ Left _ -> throwError err
867typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
1015typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
868typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
1016typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
869− funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
1017+ funcs <- atomFunctions . concreteDatabaseContext <$> gfTransForId transId
870 case atomFunctionForName funcName funcs of
1018 case atomFunctionForName funcName funcs of
871 Left err -> throwError err
1019 Left err -> throwError err
872 Right func -> do
1020 Right func -> do
@@ -884,7 +1032,7 @@ typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
884typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
1032typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
886 argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
1034 argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
887− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1035+ tConsMap <- typeConstructorMapping . concreteDatabaseContext <$> gfTransForId tid
888 lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
1036 lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
890-- | Validate that the type of the AtomExpr matches the expected type.
1038-- | Validate that the type of the AtomExpr matches the expected type.
@@ -901,12 +1049,10 @@ verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
901 case A.attributeForName attrName attrs' of
1049 case A.attributeForName attrName attrs' of
902 Left err' -> throwError err'
1050 Left err' -> throwError err'
903 Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
1051 Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
904− Left err -> throwError err
906verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
1052verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
907 lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
1053 lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
908verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
1054verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
909− context <- gfDatabaseContextForMarker tid
1055+ context <- concreteDatabaseContext <$> gfTransForId tid
910 let functions = atomFunctions context
1056 let functions = atomFunctions context
911 func <- lift $ except $ atomFunctionForName funcName functions
1057 func <- lift $ except $ atomFunctionForName funcName functions
912 let expectedArgTypes = atomFuncType func
1058 let expectedArgTypes = atomFuncType func
@@ -914,7 +1060,7 @@ verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) e
914 let handler :: RelationalError -> GraphRefRelationalExprM AtomType
1060 let handler :: RelationalError -> GraphRefRelationalExprM AtomType
915 handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
1061 handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
916 handler err = throwError err
1062 handler err = throwError err
917− verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
1063+ verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
918 funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
1064 funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
919 if length funcArgTypes /= length expectedArgTypes - 1 then
1065 if length funcArgTypes /= length expectedArgTypes - 1 then
920 throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
1066 throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
@@ -932,61 +1078,13 @@ verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
932-- | Look up the type's name and create a new attribute.
1078-- | Look up the type's name and create a new attribute.
933evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1079evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
934evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
1080evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
935− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
1081+ tConsMap <- typeConstructorMapping . concreteDatabaseContext <$> gfTransForId transId
936 aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
1082 aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
937 lift $ except $ validateAtomType aType tConsMap
1083 lift $ except $ validateAtomType aType tConsMap
938 pure $ Attribute attrName aType
1084 pure $ Attribute attrName aType
940evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
1086evalGraphRefAttrExpr (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)])))
990evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
1088evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
991evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
1089evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
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
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
@@ -1011,78 +1109,70 @@ evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
1011 --verify that the attributes match
1109 --verify that the attributes match
1012 when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1110 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
1111 --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))
1112+-- tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1015 let tup' = reorderTuple finalAttrs tup
1113 let tup' = reorderTuple finalAttrs tup
1016 --TODO: restore type resolution
1114 --TODO: restore type resolution
1017-- _ <- lift $ except (validateTuple tup' tConss)
1115-- _ <- lift $ except (validateTuple tup' tConss)
1018 pure tup'
1116 pure tup'
1020−--temporary implementation until we have a proper planner+executor
1118+{-
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)))
1021evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1168evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1022−evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1169+--evalGraphRefRelationalExpr (MakeRelationaFromExprs
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
1034evalGraphRefRelationalExpr (RelationVariable name tid) = do
1170evalGraphRefRelationalExpr (RelationVariable name tid) = do
1035− ctx <- gfDatabaseContextForMarker tid
1171+ ctx <- concreteDatabaseContext <$> gfTransForId tid
1036 case M.lookup name (relationVariables ctx) of
1172 case M.lookup name (relationVariables ctx) of
1037 Nothing -> throwError (RelVarNotDefinedError name)
1173 Nothing -> throwError (RelVarNotDefinedError name)
1038 Just rv -> evalGraphRefRelationalExpr rv
1174 Just rv -> evalGraphRefRelationalExpr rv
1039−evalGraphRefRelationalExpr (Project attrNames expr) = do
1175+
1040− attrNameSet <- evalGraphRefAttributeNames attrNames expr
1041− rel <- evalGraphRefRelationalExpr expr
1042− lift $ except $ project attrNameSet rel
1043−evalGraphRefRelationalExpr (Union exprA exprB) = do
1044− relA <- evalGraphRefRelationalExpr exprA
1045− relB <- evalGraphRefRelationalExpr exprB
1046− lift $ except $ union relA relB
1047−evalGraphRefRelationalExpr (Join exprA exprB) = do
1048− relA <- evalGraphRefRelationalExpr exprA
1049− relB <- evalGraphRefRelationalExpr exprB
1050− lift $ except $ join relA relB
1051−evalGraphRefRelationalExpr (Rename oldName newName expr) = do
1052− rel <- evalGraphRefRelationalExpr expr
1053− lift $ except $ rename oldName newName rel
1054−evalGraphRefRelationalExpr (Difference exprA exprB) = do
1055− relA <- evalGraphRefRelationalExpr exprA
1056− relB <- evalGraphRefRelationalExpr exprB
1057− lift $ except $ difference relA relB
1058−evalGraphRefRelationalExpr (Group groupAttrNames newAttrName expr) = do
1059− groupNames <- evalGraphRefAttributeNames groupAttrNames expr
1060− rel <- evalGraphRefRelationalExpr expr
1061− lift $ except $ group groupNames newAttrName rel
1062−evalGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1063− rel <- evalGraphRefRelationalExpr expr
1064− lift $ except $ ungroup groupAttrName rel
1065−evalGraphRefRelationalExpr (Restrict predExpr expr) = do
1066− rel <- evalGraphRefRelationalExpr expr
1067− filt <- predicateRestrictionFilter (attributes rel) predExpr
1068− lift $ except $ restrict filt rel
1069−evalGraphRefRelationalExpr (Equals exprA exprB) = do
1070− relA <- evalGraphRefRelationalExpr exprA
1071− relB <- evalGraphRefRelationalExpr exprB
1072− pure $ if relA == relB then relationTrue else relationFalse
1073−evalGraphRefRelationalExpr (NotEquals exprA exprB) = do
1074− relA <- evalGraphRefRelationalExpr exprA
1075− relB <- evalGraphRefRelationalExpr exprB
1076− pure $ if relA == relB then relationFalse else relationTrue
1077−evalGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1078− rel <- evalGraphRefRelationalExpr expr
1079− (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1080− lift $ except $ relMogrify tupProc newAttrs rel
1081−evalGraphRefRelationalExpr expr@With{} =
1082− --strategy A: add relation variables to the contexts in the graph
1083− --strategy B: drop in macros in place (easier programmatically)
1084− --strategy B implementation
1085− evalGraphRefRelationalExpr (substituteWithNameMacros [] expr)
1087dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1177dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1088dbContextForTransId tid graph = do
1178dbContextForTransId tid graph = do
@@ -1103,85 +1193,35 @@ transactionForId tid graph
1103typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1193typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1104typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1194typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1105typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1195typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1106−typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1196+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) =
1107− mAttrs <- case mAttrExprs of
1197+ case mAttrExprs of
1108− Just attrExprs -> do
1198+ Just attrExprs -> do
1109− attrs <- mapM evalGraphRefAttributeExpr attrExprs
1199+ attrs <- mapM (\e -> evalGraphRefAttributeExpr e) 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
1200+ pure (emptyRelationWithAttrs (attributesFromList attrs))
1118typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1201typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1119− relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1202+ relVars <- relationVariables . concreteDatabaseContext <$> gfTransForId tid
1120 case M.lookup rvName relVars of
1203 case M.lookup rvName relVars of
1121 Nothing -> throwError (RelVarNotDefinedError rvName)
1204 Nothing -> throwError (RelVarNotDefinedError rvName)
1123− typeForGraphRefRelationalExpr rvExpr
1205+ Just rvExpr -> typeForGraphRefRelationalExpr rvExpr
1124typeForGraphRefRelationalExpr (Project attrNames expr) = do
1206typeForGraphRefRelationalExpr (Project attrNames expr) = do
1125− exprType' <- typeForGraphRefRelationalExpr expr
1207+ exprType <- typeForGraphRefRelationalExpr expr
1126 projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1208 projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1127− lift $ except $ project projectionAttrs exprType'
1209+ lift $ except $ project projectionAttrs exprType
1128−typeForGraphRefRelationalExpr (Union exprA exprB) = do
1210+
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'
1171evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1211evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1172evalGraphRefAttributeNames attrNames expr = do
1212evalGraphRefAttributeNames attrNames expr = do
1173− exprType' <- typeForGraphRefRelationalExpr expr
1213+ exprType <- typeForGraphRefRelationalExpr expr
1174− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1214+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType)))
1175 case attrNames of
1215 case attrNames of
1176 AttributeNames names ->
1216 AttributeNames names ->
1177− case A.projectionAttributesForNames names (attributes exprType') of
1217+ case A.projectionAttributesForNames names (attributes exprType) of
1178 Left err -> throwError err
1218 Left err -> throwError err
1179 Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1219 Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1181 InvertedAttributeNames names -> do
1221 InvertedAttributeNames names -> do
1182 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1222 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1183 if not (S.null nonExistentAttributeNames) then
1223 if not (S.null nonExistentAttributeNames) then
1184− throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1224+ throwError (AttributeNamesMismatchError nonExistentAttributeNames)
1186 pure (A.nonMatchingAttributeNameSet names typeNameSet)
1226 pure (A.nonMatchingAttributeNameSet names typeNameSet)
@@ -1201,19 +1241,18 @@ evalGraphRefAttributeNames attrNames expr = do
1202evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1242evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1203evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1243evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1204− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1244+ tConsMap <- typeConstructorMapping . concreteDatabaseContext <$> gfTransForId tid
1205 case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1245 case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1206 Left err -> throwError err
1246 Left err -> throwError err
1207 Right aType -> do
1247 Right aType -> do
1208 case validateAtomType aType tConsMap of
1248 case validateAtomType aType tConsMap of
1209 Left err -> throwError err
1249 Left err -> throwError err
1210 Right _ -> pure (Attribute attrName aType)
1250 Right _ -> pure (Attribute attrName aType)
1211−evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1213mkEmptyRelVars :: RelationVariables -> RelationVariables
1252mkEmptyRelVars :: RelationVariables -> RelationVariables
1214−mkEmptyRelVars = M.map mkEmptyRelVar
1253+mkEmptyRelVars rvMap = M.map mkEmptyRelVar rvMap
1216− mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1255+ mkEmptyRelVar (MakeRelationFromExprs mAttrs _) = MakeRelationFromExprs mAttrs []
1217 mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1256 mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1218 mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1257 mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1219 mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
1258 mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
@@ -1224,169 +1263,32 @@ mkEmptyRelVars = M.map mkEmptyRelVar
1224 mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1263 mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1225 mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1264 mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1226 mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1265 mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1227− mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1266+ mkEmptyRelVar (Restrict pred expr) = Restrict pred (mkEmptyRelVar expr)
1228 mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1267 mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1229 mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1268 mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1230 mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1269 mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1231− mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1270+ mkEmptyRelVar (With macros expr) = With (map (\(rv, expr) -> (rv, mkEmptyRelVar expr)) macros) (mkEmptyRelVar expr)
1234dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1273dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1235dbErr err = lift (except (Left err))
1274dbErr err = lift (except (Left err))
1237-- | Return a Relation describing the relation variables.
1276-- | Return a Relation describing the relation variables.
1238−relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1277+relationVariablesAsRelation :: RelationVariables -> TransactionGraph -> Either RelationalError Relation
1239−relationVariablesAsRelation ctx graph = do
1278+relationVariablesAsRelation relVarMap graph = do
1240 let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1279 let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1241 attrs = A.attributesFromList [Attribute "name" TextAtomType,
1280 attrs = A.attributesFromList [Attribute "name" TextAtomType,
1242 Attribute "attributes" (RelationAtomType subrelAttrs)]
1281 Attribute "attributes" (RelationAtomType subrelAttrs)]
1243− relVars = relationVariables ctx
1244 mkRvDesc (rvName, gfExpr) = do
1282 mkRvDesc (rvName, gfExpr) = do
1245− let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1283+ let gfEnv = freshGraphRefRelationalExprEnv graph
1246 gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1284 gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1247 pure (rvName, gfType)
1285 pure (rvName, gfType)
1248− relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributesVec (attributes rel))]
1286+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributes rel)]
1249 attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1287 attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1250 attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1288 attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1251 Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1289 Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1252 Right rel -> RelationAtom rel
1290 Right rel -> RelationAtom rel
1253− rvs <- mapM mkRvDesc (M.toList relVars)
1291+ rvs <- mapM mkRvDesc (M.toList relVarMap)
1254 let tups = map relVarToAtomList rvs
1292 let tups = map relVarToAtomList rvs
1255 mkRelationFromList attrs tups
1293 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