@@ -1,4 +1,7 @@
11{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE OverloadedStrings #-}
25module ProjectM36.RelationalExpression where
36import ProjectM36.Relation
47import ProjectM36.Tuple
@@ -13,27 +16,38 @@ import ProjectM36.DataTypes.Primitive
1316import ProjectM36.AtomFunction
1417import ProjectM36.DatabaseContextFunction
1518import ProjectM36.Arbitrary
19+import ProjectM36.GraphRefRelationalExpr
1620import ProjectM36.Transaction
1721import qualified ProjectM36.Attribute as A
1822import qualified Data.Map as M
1923import qualified Data.HashSet as HS
2024import qualified Data.Set as S
2125import Control.Monad.State hiding (join)
22−import Control.Exception
26+import Data.Bifunctor (second)
2327import Data.Maybe
2428import Data.Either
2529import Data.Char (isUpper)
30+import Data.Time
31+import qualified Data.List.NonEmpty as NE
32+import Data.Functor.Identity
2633import qualified Data.Text as T
2734import qualified Data.Vector as V
2835import qualified ProjectM36.TypeConstructorDef as TCD
29−import Control.Monad.Trans.Except
30−import Control.Monad.Trans.Reader
36+import qualified Control.Monad.RWS.Strict as RWS
37+import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
38+import Control.Monad.Except hiding (join)
39+import Control.Monad.Trans.Except (except)
40+import Control.Monad.Reader as R hiding (join)
41+import ProjectM36.NormalizeExpr
42+import ProjectM36.WithNameExpr
3143import Test.QuickCheck
32−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
3349import GHC.Paths
34−import Data.Time.Clock
35−import Data.Time.Calendar
36−import qualified Data.List.NonEmpty as NE
50+#endif
3751
3852data DatabaseContextExprDetails = CountUpdatedTuples
3953
@@ -50,61 +64,63 @@ databaseContextExprDetailsFunc CountUpdatedTuples _ relIn = Relation attrs newTu
5064 Right ts -> ts
5165
5266-- | Used to start a fresh database state for a new database context expression.
53−freshDatabaseState :: DatabaseContext -> DatabaseStateElems
54−freshDatabaseState context = DatabaseStateElems {
55− context = context,
56− accum = M.empty,
57− dirty = False
67+mkDatabaseContextEvalState :: DatabaseContext -> DatabaseContextEvalState
68+mkDatabaseContextEvalState context = DatabaseContextEvalState {
69+ dbc_context = context,
70+ dbc_accum = M.empty,
71+ dbc_dirty = False
5872 } --future work: propagate return accumulator
5973
6074-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
6175data RelationalExprEnv = RelationalExprEnv {
6276 re_context :: DatabaseContext,
6377 re_graph :: TransactionGraph,
64− re_currentTransId :: TransactionId,
6578 re_extra :: Maybe (Either RelationTuple Attributes)
6679 }
6780
68−stateTuple :: RelationalExprEnv -> RelationTuple
69−stateTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (re_extra e))
81+envTuple :: GraphRefRelationalExprEnv -> RelationTuple
82+envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
7083
71−stateAttributes :: RelationalExprEnv -> Attributes
72−stateAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (re_extra e))
73−{-
74−data RelationalExprEnv = RelationalExprStateTupleElems DatabaseContext RelationTuple | -- used when fully evaluating a relexpr
75− RelationalExprStateAttrsElems DatabaseContext Attributes | --used when evaluating the type of a relexpr
76− RelationalExprEnv DatabaseContext --used by default at the top level of evaluation
77− -}
84+envAttributes :: GraphRefRelationalExprEnv -> Attributes
85+envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
7886
7987instance Show RelationalExprEnv where
8088 show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
8189
82−mkRelationalExprState :: DatabaseContext -> TransactionId -> TransactionGraph -> RelationalExprEnv
83−mkRelationalExprState ctx currentTransId graph =
90+--used to eval relationalexpr
91+type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
92+
93+runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
94+runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
95+
96+reGraph :: RelationalExprM TransactionGraph
97+reGraph = asks re_graph
98+
99+reContext :: RelationalExprM DatabaseContext
100+reContext = asks re_context
101+
102+mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
103+mkRelationalExprEnv ctx graph =
84104 RelationalExprEnv
85105 { re_context = ctx,
86106 re_graph = graph,
87− re_currentTransId = currentTransId,
88107 re_extra = Nothing }
89108
90−currentTrans :: RelationalExprState (Either RelationalError Transaction)
91−currentTrans = do
92− tid <- re_currentTransId <$> ask
93− graph <- re_graph <$> ask
94− pure (transactionForId tid graph)
95−
96−mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprEnv -> RelationalExprEnv
97−mergeTuplesIntoRelationalExprState tupIn e@RelationalExprEnv{} =
98− e{re_extra = new_elems }
109+askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
110+askEnv = R.ask
111+
112+mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
113+mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
114+ env { gre_extra = new_elems }
99115 where
100116 new_elems = Just (Left newTuple)
101− mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (stateTuple e))
117+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
102118 newTuple = mkRelationTupleFromMap mergedTupMap
103−
104−mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprEnv -> RelationalExprEnv
105−mergeAttributesIntoRelationalExprState attrsIn e@RelationalExprEnv{} = e{re_extra = newattrs }
119+
120+mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
121+mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
106122 where
107− newattrs = Just (Right (A.union attrsIn (stateAttributes e)))
123+ newattrs = Just (Right (A.union attrsIn (envAttributes e)))
108124
109125type ResultAccumName = StringType
110126
@@ -114,23 +130,81 @@ data ResultAccum = ResultAccum { resultAccumFunc :: ResultAccumFunc,
114130 resultAccumResult :: Relation
115131 }
116132
117−data DatabaseStateElems = DatabaseStateElems {
118− context :: DatabaseContext, --new, alterable context for a new transaction
119− accum :: M.Map ResultAccumName ResultAccum,
120− dirty :: DirtyFlag
133+data DatabaseContextEvalState = DatabaseContextEvalState {
134+ dbc_context :: DatabaseContext, --new, alterable context for a new transaction
135+ dbc_accum :: M.Map ResultAccumName ResultAccum,
136+ dbc_dirty :: DirtyFlag
121137 }
122138
123−type DatabaseState a = State DatabaseStateElems a
139+data DatabaseContextEvalEnv = DatabaseContextEvalEnv
140+ { dce_transId :: TransactionId,
141+ dce_graph :: TransactionGraph
142+ }
143+
144+mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
145+mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
146+
147+type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
148+
149+runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
150+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
151+ where
152+ freshEnv = mkDatabaseContextEvalState ctx
153+
154+
155+dbcTransId :: DatabaseContextEvalMonad TransactionId
156+dbcTransId = dce_transId <$> RWS.ask
157+
158+dbcGraph :: DatabaseContextEvalMonad TransactionGraph
159+dbcGraph = dce_graph <$> RWS.ask
124160
125−getStateContext :: DatabaseState DatabaseContext
126−getStateContext = context <$> get
161+dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
162+dbcRelationalExprEnv =
163+ mkRelationalExprEnv <$> getStateContext <*> dbcGraph
127164
128−putStateContext :: DatabaseContext -> DatabaseState ()
165+getStateContext :: DatabaseContextEvalMonad DatabaseContext
166+getStateContext = gets dbc_context
167+
168+putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
129169putStateContext ctx' = do
130170 s <- get
131− put (s {context = ctx'})
171+ put (s {dbc_context = ctx', dbc_dirty = True})
172+
173+-- | The context is optionally passed down along in cases where the current context is uncommitted.
174+data GraphRefRelationalExprEnv =
175+ GraphRefRelationalExprEnv {
176+ gre_context :: Maybe DatabaseContext,
177+ gre_graph :: TransactionGraph,
178+ gre_extra :: Maybe (Either RelationTuple Attributes)
179+ }
132180
133−type RelationalExprState a = Reader RelationalExprEnv a
181+type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
182+
183+gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
184+gfTransForId tid = do
185+ graph <- gfGraph
186+ lift $ except $ transactionForId tid graph
187+
188+gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
189+gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
190+gfDatabaseContextForMarker UncommittedContextMarker = do
191+ mctx <- gre_context <$> askEnv
192+ case mctx of
193+ Nothing -> throwError NoUncommittedContextInEvalError
194+ Just ctx -> pure ctx
195+
196+runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
197+runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
198+
199+freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
200+freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
201+ gre_context = mctx,
202+ gre_graph = graph,
203+ gre_extra = Nothing
204+ }
205+
206+gfGraph :: GraphRefRelationalExprM TransactionGraph
207+gfGraph = asks gre_graph
134208
135209envContext :: RelationalExprEnv -> DatabaseContext
136210envContext = re_context
@@ -138,416 +212,321 @@ envContext = re_context
138212setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
139213setEnvContext e ctx = e { re_context = ctx }
140214
141−--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
142−evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
143−evalRelationalExpr (RelationVariable name _) = do
144− relvarTable <- fmap (relationVariables . envContext) ask
145− return $ case M.lookup name relvarTable of
146− Just res -> Right res
147− Nothing -> Left $ RelVarNotDefinedError name
148−
149−evalRelationalExpr (Project attrNames expr) = do
150− eAttrNameSet <- evalAttributeNames attrNames expr
151− case eAttrNameSet of
152− Left err -> pure (Left err)
153− Right attrNameSet -> do
154− rel <- evalRelationalExpr expr
155− case rel of
156− Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
157− Left err -> pure $ Left err
158−
159−evalRelationalExpr (Union exprA exprB) = do
160− relA <- evalRelationalExpr exprA
161− relB <- evalRelationalExpr exprB
162− case relA of
163− Left err -> return $ Left err
164− Right relA2 -> case relB of
165− Left err -> return $ Left err
166− Right relB2 -> return $ Right (Union relA2 relB2)
167−
168−evalRelationalExpr (Join exprA exprB) = do
169− relA <- evalRelationalExpr exprA
170− relB <- evalRelationalExpr exprB
171− case relA of
172− Left err -> return $ Left err
173− Right relA2 -> case relB of
174− Left err -> return $ Left err
175− Right relB2 -> return $ Right (Join relA2 relB2)
176−
177−evalRelationalExpr (Difference exprA exprB) = do
178− relA <- evalRelationalExpr exprA
179− relB <- evalRelationalExpr exprB
180− case relA of
181− Left err -> return $ Left err
182− Right relA2 -> case relB of
183− Left err -> return $ Left err
184− Right relB2 -> return $ Right (Difference relA2 relB2)
185−
186−evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
187− case mkRelation attributeSet tupleSet of
188− Right rel -> return $ Right (ExistingRelation rel)
189− Left err -> return $ Left err
190−
191−evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
192− currentContext <- fmap envContext ask
193− let tConss = typeConstructorMapping currentContext
194− -- 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
195− runExceptT $ do
196− mAttrs <- case mAttrExprs of
197− Just _ ->
198− Just . A.attributesFromList <$> mapM (either throwE pure . evalAttrExpr tConss) (fromMaybe [] mAttrExprs)
199− Nothing -> pure Nothing
200− tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
201− let attrs = fromMaybe firstTupleAttrs mAttrs
202− firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
203− expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
204− pure (ExistingRelation expr)
205−
206−evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
207−
208−evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
209− evald <- evalRelationalExpr relExpr
210− case evald of
211− Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
212− Left err -> return $ Left err
213−
214−evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
215− eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
216− case eOldAttrNameSet of
217− Left err -> pure (Left err)
218− Right oldAttrNameSet -> do
219− evald <- evalRelationalExpr relExpr
220− case evald of
221− Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
222− Left err -> return $ Left err
223−
224−evalRelationalExpr (Ungroup attrName relExpr) = do
225− evald <- evalRelationalExpr relExpr
226− case evald of
227− Right expr -> return $ Right (Ungroup attrName expr)
228− Left err -> return $ Left err
229−
230−evalRelationalExpr (Restrict predicateExpr relExpr) = do
231− evald <- evalRelationalExpr relExpr
232− ePred <- processRestrictionPredicateExpr predicateExpr
233− case evald of
234− Left err -> return $ Left err
235− Right expr -> case ePred of
236− Left err -> pure (Left err)
237− Right pred -> pure $ Right (Restrict pred expr)
238−
239−evalRelationalExpr (Equals relExprA relExprB) = do
240− evaldA <- evalRelationalExpr relExprA
241− evaldB <- evalRelationalExpr relExprB
242− case evaldA of
243− Left err -> return $ Left err
244− Right exprA -> case evaldB of
245− Left err -> return $ Left err
246− Right exprB -> return $ Right (Equals exprA exprB)
247−{-
248−evalRelationalExpr (With views mainExpr) = do
249− rstate <- ask
250−
251− let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
252− Left (RelVarAlreadyDefinedError vname)
253− else
254− case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
255− (Left err,_) -> Left err
256− (Right (), (ctx',_,_)) -> Right ctx'
257−
258− case foldM addScopedView (stateElemsContext rstate) views of
259− Left err -> return $ Left err
260− Right ctx'' -> do
261− let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprEnv ctx'')
262− case evalMainExpr mainExpr of
263− Left err -> return $ Left err
264− Right rel -> return $ Right rel
265−-}
266−--warning: copy-pasta from above- refactor
267−evalRelationalExpr (NotEquals relExprA relExprB) = do
268− evaldA <- evalRelationalExpr relExprA
269− evaldB <- evalRelationalExpr relExprB
270− case evaldA of
271− Left err -> return $ Left err
272− Right exprA -> case evaldB of
273− Left err -> return $ Left err
274− Right exprB -> return $ Right (NotEquals exprA exprB)
275−
276−-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
277−evalRelationalExpr (Extend tupleExpression relExpr) = do
278− eExpr <- evalRelationalExpr relExpr
279− case eExpr of
280− Left err -> pure (Left err)
281− Right expr -> do
282− eTupProc <- processExtendTupleExpr tupleExpression
283− case eTupProc of
284− Left err -> pure (Left err)
285− Right tupProc -> pure (Right (Extend tupProc expr))
286−
287215--helper function to process relation variable creation/assignment
288−setRelVar :: RelVarName -> GraphRefRelationalExpr -> TransactionId -> TransactionGraph -> DatabaseState (Either RelationalError ())
289−setRelVar relVarName relExpr transId graph = do
216+setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
217+setRelVar relVarName relExpr = do
290218 currentContext <- getStateContext
291− let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
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
292222 potentialContext = currentContext { relationVariables = newRelVars }
293− --determine when to check constraints
294−
295− case checkConstraints potentialContext transId graph of
296− Left err -> pure (Left err)
297− Right _ -> do
298− putStateContext potentialContext
299− return (Right ())
223+ --optimization: if the relexpr is unchanged, skip the update
224+ if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
225+ pure ()
226+ else do
227+ --determine when to check constraints
228+ graph <- dbcGraph
229+ tid <- dbcTransId
230+ case checkConstraints potentialContext tid graph of
231+ Left err -> dbErr err
232+ Right _ -> putStateContext potentialContext
233+
234+--fast-path insertion- we already know that the previous relvar validated correctly, so we can validate just the relation that is being inserted for attribute matches- without this, even a single tuple relation inserted causes the entire relation to be re-validated unnecessarily
235+--insertIntoRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
300236
301237-- 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
302−deleteRelVar :: RelVarName -> DatabaseState (Either RelationalError ())
238+deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
303239deleteRelVar relVarName = do
304240 currContext <- getStateContext
305241 let relVars = relationVariables currContext
306242 if M.notMember relVarName relVars then
307− pure (Right ())
243+ pure ()
308244 else do
309245 let newRelVars = M.delete relVarName relVars
310246 newContext = currContext { relationVariables = newRelVars }
311247 putStateContext newContext
312− pure (Right ())
248+ pure ()
313249
314−evalDatabaseContextExpr :: DatabaseContextExpr -> TransactionId -> TransactionGraph -> DatabaseState (Either RelationalError ())
315−evalDatabaseContextExpr NoOperation _ _ = pure (Right ())
250+evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContextEvalMonad ()
251+evalGraphRefDatabaseContextExpr NoOperation = pure ()
316252
317−evalDatabaseContextExpr (Define relVarName attrExprs) transId graph = do
253+evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
254+ context <- getStateContext
318255 relvars <- fmap relationVariables getStateContext
319256 tConss <- fmap typeConstructorMapping getStateContext
320− let eAttrs = map (evalAttrExpr tConss) attrExprs
321− attrErrs = lefts eAttrs
322− attrsList = rights eAttrs
323− if not (null attrErrs) then
324− pure (Left (someErrors attrErrs))
325− else do
326− let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
327− if not (null atomTypeErrs) then
328− pure (Left (someErrors atomTypeErrs))
329− else
330− case M.member relVarName relvars of
331− True -> pure (Left (RelVarAlreadyDefinedError relVarName))
332− False -> setRelVar relVarName (ExistingRelation emptyRelation) transId graph >> pure (Right ())
257+ graph <- dbcGraph
258+ let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
259+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
260+ case eAttrs of
261+ Left err -> dbErr err
262+ Right attrsList -> do
263+ lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
264+ case M.member relVarName relvars of
265+ True -> dbErr (RelVarAlreadyDefinedError relVarName)
266+ False -> setRelVar relVarName (ExistingRelation emptyRelation)
333267 where
334268 attrs = A.attributesFromList attrsList
335269 emptyRelation = Relation attrs emptyTupleSet
336270
337−evalDatabaseContextExpr (Undefine relVarName) _ _ = deleteRelVar relVarName
271+evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
338272
339−evalDatabaseContextExpr (Assign relVarName expr) transId graph = do
273+evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
274+ graph <- re_graph <$> dbcRelationalExprEnv
340275 context <- getStateContext
341276 let existingRelVar = M.lookup relVarName (relationVariables context)
342− relExprState = mkRelationalExprState context transId graph
277+ reEnv = freshGraphRefRelationalExprEnv (Just context) graph
278+ eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
343279 case existingRelVar of
344280 Nothing -> do
345− let ervExpr = runReader (evalRelationalExpr expr) relExprState
346− case ervExpr of
347− Left err -> pure (Left err)
348− Right rvExpr -> setRelVar relVarName rvExpr transId graph
281+ case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
282+ Left err -> dbErr err
283+ Right reltype -> do
284+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
285+ setRelVar relVarName expr
349286 Just existingRel -> do
350− let eExpectedType = runReader (typeForGraphRefRelationalExpr existingRel) (mkRelationalExprState context transId graph)
351− eNewExprType = runReader (typeForRelationalExpr expr) relExprState
287+ let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
352288 case eExpectedType of
353− Left err -> pure (Left err)
289+ Left err -> dbErr err
354290 Right expectedType ->
355291 case eNewExprType of
356− Left err -> pure (Left err)
292+ Left err -> dbErr err
357293 Right newExprType -> do
358294 if newExprType == expectedType then do
359− let ervExpr = runReader (evalRelationalExpr expr) relExprState
360− case ervExpr of
361− Left err -> pure (Left err)
362− Right rvExpr -> setRelVar relVarName rvExpr transId graph
295+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
296+ setRelVar relVarName expr
363297 else
364− pure (Left (RelationTypeMismatchError (attributes expectedType) (attributes newExprType)))
365−
366−evalDatabaseContextExpr (Insert relVarName relExpr) tid graph =
367− evalDatabaseContextExpr (Assign relVarName (Union (RelationVariable relVarName ())
368− relExpr)) tid graph
369−
370−evalDatabaseContextExpr (Delete relVarName predicate) transId graph = do
371− ctx <- getStateContext
372− let rv = RelationVariable relVarName transId
373− rvState = mkRelationalExprState ctx transId graph
374− case runReader (processRestrictionPredicateExpr predicate) rvState of
375− Left err -> pure (Left err)
376− Right graphRefPredicate ->
377− setRelVar relVarName (Restrict (NotPredicate graphRefPredicate) rv) transId graph
298+ dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
299+
300+evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
301+ gfExpr <- relVarByName relVarName
302+ let optExpr = applyUnionCollapse (Union
303+ relExpr
304+ gfExpr)
305+ evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
306+
307+evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
308+ gfExpr <- relVarByName relVarName
309+ let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
310+ setRelVar relVarName optExpr
378311
379312--union of restricted+updated portion and the unrestricted+unupdated portion
380−evalDatabaseContextExpr (Update relVarName atomExprMap restrictionPredicateExpr) transId graph = do
313+evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
314+ rvExpr <- relVarByName relVarName
315+ graph <- re_graph <$> dbcRelationalExprEnv
381316 context <- getStateContext
382− let rvState = mkRelationalExprState context transId graph
383− relVarTable = relationVariables context
384− case runReader (processRestrictionPredicateExpr restrictionPredicateExpr) rvState of
385− Left err -> pure (Left err)
386− Right graphRefPredicate ->
387− case M.lookup relVarName relVarTable of
388− Nothing -> pure (Left (RelVarNotDefinedError relVarName))
389− Just existingRvExpr -> do
390− let unrestrictedPortion = Restrict (NotPredicate graphRefPredicate) rv
391− rv = RelationVariable relVarName transId
392− tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
393− updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
394− projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
395− restrictedPortion = Restrict graphRefPredicate
396− updated = foldr (\(oldname, atomExpr) accum ->
397− let procAtomExpr = runReader (processAtomExpr atomExpr) rvState in
317+ let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
318+ --get the current attributes name in the relvar to ensure that we don't conflict when renaming
319+ eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
320+ exprType' <- case eExprType of
321+ Left err -> throwError err
322+ Right t -> pure t
323+ let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
324+ tmpAttr = tmpAttrC 1
325+ tmpAttrC :: Int -> AttributeName -> AttributeName
326+ tmpAttrC c attr =
327+ let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
328+ if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
329+ tmpAttrC (c+1) attr
330+ else
331+ tmpAttrName
332+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
333+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
334+ restrictedPortion = Restrict pred' rvExpr
335+ updated = foldr (\(oldname, atomExpr) accum ->
336+ let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
398337 updateAttr oldname procAtomExpr accum
399− ) rv (M.toList atomExprMap)
338+ ) restrictedPortion (M.toList atomExprMap)
400339 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
401− updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
402− setRelVar relVarName (Union unrestrictedPortion updatedPortion) transId graph
340+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
341+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
403342
404−evalDatabaseContextExpr (AddInclusionDependency newDepName newDep) transId graph = do
343+evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
405344 currContext <- getStateContext
345+ transId <- dbcTransId
346+ graph <- dbcGraph
406347 let currDeps = inclusionDependencies currContext
407348 newDeps = M.insert newDepName newDep currDeps
408349 if M.member newDepName currDeps then
409− pure (Left (InclusionDependencyNameInUseError newDepName))
350+ dbErr (InclusionDependencyNameInUseError newDepName)
410351 else do
411352 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
412355 case checkConstraints potentialContext transId graph of
413− Left err -> pure (Left err)
414− Right _ -> do
356+ Left err -> dbErr err
357+ Right _ ->
415358 putStateContext potentialContext
416− return (Right ())
417359
418−evalDatabaseContextExpr (RemoveInclusionDependency depName) _ _ = do
360+evalGraphRefDatabaseContextExpr (RemoveInclusionDependency depName) = do
419361 currContext <- getStateContext
420362 let currDeps = inclusionDependencies currContext
421363 newDeps = M.delete depName currDeps
422364 if M.notMember depName currDeps then
423− pure (Left (InclusionDependencyNameNotInUseError depName))
424− else do
365+ dbErr (InclusionDependencyNameNotInUseError depName)
366+ else
425367 putStateContext $ currContext {inclusionDependencies = newDeps }
426− return (Right ())
427368
428369-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
429−evalDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) _ _ = do
370+evalGraphRefDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
430371 currentContext <- getStateContext
431372 let nots = notifications currentContext
432373 if M.member notName nots then
433− pure (Left (NotificationNameInUseError notName))
374+ dbErr (NotificationNameInUseError notName)
434375 else do
435376 let newNotifications = M.insert notName newNotification nots
436377 newNotification = Notification { changeExpr = triggerExpr,
437378 reportOldExpr = resultOldExpr,
438379 reportNewExpr = resultNewExpr}
439380 putStateContext $ currentContext { notifications = newNotifications }
440− return (Right ())
441381
442−evalDatabaseContextExpr (RemoveNotification notName) _ _ = do
382+evalGraphRefDatabaseContextExpr (RemoveNotification notName) = do
443383 currentContext <- getStateContext
444384 let nots = notifications currentContext
445385 if M.notMember notName nots then
446− pure (Left (NotificationNameNotInUseError notName))
386+ dbErr (NotificationNameNotInUseError notName)
447387 else do
448388 let newNotifications = M.delete notName nots
449389 putStateContext $ currentContext { notifications = newNotifications }
450− pure (Right ())
390+
451391
452392-- | Adds type and data constructors to the database context.
453393-- validate that the type *and* constructor names are unique! not yet implemented!
454−evalDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) _ _ = do
394+evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
455395 currentContext <- getStateContext
456396 let oldTypes = typeConstructorMapping currentContext
457397 tConsName = TCD.name tConsDef
458398 -- validate that the constructor's types exist
459− case validateTypeConstructorDef tConsDef dConsDefList of
460− errs@(_:_) -> pure (Left (someErrors errs))
461− [] | T.null tConsName || not (isUpper (T.head tConsName)) -> pure (Left (InvalidAtomTypeName tConsName))
462− | isJust (findTypeConstructor tConsName oldTypes) -> pure (Left (AtomTypeNameInUseError tConsName))
399+ case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
400+ Left err -> throwError err
401+ Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
402+ | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
463403 | otherwise -> do
464404 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
465405 putStateContext $ currentContext { typeConstructorMapping = newTypes }
466− pure (Right ())
467406
468407-- | Removing the atom constructor prevents new atoms of the type from being created. Existing atoms of the type remain. Thus, the atomTypes list in the DatabaseContext need not be all-inclusive.
469−evalDatabaseContextExpr (RemoveTypeConstructor tConsName) _ _ = do
408+evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
470409 currentContext <- getStateContext
471410 let oldTypes = typeConstructorMapping currentContext
472411 if isNothing (findTypeConstructor tConsName oldTypes) then
473− pure (Left (AtomTypeNameNotInUseError tConsName))
412+ dbErr (AtomTypeNameNotInUseError tConsName)
474413 else do
475414 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
476415 putStateContext $ currentContext { typeConstructorMapping = newTypes }
477− pure (Right ())
478416
479−evalDatabaseContextExpr (MultipleExpr exprs) transId graph = do
417+evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
480418 --the multiple expressions must pass the same context around- not the old unmodified context
481− evald <- forM exprs (\expr -> evalDatabaseContextExpr expr transId graph)
482− --some lifting magic needed here
483− case lefts evald of
484− [] -> pure (Right ())
485− errs -> pure (Left (someErrors errs))
486−
487−evalDatabaseContextExpr (RemoveAtomFunction funcName) _ _ = do
419+ mapM_ evalGraphRefDatabaseContextExpr exprs
420+
421+evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
488422 currentContext <- getStateContext
489423 let atomFuncs = atomFunctions currentContext
490424 case atomFunctionForName funcName atomFuncs of
491− Left err -> pure (Left err)
492− Right realFunc -> if isScriptedAtomFunction realFunc then do
493− let updatedFuncs = HS.delete realFunc atomFuncs
494− putStateContext (currentContext {atomFunctions = updatedFuncs })
495− pure (Right ())
496− else
497− pure (Left (PrecompiledFunctionRemoveError funcName))
425+ Left err -> dbErr err
426+ Right realFunc ->
427+ if isScriptedAtomFunction realFunc then do
428+ let updatedFuncs = HS.delete realFunc atomFuncs
429+ putStateContext (currentContext {atomFunctions = updatedFuncs })
430+ else
431+ dbErr (PrecompiledFunctionRemoveError funcName)
498432
499−evalDatabaseContextExpr (RemoveDatabaseContextFunction funcName) _ _ = do
433+evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
500434 context <- getStateContext
501435 let dbcFuncs = dbcFunctions context
502436 case databaseContextFunctionForName funcName dbcFuncs of
503− Left err -> pure (Left err)
504− Right realFunc -> if isScriptedDatabaseContextFunction realFunc then do
505− let updatedFuncs = HS.delete realFunc dbcFuncs
506− putStateContext (context { dbcFunctions = updatedFuncs })
507− pure (Right ())
508− else
509− pure (Left (PrecompiledFunctionRemoveError funcName))
437+ Left err -> dbErr err
438+ Right realFunc ->
439+ if isScriptedDatabaseContextFunction realFunc then do
440+ let updatedFuncs = HS.delete realFunc dbcFuncs
441+ putStateContext (context { dbcFunctions = updatedFuncs })
442+ else
443+ dbErr (PrecompiledFunctionRemoveError funcName)
510444
511−evalDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) transId graph = do
445+evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
512446 context <- getStateContext
447+ graph <- dbcGraph
513448 --resolve atom arguments
514− let relExprState = mkRelationalExprState context transId graph
515− eAtomTypes = map (\atomExpr -> runReader (typeFromAtomExpr emptyAttributes atomExpr) relExprState) atomArgExprs
449+ let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
516450 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
451+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
517452 case eFunc of
518− Left err -> pure (Left err)
453+ Left err -> dbErr err
519454 Right func -> do
520455 let expectedArgCount = length (dbcFuncType func)
521456 actualArgCount = length atomArgExprs
522457 if expectedArgCount /= actualArgCount then
523− pure (Left (FunctionArgumentCountMismatchError expectedArgCount actualArgCount))
458+ dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
524459 else
525460 --check that the atom types are valid
526− case lefts eAtomTypes of
527− _:_ -> pure (Left (someErrors (lefts eAtomTypes)))
528− [] -> do
529− let atomTypes = rights eAtomTypes
530− let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
531− Left err -> Just err
532− Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
461+ case eAtomTypes of
462+ Left err -> dbErr err
463+ Right atomTypes -> do
464+ let mValidTypes = zipWith (\ expType actType
465+ -> case atomTypeVerify expType actType of
466+ Left err -> Just err
467+ Right _ -> Nothing)
468+ (dbcFuncType func) atomTypes
533469 typeErrors = catMaybes mValidTypes
534− eAtomArgs = unimplemented
535− --eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
470+ eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
536471 if length (lefts eAtomArgs) > 1 then
537− pure (Left (someErrors (lefts eAtomArgs)))
472+ dbErr (someErrors (lefts eAtomArgs))
538473 else if not (null typeErrors) then
539− pure (Left (someErrors typeErrors))
474+ dbErr (someErrors typeErrors)
540475 else
541476 case evalDatabaseContextFunction func (rights eAtomArgs) context of
542− Left err -> pure (Left err)
543− Right newContext -> putStateContext newContext >> pure (Right ())
544−
545−evalDatabaseContextIOExpr :: Maybe ScriptSession -> DatabaseContext -> TransactionId -> TransactionGraph -> DatabaseContextIOExpr -> IO (Either RelationalError DatabaseContext)
546−evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddAtomFunction funcName funcType script) =
547− case mScriptSession of
548− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
549− Just scriptSession -> do
550− res <- try $ runGhc (Just libdir) $ do
477+ Left err -> dbErr err
478+ Right newContext -> putStateContext newContext
479+data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
480+ { dbcio_transId :: TransactionId,
481+ dbcio_graph :: TransactionGraph,
482+ dbcio_mScriptSession :: Maybe ScriptSession
483+ }
484+
485+type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
486+
487+runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
488+runDatabaseContextIOEvalMonad env ctx m = do
489+ res <- runRWST m env freshState
490+ case res of
491+ (Left err,_,_) -> pure (Left err)
492+ (Right (),s,_) -> pure (Right s)
493+ where
494+ freshState = mkDatabaseContextEvalState ctx
495+
496+requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
497+requireScriptSession = do
498+ env <- RWS.ask
499+ case dbcio_mScriptSession env of
500+ Nothing -> pure $ Left $ ScriptError ScriptCompilationDisabledError
501+ Just ss -> pure (Right ss)
502+
503+putDBCIOContext :: DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ())
504+putDBCIOContext ctx = do
505+ RWS.modify (\dbstate -> dbstate { dbc_context = ctx})
506+ pure (Right ())
507+
508+getDBCIOContext :: DatabaseContextIOEvalMonad DatabaseContext
509+getDBCIOContext = dbc_context <$> RWS.get
510+
511+getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
512+getDBCIORelationalExprEnv = do
513+ context <- getDBCIOContext
514+ mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
515+
516+evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
517+#if !defined(PM36_HASKELL_SCRIPTING)
518+evalGraphRefDatabaseContextIOExpr AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
519+evalGraphRefDatabaseContextIOExpr AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
520+evalGraphRefDatabaseContextIOExpr LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
521+evalGraphRefDatabaseContextIOExpr LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
522+#else
523+evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
524+ eScriptSession <- requireScriptSession
525+ currentContext <- getDBCIOContext
526+ case eScriptSession of
527+ Left err -> pure (Left err)
528+ Right scriptSession -> do
529+ res <- liftIO $ try $ runGhc (Just libdir) $ do
551530 setSession (hscEnv scriptSession)
552531 let atomFuncs = atomFunctions currentContext
553532 case extractAtomFunctionType funcType of
@@ -573,12 +552,13 @@ evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddAtomFunction fun
573552 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
574553 Right eContext -> case eContext of
575554 Left err -> pure (Left err)
576− Right context' -> pure (Right context')
577−
578−evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddDatabaseContextFunction funcName funcType script) =
579− case mScriptSession of
580− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
581− Just scriptSession -> do
555+ Right context' -> putDBCIOContext context'
556+evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
557+ eScriptSession <- requireScriptSession
558+ currentContext <- getDBCIOContext
559+ case eScriptSession of
560+ Left err -> pure (Left err)
561+ Right scriptSession -> do
582562 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
583563 let last2Args = reverse (take 2 (reverse funcType))
584564 atomArgs = take (length funcType - 2) funcType
@@ -588,7 +568,7 @@ evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddDatabaseContextF
588568 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
589569 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
590570 else do
591− res <- try $ runGhc (Just libdir) $ do
571+ res <- liftIO $ try $ runGhc (Just libdir) $ do
592572 setSession (hscEnv scriptSession)
593573 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
594574 pure $ case eCompiledFunc of
@@ -613,79 +593,86 @@ evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddDatabaseContextF
613593 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
614594 Right eContext -> case eContext of
615595 Left err -> pure (Left err)
616− Right context' -> pure (Right context')
617−evalDatabaseContextIOExpr _ currentContext _ _ (LoadAtomFunctions modName funcName modPath) = do
618− eLoadFunc <- loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
596+ Right context' -> putDBCIOContext context'
597+evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
598+ currentContext <- getDBCIOContext
599+ eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
619600 case eLoadFunc of
620601 Left LoadSymbolError -> pure (Left LoadFunctionError)
621602 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
622603 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
623− in pure (Right newContext)
624−evalDatabaseContextIOExpr _ currentContext _ _ (LoadDatabaseContextFunctions modName funcName modPath) = do
625− eLoadFunc <- loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
604+ in putDBCIOContext newContext
605+evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName modPath) = do
606+ currentContext <- getDBCIOContext
607+ eLoadFunc <- liftIO $ loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
626608 case eLoadFunc of
627609 Left LoadSymbolError -> pure (Left LoadFunctionError)
628610 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
629611 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
630− in pure (Right newContext)
631−
632−evalDatabaseContextIOExpr _ currentContext transId graph (CreateArbitraryRelation relVarName attrExprs range) =
612+ in putDBCIOContext newContext
613+#endif
614+evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
633615 --Define
634− case runState (evalDatabaseContextExpr (Define relVarName attrExprs) transId graph) (freshDatabaseState currentContext) of
635− (Left err,_) -> pure (Left err)
636− (Right (), elems) -> do
616+ currentContext <- getDBCIOContext
617+ env <- RWS.ask
618+ --create graph ref expr
619+ let gfExpr = Define relVarName attrExprs
620+ evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
621+ graph = dbcio_graph env
622+ case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
623+ Left err -> pure (Left err)
624+ Right dbstate -> do
637625 --Assign
638626 let existingRelVar = M.lookup relVarName relVarTable
639− relVarTable = relationVariables (context elems)
627+ relVarTable = relationVariables (dbc_context dbstate)
640628 case existingRelVar of
641629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
642630 Just existingRel -> do
643− case runReader (typeForGraphRefRelationalExpr existingRel) (mkRelationalExprState currentContext transId graph) of
631+ let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
632+ case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
644633 Left err -> pure (Left err)
645634 Right relType -> do
646635 let expectedAttributes = attributes relType
647− tcMap = typeConstructorMapping (context elems)
648− eitherRel <- generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
636+ tcMap = typeConstructorMapping (dbc_context dbstate)
637+ eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
649638 case eitherRel of
650639 Left err -> pure $ Left err
651640 Right rel ->
652− case runState (setRelVar relVarName (ExistingRelation rel) transId graph) elems of
653− (Left err,_) -> pure (Left err)
654− (Right (), elems') -> pure $ Right (context elems)
655−
656−updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
657−updateTupleWithAtomExprs exprMap context graph tupIn = do
658− --resolve all atom exprs
659− atomsAssoc <- mapM (\(attrName, atomExpr) -> do
660− let atom = unimplemented
661− --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
662− pure (attrName, atom)
663− ) (M.toList exprMap)
664− pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
641+ case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
642+ Left err -> pure (Left err)
643+ Right dbstate' -> putDBCIOContext (dbc_context dbstate')
665644
666645--run verification on all constraints
667646checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
668−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
647+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
669648 mapM_ (uncurry checkIncDep) (M.toList deps)
670649 where
671650 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
672651 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
673652 utctDayTime = secondsToDiffTime 0 }
674653 tempSchemas = Schemas context M.empty
675− tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
654+ tempTrans = Transaction U.nil tempTransInfo tempSchemas
655+ tempTransInfo = TransactionInfo { parents = transId NE.:| [],
656+ stamp = tempStamp,
657+ merkleHash = mempty
658+ }
676659
677660 deps = inclusionDependencies context
678− eval expr = evalReader (evalRelationalExpr expr)
679− evalReader f = runReader f (mkRelationalExprState 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
680662 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
681− let gfSubsetExpr = evalReader (processRelationalExpr subsetExpr)
682− gfSupersetExpr = evalReader (processRelationalExpr supersetExpr)
663+ let process = runProcessExprM UncommittedContextMarker
664+ gfSubsetExpr = process (processRelationalExpr subsetExpr)
665+ gfSupersetExpr = process (processRelationalExpr supersetExpr)
683666 --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.
684− typeSub <- evalReader (typeForRelationalExpr subsetExpr)
685− typeSuper <- evalReader (typeForRelationalExpr supersetExpr)
667+ let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
668+ runGfRel = runGraphRefRelationalExprM gfEnv
669+ typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
670+ typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
686671 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
687672 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
688− case evalGraphRefRelationalExpr checkExpr potentialGraph of
673+ gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
674+ gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
675+ case gfEvald of
689676 Left err -> Left err
690677 Right resultRel -> if resultRel == relationTrue then
691678 pure ()
@@ -695,87 +682,81 @@ checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
695682-- the type of a relational expression is equal to the relation attribute set returned from executing the relational expression; therefore, the type can be cheaply derived by evaluating a relational expression and ignoring and tuple processing
696683-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
697684
698−typeForRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
685+typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
699686typeForRelationalExpr expr = do
700687 --replace the relationVariables context element with a cloned set of relation devoid of tuples
701688 --evalRelationalExpr could still return an existing relation with tuples, so strip them
702− gfExpr <- processRelationalExpr expr
703− typeForGraphRefRelationalExpr gfExpr
704−
705−--returns a database context with all tuples removed
706−--this is useful for type checking and optimization
707−{-
708−contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
709−contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
710− where
711− relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
712−-}
689+ graph <- reGraph
690+ context <- reContext
691+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
692+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
693+ runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
694+ lift $ except runGf
713695
714696liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
715697liftE v = do
716698 y <- lift v
717699 case y of
718− Left err -> throwE err
700+ Left err -> throwError err
719701 Right val -> pure val
720702
721703{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
722−predicateRestrictionFilter :: Attributes -> RestrictionPredicateExprBase a -> RelationalExprState (Either RelationalError RestrictionFilter)
723−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
724− runExceptT $ do
725− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
726− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
727− pure (\x -> do
728− ev1 <- expr1v x
729− ev2 <- expr2v x
730− pure (ev1 && ev2))
731−
732−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
733− runExceptT $ do
734− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
735− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
704+predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
705+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
706+ expr1v <- predicateRestrictionFilter attrs expr1
707+ expr2v <- predicateRestrictionFilter attrs expr2
708+ pure (\x -> do
709+ ev1 <- expr1v x
710+ ev2 <- expr2v x
711+ pure (ev1 && ev2))
712+
713+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
714+ expr1v <- predicateRestrictionFilter attrs expr1
715+ expr2v <- predicateRestrictionFilter attrs expr2
736716 pure (\x -> do
737717 ev1 <- expr1v x
738718 ev2 <- expr2v x
739719 pure (ev1 || ev2))
740720
741−predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
721+predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
742722
743−predicateRestrictionFilter attrs (NotPredicate expr) =
744− runExceptT $ do
745− exprv <- liftE (predicateRestrictionFilter attrs expr)
746− pure (fmap not . exprv)
723+predicateRestrictionFilter attrs (NotPredicate expr) = do
724+ exprv <- predicateRestrictionFilter attrs expr
725+ pure (fmap not . exprv)
747726
748727--optimization opportunity: if the subexpression does not reference attributes in the top-level expression, then it need only be evaluated once, statically, outside the tuple filter- see historical implementation here
749−{-
750728predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
751− rstate <- ask
752− pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
729+ renv <- askEnv
730+ let eval :: RelationTuple -> Either RelationalError Relation
731+ eval tup =
732+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
733+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
734+ pure (\tup -> case eval tup of
753735 Left err -> Left err
754736 Right rel -> if arity rel /= 0 then
755737 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
756738 else
757− pure (rel == relationTrue)))
739+ pure (rel == relationTrue))
758740
759741predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
760− rstate <- ask
761− let attrs' = stateAttributes rstate
762− ctxtup' = stateTuple rstate
763− runExceptT $ do
764− atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
765− attr <- either throwE pure $ case A.attributeForName attrName attrs of
742+ env <- askEnv
743+ let attrs' = A.union attrs (envAttributes env)
744+ ctxtup' = envTuple env
745+ atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
746+ attr <- lift $ except $ case A.attributeForName attrName attrs of
766747 Right attr -> Right attr
767748 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
768749 Right ctxattr -> Right ctxattr
769750 Left err2@(NoSuchAttributeNamesError _) -> Left err2
770751 Left err -> Left err
771752 Left err -> Left err
772− if atomExprType /= A.atomType attr then
773− throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
774− else
753+ if atomExprType /= A.atomType attr then
754+ throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
755+ else
775756 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
776757 Right atomCmp -> atomCmp == atomIn
777758 Left _ -> False
778− atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
759+ atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
779760 in
780761 pure $ case atomForAttributeName attrName tupleIn of
781762 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -786,267 +767,322 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
786767-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
787768predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
788769 --merge attrs into the state attributes
789− rstate <- ask
790− runExceptT $ do
791− aType <- liftE (typeFromAtomExpr attrs atomExpr)
792− if aType /= BoolAtomType then
793− throwE (AtomTypeMismatchError aType BoolAtomType)
794− else
770+ renv <- askEnv
771+ aType <- typeForGraphRefAtomExpr attrs atomExpr
772+ if aType /= BoolAtomType then
773+ throwError (AtomTypeMismatchError aType BoolAtomType)
774+ else
795775 pure (\tupleIn ->
796− case runReader (evalAtomExpr tupleIn atomExpr) rstate of
797− Left err -> Left err
798− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
799−-}
776+ case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
777+ Left err -> Left err
778+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
779+
800780tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
801781tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
802782 Left (AttributeNameInUseError attrName)
803783 else
804784 Right rel
805785
806−extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
807−extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
808− rstate <- ask
786+extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
787+extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
788+-- renv <- askEnv
809789 -- check that the attribute name is not in use
810790 case tupleExprCheckNewAttrName newAttrName relIn of
811− Left err -> pure (Left err)
812− Right _ -> runExceptT $ do
813− atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
814− atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
791+ Left err -> throwError err
792+ Right _ -> do
793+ atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
794+ atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
815795 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
816796 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
817− pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in
818− case unimplemented {-runReader (evalAtomExpr tup atomExpr) substate-} of
819− Left err -> Left err
820− Right atom -> Right (tupleAtomExtend newAttrName atom tup)
797+ env <- ask
798+ pure (newAndOldAttrs, \tup -> do
799+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
800+ atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
801+ Right (tupleAtomExtend newAttrName atom tup)
821802 )
822803
823−
824−evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
825−evalAtomExpr = undefined
826−{-
827−
828−evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
829− Right atom -> pure (Right atom)
830− err@(Left (NoSuchAttributeNamesError _)) -> do
831− rstate <- ask
832− let stateTup = stateTuple rstate
833− pure (atomForAttributeName attrName stateTup)
834− Left err -> pure (Left err)
835−evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
836−evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
837− argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
838− context <- fmap stateElemsContext ask
839− runExceptT $ do
840− let functions = atomFunctions context
841− func <- either throwE pure (atomFunctionForName funcName functions)
842− let expectedArgCount = length (atomFuncType func) - 1
843− actualArgCount = length argTypes
844− safeInit [] = [] -- different behavior from normal init
845− safeInit xs = init xs
846− if expectedArgCount /= actualArgCount then
847− throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
848− else do
804+evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
805+evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
806+ case atomForAttributeName attrName tupIn of
807+ Right atom -> pure atom
808+ Left err@(NoSuchAttributeNamesError _) -> do
809+ env <- askEnv
810+ case gre_extra env of
811+ Nothing -> throwError err
812+ Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
813+ Just (Right _) -> throwError err
814+ Left err -> throwError err
815+evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
816+evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
817+ argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
818+ context <- gfDatabaseContextForMarker tid
819+ let functions = atomFunctions context
820+ func <- lift $ except (atomFunctionForName funcName functions)
821+ let expectedArgCount = length (atomFuncType func) - 1
822+ actualArgCount = length argTypes
823+ safeInit [] = [] -- different behavior from normal init
824+ safeInit xs = init xs
825+ if expectedArgCount /= actualArgCount then
826+ throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
827+ else do
849828 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
850− mapM_ (\(expType, eActType) -> do
851− actType <- either throwE pure eActType
852− either throwE pure (atomTypeVerify expType actType)) zippedArgs
853− evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
829+ mapM_ (\(expType, actType) ->
830+ lift $ except (atomTypeVerify expType actType)) zippedArgs
831+ evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
854832 case evalAtomFunction func evaldArgs of
855− Left err -> throwE (AtomFunctionUserError err)
833+ Left err -> throwError (AtomFunctionUserError err)
856834 Right result -> do
857835 --validate that the result matches the expected type
858− _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
836+ _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
859837 pure result
860−evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
838+evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
861839 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
862− rstate <- ask
863− runExceptT $ do
864− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
865− relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
866− pure (RelationAtom relAtom)
867−evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
868− rstate <- lift ask
869− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
870− aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
871− argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
840+ env <- ask
841+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
842+ relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
843+ pure (RelationAtom relAtom)
844+evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
845+ let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
846+ aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
847+ argAtoms <- local mergeEnv $
848+ mapM (evalGraphRefAtomExpr tupIn) dConsArgs
872849 pure (ConstructedAtom dConsName aType argAtoms)
873−-}
874−typeFromAtomExpr :: Attributes -> AtomExpr -> RelationalExprState (Either RelationalError AtomType)
875−typeFromAtomExpr attrs (AttributeAtomExpr attrName) = do
876− rstate <- ask
850+
851+typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
852+typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
853+ renv <- askEnv
877854 case A.atomTypeForAttributeName attrName attrs of
878− Right aType -> pure (Right aType)
855+ Right aType -> pure aType
879856 Left err@(NoSuchAttributeNamesError _) ->
880− let stateTup = stateTuple rstate
881− stateAttrs = stateAttributes rstate in
882− case A.attributeForName attrName stateAttrs of
883− Right attr -> pure (Right (A.atomType attr))
884− Left _ -> case atomForAttributeName attrName stateTup of
885− Right atom -> pure (Right (atomTypeForAtom atom))
886− Left _ -> pure (Left err)
887−
888−typeFromAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
889−typeFromAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
890− context <- fmap envContext ask
891− let funcs = atomFunctions context
857+ let envTup = envTuple renv
858+ envAttrs = envAttributes renv in
859+ case A.attributeForName attrName envAttrs of
860+ Right attr -> pure (A.atomType attr)
861+ Left _ -> case atomForAttributeName attrName envTup of
862+ Right atom -> pure (atomTypeForAtom atom)
863+ Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
864+ throwError err
865+ Left err -> throwError err
866+
867+typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
868+typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
869+ funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
892870 case atomFunctionForName funcName funcs of
893− Left err -> pure (Left err)
871+ Left err -> throwError err
894872 Right func -> do
895873 let funcRetType = last (atomFuncType func)
896874 funcArgTypes = init (atomFuncType func)
897− eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
898− case lefts eArgTypes of
899− errs@(_:_) -> pure (Left (someErrors errs))
900− [] -> do
901− let eTvMap = resolveTypeVariables funcArgTypes argTypes
902− argTypes = rights eArgTypes
903− case eTvMap of
904− Left err -> pure (Left err)
905− Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
906−typeFromAtomExpr attrs (RelationAtomExpr relExpr) = do
907− relType <- local (mergeAttributesIntoRelationalExprState attrs) (typeForRelationalExpr relExpr)
908− case relType of
909− Left err -> pure (Left err)
910− Right relType' ->
911− pure (pure (RelationAtomType (attributes relType')))
875+ argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
876+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
877+ case eTvMap of
878+ Left err -> throwError err
879+ Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
880+typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
881+ relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
882+ pure (RelationAtomType (attributes relType))
912883-- grab the type of the data constructor, then validate that the args match the expected types
913−typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
914− runExceptT $ do
915− argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
916− context <- fmap envContext (lift ask)
917− either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
884+typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
885+ do
886+ argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
887+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
888+ lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
918889
919890-- | Validate that the type of the AtomExpr matches the expected type.
920−verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
921−verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
922− rstate <- lift ask
891+verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
892+verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
893+ env <- askEnv
923894 case A.atomTypeForAttributeName attrName (attributes relIn) of
924− Right aType -> either throwE pure (atomTypeVerify expectedType aType)
895+ Right aType -> lift $ except $ atomTypeVerify expectedType aType
925896 (Left err@(NoSuchAttributeNamesError _)) ->
926− let attrs' = stateAttributes rstate in
897+ let attrs' = envAttributes env in
927898 if attrs' == emptyAttributes then
928− throwE err
899+ throwError err
929900 else
930901 case A.attributeForName attrName attrs' of
931− Left err' -> throwE err'
932− Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
933−verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
934−verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
935− rstate <- ask
902+ Left err' -> throwError err'
903+ Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
904+ Left err -> throwError err
905+
906+verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
907+ lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
908+verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
909+ context <- gfDatabaseContextForMarker tid
936910 let functions = atomFunctions context
937− context = envContext rstate
938− runExceptT $ do
939− func <- either throwE pure (atomFunctionForName funcName functions)
940− let expectedArgTypes = atomFuncType func
941− funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
942− Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
943− Left err -> throwE err
944− Right x -> pure x
945− ) $ zip3 funcArgExprs expectedArgTypes [1..]
946− if length funcArgTypes /= length expectedArgTypes - 1 then
947− throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
911+ func <- lift $ except $ atomFunctionForName funcName functions
912+ let expectedArgTypes = atomFuncType func
913+ funcArgVerifier (atomExpr, expectedType2, argCount) = do
914+ let handler :: RelationalError -> GraphRefRelationalExprM AtomType
915+ handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
916+ handler err = throwError err
917+ verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
918+ funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
919+ if length funcArgTypes /= length expectedArgTypes - 1 then
920+ throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
948921 else
949− either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
950−verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
951− rstate <- lift ask
952− relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
953− either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
954−verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
955− cType <- liftE (typeFromAtomExpr (attributes rel) cons)
956− either throwE pure (atomTypeVerify expectedType cType)
922+ lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
923+verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
924+ do
925+ let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
926+ relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
927+ lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
928+verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
929+ cType <- typeForGraphRefAtomExpr (attributes rel) cons
930+ lift $ except $ atomTypeVerify expectedType cType
957931
958932-- | Look up the type's name and create a new attribute.
959−evalAttrExpr :: TypeConstructorMapping -> AttributeExpr -> Either RelationalError Attribute
960−evalAttrExpr aTypes (AttributeAndTypeNameExpr attrName tCons ()) = do
961− aType <- atomTypeForTypeConstructorValidate True tCons aTypes M.empty
962− validateAtomType aType aTypes
963− Right (Attribute attrName aType)
933+evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
934+evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
935+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
936+ aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
937+ lift $ except $ validateAtomType aType tConsMap
938+ pure $ Attribute attrName aType
964939
965−evalAttrExpr _ (NakedAttributeExpr attr) = Right attr
966−
967−evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
968−evalTupleExpr mAttrs (TupleExpr tupMap) = do
969− context <- fmap envContext ask
970− runExceptT $ do
940+evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
941+
942+-- for tuple type concrete resolution (Nothing ==> Maybe Int) when the attributes hint is Nothing, we need to first process all the tuples, then extract the concrete types on a per-attribute basis, then reprocess the tuples to include the concrete types
943+evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
944+evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
945+evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
946+ tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
947+ finalAttrs <- case mAttrs of
948+ Just attrs -> pure attrs
949+ Nothing ->
950+ case tuples of
951+ [] -> pure emptyAttributes
952+ (headTuple:tailTuples) -> do
953+ --gather up resolved atom types or throw an error if an attribute cannot be made concrete from the inferred types- this could still fail if the type cannot be inferred (e.g. from [Nothing, Nothing])
954+ let
955+ processTupleAttrs (tupAttr, accAttr) =
956+ --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
957+ if isResolvedAttribute accAttr && tupAttr == accAttr then
958+ pure accAttr
959+ else
960+ lift $ except $ resolveAttributes accAttr tupAttr
961+ mostResolvedTypes <-
962+ foldM (\acc tup -> do
963+ let zipped = zip (V.toList . attributesVec $ tupleAttributes tup) acc
964+ accNames = S.fromList $ map A.attributeName acc
965+ tupNames = A.attributeNameSet (tupleAttributes tup)
966+ attrNamesDiff = S.union (S.difference accNames tupNames) (S.difference tupNames accNames)
967+ unless (null attrNamesDiff) (throwError (AttributeNamesMismatchError attrNamesDiff))
968+ nextTupleAttrs <- mapM processTupleAttrs zipped
969+ let diff = A.attributesDifference (A.attributesFromList nextTupleAttrs) (A.attributesFromList acc)
970+ if diff == A.emptyAttributes then
971+ pure nextTupleAttrs
972+ else
973+ throwError (TupleAttributeTypeMismatchError diff)
974+ ) (V.toList . attributesVec $ tupleAttributes headTuple) tailTuples
975+ pure (A.attributesFromList mostResolvedTypes)
976+ --strategy: if all the tuple expr transaction markers refer to one location, then we can pass the type constructor mapping from that location, otherwise, we cannot assume that the types are the same
977+ tConsMap <- case singularTransactions tupleExprL of
978+ SingularTransactionRef commonTransId ->
979+ typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
980+ NoTransactionsRef ->
981+ typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
982+ -- if there are multiple transaction markers in the TupleExprs, then we can't assume a single type constructor mapping- this could be improved in the future, but if all the tuples are fully resolved, then we don't need further resolution
983+ _ -> throwError TupleExprsReferenceMultipleMarkersError
984+ lift $ except $ validateAttributes tConsMap finalAttrs
985+ mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
986+
987+
988+--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
989+
990+evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
991+evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
971992 -- 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
972993 -- I could adjust this logic so that when the attributes are not specified (Nothing), then I can attempt to extract the attributes from the tuple- the type resolution will blow up if an ambiguous data constructor is used (Left 4) and this should allow simple cases to "relation{tuple{a 4}}" to be processed
973− let attrs = fromMaybe A.emptyAttributes mAttrs
974− attrAtoms <- mapM (\(attrName, aExpr) -> do
975− --provided when the relation header is available
976− let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
977− unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
978− resolvedType <- case eExpectedAtomType of
994+ let attrs = fromMaybe A.emptyAttributes mAttrs
995+ resolveOneAtom (attrName, aExpr) =
996+ do
997+ --provided when the relation header is available
998+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
999+ unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
1000+ resolvedType <- case eExpectedAtomType of
9791001 Left _ -> pure unresolvedType
980− Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
1002+ Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
9811003 --resolve atom typevars based on resolvedType?
982− newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
983− pure (attrName, newAtom, resolvedType)
984− ) (M.toList tupMap)
985− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
986− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
987− tup = mkRelationTuple tupAttrs atoms
988− tConss = typeConstructorMapping context
989− finalAttrs = fromMaybe tupAttrs mAttrs
1004+ newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
1005+ pure (attrName, newAtom, resolvedType)
1006+ attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
1007+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1008+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1009+ tup = mkRelationTuple tupAttrs atoms
1010+ finalAttrs = fromMaybe tupAttrs mAttrs
9901011 --verify that the attributes match
991− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
992− tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
993− _ <- either throwE pure (validateTuple tup' tConss)
994− pure tup'
995−
996−evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
997−evalAttributeNames attrNames expr = do
998− eExprType <- typeForRelationalExpr expr
999− case eExprType of
1000− Left err -> pure (Left err)
1001− Right exprTyp -> do
1002− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1003− case attrNames of
1004− AttributeNames names ->
1005− case A.projectionAttributesForNames names (attributes exprTyp) of
1006− Left err -> pure (Left err)
1007− Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1008−
1009− InvertedAttributeNames names -> do
1010− let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1011− if not (S.null nonExistentAttributeNames) then
1012− pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1013− else
1014− pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
1015−
1016− UnionAttributeNames namesA namesB -> do
1017− eNameSetA <- evalAttributeNames namesA expr
1018− case eNameSetA of
1019− Left err -> pure (Left err)
1020− Right nameSetA -> do
1021− eNameSetB <- evalAttributeNames namesB expr
1022− case eNameSetB of
1023− Left err -> pure (Left err)
1024− Right nameSetB ->
1025− pure (Right (S.union nameSetA nameSetB))
1026−
1027− IntersectAttributeNames namesA namesB -> do
1028− eNameSetA <- evalAttributeNames namesA expr
1029− case eNameSetA of
1030− Left err -> pure (Left err)
1031− Right nameSetA -> do
1032− eNameSetB <- evalAttributeNames namesB expr
1033− case eNameSetB of
1034− Left err -> pure (Left err)
1035− Right nameSetB ->
1036− pure (Right (S.intersection nameSetA nameSetB))
1037−
1038− RelationalExprAttributeNames attrExpr -> do
1039− eAttrExprType <- typeForRelationalExpr attrExpr
1040− case eAttrExprType of
1041− Left err -> pure (Left err)
1042− Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1043−
1044−evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError Relation
1045−evalGraphRefRelationalExpr (RelationVariable name tid) graph = do
1046− ctx <- dbContextForTransId tid graph
1012+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1013+ --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1014+ --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1015+ let tup' = reorderTuple finalAttrs tup
1016+ --TODO: restore type resolution
1017+-- _ <- lift $ except (validateTuple tup' tConss)
1018+ pure tup'
1019+
1020+--temporary implementation until we have a proper planner+executor
1021+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1022+evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1023+ mAttrs <- case mAttrExprs of
1024+ Just _ ->
1025+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1026+ Nothing -> pure Nothing
1027+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1028+ let attrs = fromMaybe firstTupleAttrs mAttrs
1029+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1030+ lift $ except $ mkRelation attrs (RelationTupleSet tuples)
1031+evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
1032+ lift $ except $ mkRelation attributeSet tupleSet
1033+evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1034+evalGraphRefRelationalExpr (RelationVariable name tid) = do
1035+ ctx <- gfDatabaseContextForMarker tid
10471036 case M.lookup name (relationVariables ctx) of
1048− Nothing -> Left (RelVarNotDefinedError name)
1049− Just rv -> evalGraphRefRelationalExpr rv graph
1037+ Nothing -> throwError (RelVarNotDefinedError name)
1038+ Just rv -> evalGraphRefRelationalExpr rv
1039+evalGraphRefRelationalExpr (Project attrNames expr) = do
1040+ attrNameSet <- evalGraphRefAttributeNames attrNames expr
1041+ rel <- evalGraphRefRelationalExpr expr
1042+ lift $ except $ project attrNameSet rel
1043+evalGraphRefRelationalExpr (Union exprA exprB) = do
1044+ relA <- evalGraphRefRelationalExpr exprA
1045+ relB <- evalGraphRefRelationalExpr exprB
1046+ lift $ except $ union relA relB
1047+evalGraphRefRelationalExpr (Join exprA exprB) = do
1048+ relA <- evalGraphRefRelationalExpr exprA
1049+ relB <- evalGraphRefRelationalExpr exprB
1050+ lift $ except $ join relA relB
1051+evalGraphRefRelationalExpr (Rename oldName newName expr) = do
1052+ rel <- evalGraphRefRelationalExpr expr
1053+ lift $ except $ rename oldName newName rel
1054+evalGraphRefRelationalExpr (Difference exprA exprB) = do
1055+ relA <- evalGraphRefRelationalExpr exprA
1056+ relB <- evalGraphRefRelationalExpr exprB
1057+ lift $ except $ difference relA relB
1058+evalGraphRefRelationalExpr (Group groupAttrNames newAttrName expr) = do
1059+ groupNames <- evalGraphRefAttributeNames groupAttrNames expr
1060+ rel <- evalGraphRefRelationalExpr expr
1061+ lift $ except $ group groupNames newAttrName rel
1062+evalGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1063+ rel <- evalGraphRefRelationalExpr expr
1064+ lift $ except $ ungroup groupAttrName rel
1065+evalGraphRefRelationalExpr (Restrict predExpr expr) = do
1066+ rel <- evalGraphRefRelationalExpr expr
1067+ filt <- predicateRestrictionFilter (attributes rel) predExpr
1068+ lift $ except $ restrict filt rel
1069+evalGraphRefRelationalExpr (Equals exprA exprB) = do
1070+ relA <- evalGraphRefRelationalExpr exprA
1071+ relB <- evalGraphRefRelationalExpr exprB
1072+ pure $ if relA == relB then relationTrue else relationFalse
1073+evalGraphRefRelationalExpr (NotEquals exprA exprB) = do
1074+ relA <- evalGraphRefRelationalExpr exprA
1075+ relB <- evalGraphRefRelationalExpr exprB
1076+ pure $ if relA == relB then relationFalse else relationTrue
1077+evalGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1078+ rel <- evalGraphRefRelationalExpr expr
1079+ (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1080+ lift $ except $ relMogrify tupProc newAttrs rel
1081+evalGraphRefRelationalExpr expr@With{} =
1082+ --strategy A: add relation variables to the contexts in the graph
1083+ --strategy B: drop in macros in place (easier programmatically)
1084+ --strategy B implementation
1085+ evalGraphRefRelationalExpr (substituteWithNameMacros [] expr)
10501086
10511087dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
10521088dbContextForTransId tid graph = do
@@ -1064,176 +1100,120 @@ transactionForId tid graph
10641100 where
10651101 matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
10661102
1067−processRestrictionPredicateExpr :: RestrictionPredicateExpr -> RelationalExprState (Either RelationalError GraphRefRestrictionPredicateExpr)
1068−processRestrictionPredicateExpr TruePredicate = pure (Right TruePredicate)
1069−processRestrictionPredicateExpr (AndPredicate a b) = do
1070− a' <- processRestrictionPredicateExpr a
1071− b' <- processRestrictionPredicateExpr b
1072− case a' of
1073− Left err -> pure (Left err)
1074− Right a'' -> case b' of
1075− Left err -> pure (Left err)
1076− Right b'' ->
1077− pure (Right (AndPredicate a'' b''))
1078−processRestrictionPredicateExpr (OrPredicate a b) = do
1079− a' <- processRestrictionPredicateExpr a
1080− b' <- processRestrictionPredicateExpr b
1081− case a' of
1082− Left err -> pure (Left err)
1083− Right a'' -> case b' of
1084− Left err -> pure (Left err)
1085− Right b'' ->
1086− pure (Right (OrPredicate a'' b''))
1087−processRestrictionPredicateExpr (NotPredicate a) = do
1088− a' <- processRestrictionPredicateExpr a
1089− case a' of
1090− Left err -> pure (Left err)
1091− Right a'' ->
1092− pure (Right (NotPredicate a''))
1093−processRestrictionPredicateExpr (RelationalExprPredicate expr) = do
1094− e <- evalRelationalExpr expr
1095− pure $ case e of
1096− Left err -> Left err
1097− Right e' -> Right (RelationalExprPredicate e')
1098−processRestrictionPredicateExpr (AtomExprPredicate expr) = do
1099− e <- processAtomExpr expr
1100− pure (Right (AtomExprPredicate e))
1101−processRestrictionPredicateExpr (AttributeEqualityPredicate nam expr) = do
1102− e <- processAtomExpr expr
1103− pure (Right (AttributeEqualityPredicate nam e))
1103+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1104+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1105+typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1106+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1107+ mAttrs <- case mAttrExprs of
1108+ Just attrExprs -> do
1109+ attrs <- mapM evalGraphRefAttributeExpr attrExprs
1110+ pure (Just (attributesFromList attrs))
1111+ Nothing -> pure Nothing
1112+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1113+ let retAttrs = case tuples of
1114+ (tup:_) -> tupleAttributes tup
1115+ [] -> fromMaybe A.emptyAttributes mAttrs
1116+ pure $ emptyRelationWithAttrs retAttrs
11041117
1105−processExtendTupleExpr :: ExtendTupleExpr -> RelationalExprState (Either RelationalError GraphRefExtendTupleExpr)
1106−processExtendTupleExpr (AttributeExtendTupleExpr nam atomExpr) = do
1107− e <- processAtomExpr atomExpr
1108− pure (Right (AttributeExtendTupleExpr nam e))
1109−
1110−typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> RelationalExprState (Either RelationalError Relation)
1111−typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = pure $ mkRelation attrs emptyTupleSet
1112−typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (Right (emptyRelationWithAttrs (attributes rel)))
1113−typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) =
1114− case mAttrExprs of
1115− Just attrExprs -> do
1116− eAttrs <- mapM (\e -> evalGraphRefAttributeExpr e) attrExprs
1117− case lefts eAttrs of
1118− [] -> pure (Right (emptyRelationWithAttrs (attributesFromList (rights eAttrs))))
1119− _ -> pure (Left (someErrors (lefts eAttrs)))
11201118typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1121− eTrans <- currentTrans
1122− case eTrans of
1123− Left err -> pure (Left err)
1124− Right trans -> do
1125− let relVars = relationVariables (concreteDatabaseContext trans)
1126− case M.lookup rvName relVars of
1127− Nothing -> pure (Left (RelVarNotDefinedError rvName))
1128− Just rvExpr -> typeForGraphRefRelationalExpr rvExpr
1119+ relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1120+ case M.lookup rvName relVars of
1121+ Nothing -> throwError (RelVarNotDefinedError rvName)
1122+ Just rvExpr ->
1123+ typeForGraphRefRelationalExpr rvExpr
11291124typeForGraphRefRelationalExpr (Project attrNames expr) = do
1130− eExprType <- typeForGraphRefRelationalExpr expr
1131− case eExprType of
1132− Left err -> pure (Left err)
1133− Right exprType -> do
1134− eProjectionAttrs <- evalGraphRefAttributeNames attrNames expr
1135− pure $ case eProjectionAttrs of
1136− Left err -> Left err
1137− Right projectionAttrs -> project projectionAttrs exprType
1138−
1139−evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
1125+ exprType' <- typeForGraphRefRelationalExpr expr
1126+ projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1127+ lift $ except $ project projectionAttrs exprType'
1128+typeForGraphRefRelationalExpr (Union exprA exprB) = do
1129+ exprA' <- typeForGraphRefRelationalExpr exprA
1130+ exprB' <- typeForGraphRefRelationalExpr exprB
1131+ lift $ except $ union exprA' exprB'
1132+typeForGraphRefRelationalExpr (Join exprA exprB) = do
1133+ exprA' <- typeForGraphRefRelationalExpr exprA
1134+ exprB' <- typeForGraphRefRelationalExpr exprB
1135+ lift $ except $ join exprA' exprB'
1136+typeForGraphRefRelationalExpr (Rename oldAttr newAttr expr) = do
1137+ expr' <- typeForGraphRefRelationalExpr expr
1138+ lift $ except $ rename oldAttr newAttr expr'
1139+typeForGraphRefRelationalExpr (Difference exprA exprB) = do
1140+ exprA' <- typeForGraphRefRelationalExpr exprA
1141+ exprB' <- typeForGraphRefRelationalExpr exprB
1142+ lift $ except $ difference exprA' exprB'
1143+typeForGraphRefRelationalExpr (Group groupNames attrName expr) = do
1144+ expr' <- typeForGraphRefRelationalExpr expr
1145+ groupNames' <- evalGraphRefAttributeNames groupNames expr
1146+ lift $ except $ group groupNames' attrName expr'
1147+typeForGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1148+ expr' <- typeForGraphRefRelationalExpr expr
1149+ lift $ except $ ungroup groupAttrName expr'
1150+typeForGraphRefRelationalExpr (Restrict pred' expr) = do
1151+ expr' <- typeForGraphRefRelationalExpr expr
1152+ filt <- predicateRestrictionFilter (attributes expr') pred'
1153+ lift $ except $ restrict filt expr'
1154+typeForGraphRefRelationalExpr Equals{} =
1155+ pure relationFalse
1156+typeForGraphRefRelationalExpr NotEquals{} =
1157+ pure relationFalse
1158+typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1159+ rel <- typeForGraphRefRelationalExpr expr
1160+ evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1161+typeForGraphRefRelationalExpr expr@(With withs _) = do
1162+ let expr' = substituteWithNameMacros [] expr
1163+ checkMacroName (WithNameExpr macroName tid) = do
1164+ rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1165+ case M.lookup macroName rvs of
1166+ Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1167+ Nothing -> pure ()
1168+ mapM_ (checkMacroName . fst) withs
1169+ typeForGraphRefRelationalExpr expr'
1170+
1171+evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
11401172evalGraphRefAttributeNames attrNames expr = do
1141− eExprType <- typeForGraphRefRelationalExpr expr
1142− case eExprType of
1143− Left err -> pure (Left err)
1144− Right exprTyp -> do
1145− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1146− case attrNames of
1147− AttributeNames names ->
1148− case A.projectionAttributesForNames names (attributes exprTyp) of
1149− Left err -> pure (Left err)
1150− Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1173+ exprType' <- typeForGraphRefRelationalExpr expr
1174+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1175+ case attrNames of
1176+ AttributeNames names ->
1177+ case A.projectionAttributesForNames names (attributes exprType') of
1178+ Left err -> throwError err
1179+ Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
11511180
1152− InvertedAttributeNames names -> do
1181+ InvertedAttributeNames names -> do
11531182 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
11541183 if not (S.null nonExistentAttributeNames) then
1155− pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1184+ throwError $ AttributeNamesMismatchError nonExistentAttributeNames
11561185 else
1157− pure (pure (A.nonMatchingAttributeNameSet names typeNameSet))
1158−
1159− UnionAttributeNames namesA namesB -> do
1160− eNameSetA <- evalGraphRefAttributeNames namesA expr
1161− case eNameSetA of
1162− Left err -> pure (Left err)
1163− Right nameSetA -> do
1164− eNameSetB <- evalGraphRefAttributeNames namesB expr
1165− case eNameSetB of
1166− Left err -> pure (Left err)
1167− Right nameSetB ->
1168− pure (Right (S.union nameSetA nameSetB))
1186+ pure (A.nonMatchingAttributeNameSet names typeNameSet)
11691187
1170− IntersectAttributeNames namesA namesB -> do
1171− eNameSetA <- evalGraphRefAttributeNames namesA expr
1172− case eNameSetA of
1173− Left err -> pure (Left err)
1174− Right nameSetA -> do
1175− eNameSetB <- evalGraphRefAttributeNames namesB expr
1176− case eNameSetB of
1177− Left err -> pure (Left err)
1178− Right nameSetB ->
1179− pure (Right (S.intersection nameSetA nameSetB))
1188+ UnionAttributeNames namesA namesB -> do
1189+ nameSetA <- evalGraphRefAttributeNames namesA expr
1190+ nameSetB <- evalGraphRefAttributeNames namesB expr
1191+ pure (S.union nameSetA nameSetB)
11801192
1181− RelationalExprAttributeNames attrExpr -> do
1182− eAttrExprType <- typeForGraphRefRelationalExpr attrExpr
1183− case eAttrExprType of
1184− Left err -> pure (Left err)
1185− Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1193+ IntersectAttributeNames namesA namesB -> do
1194+ nameSetA <- evalGraphRefAttributeNames namesA expr
1195+ nameSetB <- evalGraphRefAttributeNames namesB expr
1196+ pure (S.intersection nameSetA nameSetB)
11861197
1198+ RelationalExprAttributeNames attrExpr -> do
1199+ attrExprType <- typeForGraphRefRelationalExpr attrExpr
1200+ pure (A.attributeNameSet (attributes attrExprType))
11871201
1188−
1189−
1190−processAtomExpr :: AtomExpr -> RelationalExprState GraphRefAtomExpr
1191−processAtomExpr (AttributeAtomExpr nam) = pure $ AttributeAtomExpr nam
1192−processAtomExpr (NakedAtomExpr atom) = pure $ NakedAtomExpr atom
1193−processAtomExpr (FunctionAtomExpr fName atomExprs ()) = do
1194− tid <- re_currentTransId <$> ask
1195− FunctionAtomExpr fName <$> mapM processAtomExpr atomExprs <*> pure tid
1196−processAtomExpr (RelationAtomExpr expr) = RelationAtomExpr <$> processRelationalExpr expr
1197−processAtomExpr (ConstructedAtomExpr dConsName atomExprs ()) = ConstructedAtomExpr dConsName <$> mapM processAtomExpr atomExprs <*> (re_currentTransId <$> ask)
1198−
1199−processTupleExpr :: TupleExpr -> RelationalExprState GraphRefTupleExpr
1200−processTupleExpr (TupleExpr tMap) =
1201− TupleExpr . M.fromList <$> mapM (\(k,v) -> (,) k <$> processAtomExpr v) (M.toList tMap)
1202−
1203−evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> RelationalExprState (Either RelationalError Attribute)
1202+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
12041203evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1205− graph <- re_graph <$> ask
1206− case transactionForId tid graph of
1207− Left err -> pure (Left err)
1208− Right trans -> do
1209− let tConsMap = typeConstructorMapping (concreteDatabaseContext trans)
1210− case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1211− Left err -> pure (Left err)
1212− Right aType -> do
1213− case validateAtomType aType tConsMap of
1214− Left err -> pure (Left err)
1215− Right _ -> pure (Right (Attribute attrName aType))
1216−
1217−--convert AttributeExpr to GraphRefAttributeExpr
1218−processAttributeExpr :: AttributeExpr -> RelationalExprState GraphRefAttributeExpr
1219−processAttributeExpr (AttributeAndTypeNameExpr nam tCons ()) = do
1220− tid <- re_currentTransId <$> ask
1221− pure $ AttributeAndTypeNameExpr nam tCons tid
1222−processAttributeExpr (NakedAttributeExpr attr) = pure $ NakedAttributeExpr attr
1223−
1224−-- convert a RelationalExpr into a GraphRefRelationalExpr
1225−processRelationalExpr :: RelationalExpr -> RelationalExprState GraphRefRelationalExpr
1226−processRelationalExpr (MakeRelationFromExprs mAttrs tupleExprs) = do
1227− mAttrs' <- case mAttrs of
1228− Nothing -> pure Nothing
1229− Just mAttrs'' -> Just <$> mapM processAttributeExpr mAttrs''
1230− MakeRelationFromExprs mAttrs' <$> mapM processTupleExpr tupleExprs
1231−
1204+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1205+ case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1206+ Left err -> throwError err
1207+ Right aType -> do
1208+ case validateAtomType aType tConsMap of
1209+ Left err -> throwError err
1210+ Right _ -> pure (Attribute attrName aType)
1211+evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
12321212
12331213mkEmptyRelVars :: RelationVariables -> RelationVariables
1234−mkEmptyRelVars rvMap = M.map mkEmptyRelVar rvMap
1214+mkEmptyRelVars = M.map mkEmptyRelVar
12351215 where
1236− 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
12371217 mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
12381218 mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
12391219 mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
@@ -1244,14 +1224,169 @@ mkEmptyRelVars rvMap = M.map mkEmptyRelVar rvMap
12441224 mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
12451225 mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
12461226 mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1247− mkEmptyRelVar (Restrict pred expr) = Restrict pred (mkEmptyRelVar expr)
1227+ mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
12481228 mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
12491229 mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
12501230 mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1251− 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)
12521232
1253−processAttributeNames :: AttributeNames -> RelationalExprState GraphRefAttributeNames
1254−processAttributeNames (AttributeNames nameSet) = pure $ AttributeNames nameSet
1255−processAttributeNames (UnionAttributeNames attrNamesA attrNamesB) = UnionAttributeNames <$> processAttributeNames attrNamesA <*> processAttributeNames attrNamesB
1256−processAttributeNames (IntersectAttributeNames attrNamesA attrNamesB) = IntersectAttributeNames <$> processAttributeNames attrNamesA <*> processAttributeNames attrNamesB
1257−processAttributeNames (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> processRelationalExpr expr
1233+
1234+dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1235+dbErr err = lift (except (Left err))
1236+
1237+-- | Return a Relation describing the relation variables.
1238+relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1239+relationVariablesAsRelation ctx graph = do
1240+ let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1241+ attrs = A.attributesFromList [Attribute "name" TextAtomType,
1242+ Attribute "attributes" (RelationAtomType subrelAttrs)]
1243+ relVars = relationVariables ctx
1244+ mkRvDesc (rvName, gfExpr) = do
1245+ let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1246+ gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1247+ pure (rvName, gfType)
1248+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributesVec (attributes rel))]
1249+ attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1250+ attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1251+ Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1252+ Right rel -> RelationAtom rel
1253+ rvs <- mapM mkRvDesc (M.toList relVars)
1254+ let tups = map relVarToAtomList rvs
1255+ mkRelationFromList attrs tups
1256+
1257+-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1258+evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1259+evalRelationalExpr expr = do
1260+ graph <- reGraph
1261+ context <- reContext
1262+ let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1263+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1264+ case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1265+ Left err -> throwError err
1266+ Right rel -> pure rel
1267+
1268+class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1269+ getContext :: m DatabaseContext
1270+
1271+instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1272+ getContext = gfDatabaseContextForMarker UncommittedContextMarker
1273+
1274+instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1275+ getContext = getStateContext
1276+
1277+relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1278+relVarByName rvName = do
1279+ relvars <- relationVariables <$> getContext
1280+ case M.lookup rvName relvars of
1281+ Nothing -> throwError (RelVarNotDefinedError rvName)
1282+ Just gfexpr -> pure gfexpr
1283+
1284+-- | resolve UncommittedTransactionMarker whenever possible- this is important in the DatabaseContext in order to mitigate self-referencing loops for updates
1285+class ResolveGraphRefTransactionMarker a where
1286+ resolve :: a -> DatabaseContextEvalMonad a
1287+
1288+-- s := s union t
1289+instance ResolveGraphRefTransactionMarker GraphRefRelationalExpr where
1290+ resolve (MakeRelationFromExprs mAttrs tupleExprs) =
1291+ MakeRelationFromExprs mAttrs <$> resolve tupleExprs
1292+ resolve orig@MakeStaticRelation{} = pure orig
1293+ resolve orig@ExistingRelation{} = pure orig
1294+ resolve orig@(RelationVariable rvName UncommittedContextMarker) = do
1295+ rvMap <- relationVariables <$> getStateContext
1296+ case M.lookup rvName rvMap of
1297+ Nothing -> pure orig
1298+ Just resolvedRv -> resolve resolvedRv
1299+ resolve orig@RelationVariable{} = pure orig
1300+ resolve (Project attrNames relExpr) = Project <$> resolve attrNames <*> resolve relExpr
1301+ resolve (Union exprA exprB) = Union <$> resolve exprA <*> resolve exprB
1302+ resolve (Join exprA exprB) = Join <$> resolve exprA <*> resolve exprB
1303+ resolve (Rename attrA attrB expr) = Rename attrA attrB <$> resolve expr
1304+ resolve (Difference exprA exprB) = Difference <$> resolve exprA <*> resolve exprB
1305+ resolve (Group namesA nameB expr) = Group <$> resolve namesA <*> pure nameB <*> resolve expr
1306+ resolve (Ungroup nameA expr) = Ungroup nameA <$> resolve expr
1307+ resolve (Restrict restrictExpr relExpr) = Restrict <$> resolve restrictExpr <*> resolve relExpr
1308+ resolve (Equals exprA exprB) = Equals <$> resolve exprA <*> resolve exprB
1309+ resolve (NotEquals exprA exprB) = NotEquals <$> resolve exprA <*> resolve exprB
1310+ resolve (Extend extendExpr relExpr) = Extend <$> resolve extendExpr <*> resolve relExpr
1311+ resolve (With withExprs relExpr) = With <$> mapM (\(nam, expr) -> (,) <$> resolve nam <*> resolve expr) withExprs <*> resolve relExpr
1312+
1313+instance ResolveGraphRefTransactionMarker GraphRefTupleExprs where
1314+ resolve (TupleExprs marker tupleExprs) =
1315+ TupleExprs marker <$> mapM resolve tupleExprs
1316+
1317+instance ResolveGraphRefTransactionMarker GraphRefTupleExpr where
1318+ resolve (TupleExpr tupMap) = do
1319+ tupMap' <- mapM (\(attrName, expr) -> (,) attrName <$> resolve expr ) (M.toList tupMap)
1320+ pure (TupleExpr (M.fromList tupMap'))
1321+
1322+instance ResolveGraphRefTransactionMarker GraphRefAttributeNames where
1323+ resolve orig@AttributeNames{} = pure orig
1324+ resolve orig@InvertedAttributeNames{} = pure orig
1325+ resolve (UnionAttributeNames namesA namesB) = UnionAttributeNames <$> resolve namesA <*> resolve namesB
1326+ resolve (IntersectAttributeNames namesA namesB) = IntersectAttributeNames <$> resolve namesA <*> resolve namesB
1327+ resolve (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> resolve expr
1328+
1329+instance ResolveGraphRefTransactionMarker GraphRefRestrictionPredicateExpr where
1330+ resolve TruePredicate = pure TruePredicate
1331+ resolve (AndPredicate exprA exprB) = AndPredicate <$> resolve exprA <*> resolve exprB
1332+ resolve (OrPredicate exprA exprB) = OrPredicate <$> resolve exprA <*> resolve exprB
1333+ resolve (NotPredicate expr) = NotPredicate <$> resolve expr
1334+ resolve (RelationalExprPredicate expr) = RelationalExprPredicate <$> resolve expr
1335+ resolve (AtomExprPredicate expr) = AtomExprPredicate <$> resolve expr
1336+ resolve (AttributeEqualityPredicate nam expr)= AttributeEqualityPredicate nam <$> resolve expr
1337+
1338+instance ResolveGraphRefTransactionMarker GraphRefExtendTupleExpr where
1339+ resolve (AttributeExtendTupleExpr nam atomExpr) = AttributeExtendTupleExpr nam <$> resolve atomExpr
1340+
1341+instance ResolveGraphRefTransactionMarker GraphRefWithNameExpr where
1342+ resolve orig@WithNameExpr{} = pure orig -- match uncommitted marker?
1343+
1344+instance ResolveGraphRefTransactionMarker GraphRefAtomExpr where
1345+ resolve orig@AttributeAtomExpr{} = pure orig
1346+ resolve orig@NakedAtomExpr{} = pure orig
1347+ resolve (FunctionAtomExpr nam atomExprs marker) =
1348+ FunctionAtomExpr nam <$> mapM resolve atomExprs <*> pure marker
1349+ resolve (RelationAtomExpr expr) = RelationAtomExpr <$> resolve expr
1350+ resolve (ConstructedAtomExpr dConsName atomExprs marker) =
1351+ ConstructedAtomExpr dConsName <$> mapM resolve atomExprs <*> pure marker
1352+
1353+--convert series of simple Union queries into MakeStaticRelation
1354+-- this is especially useful for long, nested applications of Union with simple tuples
1355+-- Union (MakeRelation x y) (MakeRelation x y') -> MakeRelation x (y + y')
1356+
1357+--MakeRelationFromExprs Nothing (TupleExprs UncommittedContextMarker [TupleExpr (fromList [("name", NakedAtomExpr (TextAtom "steve"))])])
1358+
1359+applyUnionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1360+applyUnionCollapse = Fold.cata opt
1361+ where
1362+ opt :: RelationalExprBaseF GraphRefTransactionMarker GraphRefRelationalExpr -> GraphRefRelationalExpr
1363+ opt (UnionF exprA exprB) | exprA == exprB = exprA
1364+ opt (UnionF
1365+ exprA@(MakeRelationFromExprs mAttrs1 tupExprs1)
1366+ exprB@(MakeRelationFromExprs mAttrs2 tupExprs2)) | tupExprs1 == tupExprs2 = MakeRelationFromExprs (mAttrs1 <|> mAttrs2) tupExprs1
1367+ | tupExprsNull tupExprs1 = exprB
1368+ | tupExprsNull tupExprs2 = exprA
1369+ opt x = Fold.embed x
1370+ tupExprsNull (TupleExprs _ []) = True
1371+ tupExprsNull _ = False
1372+
1373+
1374+--UPDATE optimization- find matching where clause in "lower" levels of renaming
1375+--update x where y=1 set (x:=5,z:=10); update x where y=1 set(x:=6,z:=11)
1376+-- =>
1377+-- update x where y=1 set (x:=6,z:=11)
1378+-- future opt: match individual attributes update x where y=1 set (x:=5); update x where y=1 set (z:=11) => update x where y=1 set (x:=5,z:=11)
1379+
1380+--strategy: try to collapse the top-level update (union (restrict pred MakeRelationFromExpr) expr) if it contains the same predicate and resultant relation
1381+
1382+--DELETE optimization
1383+-- if a restriction matches a previous restriction, combine them
1384+-- O(1) since it only scans at the top level, critical in benchmarks generating redundant deletions
1385+applyRestrictionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1386+applyRestrictionCollapse orig@(Restrict npred@(NotPredicate _) expr) =
1387+ case expr of
1388+ orig'@(Restrict npred'@(NotPredicate _) _) | npred == npred' -> orig'
1389+ _ -> orig
1390+applyRestrictionCollapse expr = expr
1391+
1392+