@@ -1,39 +1,51 @@
1{-# LANGUAGE ScopedTypeVariables #-}
1{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE FlexibleContexts #-}
2module ProjectM36.RelationalExpression where
4module ProjectM36.RelationalExpression where
3import ProjectM36.Relation
5import ProjectM36.Relation
4import ProjectM36.Tuple
6import ProjectM36.Tuple
5import ProjectM36.TupleSet
7import ProjectM36.TupleSet
6import ProjectM36.Base
8import ProjectM36.Base
9+import qualified Data.UUID as U
7import ProjectM36.Error
10import ProjectM36.Error
8import ProjectM36.AtomType
11import ProjectM36.AtomType
9−import ProjectM36.Attribute (emptyAttributes)
12+import ProjectM36.Attribute (emptyAttributes, attributesFromList)
10import ProjectM36.ScriptSession
13import ProjectM36.ScriptSession
11import ProjectM36.DataTypes.Primitive
14import ProjectM36.DataTypes.Primitive
12import ProjectM36.AtomFunction
15import ProjectM36.AtomFunction
13import ProjectM36.DatabaseContextFunction
16import ProjectM36.DatabaseContextFunction
14import ProjectM36.Arbitrary
17import ProjectM36.Arbitrary
18+import ProjectM36.GraphRefRelationalExpr
19+import ProjectM36.Transaction
15import qualified ProjectM36.Attribute as A
20import qualified ProjectM36.Attribute as A
16import qualified Data.Map as M
21import qualified Data.Map as M
17import qualified Data.HashSet as HS
22import qualified Data.HashSet as HS
18import qualified Data.Set as S
23import qualified Data.Set as S
19import Control.Monad.State hiding (join)
24import Control.Monad.State hiding (join)
25+import Data.Bifunctor (second)
20import Data.Maybe
26import Data.Maybe
21import Data.Either
27import Data.Either
22import Data.Char (isUpper)
28import Data.Char (isUpper)
30+import qualified Data.List.NonEmpty as NE
31+import Data.Functor.Identity
23import qualified Data.Text as T
32import qualified Data.Text as T
24import qualified Data.Vector as V
33import qualified Data.Vector as V
25import qualified ProjectM36.TypeConstructorDef as TCD
34import qualified ProjectM36.TypeConstructorDef as TCD
26−import Control.Monad.Trans.Except
35+import qualified Control.Monad.RWS.Strict as RWS
36+import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
37+import Control.Monad.Except hiding (join)
27−import Control.Monad.Trans.Reader
38+import Control.Monad.Trans.Except (except)
39+import Control.Monad.Reader as R hiding (join)
40+import ProjectM36.NormalizeExpr
41+import ProjectM36.WithNameExpr
28import Test.QuickCheck
42import Test.QuickCheck
30#ifdef PM36_HASKELL_SCRIPTING
43#ifdef PM36_HASKELL_SCRIPTING
31−import GHC
44+import GHC hiding (getContext)
32import Control.Exception
45import Control.Exception
33import GHC.Paths
46import GHC.Paths
37data DatabaseContextExprDetails = CountUpdatedTuples
49data DatabaseContextExprDetails = CountUpdatedTuples
39databaseContextExprDetailsFunc :: DatabaseContextExprDetails -> ResultAccumFunc
51databaseContextExprDetailsFunc :: DatabaseContextExprDetails -> ResultAccumFunc
@@ -49,32 +61,63 @@ databaseContextExprDetailsFunc CountUpdatedTuples _ relIn = Relation attrs newTu
49 Right ts -> ts
61 Right ts -> ts
51-- | Used to start a fresh database state for a new database context expression.
63-- | Used to start a fresh database state for a new database context expression.
52−freshDatabaseState :: DatabaseContext -> DatabaseStateElems
64+mkDatabaseContextEvalState :: DatabaseContext -> DatabaseContextEvalState
65+mkDatabaseContextEvalState context = DatabaseContextEvalState {
66+ dbc_context = context,
53−freshDatabaseState ctx = (ctx, M.empty, False) --future work: propagate return accumulator
69+ } --future work: propagate return accumulator
55-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
71-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
56−data RelationalExprStateElems = RelationalExprStateTupleElems DatabaseContext RelationTuple | -- used when fully evaluating a relexpr
72+data RelationalExprEnv = RelationalExprEnv {
57− RelationalExprStateAttrsElems DatabaseContext Attributes | --used when evaluating the type of a relexpr
73+ re_context :: DatabaseContext,
58− RelationalExprStateElems DatabaseContext --used by default at the top level of evaluation
74+ re_graph :: TransactionGraph,
59−
75+ re_extra :: Maybe (Either RelationTuple Attributes)
60−instance Show RelationalExprStateElems where
76+ }
61− show (RelationalExprStateTupleElems _ tup) = "RelationalExprStateTupleElems " ++ show tup
77+
62− show (RelationalExprStateAttrsElems _ attrs) = "RelationalExprStateAttrsElems" ++ show attrs
78+envTuple :: GraphRefRelationalExprEnv -> RelationTuple
63− show (RelationalExprStateElems _) = "RelationalExprStateElems"
79+envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
65−mkRelationalExprState :: DatabaseContext -> RelationalExprStateElems
81+envAttributes :: GraphRefRelationalExprEnv -> Attributes
66−mkRelationalExprState = RelationalExprStateElems
82+envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
68−mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprStateElems -> RelationalExprStateElems
69−mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateElems ctx) = RelationalExprStateTupleElems ctx tupIn
70−mergeTuplesIntoRelationalExprState _ st@(RelationalExprStateAttrsElems _ _) = st
71−mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateTupleElems ctx existingTuple) = let mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap existingTuple) in
72− RelationalExprStateTupleElems ctx (mkRelationTupleFromMap mergedTupMap)
74−mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprStateElems -> RelationalExprStateElems
84+instance Show RelationalExprEnv where
75−mergeAttributesIntoRelationalExprState attrs (RelationalExprStateElems ctx) = RelationalExprStateAttrsElems ctx attrs
85+ show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
76−mergeAttributesIntoRelationalExprState _ st@(RelationalExprStateTupleElems _ _) = st
86+
77−mergeAttributesIntoRelationalExprState attrsIn (RelationalExprStateAttrsElems ctx attrs) = RelationalExprStateAttrsElems ctx (A.union attrsIn attrs)
87+--used to eval relationalexpr
88+type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
90+runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
91+runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
93+reGraph :: RelationalExprM TransactionGraph
94+reGraph = asks re_graph
96+reContext :: RelationalExprM DatabaseContext
97+reContext = asks re_context
99+mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
100+mkRelationalExprEnv ctx graph =
104+ re_extra = Nothing }
106+askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
109+mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
110+mergeTuplesIntoGraphRefRelationalExprEnv tupIn e =
111+ e{ gre_extra = new_elems }
113+ new_elems = Just (Left newTuple)
114+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple e))
115+ newTuple = mkRelationTupleFromMap mergedTupMap
117+mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
118+mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
120+ newattrs = Just (Right (A.union attrsIn (envAttributes e)))
79type ResultAccumName = StringType
122type ResultAccumName = StringType
@@ -84,36 +127,103 @@ data ResultAccum = ResultAccum { resultAccumFunc :: ResultAccumFunc,
84 resultAccumResult :: Relation
127 resultAccumResult :: Relation
130+data DatabaseContextEvalState = DatabaseContextEvalState {
131+ dbc_context :: DatabaseContext, --new, alterable context for a new transaction
87−type DatabaseStateElems = (DatabaseContext, M.Map ResultAccumName ResultAccum, DirtyFlag)
132+ dbc_accum :: M.Map ResultAccumName ResultAccum,
133+ dbc_dirty :: DirtyFlag
89−type DatabaseState a = State DatabaseStateElems a
136+data DatabaseContextEvalEnv = DatabaseContextEvalEnv
137+ { dce_transId :: TransactionId,
138+ dce_graph :: TransactionGraph
91−getStateContext :: DatabaseState DatabaseContext
141+mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
92−getStateContext = do
142+mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
93− (ctx,_, _) <- get
143+
94− pure ctx
144+type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
146+runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
147+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
149+ freshEnv = mkDatabaseContextEvalState ctx
152+dbcTransId :: DatabaseContextEvalMonad TransactionId
153+dbcTransId = dce_transId <$> RWS.ask
155+dbcGraph :: DatabaseContextEvalMonad TransactionGraph
156+dbcGraph = dce_graph <$> RWS.ask
158+dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
159+dbcRelationalExprEnv =
160+ mkRelationalExprEnv <$> getStateContext <*> dbcGraph
162+getStateContext :: DatabaseContextEvalMonad DatabaseContext
163+getStateContext = gets dbc_context
96−putStateContext :: DatabaseContext -> DatabaseState ()
165+putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
97−putStateContext ctx = do
166+putStateContext ctx' = do
98− (_, accum, _) <- get
167+ s <- get
99− put (ctx, accum, True)
168+ put (s {dbc_context = ctx', dbc_dirty = True})
170+-- | The context is optionally passed down along in cases where the current context is uncommitted.
171+data GraphRefRelationalExprEnv =
172+ GraphRefRelationalExprEnv {
173+ gre_context :: Maybe DatabaseContext,
174+ gre_graph :: TransactionGraph,
175+ gre_extra :: Maybe (Either RelationTuple Attributes)
101−type RelationalExprState a = Reader RelationalExprStateElems a
178+type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
180+gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
181+gfTransForId tid = do
183+ lift $ except $ transactionForId tid graph
185+gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
186+gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
187+gfDatabaseContextForMarker UncommittedContextMarker = do
188+ mctx <- gre_context <$> askEnv
190+ Nothing -> throwError NoUncommittedContextInEvalError
191+ Just ctx -> pure ctx
193+runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
194+runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
196+freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
197+freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
203+gfGraph :: GraphRefRelationalExprM TransactionGraph
204+gfGraph = asks gre_graph
103−stateElemsContext :: RelationalExprStateElems -> DatabaseContext
206+envContext :: RelationalExprEnv -> DatabaseContext
104−stateElemsContext (RelationalExprStateTupleElems ctx _) = ctx
207+envContext = re_context
105−stateElemsContext (RelationalExprStateElems ctx) = ctx
106−stateElemsContext (RelationalExprStateAttrsElems ctx _) = ctx
108−setStateElemsContext :: RelationalExprStateElems -> DatabaseContext -> RelationalExprStateElems
209+setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
109−setStateElemsContext (RelationalExprStateTupleElems _ tup) ctx = RelationalExprStateTupleElems ctx tup
210+setEnvContext e ctx = e { re_context = ctx }
110−setStateElemsContext (RelationalExprStateElems _) ctx = RelationalExprStateElems ctx
111−setStateElemsContext (RelationalExprStateAttrsElems _ attrs) ctx = RelationalExprStateAttrsElems ctx attrs
213+--full evaluation down the graph
214+eval :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
217+ eGfExpr <- processRelationalExpr expr
219+ Left err -> pure (Left err)
220+ Right gfExpr -> pure $ evalGraphRefRelationalExpr gfExpr (re_graph env)
113--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
223--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
114−evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
224+evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
115evalRelationalExpr (RelationVariable name _) = do
225evalRelationalExpr (RelationVariable name _) = do
116− relvarTable <- fmap (relationVariables . stateElemsContext) ask
226+ relvarTable <- fmap (relationVariables . envContext) askEnv
117 return $ case M.lookup name relvarTable of
227 return $ case M.lookup name relvarTable of
118 Just res -> Right res
228 Just res -> Right res
119 Nothing -> Left $ RelVarNotDefinedError name
229 Nothing -> Left $ RelVarNotDefinedError name
@@ -125,7 +235,7 @@ evalRelationalExpr (Project attrNames expr) = do
125 Right attrNameSet -> do
235 Right attrNameSet -> do
126 rel <- evalRelationalExpr expr
236 rel <- evalRelationalExpr expr
127 case rel of
237 case rel of
128− Right rel2 -> pure $ project attrNameSet rel2
238+ Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
129 Left err -> pure $ Left err
239 Left err -> pure $ Left err
131evalRelationalExpr (Union exprA exprB) = do
241evalRelationalExpr (Union exprA exprB) = do
@@ -135,7 +245,7 @@ evalRelationalExpr (Union exprA exprB) = do
135 Left err -> return $ Left err
245 Left err -> return $ Left err
136 Right relA2 -> case relB of
246 Right relA2 -> case relB of
137 Left err -> return $ Left err
247 Left err -> return $ Left err
138− Right relB2 -> return $ union relA2 relB2
248+ Right relB2 -> return $ Right (Union relA2 relB2)
140evalRelationalExpr (Join exprA exprB) = do
250evalRelationalExpr (Join exprA exprB) = do
141 relA <- evalRelationalExpr exprA
251 relA <- evalRelationalExpr exprA
@@ -144,7 +254,7 @@ evalRelationalExpr (Join exprA exprB) = do
144 Left err -> return $ Left err
254 Left err -> return $ Left err
145 Right relA2 -> case relB of
255 Right relA2 -> case relB of
146 Left err -> return $ Left err
256 Left err -> return $ Left err
147− Right relB2 -> return $ join relA2 relB2
257+ Right relB2 -> return $ Right (Join relA2 relB2)
149evalRelationalExpr (Difference exprA exprB) = do
259evalRelationalExpr (Difference exprA exprB) = do
150 relA <- evalRelationalExpr exprA
260 relA <- evalRelationalExpr exprA
@@ -153,33 +263,34 @@ evalRelationalExpr (Difference exprA exprB) = do
153 Left err -> return $ Left err
263 Left err -> return $ Left err
154 Right relA2 -> case relB of
264 Right relA2 -> case relB of
155 Left err -> return $ Left err
265 Left err -> return $ Left err
156− Right relB2 -> return $ difference relA2 relB2
266+ Right relB2 -> return $ Right (Difference relA2 relB2)
158evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
268evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
159 case mkRelation attributeSet tupleSet of
269 case mkRelation attributeSet tupleSet of
160− Right rel -> return $ Right rel
270+ Right rel -> return $ Right (ExistingRelation rel)
161 Left err -> return $ Left err
271 Left err -> return $ Left err
163evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
273evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
164− currentContext <- fmap stateElemsContext ask
274+ currentContext <- fmap envContext askEnv
165 let tConss = typeConstructorMapping currentContext
275 let tConss = typeConstructorMapping currentContext
166 -- 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
276 -- 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
167 runExceptT $ do
277 runExceptT $ do
168 mAttrs <- case mAttrExprs of
278 mAttrs <- case mAttrExprs of
169 Just _ ->
279 Just _ ->
170− Just . A.attributesFromList <$> mapM (either throwE pure . evalAttrExpr tConss) (fromMaybe [] mAttrExprs)
280+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
171 Nothing -> pure Nothing
281 Nothing -> pure Nothing
172 tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
282 tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
173 let attrs = fromMaybe firstTupleAttrs mAttrs
283 let attrs = fromMaybe firstTupleAttrs mAttrs
174 firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
284 firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
175− either throwE pure (mkRelation attrs (RelationTupleSet tuples))
285+ expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
286+ pure (ExistingRelation expr)
177−evalRelationalExpr (ExistingRelation rel) = pure (Right rel)
288+evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
179evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
290evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
180 evald <- evalRelationalExpr relExpr
291 evald <- evalRelationalExpr relExpr
181 case evald of
292 case evald of
182− Right rel -> return $ rename oldAttrName newAttrName rel
293+ Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
183 Left err -> return $ Left err
294 Left err -> return $ Left err
185evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
296evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
@@ -189,35 +300,32 @@ evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
189 Right oldAttrNameSet -> do
300 Right oldAttrNameSet -> do
190 evald <- evalRelationalExpr relExpr
301 evald <- evalRelationalExpr relExpr
191 case evald of
302 case evald of
192− Right rel -> return $ group oldAttrNameSet newAttrName rel
303+ Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
193 Left err -> return $ Left err
304 Left err -> return $ Left err
195evalRelationalExpr (Ungroup attrName relExpr) = do
306evalRelationalExpr (Ungroup attrName relExpr) = do
196 evald <- evalRelationalExpr relExpr
307 evald <- evalRelationalExpr relExpr
197 case evald of
308 case evald of
198− Right rel -> return $ ungroup attrName rel
309+ Right expr -> return $ Right (Ungroup attrName expr)
199 Left err -> return $ Left err
310 Left err -> return $ Left err
201evalRelationalExpr (Restrict predicateExpr relExpr) = do
312evalRelationalExpr (Restrict predicateExpr relExpr) = do
202 evald <- evalRelationalExpr relExpr
313 evald <- evalRelationalExpr relExpr
314+ pred <- processRestrictionPredicateExpr predicateExpr
203 case evald of
315 case evald of
204 Left err -> return $ Left err
316 Left err -> return $ Left err
205− Right rel -> do
317+ Right expr ->
206− eFilterFunc <- predicateRestrictionFilter (attributes rel) predicateExpr
318+ pure $ Right (Restrict pred expr)
208− Left err -> return $ Left err
210− pure (restrict filterfunc rel)
212evalRelationalExpr (Equals relExprA relExprB) = do
320evalRelationalExpr (Equals relExprA relExprB) = do
213 evaldA <- evalRelationalExpr relExprA
321 evaldA <- evalRelationalExpr relExprA
214 evaldB <- evalRelationalExpr relExprB
322 evaldB <- evalRelationalExpr relExprB
215 case evaldA of
323 case evaldA of
216 Left err -> return $ Left err
324 Left err -> return $ Left err
217− Right relA -> case evaldB of
325+ Right exprA -> case evaldB of
218 Left err -> return $ Left err
326 Left err -> return $ Left err
219− Right relB -> return $ Right $ if relA == relB then relationTrue else relationFalse
327+ Right exprB -> return $ Right (Equals exprA exprB)
221evalRelationalExpr (With views mainExpr) = do
329evalRelationalExpr (With views mainExpr) = do
222 rstate <- ask
330 rstate <- ask
@@ -231,310 +339,325 @@ evalRelationalExpr (With views mainExpr) = do
231 case foldM addScopedView (stateElemsContext rstate) views of
339 case foldM addScopedView (stateElemsContext rstate) views of
232 Left err -> return $ Left err
340 Left err -> return $ Left err
233 Right ctx'' -> do
341 Right ctx'' -> do
234− let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprStateElems ctx'')
342+ let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprEnv ctx'')
235 case evalMainExpr mainExpr of
343 case evalMainExpr mainExpr of
236 Left err -> return $ Left err
344 Left err -> return $ Left err
237 Right rel -> return $ Right rel
345 Right rel -> return $ Right rel
239--warning: copy-pasta from above- refactor
347--warning: copy-pasta from above- refactor
240evalRelationalExpr (NotEquals relExprA relExprB) = do
348evalRelationalExpr (NotEquals relExprA relExprB) = do
241 evaldA <- evalRelationalExpr relExprA
349 evaldA <- evalRelationalExpr relExprA
242 evaldB <- evalRelationalExpr relExprB
350 evaldB <- evalRelationalExpr relExprB
243 case evaldA of
351 case evaldA of
244 Left err -> return $ Left err
352 Left err -> return $ Left err
245− Right relA -> case evaldB of
353+ Right exprA -> case evaldB of
246 Left err -> return $ Left err
354 Left err -> return $ Left err
247− Right relB -> return $ Right $ if relA /= relB then relationTrue else relationFalse
355+ Right exprB -> return $ Right (NotEquals exprA exprB)
249-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
357-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
250evalRelationalExpr (Extend tupleExpression relExpr) = do
358evalRelationalExpr (Extend tupleExpression relExpr) = do
252− let evald = runReader (evalRelationalExpr relExpr) rstate
359+ eExpr <- evalRelationalExpr relExpr
253− case evald of
360+ case eExpr of
254 Left err -> pure (Left err)
361 Left err -> pure (Left err)
255− Right rel -> do
362+ Right expr -> do
256− tupProc <- extendTupleExpressionProcessor rel tupleExpression
363+ tupProc <- processExtendTupleExpr tupleExpression
257− case tupProc of
364+ pure (Right (Extend tupProc expr))
258− Left err -> pure (Left err)
365+-}
259− Right (newAttrs, tupProc') -> pure $ relMogrify tupProc' newAttrs rel
261--helper function to process relation variable creation/assignment
366--helper function to process relation variable creation/assignment
262−setRelVar :: RelVarName -> Relation -> DatabaseState (Either RelationalError ())
367+setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
263−setRelVar relVarName rel = do
368+setRelVar relVarName relExpr = do
264 currentContext <- getStateContext
369 currentContext <- getStateContext
370+ --prevent recursive relvar definition
265− let newRelVars = M.insert relVarName rel $ relationVariables currentContext
371+ let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
266 potentialContext = currentContext { relationVariables = newRelVars }
372 potentialContext = currentContext { relationVariables = newRelVars }
267−
373+ --optimization: if the relexpr is unchanged, skip the update
374+ if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
377+ --determine when to check constraints
268− case checkConstraints potentialContext of
380+ case checkConstraints potentialContext tid graph of
269− Left err -> pure (Left err)
381+ Left err -> dbErr err
271− putStateContext potentialContext
382+ Right _ -> putStateContext potentialContext
274-- 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
384-- 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
275−deleteRelVar :: RelVarName -> DatabaseState (Either RelationalError ())
385+deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
276deleteRelVar relVarName = do
386deleteRelVar relVarName = do
277 currContext <- getStateContext
387 currContext <- getStateContext
278 let relVars = relationVariables currContext
388 let relVars = relationVariables currContext
279 if M.notMember relVarName relVars then
389 if M.notMember relVarName relVars then
280− pure (Right ())
390+ pure ()
282 let newRelVars = M.delete relVarName relVars
392 let newRelVars = M.delete relVarName relVars
283 newContext = currContext { relationVariables = newRelVars }
393 newContext = currContext { relationVariables = newRelVars }
284 putStateContext newContext
394 putStateContext newContext
285− pure (Right ())
395+ pure ()
287−evalDatabaseContextExpr :: DatabaseContextExpr -> DatabaseState (Either RelationalError ())
397+evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContextEvalMonad ()
288−evalDatabaseContextExpr NoOperation = pure (Right ())
398+evalGraphRefDatabaseContextExpr NoOperation = pure ()
290−evalDatabaseContextExpr (Define relVarName attrExprs) = do
400+evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
401+ context <- getStateContext
291 relvars <- fmap relationVariables getStateContext
402 relvars <- fmap relationVariables getStateContext
292 tConss <- fmap typeConstructorMapping getStateContext
403 tConss <- fmap typeConstructorMapping getStateContext
293− let eAttrs = map (evalAttrExpr tConss) attrExprs
404+ graph <- dbcGraph
294− attrErrs = lefts eAttrs
405+ let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
295− attrsList = rights eAttrs
406+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
296− if not (null attrErrs) then
407+ case eAttrs of
297− pure (Left (someErrors attrErrs))
408+ Left err -> dbErr err
298− else do
409+ Right attrsList -> do
299− let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
410+ lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
300− if not (null atomTypeErrs) then
301− pure (Left (someErrors atomTypeErrs))
303− case M.member relVarName relvars of
411+ case M.member relVarName relvars of
304− True -> pure (Left (RelVarAlreadyDefinedError relVarName))
412+ True -> dbErr (RelVarAlreadyDefinedError relVarName)
305− False -> setRelVar relVarName emptyRelation >> pure (Right ())
413+ False -> setRelVar relVarName (ExistingRelation emptyRelation)
307 attrs = A.attributesFromList attrsList
415 attrs = A.attributesFromList attrsList
308 emptyRelation = Relation attrs emptyTupleSet
416 emptyRelation = Relation attrs emptyTupleSet
310−evalDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
418+evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
312−evalDatabaseContextExpr (Assign relVarName expr) = do
420+evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
313− -- in the future, it would be nice to get types from the RelationalExpr instead of needing to evaluate it
421+ graph <- re_graph <$> dbcRelationalExprEnv
314 context <- getStateContext
422 context <- getStateContext
315− let existingRelVar = M.lookup relVarName relVarTable
423+ let existingRelVar = M.lookup relVarName (relationVariables context)
316− relVarTable = relationVariables context
424+ reEnv = freshGraphRefRelationalExprEnv (Just context) graph
317− value = runReader (evalRelationalExpr expr) (RelationalExprStateElems context)
425+ eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
319− Left err -> pure (Left err)
320− Right rel -> case existingRelVar of
426+ case existingRelVar of
321− Nothing -> setRelVar relVarName rel
427+ Nothing -> do
322− Just existingRel -> let expectedAttributes = attributes existingRel
428+ case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
323− foundAttributes = attributes rel in
429+ Left err -> dbErr err
324− if A.attributesEqual expectedAttributes foundAttributes then
430+ Right reltype -> do
325− setRelVar relVarName rel
431+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
326− else
432+ setRelVar relVarName expr
327− pure (Left (RelationTypeMismatchError expectedAttributes foundAttributes))
433+ Just existingRel -> do
328−
434+ let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
329−evalDatabaseContextExpr (Insert relVarName relExpr) = do
435+ case eExpectedType of
330− context <- getStateContext
331− let unionexp = Union relExpr rv
332− rv = RelationVariable relVarName ()
333− unioned = runReader (evalRelationalExpr unionexp) (RelationalExprStateElems context)
334− origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
336− Left err -> pure (Left err)
436+ Left err -> dbErr err
337− Right unioned' -> case origRel of
437+ Right expectedType ->
438+ case eNewExprType of
338− Left err -> pure (Left err)
439+ Left err -> dbErr err
339− Right origRel' -> if cardinality unioned' == cardinality origRel' then --no tuples actually inserted
440+ Right newExprType -> do
340− pure (Right ())
441+ if newExprType == expectedType then do
442+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
443+ setRelVar relVarName expr
342− evalDatabaseContextExpr $ Assign relVarName (ExistingRelation unioned')
445+ dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
344−evalDatabaseContextExpr (Delete relVarName predicate) = do
447+evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
345− context <- getStateContext
448+ gfExpr <- relVarByName relVarName
346− let rv = RelationVariable relVarName ()
449+ evalGraphRefDatabaseContextExpr (Assign relVarName
347− let updatedRel = runReader (evalRelationalExpr (Restrict (NotPredicate predicate) rv)) (RelationalExprStateElems context)
450+ (Union
348− origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
451+ gfExpr
349− case updatedRel of
452+ relExpr))
350− Left err -> pure (Left err)
351− Right updatedRel' -> case origRel of
352− Left err -> pure (Left err)
353− Right origRel' -> if cardinality origRel' == cardinality updatedRel' then
356− setRelVar relVarName updatedRel'
454+evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
455+ gfExpr <- relVarByName relVarName
456+ setRelVar relVarName (Restrict (NotPredicate predicate) gfExpr)
358--union of restricted+updated portion and the unrestricted+unupdated portion
458--union of restricted+updated portion and the unrestricted+unupdated portion
359−evalDatabaseContextExpr (Update relVarName atomExprMap restrictionPredicateExpr) = do
459+evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
360− context <- getStateContext
460+ rvExpr <- relVarByName relVarName
361− let relVarTable = relationVariables context
461+ let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
362− case M.lookup relVarName relVarTable of
462+ tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
363− Nothing -> pure (Left (RelVarNotDefinedError relVarName))
463+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
364− Just rel ->
464+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
365− case runReader (predicateRestrictionFilter (attributes rel) restrictionPredicateExpr) (RelationalExprStateElems context) of
465+ restrictedPortion = Restrict pred' rvExpr
366− Left err -> pure (Left err)
466+ updated = foldr (\(oldname, atomExpr) accum ->
367− Right predicateFunc -> do
467+ let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
368− let ret = do
468+ updateAttr oldname procAtomExpr accum
369− restrictedPortion <- restrict predicateFunc rel
469+ ) restrictedPortion (M.toList atomExprMap)
370− if cardinality restrictedPortion == Finite 0 then
470+ -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
371− pure Nothing
471+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
372− else do
472+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
373− unrestrictedPortion <- restrict (predicateFunc >=> (pure . not)) rel
374− updatedPortion <- relMap (updateTupleWithAtomExprs atomExprMap context) restrictedPortion
375− updatedRel <- updatedPortion `union` unrestrictedPortion
376− pure (Just updatedRel)
378− Left err -> pure (Left err)
379− Right Nothing -> pure (Right ())
380− Right (Just updatedRel) -> setRelVar relVarName updatedRel
382−evalDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
474+evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
383 currContext <- getStateContext
475 currContext <- getStateContext
476+ transId <- dbcTransId
384 let currDeps = inclusionDependencies currContext
478 let currDeps = inclusionDependencies currContext
385 newDeps = M.insert newDepName newDep currDeps
479 newDeps = M.insert newDepName newDep currDeps
386 if M.member newDepName currDeps then
480 if M.member newDepName currDeps then
387− pure (Left (InclusionDependencyNameInUseError newDepName))
481+ dbErr (InclusionDependencyNameInUseError newDepName)
389 let potentialContext = currContext { inclusionDependencies = newDeps }
483 let potentialContext = currContext { inclusionDependencies = newDeps }
484+ -- if the potential context passes all constraints, then save it
485+ -- potential optimization: validate only the new constraint- all old constraints must already hold
390− case checkConstraints potentialContext of
486+ case checkConstraints potentialContext transId graph of
391− Left err -> pure (Left err)
487+ Left err -> dbErr err
392− Right _ -> do
488+ Right _ ->
393 putStateContext potentialContext
489 putStateContext potentialContext
396−evalDatabaseContextExpr (RemoveInclusionDependency depName) = do
491+evalGraphRefDatabaseContextExpr (RemoveInclusionDependency depName) = do
397 currContext <- getStateContext
492 currContext <- getStateContext
398 let currDeps = inclusionDependencies currContext
493 let currDeps = inclusionDependencies currContext
399 newDeps = M.delete depName currDeps
494 newDeps = M.delete depName currDeps
400 if M.notMember depName currDeps then
495 if M.notMember depName currDeps then
401− pure (Left (InclusionDependencyNameNotInUseError depName))
496+ dbErr (InclusionDependencyNameNotInUseError depName)
403 putStateContext $ currContext {inclusionDependencies = newDeps }
498 putStateContext $ currContext {inclusionDependencies = newDeps }
406-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
500-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
407−evalDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
501+evalGraphRefDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
408 currentContext <- getStateContext
502 currentContext <- getStateContext
409 let nots = notifications currentContext
503 let nots = notifications currentContext
410 if M.member notName nots then
504 if M.member notName nots then
411− pure (Left (NotificationNameInUseError notName))
505+ dbErr (NotificationNameInUseError notName)
413 let newNotifications = M.insert notName newNotification nots
507 let newNotifications = M.insert notName newNotification nots
414 newNotification = Notification { changeExpr = triggerExpr,
508 newNotification = Notification { changeExpr = triggerExpr,
415 reportOldExpr = resultOldExpr,
509 reportOldExpr = resultOldExpr,
416 reportNewExpr = resultNewExpr}
510 reportNewExpr = resultNewExpr}
417 putStateContext $ currentContext { notifications = newNotifications }
511 putStateContext $ currentContext { notifications = newNotifications }
420−evalDatabaseContextExpr (RemoveNotification notName) = do
513+evalGraphRefDatabaseContextExpr (RemoveNotification notName) = do
421 currentContext <- getStateContext
514 currentContext <- getStateContext
422 let nots = notifications currentContext
515 let nots = notifications currentContext
423 if M.notMember notName nots then
516 if M.notMember notName nots then
424− pure (Left (NotificationNameNotInUseError notName))
517+ dbErr (NotificationNameNotInUseError notName)
426 let newNotifications = M.delete notName nots
519 let newNotifications = M.delete notName nots
427 putStateContext $ currentContext { notifications = newNotifications }
520 putStateContext $ currentContext { notifications = newNotifications }
430-- | Adds type and data constructors to the database context.
523-- | Adds type and data constructors to the database context.
431-- validate that the type *and* constructor names are unique! not yet implemented!
524-- validate that the type *and* constructor names are unique! not yet implemented!
432−evalDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
525+evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
433 currentContext <- getStateContext
526 currentContext <- getStateContext
434 let oldTypes = typeConstructorMapping currentContext
527 let oldTypes = typeConstructorMapping currentContext
435 tConsName = TCD.name tConsDef
528 tConsName = TCD.name tConsDef
436 -- validate that the constructor's types exist
529 -- validate that the constructor's types exist
437 case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
530 case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
438− Left err -> pure (Left err)
531+ Left err -> throwError err
439− Right _ | T.null tConsName || not (isUpper (T.head tConsName)) -> pure (Left (InvalidAtomTypeName tConsName))
532+ Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
440− | isJust (findTypeConstructor tConsName oldTypes) -> pure (Left (AtomTypeNameInUseError tConsName))
533+ | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
441− | otherwise -> do
534+ | otherwise -> do
442− let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
535+ let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
443− putStateContext $ currentContext { typeConstructorMapping = newTypes }
536+ putStateContext $ currentContext { typeConstructorMapping = newTypes }
446-- | 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.
538-- | 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.
447−evalDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
539+evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
448 currentContext <- getStateContext
540 currentContext <- getStateContext
449 let oldTypes = typeConstructorMapping currentContext
541 let oldTypes = typeConstructorMapping currentContext
450 if isNothing (findTypeConstructor tConsName oldTypes) then
542 if isNothing (findTypeConstructor tConsName oldTypes) then
451− pure (Left (AtomTypeNameNotInUseError tConsName))
543+ dbErr (AtomTypeNameNotInUseError tConsName)
453 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
545 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
454 putStateContext $ currentContext { typeConstructorMapping = newTypes }
546 putStateContext $ currentContext { typeConstructorMapping = newTypes }
457−evalDatabaseContextExpr (MultipleExpr exprs) = do
548+evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
458 --the multiple expressions must pass the same context around- not the old unmodified context
549 --the multiple expressions must pass the same context around- not the old unmodified context
459− evald <- forM exprs evalDatabaseContextExpr
550+ mapM_ evalGraphRefDatabaseContextExpr exprs
460− --some lifting magic needed here
551+
462− [] -> pure (Right ())
463− errs -> pure (Left (someErrors errs))
465−evalDatabaseContextExpr (RemoveAtomFunction funcName) = do
552+evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
466 currentContext <- getStateContext
553 currentContext <- getStateContext
467 let atomFuncs = atomFunctions currentContext
554 let atomFuncs = atomFunctions currentContext
468 case atomFunctionForName funcName atomFuncs of
555 case atomFunctionForName funcName atomFuncs of
469− Left err -> pure (Left err)
556+ Left err -> dbErr err
470− Right realFunc -> if isScriptedAtomFunction realFunc then do
558+ if isScriptedAtomFunction realFunc then do
471− let updatedFuncs = HS.delete realFunc atomFuncs
559+ let updatedFuncs = HS.delete realFunc atomFuncs
472− putStateContext (currentContext {atomFunctions = updatedFuncs })
560+ putStateContext (currentContext {atomFunctions = updatedFuncs })
475− pure (Left (PrecompiledFunctionRemoveError funcName))
562+ dbErr (PrecompiledFunctionRemoveError funcName)
477−evalDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
564+evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
478 context <- getStateContext
565 context <- getStateContext
479 let dbcFuncs = dbcFunctions context
566 let dbcFuncs = dbcFunctions context
480 case databaseContextFunctionForName funcName dbcFuncs of
567 case databaseContextFunctionForName funcName dbcFuncs of
481− Left err -> pure (Left err)
568+ Left err -> dbErr err
482− Right realFunc -> if isScriptedDatabaseContextFunction realFunc then do
570+ if isScriptedDatabaseContextFunction realFunc then do
483− let updatedFuncs = HS.delete realFunc dbcFuncs
571+ let updatedFuncs = HS.delete realFunc dbcFuncs
484− putStateContext (context { dbcFunctions = updatedFuncs })
572+ putStateContext (context { dbcFunctions = updatedFuncs })
487− pure (Left (PrecompiledFunctionRemoveError funcName))
574+ dbErr (PrecompiledFunctionRemoveError funcName)
489−evalDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
576+evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
490 context <- getStateContext
577 context <- getStateContext
491 --resolve atom arguments
579 --resolve atom arguments
492− let relExprState = mkRelationalExprState context
580+ let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
493− eAtomTypes = map (\atomExpr -> runReader (typeFromAtomExpr emptyAttributes atomExpr) relExprState) atomArgExprs
494 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
581 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
582+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
495 case eFunc of
583 case eFunc of
496− Left err -> pure (Left err)
584+ Left err -> dbErr err
497 Right func -> do
585 Right func -> do
498 let expectedArgCount = length (dbcFuncType func)
586 let expectedArgCount = length (dbcFuncType func)
499 actualArgCount = length atomArgExprs
587 actualArgCount = length atomArgExprs
500 if expectedArgCount /= actualArgCount then
588 if expectedArgCount /= actualArgCount then
501− pure (Left (FunctionArgumentCountMismatchError expectedArgCount actualArgCount))
589+ dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
503 --check that the atom types are valid
591 --check that the atom types are valid
504− case lefts eAtomTypes of
592+ case eAtomTypes of
505− _:_ -> pure (Left (someErrors (lefts eAtomTypes)))
593+ Left err -> dbErr err
506− [] -> do
594+ Right atomTypes -> do
507− let atomTypes = rights eAtomTypes
508− let mValidTypes = zipWith
595+ let mValidTypes = zipWith (\ expType actType
510− -> case atomTypeVerify expType actType of
596+ -> case atomTypeVerify expType actType of
511− Left err -> Just err
597+ Left err -> Just err
512− Right _ -> Nothing)
598+ Right _ -> Nothing)
513− (dbcFuncType func)
599+ (dbcFuncType func) atomTypes
515− typeErrors = catMaybes mValidTypes
600+ typeErrors = catMaybes mValidTypes
516− eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
601+ eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
517 if length (lefts eAtomArgs) > 1 then
602 if length (lefts eAtomArgs) > 1 then
518− pure (Left (someErrors (lefts eAtomArgs)))
603+ dbErr (someErrors (lefts eAtomArgs))
519 else if not (null typeErrors) then
604 else if not (null typeErrors) then
520− pure (Left (someErrors typeErrors))
605+ dbErr (someErrors typeErrors)
522 case evalDatabaseContextFunction func (rights eAtomArgs) context of
607 case evalDatabaseContextFunction func (rights eAtomArgs) context of
523− Left err -> pure (Left err)
608+ Left err -> dbErr err
524− Right newContext -> putStateContext newContext >> pure (Right ())
609+ Right newContext -> putStateContext newContext
525−
610+data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
526−evalDatabaseContextIOExpr :: Maybe ScriptSession -> DatabaseContext -> DatabaseContextIOExpr -> IO (Either RelationalError DatabaseContext)
611+ { dbcio_transId :: TransactionId,
612+ dbcio_graph :: TransactionGraph,
613+ dbcio_mScriptSession :: Maybe ScriptSession
616+type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
618+runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
619+runDatabaseContextIOEvalMonad env ctx m = do
620+ res <- runRWST m env freshState
622+ (Left err,_,_) -> pure (Left err)
623+ (Right (),s,_) -> pure (Right s)
625+ freshState = mkDatabaseContextEvalState ctx
627+requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
628+requireScriptSession = do
630+ case dbcio_mScriptSession env of
631+ Nothing -> pure $ Left $ ScriptError ScriptCompilationDisabledError
632+ Just ss -> pure (Right ss)
634+putDBCIOContext :: DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ())
635+putDBCIOContext ctx = do
636+ RWS.modify (\dbstate -> dbstate { dbc_context = ctx})
639+getDBCIOContext :: DatabaseContextIOEvalMonad DatabaseContext
640+getDBCIOContext = dbc_context <$> RWS.get
642+getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
643+getDBCIORelationalExprEnv = do
644+ context <- getDBCIOContext
645+ mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
647+evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
527−#if !defined(PM36_HASKELL_SCRIPTING)
648+#if !defined(PM36_HASKELL_SCRIPTING)
528−evalDatabaseContextIOExpr _ _ AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
649+evalGraphRefDatabaseContextIOExpr AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
529−evalDatabaseContextIOExpr _ _ AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
650+evalGraphRefDatabaseContextIOExpr AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
530−evalDatabaseContextIOExpr _ _ LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
651+evalGraphRefDatabaseContextIOExpr LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
531−evalDatabaseContextIOExpr _ _ LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
652+evalGraphRefDatabaseContextIOExpr LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
533−evalDatabaseContextIOExpr mScriptSession currentContext (AddAtomFunction funcName funcType script) =
654+evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
534− case mScriptSession of
655+ eScriptSession <- requireScriptSession
535− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
656+ currentContext <- getDBCIOContext
657+ case eScriptSession of
658+ Left err -> pure (Left err)
536− Just scriptSession -> do
659+ Right scriptSession -> do
537− res <- try $ runGhc (Just libdir) $ do
660+ res <- liftIO $ try $ runGhc (Just libdir) $ do
538 setSession (hscEnv scriptSession)
661 setSession (hscEnv scriptSession)
539 let atomFuncs = atomFunctions currentContext
662 let atomFuncs = atomFunctions currentContext
540 case extractAtomFunctionType funcType of
663 case extractAtomFunctionType funcType of
@@ -560,12 +683,13 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddAtomFunction funcNam
560 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
683 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
561 Right eContext -> case eContext of
684 Right eContext -> case eContext of
562 Left err -> pure (Left err)
685 Left err -> pure (Left err)
563− Right context' -> pure (Right context')
686+ Right context' -> putDBCIOContext context'
565−evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunction funcName funcType script) =
687+evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
566− case mScriptSession of
688+ eScriptSession <- requireScriptSession
567− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
689+ currentContext <- getDBCIOContext
690+ case eScriptSession of
691+ Left err -> pure (Left err)
568− Just scriptSession -> do
692+ Right scriptSession -> do
569 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
693 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
570 let last2Args = reverse (take 2 (reverse funcType))
694 let last2Args = reverse (take 2 (reverse funcType))
571 atomArgs = take (length funcType - 2) funcType
695 atomArgs = take (length funcType - 2) funcType
@@ -575,7 +699,7 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunct
575 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
699 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
576 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
700 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
578− res <- try $ runGhc (Just libdir) $ do
702+ res <- liftIO $ try $ runGhc (Just libdir) $ do
579 setSession (hscEnv scriptSession)
703 setSession (hscEnv scriptSession)
580 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
704 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
581 pure $ case eCompiledFunc of
705 pure $ case eCompiledFunc of
@@ -600,68 +724,93 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunct
600 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
724 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
601 Right eContext -> case eContext of
725 Right eContext -> case eContext of
602 Left err -> pure (Left err)
726 Left err -> pure (Left err)
603− Right context' -> pure (Right context')
727+ Right context' -> putDBCIOContext context'
604−evalDatabaseContextIOExpr _ currentContext (LoadAtomFunctions modName funcName modPath) = do
728+evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
729+ currentContext <- getDBCIOContext
605− eLoadFunc <- loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
730+ eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
606 case eLoadFunc of
731 case eLoadFunc of
607 Left LoadSymbolError -> pure (Left LoadFunctionError)
732 Left LoadSymbolError -> pure (Left LoadFunctionError)
608 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
733 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
609 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
734 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
610− in pure (Right newContext)
735+ in putDBCIOContext newContext
611−evalDatabaseContextIOExpr _ currentContext (LoadDatabaseContextFunctions modName funcName modPath) = do
736+evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName modPath) = do
737+ currentContext <- getDBCIOContext
612− eLoadFunc <- loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
738+ eLoadFunc <- liftIO $ loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
613 case eLoadFunc of
739 case eLoadFunc of
614 Left LoadSymbolError -> pure (Left LoadFunctionError)
740 Left LoadSymbolError -> pure (Left LoadFunctionError)
615 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
741 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
616 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
742 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
617− in pure (Right newContext)
743+ in putDBCIOContext newContext
620−evalDatabaseContextIOExpr _ currentContext (CreateArbitraryRelation relVarName attrExprs range) =
744+evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
622− case runState ( evalDatabaseContextExpr (Define relVarName attrExprs)) (freshDatabaseState currentContext) of
746+ currentContext <- getDBCIOContext
748+ --create graph ref expr
749+ let gfExpr = Define relVarName attrExprs
750+ evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
751+ graph = dbcio_graph env
752+ case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
623− (Left err,_) -> pure (Left err)
753+ Left err -> pure (Left err)
624− (Right (), elems@(ctx,_,_)) -> do
754+ Right dbstate -> do
626 let existingRelVar = M.lookup relVarName relVarTable
756 let existingRelVar = M.lookup relVarName relVarTable
627− relVarTable = relationVariables ctx
757+ relVarTable = relationVariables (dbc_context dbstate)
628 case existingRelVar of
758 case existingRelVar of
629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
759 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
630 Just existingRel -> do
760 Just existingRel -> do
761+ let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
762+ case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
763+ Left err -> pure (Left err)
631− let expectedAttributes = attributes existingRel
765+ let expectedAttributes = attributes relType
632− let tcMap = typeConstructorMapping ctx
766+ tcMap = typeConstructorMapping (dbc_context dbstate)
633− eitherRel <- generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
767+ eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
634− case eitherRel of
768+ case eitherRel of
635− Left err -> pure $ Left err
769+ Left err -> pure $ Left err
636− Right rel ->
770+ Right rel ->
637− case runState (setRelVar relVarName rel) elems of
771+ case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
638− (Left err,_) -> pure (Left err)
772+ Left err -> pure (Left err)
639− (Right (), (ctx',_,_)) -> pure $ Right ctx'
773+ Right dbstate' -> putDBCIOContext (dbc_context dbstate')
641−updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> RelationTuple -> Either RelationalError RelationTuple
776+updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
642−updateTupleWithAtomExprs exprMap context tupIn = do
777+updateTupleWithAtomExprs exprMap context graph tupIn = do
643 --resolve all atom exprs
778 --resolve all atom exprs
644 atomsAssoc <- mapM (\(attrName, atomExpr) -> do
780 atomsAssoc <- mapM (\(attrName, atomExpr) -> do
781+ let atom = unimplemented
645− atom <- runReader (evalAtomExpr tupIn atomExpr) (RelationalExprStateElems context)
782+ --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
646 pure (attrName, atom)
783 pure (attrName, atom)
647 ) (M.toList exprMap)
784 ) (M.toList exprMap)
648 pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
785 pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
650--run verification on all constraints
787--run verification on all constraints
651−checkConstraints :: DatabaseContext -> Either RelationalError ()
788+checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
652−checkConstraints context =
789+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
653 mapM_ (uncurry checkIncDep) (M.toList deps)
790 mapM_ (uncurry checkIncDep) (M.toList deps)
792+ potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
793+ tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
794+ utctDayTime = secondsToDiffTime 0 }
795+ tempSchemas = Schemas context M.empty
796+ tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
655 deps = inclusionDependencies context
798 deps = inclusionDependencies context
656− eval expr = evalReader (evalRelationalExpr expr)
799+ -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
657− evalReader f = runReader f (RelationalExprStateElems context)
658 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
800 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
801+ let process = runProcessExprM UncommittedContextMarker
802+ gfSubsetExpr = process (processRelationalExpr subsetExpr)
803+ gfSupersetExpr = process (processRelationalExpr supersetExpr)
659 --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.
804 --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.
660− typeSub <- evalReader (typeForRelationalExpr subsetExpr)
805+ let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
661− typeSuper <- evalReader (typeForRelationalExpr supersetExpr)
806+ runGfRel = runGraphRefRelationalExprM gfEnv
807+ typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
808+ typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
662 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
809 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
663− let checkExpr = Equals supersetExpr (Union subsetExpr supersetExpr)
810+ let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
664− case eval checkExpr of
811+ gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
812+ gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
665 Left err -> Left err
814 Left err -> Left err
666 Right resultRel -> if resultRel == relationTrue then
815 Right resultRel -> if resultRel == relationTrue then
@@ -671,91 +820,90 @@ checkConstraints context =
671-- 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
820-- 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
672-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
821-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
674−typeForRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
823+typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
675typeForRelationalExpr expr = do
824typeForRelationalExpr expr = do
677− let context = stateElemsContext rstate
678 --replace the relationVariables context element with a cloned set of relation devoid of tuples
825 --replace the relationVariables context element with a cloned set of relation devoid of tuples
679− let context' = contextWithEmptyTupleSets context
680− rstate' = setStateElemsContext rstate context'
681 --evalRelationalExpr could still return an existing relation with tuples, so strip them
826 --evalRelationalExpr could still return an existing relation with tuples, so strip them
682− pure $ case runReader (evalRelationalExpr expr) rstate' of
827+ graph <- reGraph
683− Left err -> Left err
828+ context <- reContext
684− Right typeRel -> Right (relationWithEmptyTupleSet typeRel)
829+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
830+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
831+ runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
686--returns a database context with all tuples removed
834--returns a database context with all tuples removed
687--this is useful for type checking and optimization
835--this is useful for type checking and optimization
688contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
837contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
689contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
838contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
691− relVars = M.map (\rel -> Relation (attributes rel) emptyTupleSet) (relationVariables contextIn)
840+ relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
693liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
843liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
694liftE v = do
844liftE v = do
695 y <- lift v
845 y <- lift v
696 case y of
846 case y of
697− Left err -> throwE err
847+ Left err -> throwError err
698 Right val -> pure val
848 Right val -> pure val
700{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
850{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
701−predicateRestrictionFilter :: Attributes -> RestrictionPredicateExpr -> RelationalExprState (Either RelationalError RestrictionFilter)
851+predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
702−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
852+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
704− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
853+ expr1v <- predicateRestrictionFilter attrs expr1
705− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
854+ expr2v <- predicateRestrictionFilter attrs expr2
706− pure (\x -> do
855+ pure (\x -> do
707− ev1 <- expr1v x
856+ ev1 <- expr1v x
708− ev2 <- expr2v x
857+ ev2 <- expr2v x
709− pure (ev1 && ev2))
858+ pure (ev1 && ev2))
711−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
860+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
713− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
861+ expr1v <- predicateRestrictionFilter attrs expr1
714− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
862+ expr2v <- predicateRestrictionFilter attrs expr2
715 pure (\x -> do
863 pure (\x -> do
716 ev1 <- expr1v x
864 ev1 <- expr1v x
717 ev2 <- expr2v x
865 ev2 <- expr2v x
718 pure (ev1 || ev2))
866 pure (ev1 || ev2))
720−predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
868+predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
722−predicateRestrictionFilter attrs (NotPredicate expr) =
870+predicateRestrictionFilter attrs (NotPredicate expr) = do
724− exprv <- liftE (predicateRestrictionFilter attrs expr)
871+ exprv <- predicateRestrictionFilter attrs expr
725− pure (fmap not . exprv)
872+ pure (fmap not . exprv)
727--optimization opportunity: if the subexpression does not reference attributes in the top-level expression, then it need only be evaluated once, statically, outside the tuple filter- see historical implementation here
874--optimization opportunity: if the subexpression does not reference attributes in the top-level expression, then it need only be evaluated once, statically, outside the tuple filter- see historical implementation here
728predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
875predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
729− rstate <- ask
876+ renv <- askEnv
730− pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
877+ let eval :: RelationTuple -> Either RelationalError Relation
879+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
880+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
881+ pure (\tup -> case eval tup of
731 Left err -> Left err
882 Left err -> Left err
732 Right rel -> if arity rel /= 0 then
883 Right rel -> if arity rel /= 0 then
733 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
884 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
735− pure (rel == relationTrue)))
886+ pure (rel == relationTrue))
737predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
888predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
738− rstate <- ask
889+ env <- askEnv
739− let (attrs', ctxtup') = case rstate of
890+ let attrs' = A.union attrs (envAttributes env)
740− RelationalExprStateElems _ -> (attrs, emptyTuple)
891+ ctxtup' = envTuple env
741− RelationalExprStateAttrsElems _ _ -> (attrs, emptyTuple)
742− RelationalExprStateTupleElems _ ctxtup -> (A.union attrs (tupleAttributes ctxtup), ctxtup)
744− atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
892+ atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
745− attr <- either throwE pure $ case A.attributeForName attrName attrs of
893+ attr <- lift $ except $ case A.attributeForName attrName attrs of
746 Right attr -> Right attr
894 Right attr -> Right attr
747 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
895 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
748 Right ctxattr -> Right ctxattr
896 Right ctxattr -> Right ctxattr
749 Left err2@(NoSuchAttributeNamesError _) -> Left err2
897 Left err2@(NoSuchAttributeNamesError _) -> Left err2
750 Left err -> Left err
898 Left err -> Left err
751 Left err -> Left err
899 Left err -> Left err
752− if atomExprType /= A.atomType attr then
900+ if atomExprType /= A.atomType attr then
753− throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
901+ throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
755 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
903 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
756 Right atomCmp -> atomCmp == atomIn
904 Right atomCmp -> atomCmp == atomIn
757 Left _ -> False
905 Left _ -> False
758− atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
906+ atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
760 pure $ case atomForAttributeName attrName tupleIn of
908 pure $ case atomForAttributeName attrName tupleIn of
761 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
909 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -766,16 +914,15 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
766-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
914-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
767predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
915predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
768 --merge attrs into the state attributes
916 --merge attrs into the state attributes
769− rstate <- ask
917+ renv <- askEnv
771− aType <- liftE (typeFromAtomExpr attrs atomExpr)
918+ aType <- typeForGraphRefAtomExpr attrs atomExpr
772− if aType /= BoolAtomType then
919+ if aType /= BoolAtomType then
773− throwE (AtomTypeMismatchError aType BoolAtomType)
920+ throwError (AtomTypeMismatchError aType BoolAtomType)
775 pure (\tupleIn ->
922 pure (\tupleIn ->
776− case runReader (evalAtomExpr tupleIn atomExpr) rstate of
923+ case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
777− Left err -> Left err
924+ Left err -> Left err
778− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
925+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
780tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
927tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
781tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
928tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
@@ -783,31 +930,83 @@ tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName r
784 Right rel
931 Right rel
786−extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
933+extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
787−extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
934+extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
788− rstate <- ask
935+-- renv <- askEnv
789 -- check that the attribute name is not in use
936 -- check that the attribute name is not in use
790 case tupleExprCheckNewAttrName newAttrName relIn of
937 case tupleExprCheckNewAttrName newAttrName relIn of
791− Left err -> pure (Left err)
938+ Left err -> throwError err
792− Right _ -> runExceptT $ do
939+ Right _ -> do
793− atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
940+ atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
794− atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
941+ atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
795 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
942 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
796 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
943 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
797− pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in case runReader (evalAtomExpr tup atomExpr) substate of
944+ env <- ask
798− Left err -> Left err
945+ pure (newAndOldAttrs, \tup -> do
946+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
947+ atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
799− Right atom -> Right (tupleAtomExtend newAttrName atom tup)
948+ Right (tupleAtomExtend newAttrName atom tup)
951+evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
952+evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
953+ case atomForAttributeName attrName tupIn of
954+ Right atom -> pure atom
955+ Left err@(NoSuchAttributeNamesError _) -> do
957+ case gre_extra env of
958+ Nothing -> throwError err
959+ Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
960+ Just (Right _) -> throwError err
961+ Left err -> throwError err
962+evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
963+evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
964+ argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
965+ context <- gfDatabaseContextForMarker tid
966+ let functions = atomFunctions context
967+ func <- lift $ except (atomFunctionForName funcName functions)
968+ let expectedArgCount = length (atomFuncType func) - 1
969+ actualArgCount = length argTypes
970+ safeInit [] = [] -- different behavior from normal init
971+ safeInit xs = init xs
972+ if expectedArgCount /= actualArgCount then
973+ throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
975+ let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
976+ mapM_ (\(expType, actType) ->
977+ lift $ except (atomTypeVerify expType actType)) zippedArgs
978+ evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
979+ case evalAtomFunction func evaldArgs of
980+ Left err -> throwError (AtomFunctionUserError err)
982+ --validate that the result matches the expected type
983+ _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
985+evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
986+ --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
988+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
989+ relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
990+ pure (RelationAtom relAtom)
991+evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
992+ let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
993+ aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
994+ argAtoms <- local mergeEnv $
995+ mapM (evalGraphRefAtomExpr tupIn) dConsArgs
996+ pure (ConstructedAtom dConsName aType argAtoms)
802−evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
999+evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprM Atom
1000+evalAtomExpr tupIn expr =
803evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
1004evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
804 Right atom -> pure (Right atom)
1005 Right atom -> pure (Right atom)
805 err@(Left (NoSuchAttributeNamesError _)) -> do
1006 err@(Left (NoSuchAttributeNamesError _)) -> do
806 rstate <- ask
1007 rstate <- ask
807− case rstate of
1008+ let stateTup = stateTuple rstate
808− RelationalExprStateElems _ -> pure err
809− RelationalExprStateAttrsElems _ _ -> pure err
810− RelationalExprStateTupleElems _ ctxtup -> pure (atomForAttributeName attrName ctxtup)
1009+ pure (atomForAttributeName attrName stateTup)
811 Left err -> pure (Left err)
1010 Left err -> pure (Left err)
812evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
1011evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
813evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
1012evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
@@ -847,131 +1046,170 @@ evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExcept
847 aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
1046 aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
848 argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
1047 argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
849 pure (ConstructedAtom dConsName aType argAtoms)
1048 pure (ConstructedAtom dConsName aType argAtoms)
851−typeFromAtomExpr :: Attributes -> AtomExpr -> RelationalExprState (Either RelationalError AtomType)
1050+typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
852−typeFromAtomExpr attrs (AttributeAtomExpr attrName) = do
1051+typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
853− rstate <- ask
1052+ renv <- askEnv
854 case A.atomTypeForAttributeName attrName attrs of
1053 case A.atomTypeForAttributeName attrName attrs of
855− Right aType -> pure (Right aType)
1054+ Right aType -> pure aType
856− Left err@(NoSuchAttributeNamesError _) -> case rstate of
1055+ Left err@(NoSuchAttributeNamesError _) ->
1056+ let envTup = envTuple renv
1057+ envAttrs = envAttributes renv in
857− RelationalExprStateAttrsElems _ attrs' -> case A.attributeForName attrName attrs' of
1058+ case A.attributeForName attrName envAttrs of
858− Left err' -> pure (Left err')
859− Right attr -> pure (Right (A.atomType attr))
1059+ Right attr -> pure (A.atomType attr)
860− RelationalExprStateElems _ -> pure (Left err)
861− RelationalExprStateTupleElems _ tup -> case atomForAttributeName attrName tup of
1060+ Left _ -> case atomForAttributeName attrName envTup of
862− Left err' -> pure (Left err')
1061+ Right atom -> pure (atomTypeForAtom atom)
863− Right atom -> pure (Right (atomTypeForAtom atom))
1062+ Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
864− Left err -> pure (Left err)
1064+ Left err -> throwError err
865−typeFromAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
1066+typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
866−typeFromAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
1067+typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
867− context <- fmap stateElemsContext ask
1068+ funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
868− let funcs = atomFunctions context
869 case atomFunctionForName funcName funcs of
1069 case atomFunctionForName funcName funcs of
870− Left err -> pure (Left err)
1070+ Left err -> throwError err
871 Right func -> do
1071 Right func -> do
872 let funcRetType = last (atomFuncType func)
1072 let funcRetType = last (atomFuncType func)
873 funcArgTypes = init (atomFuncType func)
1073 funcArgTypes = init (atomFuncType func)
874− eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
1074+ argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
875− case lefts eArgTypes of
876− errs@(_:_) -> pure (Left (someErrors errs))
878− let eTvMap = resolveTypeVariables funcArgTypes argTypes
1075+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
879− argTypes = rights eArgTypes
880− case eTvMap of
1076+ case eTvMap of
881− Left err -> pure (Left err)
1077+ Left err -> throwError err
882− Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
1078+ Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
883−typeFromAtomExpr attrs (RelationAtomExpr relExpr) = runExceptT $ do
1079+typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
884− rstate <- lift ask
1080+ relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
885− relType <- either throwE pure (runReader (typeForRelationalExpr relExpr) (mergeAttributesIntoRelationalExprState attrs rstate))
886 pure (RelationAtomType (attributes relType))
1081 pure (RelationAtomType (attributes relType))
887-- grab the type of the data constructor, then validate that the args match the expected types
1082-- grab the type of the data constructor, then validate that the args match the expected types
888−typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
1083+typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
889− runExceptT $ do
1084+ do
890− argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
1085+ argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
891− context <- fmap stateElemsContext (lift ask)
1086+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
892− either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
1087+ lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
894-- | Validate that the type of the AtomExpr matches the expected type.
1089-- | Validate that the type of the AtomExpr matches the expected type.
895−verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
1090+verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
896−verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
1091+verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
897− rstate <- lift ask
1092+ env <- askEnv
898 case A.atomTypeForAttributeName attrName (attributes relIn) of
1093 case A.atomTypeForAttributeName attrName (attributes relIn) of
899− Right aType -> either throwE pure (atomTypeVerify expectedType aType)
1094+ Right aType -> lift $ except $ atomTypeVerify expectedType aType
900− (Left err@(NoSuchAttributeNamesError _)) -> case rstate of
1095+ (Left err@(NoSuchAttributeNamesError _)) ->
901− RelationalExprStateTupleElems _ _ -> throwE err
1096+ let attrs' = envAttributes env in
902− RelationalExprStateElems _ -> throwE err
1097+ if attrs' == emptyAttributes then
903− RelationalExprStateAttrsElems _ attrs -> case A.attributeForName attrName attrs of
1100+ case A.attributeForName attrName attrs' of
904− Left err' -> throwE err'
1101+ Left err' -> throwError err'
905− Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
1102+ Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
906− Left err -> throwE err
1103+ Left err -> throwError err
1105+verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
907−verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
1106+ lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
908−verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
1107+verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
909− rstate <- ask
1108+ context <- gfDatabaseContextForMarker tid
910 let functions = atomFunctions context
1109 let functions = atomFunctions context
911− context = stateElemsContext rstate
913− func <- either throwE pure (atomFunctionForName funcName functions)
1110+ func <- lift $ except $ atomFunctionForName funcName functions
914− let expectedArgTypes = atomFuncType func
1111+ let expectedArgTypes = atomFuncType func
915− funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
1112+ funcArgVerifier (atomExpr, expectedType2, argCount) = do
1113+ let handler :: RelationalError -> GraphRefRelationalExprM AtomType
916− Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
1114+ handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
917− Left err -> throwE err
1115+ handler err = throwError err
918− Right x -> pure x
1116+ verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
919− ) $ zip3 funcArgExprs expectedArgTypes [1..]
1117+ funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
920− if length funcArgTypes /= length expectedArgTypes - 1 then
1118+ if length funcArgTypes /= length expectedArgTypes - 1 then
921− throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
1119+ throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
923− either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
1121+ lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
924−verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
1122+verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
925− rstate <- lift ask
1123+ do
926− relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
1124+ let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
1125+ relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
927− either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
1126+ lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
928−verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
1127+verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
929− cType <- liftE (typeFromAtomExpr (attributes rel) cons)
1128+ cType <- typeForGraphRefAtomExpr (attributes rel) cons
930− either throwE pure (atomTypeVerify expectedType cType)
1129+ lift $ except $ atomTypeVerify expectedType cType
932-- | Look up the type's name and create a new attribute.
1131-- | Look up the type's name and create a new attribute.
933−evalAttrExpr :: TypeConstructorMapping -> AttributeExpr -> Either RelationalError Attribute
1132+evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
934−evalAttrExpr aTypes (AttributeAndTypeNameExpr attrName tCons ()) = do
1133+evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
1134+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
935− aType <- atomTypeForTypeConstructorValidate True tCons aTypes M.empty
1135+ aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
936− validateAtomType aType aTypes
1136+ lift $ except $ validateAtomType aType tConsMap
937− Right (Attribute attrName aType)
1137+ pure $ Attribute attrName aType
939−evalAttrExpr _ (NakedAttributeExpr attr) = Right attr
1139+evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
941−evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
1141+-- 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
1142+evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
1143+evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
1144+evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
1145+ tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
1146+ finalAttrs <- case mAttrs of
1147+ Just attrs -> pure attrs
1150+ [] -> pure emptyAttributes
1151+ (headTuple:tailTuples) -> do
1152+ --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])
1153+ let mostResolvedTypes =
1155+ fmap (\(tupAttr,accAttr) -> --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
1156+ if isResolvedAttribute accAttr then
1159+ case resolveAttributes accAttr tupAttr of
1161+ Right val -> val) (zip (V.toList $ tupleAttributes tup) acc)) (V.toList $ tupleAttributes headTuple) tailTuples
1162+ pure (A.attributesFromList mostResolvedTypes)
1163+ --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
1164+ tConsMap <- case singularTransactions tupleExprL of
1165+ SingularTransactionRef commonTransId ->
1166+ typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
1167+ NoTransactionsRef ->
1168+ typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
1169+ -- 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
1170+ _ -> throwError TupleExprsReferenceMultipleMarkersError
1171+ lift $ except $ validateAttributes tConsMap finalAttrs
1172+ mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
1175+--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
1177+evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
942−evalTupleExpr mAttrs (TupleExpr tupMap) = do
1178+evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
943− context <- fmap stateElemsContext ask
945 -- 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
1179 -- 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
946 -- 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
1180 -- 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
947− let attrs = fromMaybe A.emptyAttributes mAttrs
1181+ let attrs = fromMaybe A.emptyAttributes mAttrs
948− attrAtoms <- mapM (\(attrName, aExpr) -> do
1182+ resolveOneAtom (attrName, aExpr) =
949− --provided when the relation header is available
1184+ --provided when the relation header is available
950− let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
1185+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
951− unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
1186+ unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
952− resolvedType <- case eExpectedAtomType of
1187+ resolvedType <- case eExpectedAtomType of
953 Left _ -> pure unresolvedType
1188 Left _ -> pure unresolvedType
954− Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
1189+ Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
955 --resolve atom typevars based on resolvedType?
1190 --resolve atom typevars based on resolvedType?
956− newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
1191+ newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
957− pure (attrName, newAtom, resolvedType)
1192+ pure (attrName, newAtom, resolvedType)
958− ) (M.toList tupMap)
1193+ attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
959− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1194+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
960− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1195+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
961− tup = mkRelationTuple tupAttrs atoms
1196+ tup = mkRelationTuple tupAttrs atoms
962− tConss = typeConstructorMapping context
963− finalAttrs = fromMaybe tupAttrs mAttrs
1197+ finalAttrs = fromMaybe tupAttrs mAttrs
964 --verify that the attributes match
1198 --verify that the attributes match
965− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
1199+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1200+ --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
966− tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1201+ --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1202+ let tup' = reorderTuple finalAttrs tup
1203+ --TODO: restore type resolution
967− _ <- either throwE pure (validateTuple tup' tConss)
1204+-- _ <- lift $ except (validateTuple tup' tConss)
968− pure tup'
1205+ pure tup'
970−evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
1208+evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprM (Either RelationalError (S.Set AttributeName))
971evalAttributeNames attrNames expr = do
1209evalAttributeNames attrNames expr = do
972 eExprType <- typeForRelationalExpr expr
1210 eExprType <- typeForRelationalExpr expr
973 case eExprType of
1211 case eExprType of
974− Left err -> pure (Left err)
1212+ Left err -> throwError err
975 Right exprTyp -> do
1213 Right exprTyp -> do
976 let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1214 let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
977 case attrNames of
1215 case attrNames of
@@ -1014,4 +1252,278 @@ evalAttributeNames attrNames expr = do
1014 case eAttrExprType of
1252 case eAttrExprType of
1015 Left err -> pure (Left err)
1253 Left err -> pure (Left err)
1016 Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1254 Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1257+--temporary implementation until we have a proper planner+executor
1258+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1259+evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1260+ mAttrs <- case mAttrExprs of
1262+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1263+ Nothing -> pure Nothing
1264+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1265+ let attrs = fromMaybe firstTupleAttrs mAttrs
1266+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1267+ lift $ except $ mkRelation attrs (RelationTupleSet tuples)
1268+evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
1269+ lift $ except $ mkRelation attributeSet tupleSet
1270+evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1271+evalGraphRefRelationalExpr (RelationVariable name tid) = do
1272+ ctx <- gfDatabaseContextForMarker tid
1273+ case M.lookup name (relationVariables ctx) of
1274+ Nothing -> throwError (RelVarNotDefinedError name)
1275+ Just rv -> evalGraphRefRelationalExpr rv
1276+evalGraphRefRelationalExpr (Project attrNames expr) = do
1277+ attrNameSet <- evalGraphRefAttributeNames attrNames expr
1278+ rel <- evalGraphRefRelationalExpr expr
1279+ lift $ except $ project attrNameSet rel
1280+evalGraphRefRelationalExpr (Union exprA exprB) = do
1281+ relA <- evalGraphRefRelationalExpr exprA
1282+ relB <- evalGraphRefRelationalExpr exprB
1283+ lift $ except $ union relA relB
1284+evalGraphRefRelationalExpr (Join exprA exprB) = do
1285+ relA <- evalGraphRefRelationalExpr exprA
1286+ relB <- evalGraphRefRelationalExpr exprB
1287+ lift $ except $ join relA relB
1288+evalGraphRefRelationalExpr (Rename oldName newName expr) = do
1289+ rel <- evalGraphRefRelationalExpr expr
1290+ lift $ except $ rename oldName newName rel
1291+evalGraphRefRelationalExpr (Difference exprA exprB) = do
1292+ relA <- evalGraphRefRelationalExpr exprA
1293+ relB <- evalGraphRefRelationalExpr exprB
1294+ lift $ except $ difference relA relB
1295+evalGraphRefRelationalExpr (Group groupAttrNames newAttrName expr) = do
1296+ groupNames <- evalGraphRefAttributeNames groupAttrNames expr
1297+ rel <- evalGraphRefRelationalExpr expr
1298+ lift $ except $ group groupNames newAttrName rel
1299+evalGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1300+ rel <- evalGraphRefRelationalExpr expr
1301+ lift $ except $ ungroup groupAttrName rel
1302+evalGraphRefRelationalExpr (Restrict predExpr expr) = do
1303+ rel <- evalGraphRefRelationalExpr expr
1304+ filt <- predicateRestrictionFilter (attributes rel) predExpr
1305+ lift $ except $ restrict filt rel
1306+evalGraphRefRelationalExpr (Equals exprA exprB) = do
1307+ relA <- evalGraphRefRelationalExpr exprA
1308+ relB <- evalGraphRefRelationalExpr exprB
1309+ pure $ if relA == relB then relationTrue else relationFalse
1310+evalGraphRefRelationalExpr (NotEquals exprA exprB) = do
1311+ relA <- evalGraphRefRelationalExpr exprA
1312+ relB <- evalGraphRefRelationalExpr exprB
1313+ pure $ if relA == relB then relationFalse else relationTrue
1314+evalGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1315+ rel <- evalGraphRefRelationalExpr expr
1316+ (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1317+ lift $ except $ relMogrify tupProc newAttrs rel
1318+evalGraphRefRelationalExpr expr@With{} =
1319+ --strategy A: add relation variables to the contexts in the graph
1320+ --strategy B: drop in macros in place (easier programmatically)
1321+ --strategy B implementation
1322+ evalGraphRefRelationalExpr (substituteWithNameMacros [] expr)
1324+dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1325+dbContextForTransId tid graph = do
1326+ trans <- transactionForId tid graph
1327+ pure (concreteDatabaseContext trans)
1329+transactionForId :: TransactionId -> TransactionGraph -> Either RelationalError Transaction
1330+transactionForId tid graph
1332+ Left RootTransactionTraversalError
1333+ | S.null matchingTrans =
1334+ Left $ NoSuchTransactionError tid
1336+ Right $ head (S.toList matchingTrans)
1338+ matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
1340+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1341+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1342+typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1343+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1344+ mAttrs <- case mAttrExprs of
1345+ Just attrExprs -> do
1346+ attrs <- mapM evalGraphRefAttributeExpr attrExprs
1347+ pure (Just (attributesFromList attrs))
1348+ Nothing -> pure Nothing
1349+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1350+ let retAttrs = case tuples of
1351+ (tup:_) -> tupleAttributes tup
1352+ [] -> fromMaybe A.emptyAttributes mAttrs
1353+ pure $ emptyRelationWithAttrs retAttrs
1355+typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1356+ relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1357+ case M.lookup rvName relVars of
1358+ Nothing -> throwError (RelVarNotDefinedError rvName)
1360+ typeForGraphRefRelationalExpr rvExpr
1361+typeForGraphRefRelationalExpr (Project attrNames expr) = do
1362+ exprType' <- typeForGraphRefRelationalExpr expr
1363+ projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1364+ lift $ except $ project projectionAttrs exprType'
1365+typeForGraphRefRelationalExpr (Union exprA exprB) = do
1366+ exprA' <- typeForGraphRefRelationalExpr exprA
1367+ exprB' <- typeForGraphRefRelationalExpr exprB
1368+ lift $ except $ union exprA' exprB'
1369+typeForGraphRefRelationalExpr (Join exprA exprB) = do
1370+ exprA' <- typeForGraphRefRelationalExpr exprA
1371+ exprB' <- typeForGraphRefRelationalExpr exprB
1372+ lift $ except $ join exprA' exprB'
1373+typeForGraphRefRelationalExpr (Rename oldAttr newAttr expr) = do
1374+ expr' <- typeForGraphRefRelationalExpr expr
1375+ lift $ except $ rename oldAttr newAttr expr'
1376+typeForGraphRefRelationalExpr (Difference exprA exprB) = do
1377+ exprA' <- typeForGraphRefRelationalExpr exprA
1378+ exprB' <- typeForGraphRefRelationalExpr exprB
1379+ lift $ except $ difference exprA' exprB'
1380+typeForGraphRefRelationalExpr (Group groupNames attrName expr) = do
1381+ expr' <- typeForGraphRefRelationalExpr expr
1382+ groupNames' <- evalGraphRefAttributeNames groupNames expr
1383+ lift $ except $ group groupNames' attrName expr'
1384+typeForGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1385+ expr' <- typeForGraphRefRelationalExpr expr
1386+ lift $ except $ ungroup groupAttrName expr'
1387+typeForGraphRefRelationalExpr (Restrict pred' expr) = do
1388+ expr' <- typeForGraphRefRelationalExpr expr
1389+ filt <- predicateRestrictionFilter (attributes expr') pred'
1390+ lift $ except $ restrict filt expr'
1391+typeForGraphRefRelationalExpr Equals{} =
1393+typeForGraphRefRelationalExpr NotEquals{} =
1395+typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1396+ rel <- typeForGraphRefRelationalExpr expr
1397+ evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1398+typeForGraphRefRelationalExpr expr@(With withs _) = do
1399+ let expr' = substituteWithNameMacros [] expr
1400+ checkMacroName (WithNameExpr macroName tid) = do
1401+ rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1402+ case M.lookup macroName rvs of
1403+ Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1405+ mapM_ (checkMacroName . fst) withs
1406+ typeForGraphRefRelationalExpr expr'
1408+evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1409+evalGraphRefAttributeNames attrNames expr = do
1410+ exprType' <- typeForGraphRefRelationalExpr expr
1411+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1413+ AttributeNames names ->
1414+ case A.projectionAttributesForNames names (attributes exprType') of
1415+ Left err -> throwError err
1416+ Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1418+ InvertedAttributeNames names -> do
1419+ let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1420+ if not (S.null nonExistentAttributeNames) then
1421+ throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1423+ pure (A.nonMatchingAttributeNameSet names typeNameSet)
1425+ UnionAttributeNames namesA namesB -> do
1426+ nameSetA <- evalGraphRefAttributeNames namesA expr
1427+ nameSetB <- evalGraphRefAttributeNames namesB expr
1428+ pure (S.union nameSetA nameSetB)
1430+ IntersectAttributeNames namesA namesB -> do
1431+ nameSetA <- evalGraphRefAttributeNames namesA expr
1432+ nameSetB <- evalGraphRefAttributeNames namesB expr
1433+ pure (S.intersection nameSetA nameSetB)
1435+ RelationalExprAttributeNames attrExpr -> do
1436+ attrExprType <- typeForGraphRefRelationalExpr attrExpr
1437+ pure (A.attributeNameSet (attributes attrExprType))
1439+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1440+evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1441+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1442+ case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1443+ Left err -> throwError err
1445+ case validateAtomType aType tConsMap of
1446+ Left err -> throwError err
1447+ Right _ -> pure (Attribute attrName aType)
1448+evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1450+mkEmptyRelVars :: RelationVariables -> RelationVariables
1451+mkEmptyRelVars = M.map mkEmptyRelVar
1453+ mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1454+ mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1455+ mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1456+ mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
1457+ mkEmptyRelVar (Project attrNames expr) = Project attrNames (mkEmptyRelVar expr)
1458+ mkEmptyRelVar (Union exprA exprB) = Union (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1459+ mkEmptyRelVar (Join exprA exprB) = Join (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1460+ mkEmptyRelVar (Rename nameA nameB expr) = Rename nameA nameB (mkEmptyRelVar expr)
1461+ mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1462+ mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1463+ mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1464+ mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1465+ mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1466+ mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1467+ mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1468+ mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1471+dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1472+dbErr err = lift (except (Left err))
1474+-- | Return a Relation describing the relation variables.
1475+relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1476+relationVariablesAsRelation ctx graph = do
1477+ let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1478+ attrs = A.attributesFromList [Attribute "name" TextAtomType,
1479+ Attribute "attributes" (RelationAtomType subrelAttrs)]
1480+ relVars = relationVariables ctx
1481+ mkRvDesc (rvName, gfExpr) = do
1482+ let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1483+ gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1484+ pure (rvName, gfType)
1485+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributes rel)]
1486+ attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1487+ attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1488+ Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1489+ Right rel -> RelationAtom rel
1490+ rvs <- mapM mkRvDesc (M.toList relVars)
1491+ let tups = map relVarToAtomList rvs
1492+ mkRelationFromList attrs tups
1494+-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1495+evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1496+evalRelationalExpr expr = do
1498+ context <- reContext
1499+ let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1500+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1501+ case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1502+ Left err -> throwError err
1503+ Right rel -> pure rel
1506+relVarByName :: RelVarName -> GraphRefRelationalExprM GraphRefRelationalExpr
1508+ relvars <- relationVariables <$> getStateContext
1509+ case M.lookup relVarName relvars of
1510+ Nothing -> dbErr (RelVarNotDefinedError relVarName)
1511+ Just gfexpr -> pure gfExpr
1514+class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1515+ getContext :: m DatabaseContext
1517+instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1518+ getContext = gfDatabaseContextForMarker UncommittedContextMarker
1520+instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1521+ getContext = getStateContext
1523+relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1524+relVarByName rvName = do
1525+ relvars <- relationVariables <$> getContext
1526+ case M.lookup rvName relvars of
1527+ Nothing -> throwError (RelVarNotDefinedError rvName)
1528+ Just gfexpr -> pure gfexpr