@@ -1,4 +1,7 @@
1{-# LANGUAGE ScopedTypeVariables #-}
1{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE OverloadedStrings #-}
2module ProjectM36.RelationalExpression where
5module ProjectM36.RelationalExpression where
3import ProjectM36.Relation
6import ProjectM36.Relation
4import ProjectM36.Tuple
7import ProjectM36.Tuple
@@ -13,27 +16,38 @@ import ProjectM36.DataTypes.Primitive
13import ProjectM36.AtomFunction
16import ProjectM36.AtomFunction
14import ProjectM36.DatabaseContextFunction
17import ProjectM36.DatabaseContextFunction
15import ProjectM36.Arbitrary
18import ProjectM36.Arbitrary
19+import ProjectM36.GraphRefRelationalExpr
16import ProjectM36.Transaction
20import ProjectM36.Transaction
17import qualified ProjectM36.Attribute as A
21import qualified ProjectM36.Attribute as A
18import qualified Data.Map as M
22import qualified Data.Map as M
19import qualified Data.HashSet as HS
23import qualified Data.HashSet as HS
20import qualified Data.Set as S
24import qualified Data.Set as S
21import Control.Monad.State hiding (join)
25import Control.Monad.State hiding (join)
22−import Control.Exception
26+import Data.Bifunctor (second)
23import Data.Maybe
27import Data.Maybe
24import Data.Either
28import Data.Either
25import Data.Char (isUpper)
29import Data.Char (isUpper)
31+import qualified Data.List.NonEmpty as NE
32+import Data.Functor.Identity
26import qualified Data.Text as T
33import qualified Data.Text as T
27import qualified Data.Vector as V
34import qualified Data.Vector as V
28import qualified ProjectM36.TypeConstructorDef as TCD
35import qualified ProjectM36.TypeConstructorDef as TCD
29−import Control.Monad.Trans.Except
36+import qualified Control.Monad.RWS.Strict as RWS
37+import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
38+import Control.Monad.Except hiding (join)
30−import Control.Monad.Trans.Reader
39+import Control.Monad.Trans.Except (except)
40+import Control.Monad.Reader as R hiding (join)
41+import ProjectM36.NormalizeExpr
42+import ProjectM36.WithNameExpr
31import Test.QuickCheck
43import Test.QuickCheck
32−import GHC
44+import qualified Data.Functor.Foldable as Fold
45+import Control.Applicative
46+#ifdef PM36_HASKELL_SCRIPTING
47+import GHC hiding (getContext)
48+import Control.Exception
33import GHC.Paths
49import GHC.Paths
34−import Data.Time.Clock
50+#endif
35−import Data.Time.Calendar
36−import qualified Data.List.NonEmpty as NE
38data DatabaseContextExprDetails = CountUpdatedTuples
52data DatabaseContextExprDetails = CountUpdatedTuples
@@ -50,60 +64,63 @@ databaseContextExprDetailsFunc CountUpdatedTuples _ relIn = Relation attrs newTu
50 Right ts -> ts
64 Right ts -> ts
52-- | Used to start a fresh database state for a new database context expression.
66-- | Used to start a fresh database state for a new database context expression.
53−freshDatabaseState :: DatabaseContext -> DatabaseStateElems
67+mkDatabaseContextEvalState :: DatabaseContext -> DatabaseContextEvalState
54−freshDatabaseState context = DatabaseStateElems {
68+mkDatabaseContextEvalState context = DatabaseContextEvalState {
55− context = context,
69+ dbc_context = context,
56− accum = M.empty,
70+ dbc_accum = M.empty,
57− dirty = False
71+ dbc_dirty = False
58 } --future work: propagate return accumulator
72 } --future work: propagate return accumulator
60-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
74-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
61−data RelationalExprStateElems = RelationalExprStateElems {
75+data RelationalExprEnv = RelationalExprEnv {
62− elems_context :: DatabaseContext,
76+ re_context :: DatabaseContext,
63− elems_graph :: TransactionGraph,
77+ re_graph :: TransactionGraph,
64− elems_currentTransId :: TransactionId,
65− elems_extra :: Maybe (Either RelationTuple Attributes)
78+ re_extra :: Maybe (Either RelationTuple Attributes)
68−stateTuple :: RelationalExprStateElems -> RelationTuple
81+envTuple :: GraphRefRelationalExprEnv -> RelationTuple
69−stateTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (elems_extra e))
82+envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
71−stateAttributes :: RelationalExprStateElems -> Attributes
84+envAttributes :: GraphRefRelationalExprEnv -> Attributes
72−stateAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (elems_extra e))
85+envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
74−data RelationalExprStateElems = RelationalExprStateTupleElems DatabaseContext RelationTuple | -- used when fully evaluating a relexpr
75− RelationalExprStateAttrsElems DatabaseContext Attributes | --used when evaluating the type of a relexpr
76− RelationalExprStateElems DatabaseContext --used by default at the top level of evaluation
79−instance Show RelationalExprStateElems where show e@RelationalExprStateElems{} = "RelationalExprStateElems " ++ show (elems_extra e)
87+instance Show RelationalExprEnv where
80−
88+ show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
81−mkRelationalExprState :: DatabaseContext -> TransactionId -> TransactionGraph -> RelationalExprStateElems
89+
82−mkRelationalExprState ctx currentTransId graph =
90+--used to eval relationalexpr
83− RelationalExprStateElems
91+type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
84− { elems_context = ctx,
92+
85− elems_graph = graph,
93+runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
86− elems_currentTransId = currentTransId,
94+runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
87− elems_extra = Nothing }
95+
88−
96+reGraph :: RelationalExprM TransactionGraph
89−currentTrans :: RelationalExprState (Either RelationalError Transaction)
97+reGraph = asks re_graph
91− tid <- elems_currentTransId <$> ask
99+reContext :: RelationalExprM DatabaseContext
92− graph <- elems_graph <$> ask
100+reContext = asks re_context
93− pure (transactionForId tid graph)
101+
94−
102+mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
95−mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprStateElems -> RelationalExprStateElems
103+mkRelationalExprEnv ctx graph =
96−mergeTuplesIntoRelationalExprState tupIn e@RelationalExprStateElems{} =
104+ RelationalExprEnv
107+ re_extra = Nothing }
109+askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
112+mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
113+mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
97− e{elems_extra = new_elems }
114+ env { gre_extra = new_elems }
99 new_elems = Just (Left newTuple)
116 new_elems = Just (Left newTuple)
100− mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (stateTuple e))
117+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
101 newTuple = mkRelationTupleFromMap mergedTupMap
118 newTuple = mkRelationTupleFromMap mergedTupMap
103−mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprStateElems -> RelationalExprStateElems
120+mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
104−mergeAttributesIntoRelationalExprState attrsIn e@RelationalExprStateElems{} = e{elems_extra = newattrs }
121+mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
106− newattrs = Just (Right (A.union attrsIn (stateAttributes e)))
123+ newattrs = Just (Right (A.union attrsIn (envAttributes e)))
108type ResultAccumName = StringType
125type ResultAccumName = StringType
@@ -113,440 +130,403 @@ data ResultAccum = ResultAccum { resultAccumFunc :: ResultAccumFunc,
113 resultAccumResult :: Relation
130 resultAccumResult :: Relation
116−data DatabaseStateElems = DatabaseStateElems {
133+data DatabaseContextEvalState = DatabaseContextEvalState {
117− context :: DatabaseContext, --new, alterable context for a new transaction
134+ dbc_context :: DatabaseContext, --new, alterable context for a new transaction
118− accum :: M.Map ResultAccumName ResultAccum,
135+ dbc_accum :: M.Map ResultAccumName ResultAccum,
119− dirty :: DirtyFlag
136+ dbc_dirty :: DirtyFlag
139+data DatabaseContextEvalEnv = DatabaseContextEvalEnv
140+ { dce_transId :: TransactionId,
141+ dce_graph :: TransactionGraph
122−type DatabaseState a = State DatabaseStateElems a
144+mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
145+mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
147+type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
149+runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
150+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
152+ freshEnv = mkDatabaseContextEvalState ctx
155+dbcTransId :: DatabaseContextEvalMonad TransactionId
156+dbcTransId = dce_transId <$> RWS.ask
158+dbcGraph :: DatabaseContextEvalMonad TransactionGraph
159+dbcGraph = dce_graph <$> RWS.ask
161+dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
162+dbcRelationalExprEnv =
163+ mkRelationalExprEnv <$> getStateContext <*> dbcGraph
124−getStateContext :: DatabaseState DatabaseContext
165+getStateContext :: DatabaseContextEvalMonad DatabaseContext
125−getStateContext = context <$> get
166+getStateContext = gets dbc_context
127−putStateContext :: DatabaseContext -> DatabaseState ()
168+putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
128putStateContext ctx' = do
169putStateContext ctx' = do
130− put (s {context = ctx'})
171+ put (s {dbc_context = ctx', dbc_dirty = True})
132−type RelationalExprState a = Reader RelationalExprStateElems a
173+-- | The context is optionally passed down along in cases where the current context is uncommitted.
133−
174+data GraphRefRelationalExprEnv =
134−stateElemsContext :: RelationalExprStateElems -> DatabaseContext
175+ GraphRefRelationalExprEnv {
135−stateElemsContext = elems_context
176+ gre_context :: Maybe DatabaseContext,
136−
177+ gre_graph :: TransactionGraph,
137−setStateElemsContext :: RelationalExprStateElems -> DatabaseContext -> RelationalExprStateElems
178+ gre_extra :: Maybe (Either RelationTuple Attributes)
138−setStateElemsContext e ctx = e { elems_context = ctx }
179+ }
140−--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
141−evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
142−evalRelationalExpr (RelationVariable name _) = do
143− relvarTable <- fmap (relationVariables . stateElemsContext) ask
144− return $ case M.lookup name relvarTable of
145− Just res -> Right res
146− Nothing -> Left $ RelVarNotDefinedError name
148−evalRelationalExpr (Project attrNames expr) = do
149− eAttrNameSet <- evalAttributeNames attrNames expr
150− case eAttrNameSet of
151− Left err -> pure (Left err)
152− Right attrNameSet -> do
153− rel <- evalRelationalExpr expr
155− Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
156− Left err -> pure $ Left err
158−evalRelationalExpr (Union exprA exprB) = do
159− relA <- evalRelationalExpr exprA
160− relB <- evalRelationalExpr exprB
162− Left err -> return $ Left err
163− Right relA2 -> case relB of
164− Left err -> return $ Left err
165− Right relB2 -> return $ Right (Union relA2 relB2)
167−evalRelationalExpr (Join exprA exprB) = do
168− relA <- evalRelationalExpr exprA
169− relB <- evalRelationalExpr exprB
171− Left err -> return $ Left err
172− Right relA2 -> case relB of
173− Left err -> return $ Left err
174− Right relB2 -> return $ Right (Join relA2 relB2)
176−evalRelationalExpr (Difference exprA exprB) = do
177− relA <- evalRelationalExpr exprA
178− relB <- evalRelationalExpr exprB
180− Left err -> return $ Left err
181− Right relA2 -> case relB of
182− Left err -> return $ Left err
183− Right relB2 -> return $ Right (Difference relA2 relB2)
185−evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
186− case mkRelation attributeSet tupleSet of
187− Right rel -> return $ Right (ExistingRelation rel)
188− Left err -> return $ Left err
190−evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
191− currentContext <- fmap stateElemsContext ask
192− let tConss = typeConstructorMapping currentContext
193− -- if the mAttrExprs is Nothing, then we should attempt to infer the tuple attributes from the first tuple itself- note that this is not always possible
195− mAttrs <- case mAttrExprs of
197− Just . A.attributesFromList <$> mapM (either throwE pure . evalAttrExpr tConss) (fromMaybe [] mAttrExprs)
198− Nothing -> pure Nothing
199− tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
200− let attrs = fromMaybe firstTupleAttrs mAttrs
201− firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
202− expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
203− pure (ExistingRelation expr)
205−evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
181+type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
183+gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
184+gfTransForId tid = do
186+ lift $ except $ transactionForId tid graph
188+gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
189+gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
190+gfDatabaseContextForMarker UncommittedContextMarker = do
191+ mctx <- gre_context <$> askEnv
193+ Nothing -> throwError NoUncommittedContextInEvalError
194+ Just ctx -> pure ctx
196+runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
197+runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
199+freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
200+freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
207−evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
206+gfGraph :: GraphRefRelationalExprM TransactionGraph
208− evald <- evalRelationalExpr relExpr
207+gfGraph = asks gre_graph
210− Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
211− Left err -> return $ Left err
213−evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
209+envContext :: RelationalExprEnv -> DatabaseContext
214− eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
210+envContext = re_context
215− case eOldAttrNameSet of
211+
216− Left err -> pure (Left err)
212+setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
217− Right oldAttrNameSet -> do
213+setEnvContext e ctx = e { re_context = ctx }
218− evald <- evalRelationalExpr relExpr
220− Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
221− Left err -> return $ Left err
223−evalRelationalExpr (Ungroup attrName relExpr) = do
224− evald <- evalRelationalExpr relExpr
226− Right expr -> return $ Right (Ungroup attrName expr)
227− Left err -> return $ Left err
229−evalRelationalExpr (Restrict predicateExpr relExpr) = do
230− evald <- evalRelationalExpr relExpr
231− ePred <- processRestrictionPredicateExpr predicateExpr
233− Left err -> return $ Left err
234− Right expr -> case ePred of
235− Left err -> pure (Left err)
236− Right pred -> pure $ Right (Restrict pred expr)
238−evalRelationalExpr (Equals relExprA relExprB) = do
239− evaldA <- evalRelationalExpr relExprA
240− evaldB <- evalRelationalExpr relExprB
242− Left err -> return $ Left err
243− Right exprA -> case evaldB of
244− Left err -> return $ Left err
245− Right exprB -> return $ Right (Equals exprA exprB)
247−evalRelationalExpr (With views mainExpr) = do
250− let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
251− Left (RelVarAlreadyDefinedError vname)
253− case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
254− (Left err,_) -> Left err
255− (Right (), (ctx',_,_)) -> Right ctx'
257− case foldM addScopedView (stateElemsContext rstate) views of
258− Left err -> return $ Left err
260− let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprStateElems ctx'')
261− case evalMainExpr mainExpr of
262− Left err -> return $ Left err
263− Right rel -> return $ Right rel
265−--warning: copy-pasta from above- refactor
266−evalRelationalExpr (NotEquals relExprA relExprB) = do
267− evaldA <- evalRelationalExpr relExprA
268− evaldB <- evalRelationalExpr relExprB
270− Left err -> return $ Left err
271− Right exprA -> case evaldB of
272− Left err -> return $ Left err
273− Right exprB -> return $ Right (NotEquals exprA exprB)
275−-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
276−evalRelationalExpr (Extend tupleExpression relExpr) = do
277− eExpr <- evalRelationalExpr relExpr
279− Left err -> pure (Left err)
281− eTupProc <- processExtendTupleExpr tupleExpression
283− Left err -> pure (Left err)
284− Right tupProc -> pure (Right (Extend tupProc expr))
286--helper function to process relation variable creation/assignment
215--helper function to process relation variable creation/assignment
287−setRelVar :: RelVarName -> GraphRefRelationalExpr -> TransactionId -> TransactionGraph -> DatabaseState (Either RelationalError ())
216+setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
288−setRelVar relVarName relExpr transId graph = do
217+setRelVar relVarName relExpr = do
289 currentContext <- getStateContext
218 currentContext <- getStateContext
219+ --prevent recursive relvar definition by resolving references to relvars in previous states
220+ relExpr' <- resolve relExpr
290− let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
221+ let newRelVars = M.insert relVarName relExpr' $ relationVariables currentContext
291 potentialContext = currentContext { relationVariables = newRelVars }
222 potentialContext = currentContext { relationVariables = newRelVars }
223+ --optimization: if the relexpr is unchanged, skip the update
224+ if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
292− --determine when to check constraints
227+ --determine when to check constraints
293−
228+ graph <- dbcGraph
294− case checkConstraints potentialContext transId graph of
230+ case checkConstraints potentialContext tid graph of
295− Left err -> pure (Left err)
231+ Left err -> dbErr err
297− putStateContext potentialContext
232+ Right _ -> putStateContext potentialContext
298− return (Right ())
233+
234+--fast-path insertion- we already know that the previous relvar validated correctly, so we can validate just the relation that is being inserted for attribute matches- without this, even a single tuple relation inserted causes the entire relation to be re-validated unnecessarily
235+--insertIntoRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
300-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
237-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
301−deleteRelVar :: RelVarName -> DatabaseState (Either RelationalError ())
238+deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
302deleteRelVar relVarName = do
239deleteRelVar relVarName = do
303 currContext <- getStateContext
240 currContext <- getStateContext
304 let relVars = relationVariables currContext
241 let relVars = relationVariables currContext
305 if M.notMember relVarName relVars then
242 if M.notMember relVarName relVars then
306− pure (Right ())
243+ pure ()
308 let newRelVars = M.delete relVarName relVars
245 let newRelVars = M.delete relVarName relVars
309 newContext = currContext { relationVariables = newRelVars }
246 newContext = currContext { relationVariables = newRelVars }
310 putStateContext newContext
247 putStateContext newContext
311− pure (Right ())
248+ pure ()
313−evalDatabaseContextExpr :: DatabaseContextExpr -> TransactionId -> TransactionGraph -> DatabaseState (Either RelationalError ())
250+evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContextEvalMonad ()
314−evalDatabaseContextExpr NoOperation _ _ = pure (Right ())
251+evalGraphRefDatabaseContextExpr NoOperation = pure ()
316−evalDatabaseContextExpr (Define relVarName attrExprs) transId graph = do
253+evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
254+ context <- getStateContext
317 relvars <- fmap relationVariables getStateContext
255 relvars <- fmap relationVariables getStateContext
318 tConss <- fmap typeConstructorMapping getStateContext
256 tConss <- fmap typeConstructorMapping getStateContext
319− let eAttrs = map (evalAttrExpr tConss) attrExprs
257+ graph <- dbcGraph
320− attrErrs = lefts eAttrs
258+ let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
321− attrsList = rights eAttrs
259+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
322− if not (null attrErrs) then
260+ case eAttrs of
323− pure (Left (someErrors attrErrs))
261+ Left err -> dbErr err
324− else do
262+ Right attrsList -> do
325− let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
263+ lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
326− if not (null atomTypeErrs) then
327− pure (Left (someErrors atomTypeErrs))
329− case M.member relVarName relvars of
264+ case M.member relVarName relvars of
330− True -> pure (Left (RelVarAlreadyDefinedError relVarName))
265+ True -> dbErr (RelVarAlreadyDefinedError relVarName)
331− False -> setRelVar relVarName (ExistingRelation emptyRelation) transId graph >> pure (Right ())
266+ False -> setRelVar relVarName (ExistingRelation emptyRelation)
333 attrs = A.attributesFromList attrsList
268 attrs = A.attributesFromList attrsList
334 emptyRelation = Relation attrs emptyTupleSet
269 emptyRelation = Relation attrs emptyTupleSet
336−evalDatabaseContextExpr (Undefine relVarName) _ _ = deleteRelVar relVarName
271+evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
338−evalDatabaseContextExpr (Assign relVarName expr) transId graph = do
273+evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
274+ graph <- re_graph <$> dbcRelationalExprEnv
339 context <- getStateContext
275 context <- getStateContext
340 let existingRelVar = M.lookup relVarName (relationVariables context)
276 let existingRelVar = M.lookup relVarName (relationVariables context)
341− relExprState = mkRelationalExprState context transId graph
277+ reEnv = freshGraphRefRelationalExprEnv (Just context) graph
278+ eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
342 case existingRelVar of
279 case existingRelVar of
343 Nothing -> do
280 Nothing -> do
344− let ervExpr = runReader (evalRelationalExpr expr) relExprState
281+ case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
346− Left err -> pure (Left err)
282+ Left err -> dbErr err
284+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
347− Right rvExpr -> setRelVar relVarName rvExpr transId graph
285+ setRelVar relVarName expr
348 Just existingRel -> do
286 Just existingRel -> do
349− let eExpectedType = runReader (typeForGraphRefRelationalExpr existingRel) (mkRelationalExprState context transId graph)
287+ let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
350− eNewExprType = runReader (typeForRelationalExpr expr) relExprState
351 case eExpectedType of
288 case eExpectedType of
352− Left err -> pure (Left err)
289+ Left err -> dbErr err
353 Right expectedType ->
290 Right expectedType ->
354 case eNewExprType of
291 case eNewExprType of
355− Left err -> pure (Left err)
292+ Left err -> dbErr err
356 Right newExprType -> do
293 Right newExprType -> do
357 if newExprType == expectedType then do
294 if newExprType == expectedType then do
358− let ervExpr = runReader (evalRelationalExpr expr) relExprState
295+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
360− Left err -> pure (Left err)
361− Right rvExpr -> setRelVar relVarName rvExpr transId graph
296+ setRelVar relVarName expr
363− pure (Left (RelationTypeMismatchError (attributes expectedType) (attributes newExprType)))
298+ dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
365−evalDatabaseContextExpr (Insert relVarName relExpr) tid graph =
300+evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
366− evalDatabaseContextExpr (Assign relVarName (Union (RelationVariable relVarName ())
301+ gfExpr <- relVarByName relVarName
367− relExpr)) tid graph
302+ let optExpr = applyUnionCollapse (Union
305+ evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
369−evalDatabaseContextExpr (Delete relVarName predicate) transId graph = do
307+evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
370− ctx <- getStateContext
308+ gfExpr <- relVarByName relVarName
371− let rv = RelationVariable relVarName transId
309+ let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
372− rvState = mkRelationalExprState ctx transId graph
310+ setRelVar relVarName optExpr
373− case runReader (processRestrictionPredicateExpr predicate) rvState of
374− Left err -> pure (Left err)
375− Right graphRefPredicate ->
376− setRelVar relVarName (Restrict (NotPredicate graphRefPredicate) rv) transId graph
378--union of restricted+updated portion and the unrestricted+unupdated portion
312--union of restricted+updated portion and the unrestricted+unupdated portion
379−evalDatabaseContextExpr (Update relVarName atomExprMap restrictionPredicateExpr) transId graph = do
313+evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
314+ rvExpr <- relVarByName relVarName
315+ graph <- re_graph <$> dbcRelationalExprEnv
380 context <- getStateContext
316 context <- getStateContext
381− let rvState = mkRelationalExprState context transId graph
317+ let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
382− relVarTable = relationVariables context
318+ --get the current attributes name in the relvar to ensure that we don't conflict when renaming
383− case runReader (processRestrictionPredicateExpr restrictionPredicateExpr) rvState of
319+ eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
320+ exprType' <- case eExprType of
384− Left err -> pure (Left err)
321+ Left err -> throwError err
385− Right graphRefPredicate ->
322+ Right t -> pure t
386− case M.lookup relVarName relVarTable of
387− Nothing -> pure (Left (RelVarNotDefinedError relVarName))
388− Just existingRvExpr -> do
389− let unrestrictedPortion = Restrict (NotPredicate graphRefPredicate) rv
323+ let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
390− rv = RelationVariable relVarName transId
324+ tmpAttr = tmpAttrC 1
391− tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
325+ tmpAttrC :: Int -> AttributeName -> AttributeName
327+ let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
328+ if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
392− updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
332+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
393− projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
333+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
394− restrictedPortion = Restrict graphRefPredicate
334+ restrictedPortion = Restrict pred' rvExpr
395− updated = foldr (\(oldname, atomExpr) accum ->
335+ updated = foldr (\(oldname, atomExpr) accum ->
396− let procAtomExpr = runReader (processAtomExpr atomExpr) rvState in
336+ let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
397 updateAttr oldname procAtomExpr accum
337 updateAttr oldname procAtomExpr accum
398− ) rv (M.toList atomExprMap)
338+ ) restrictedPortion (M.toList atomExprMap)
399 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
339 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
400− updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
340+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
401− setRelVar relVarName (Union unrestrictedPortion updatedPortion) transId graph
341+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
403−evalDatabaseContextExpr (AddInclusionDependency newDepName newDep) transId graph = do
343+evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
404 currContext <- getStateContext
344 currContext <- getStateContext
345+ transId <- dbcTransId
405 let currDeps = inclusionDependencies currContext
347 let currDeps = inclusionDependencies currContext
406 newDeps = M.insert newDepName newDep currDeps
348 newDeps = M.insert newDepName newDep currDeps
407 if M.member newDepName currDeps then
349 if M.member newDepName currDeps then
408− pure (Left (InclusionDependencyNameInUseError newDepName))
350+ dbErr (InclusionDependencyNameInUseError newDepName)
410 let potentialContext = currContext { inclusionDependencies = newDeps }
352 let potentialContext = currContext { inclusionDependencies = newDeps }
353+ -- if the potential context passes all constraints, then save it
354+ -- potential optimization: validate only the new constraint- all old constraints must already hold
411 case checkConstraints potentialContext transId graph of
355 case checkConstraints potentialContext transId graph of
412− Left err -> pure (Left err)
356+ Left err -> dbErr err
413− Right _ -> do
357+ Right _ ->
414 putStateContext potentialContext
358 putStateContext potentialContext
417−evalDatabaseContextExpr (RemoveInclusionDependency depName) _ _ = do
360+evalGraphRefDatabaseContextExpr (RemoveInclusionDependency depName) = do
418 currContext <- getStateContext
361 currContext <- getStateContext
419 let currDeps = inclusionDependencies currContext
362 let currDeps = inclusionDependencies currContext
420 newDeps = M.delete depName currDeps
363 newDeps = M.delete depName currDeps
421 if M.notMember depName currDeps then
364 if M.notMember depName currDeps then
422− pure (Left (InclusionDependencyNameNotInUseError depName))
365+ dbErr (InclusionDependencyNameNotInUseError depName)
424 putStateContext $ currContext {inclusionDependencies = newDeps }
367 putStateContext $ currContext {inclusionDependencies = newDeps }
427-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
369-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
428−evalDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) _ _ = do
370+evalGraphRefDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
429 currentContext <- getStateContext
371 currentContext <- getStateContext
430 let nots = notifications currentContext
372 let nots = notifications currentContext
431 if M.member notName nots then
373 if M.member notName nots then
432− pure (Left (NotificationNameInUseError notName))
374+ dbErr (NotificationNameInUseError notName)
434 let newNotifications = M.insert notName newNotification nots
376 let newNotifications = M.insert notName newNotification nots
435 newNotification = Notification { changeExpr = triggerExpr,
377 newNotification = Notification { changeExpr = triggerExpr,
436 reportOldExpr = resultOldExpr,
378 reportOldExpr = resultOldExpr,
437 reportNewExpr = resultNewExpr}
379 reportNewExpr = resultNewExpr}
438 putStateContext $ currentContext { notifications = newNotifications }
380 putStateContext $ currentContext { notifications = newNotifications }
441−evalDatabaseContextExpr (RemoveNotification notName) _ _ = do
382+evalGraphRefDatabaseContextExpr (RemoveNotification notName) = do
442 currentContext <- getStateContext
383 currentContext <- getStateContext
443 let nots = notifications currentContext
384 let nots = notifications currentContext
444 if M.notMember notName nots then
385 if M.notMember notName nots then
445− pure (Left (NotificationNameNotInUseError notName))
386+ dbErr (NotificationNameNotInUseError notName)
447 let newNotifications = M.delete notName nots
388 let newNotifications = M.delete notName nots
448 putStateContext $ currentContext { notifications = newNotifications }
389 putStateContext $ currentContext { notifications = newNotifications }
451-- | Adds type and data constructors to the database context.
392-- | Adds type and data constructors to the database context.
452-- validate that the type *and* constructor names are unique! not yet implemented!
393-- validate that the type *and* constructor names are unique! not yet implemented!
453−evalDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) _ _ = do
394+evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
454 currentContext <- getStateContext
395 currentContext <- getStateContext
455 let oldTypes = typeConstructorMapping currentContext
396 let oldTypes = typeConstructorMapping currentContext
456 tConsName = TCD.name tConsDef
397 tConsName = TCD.name tConsDef
457 -- validate that the constructor's types exist
398 -- validate that the constructor's types exist
458− case validateTypeConstructorDef tConsDef dConsDefList of
399+ case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
459− errs@(_:_) -> pure (Left (someErrors errs))
400+ Left err -> throwError err
460− [] | T.null tConsName || not (isUpper (T.head tConsName)) -> pure (Left (InvalidAtomTypeName tConsName))
401+ Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
461− | isJust (findTypeConstructor tConsName oldTypes) -> pure (Left (AtomTypeNameInUseError tConsName))
402+ | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
462 | otherwise -> do
403 | otherwise -> do
463 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
404 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
464 putStateContext $ currentContext { typeConstructorMapping = newTypes }
405 putStateContext $ currentContext { typeConstructorMapping = newTypes }
467-- | 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.
407-- | 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.
468−evalDatabaseContextExpr (RemoveTypeConstructor tConsName) _ _ = do
408+evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
469 currentContext <- getStateContext
409 currentContext <- getStateContext
470 let oldTypes = typeConstructorMapping currentContext
410 let oldTypes = typeConstructorMapping currentContext
471 if isNothing (findTypeConstructor tConsName oldTypes) then
411 if isNothing (findTypeConstructor tConsName oldTypes) then
472− pure (Left (AtomTypeNameNotInUseError tConsName))
412+ dbErr (AtomTypeNameNotInUseError tConsName)
474 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
414 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
475 putStateContext $ currentContext { typeConstructorMapping = newTypes }
415 putStateContext $ currentContext { typeConstructorMapping = newTypes }
478−evalDatabaseContextExpr (MultipleExpr exprs) transId graph = do
417+evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
479 --the multiple expressions must pass the same context around- not the old unmodified context
418 --the multiple expressions must pass the same context around- not the old unmodified context
480− evald <- forM exprs (\expr -> evalDatabaseContextExpr expr transId graph)
419+ mapM_ evalGraphRefDatabaseContextExpr exprs
481− --some lifting magic needed here
420+
483− [] -> pure (Right ())
484− errs -> pure (Left (someErrors errs))
486−evalDatabaseContextExpr (RemoveAtomFunction funcName) _ _ = do
421+evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
487 currentContext <- getStateContext
422 currentContext <- getStateContext
488 let atomFuncs = atomFunctions currentContext
423 let atomFuncs = atomFunctions currentContext
489 case atomFunctionForName funcName atomFuncs of
424 case atomFunctionForName funcName atomFuncs of
490− Left err -> pure (Left err)
425+ Left err -> dbErr err
491− Right realFunc -> if isScriptedAtomFunction realFunc then do
427+ if isScriptedAtomFunction realFunc then do
492− let updatedFuncs = HS.delete realFunc atomFuncs
428+ let updatedFuncs = HS.delete realFunc atomFuncs
493− putStateContext (currentContext {atomFunctions = updatedFuncs })
429+ putStateContext (currentContext {atomFunctions = updatedFuncs })
496− pure (Left (PrecompiledFunctionRemoveError funcName))
431+ dbErr (PrecompiledFunctionRemoveError funcName)
498−evalDatabaseContextExpr (RemoveDatabaseContextFunction funcName) _ _ = do
433+evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
499 context <- getStateContext
434 context <- getStateContext
500 let dbcFuncs = dbcFunctions context
435 let dbcFuncs = dbcFunctions context
501 case databaseContextFunctionForName funcName dbcFuncs of
436 case databaseContextFunctionForName funcName dbcFuncs of
502− Left err -> pure (Left err)
437+ Left err -> dbErr err
503− Right realFunc -> if isScriptedDatabaseContextFunction realFunc then do
439+ if isScriptedDatabaseContextFunction realFunc then do
504− let updatedFuncs = HS.delete realFunc dbcFuncs
440+ let updatedFuncs = HS.delete realFunc dbcFuncs
505− putStateContext (context { dbcFunctions = updatedFuncs })
441+ putStateContext (context { dbcFunctions = updatedFuncs })
508− pure (Left (PrecompiledFunctionRemoveError funcName))
443+ dbErr (PrecompiledFunctionRemoveError funcName)
510−evalDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) transId graph = do
445+evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
511 context <- getStateContext
446 context <- getStateContext
512 --resolve atom arguments
448 --resolve atom arguments
513− let relExprState = mkRelationalExprState context transId graph
449+ let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
514− eAtomTypes = map (\atomExpr -> runReader (typeFromAtomExpr emptyAttributes atomExpr) relExprState) atomArgExprs
515 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
450 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
451+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
516 case eFunc of
452 case eFunc of
517− Left err -> pure (Left err)
453+ Left err -> dbErr err
518 Right func -> do
454 Right func -> do
519 let expectedArgCount = length (dbcFuncType func)
455 let expectedArgCount = length (dbcFuncType func)
520 actualArgCount = length atomArgExprs
456 actualArgCount = length atomArgExprs
521 if expectedArgCount /= actualArgCount then
457 if expectedArgCount /= actualArgCount then
522− pure (Left (FunctionArgumentCountMismatchError expectedArgCount actualArgCount))
458+ dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
524 --check that the atom types are valid
460 --check that the atom types are valid
525− case lefts eAtomTypes of
461+ case eAtomTypes of
526− _:_ -> pure (Left (someErrors (lefts eAtomTypes)))
462+ Left err -> dbErr err
527− [] -> do
463+ Right atomTypes -> do
528− let atomTypes = rights eAtomTypes
464+ let mValidTypes = zipWith (\ expType actType
529− let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
465+ -> case atomTypeVerify expType actType of
530− Left err -> Just err
466+ Left err -> Just err
531− Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
468+ (dbcFuncType func) atomTypes
532 typeErrors = catMaybes mValidTypes
469 typeErrors = catMaybes mValidTypes
533− eAtomArgs = unimplemented
470+ eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
534− --eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
535 if length (lefts eAtomArgs) > 1 then
471 if length (lefts eAtomArgs) > 1 then
536− pure (Left (someErrors (lefts eAtomArgs)))
472+ dbErr (someErrors (lefts eAtomArgs))
537 else if not (null typeErrors) then
473 else if not (null typeErrors) then
538− pure (Left (someErrors typeErrors))
474+ dbErr (someErrors typeErrors)
540 case evalDatabaseContextFunction func (rights eAtomArgs) context of
476 case evalDatabaseContextFunction func (rights eAtomArgs) context of
541− Left err -> pure (Left err)
477+ Left err -> dbErr err
542− Right newContext -> putStateContext newContext >> pure (Right ())
478+ Right newContext -> putStateContext newContext
543−
479+data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
544−evalDatabaseContextIOExpr :: Maybe ScriptSession -> DatabaseContext -> TransactionId -> TransactionGraph -> DatabaseContextIOExpr -> IO (Either RelationalError DatabaseContext)
480+ { dbcio_transId :: TransactionId,
481+ dbcio_graph :: TransactionGraph,
482+ dbcio_mScriptSession :: Maybe ScriptSession
485+type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
487+runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
488+runDatabaseContextIOEvalMonad env ctx m = do
489+ res <- runRWST m env freshState
491+ (Left err,_,_) -> pure (Left err)
492+ (Right (),s,_) -> pure (Right s)
494+ freshState = mkDatabaseContextEvalState ctx
496+requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
497+requireScriptSession = do
499+ case dbcio_mScriptSession env of
500+ Nothing -> pure $ Left $ ScriptError ScriptCompilationDisabledError
501+ Just ss -> pure (Right ss)
503+putDBCIOContext :: DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ())
504+putDBCIOContext ctx = do
505+ RWS.modify (\dbstate -> dbstate { dbc_context = ctx})
508+getDBCIOContext :: DatabaseContextIOEvalMonad DatabaseContext
509+getDBCIOContext = dbc_context <$> RWS.get
511+getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
512+getDBCIORelationalExprEnv = do
513+ context <- getDBCIOContext
514+ mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
516+evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
517+#if !defined(PM36_HASKELL_SCRIPTING)
518+evalGraphRefDatabaseContextIOExpr AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
519+evalGraphRefDatabaseContextIOExpr AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
520+evalGraphRefDatabaseContextIOExpr LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
521+evalGraphRefDatabaseContextIOExpr LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
545−evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddAtomFunction funcName funcType script) =
523+evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
546− case mScriptSession of
524+ eScriptSession <- requireScriptSession
547− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
525+ currentContext <- getDBCIOContext
526+ case eScriptSession of
527+ Left err -> pure (Left err)
548− Just scriptSession -> do
528+ Right scriptSession -> do
549− res <- try $ runGhc (Just libdir) $ do
529+ res <- liftIO $ try $ runGhc (Just libdir) $ do
550 setSession (hscEnv scriptSession)
530 setSession (hscEnv scriptSession)
551 let atomFuncs = atomFunctions currentContext
531 let atomFuncs = atomFunctions currentContext
552 case extractAtomFunctionType funcType of
532 case extractAtomFunctionType funcType of
@@ -572,12 +552,13 @@ evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddAtomFunction fun
572 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
552 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
573 Right eContext -> case eContext of
553 Right eContext -> case eContext of
574 Left err -> pure (Left err)
554 Left err -> pure (Left err)
575− Right context' -> pure (Right context')
555+ Right context' -> putDBCIOContext context'
577−evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddDatabaseContextFunction funcName funcType script) =
556+evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
578− case mScriptSession of
557+ eScriptSession <- requireScriptSession
579− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
558+ currentContext <- getDBCIOContext
559+ case eScriptSession of
560+ Left err -> pure (Left err)
580− Just scriptSession -> do
561+ Right scriptSession -> do
581 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
562 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
582 let last2Args = reverse (take 2 (reverse funcType))
563 let last2Args = reverse (take 2 (reverse funcType))
583 atomArgs = take (length funcType - 2) funcType
564 atomArgs = take (length funcType - 2) funcType
@@ -587,7 +568,7 @@ evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddDatabaseContextF
587 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
568 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
588 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
569 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
590− res <- try $ runGhc (Just libdir) $ do
571+ res <- liftIO $ try $ runGhc (Just libdir) $ do
591 setSession (hscEnv scriptSession)
572 setSession (hscEnv scriptSession)
592 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
573 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
593 pure $ case eCompiledFunc of
574 pure $ case eCompiledFunc of
@@ -612,79 +593,86 @@ evalDatabaseContextIOExpr mScriptSession currentContext _ _ (AddDatabaseContextF
612 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
593 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
613 Right eContext -> case eContext of
594 Right eContext -> case eContext of
614 Left err -> pure (Left err)
595 Left err -> pure (Left err)
615− Right context' -> pure (Right context')
596+ Right context' -> putDBCIOContext context'
616−evalDatabaseContextIOExpr _ currentContext _ _ (LoadAtomFunctions modName funcName modPath) = do
597+evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
598+ currentContext <- getDBCIOContext
617− eLoadFunc <- loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
599+ eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
618 case eLoadFunc of
600 case eLoadFunc of
619 Left LoadSymbolError -> pure (Left LoadFunctionError)
601 Left LoadSymbolError -> pure (Left LoadFunctionError)
620 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
602 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
621 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
603 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
622− in pure (Right newContext)
604+ in putDBCIOContext newContext
623−evalDatabaseContextIOExpr _ currentContext _ _ (LoadDatabaseContextFunctions modName funcName modPath) = do
605+evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName modPath) = do
606+ currentContext <- getDBCIOContext
624− eLoadFunc <- loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
607+ eLoadFunc <- liftIO $ loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
625 case eLoadFunc of
608 case eLoadFunc of
626 Left LoadSymbolError -> pure (Left LoadFunctionError)
609 Left LoadSymbolError -> pure (Left LoadFunctionError)
627 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
610 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
628 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
611 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
629− in pure (Right newContext)
612+ in putDBCIOContext newContext
631−evalDatabaseContextIOExpr _ currentContext transId graph (CreateArbitraryRelation relVarName attrExprs range) =
614+evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
633− case runState (evalDatabaseContextExpr (Define relVarName attrExprs) transId graph) (freshDatabaseState currentContext) of
616+ currentContext <- getDBCIOContext
618+ --create graph ref expr
619+ let gfExpr = Define relVarName attrExprs
620+ evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
621+ graph = dbcio_graph env
622+ case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
634− (Left err,_) -> pure (Left err)
623+ Left err -> pure (Left err)
635− (Right (), elems) -> do
624+ Right dbstate -> do
637 let existingRelVar = M.lookup relVarName relVarTable
626 let existingRelVar = M.lookup relVarName relVarTable
638− relVarTable = relationVariables (context elems)
627+ relVarTable = relationVariables (dbc_context dbstate)
639 case existingRelVar of
628 case existingRelVar of
640 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
641 Just existingRel -> do
630 Just existingRel -> do
631+ let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
642− case runReader (typeForGraphRefRelationalExpr existingRel) (mkRelationalExprState currentContext transId graph) of
632+ case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
643 Left err -> pure (Left err)
633 Left err -> pure (Left err)
644 Right relType -> do
634 Right relType -> do
645 let expectedAttributes = attributes relType
635 let expectedAttributes = attributes relType
646− tcMap = typeConstructorMapping (context elems)
636+ tcMap = typeConstructorMapping (dbc_context dbstate)
647− eitherRel <- generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
637+ eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
648 case eitherRel of
638 case eitherRel of
649 Left err -> pure $ Left err
639 Left err -> pure $ Left err
650 Right rel ->
640 Right rel ->
651− case runState (setRelVar relVarName (ExistingRelation rel) transId graph) elems of
641+ case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
652− (Left err,_) -> pure (Left err)
642+ Left err -> pure (Left err)
653− (Right (), elems') -> pure $ Right (context elems)
643+ Right dbstate' -> putDBCIOContext (dbc_context dbstate')
655−updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
656−updateTupleWithAtomExprs exprMap context graph tupIn = do
657− --resolve all atom exprs
658− atomsAssoc <- mapM (\(attrName, atomExpr) -> do
659− let atom = unimplemented
660− --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
661− pure (attrName, atom)
662− ) (M.toList exprMap)
663− pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
665--run verification on all constraints
645--run verification on all constraints
666checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
646checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
667−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
647+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
668 mapM_ (uncurry checkIncDep) (M.toList deps)
648 mapM_ (uncurry checkIncDep) (M.toList deps)
670 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
650 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
671 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
651 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
672 utctDayTime = secondsToDiffTime 0 }
652 utctDayTime = secondsToDiffTime 0 }
673 tempSchemas = Schemas context M.empty
653 tempSchemas = Schemas context M.empty
654+ tempTrans = Transaction U.nil tempTransInfo tempSchemas
674− tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
655+ tempTransInfo = TransactionInfo { parents = transId NE.:| [],
676 deps = inclusionDependencies context
660 deps = inclusionDependencies context
677− eval expr = evalReader (evalRelationalExpr expr)
661+ -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
678− evalReader f = runReader f (mkRelationalExprState context transId graph)
679 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
662 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
663+ let process = runProcessExprM UncommittedContextMarker
680− let gfSubsetExpr = evalReader (processRelationalExpr subsetExpr)
664+ gfSubsetExpr = process (processRelationalExpr subsetExpr)
681− gfSupersetExpr = evalReader (processRelationalExpr supersetExpr)
665+ gfSupersetExpr = process (processRelationalExpr supersetExpr)
682 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
666 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
683− typeSub <- evalReader (typeForRelationalExpr subsetExpr)
667+ let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
684− typeSuper <- evalReader (typeForRelationalExpr supersetExpr)
668+ runGfRel = runGraphRefRelationalExprM gfEnv
669+ typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
670+ typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
685 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
671 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
686 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
672 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
687− case evalGraphRefRelationalExpr checkExpr potentialGraph of
673+ gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
674+ gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
688 Left err -> Left err
676 Left err -> Left err
689 Right resultRel -> if resultRel == relationTrue then
677 Right resultRel -> if resultRel == relationTrue then
@@ -694,87 +682,81 @@ checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
694-- 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
682-- 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
695-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
683-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
697−typeForRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
685+typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
698typeForRelationalExpr expr = do
686typeForRelationalExpr expr = do
699 --replace the relationVariables context element with a cloned set of relation devoid of tuples
687 --replace the relationVariables context element with a cloned set of relation devoid of tuples
700 --evalRelationalExpr could still return an existing relation with tuples, so strip them
688 --evalRelationalExpr could still return an existing relation with tuples, so strip them
690+ context <- reContext
701− gfExpr <- processRelationalExpr expr
691+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
692+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
702− typeForGraphRefRelationalExpr gfExpr
693+ runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
703−
694+ lift $ except runGf
704−--returns a database context with all tuples removed
705−--this is useful for type checking and optimization
707−contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
708−contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
710− relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
713liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
696liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
714liftE v = do
697liftE v = do
715 y <- lift v
698 y <- lift v
716 case y of
699 case y of
717− Left err -> throwE err
700+ Left err -> throwError err
718 Right val -> pure val
701 Right val -> pure val
720{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
703{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
721−predicateRestrictionFilter :: Attributes -> RestrictionPredicateExprBase a -> RelationalExprState (Either RelationalError RestrictionFilter)
704+predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
722−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
705+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
724− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
706+ expr1v <- predicateRestrictionFilter attrs expr1
725− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
707+ expr2v <- predicateRestrictionFilter attrs expr2
726− pure (\x -> do
708+ pure (\x -> do
727− ev1 <- expr1v x
709+ ev1 <- expr1v x
728− ev2 <- expr2v x
710+ ev2 <- expr2v x
729− pure (ev1 && ev2))
711+ pure (ev1 && ev2))
731−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
713+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
733− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
714+ expr1v <- predicateRestrictionFilter attrs expr1
734− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
715+ expr2v <- predicateRestrictionFilter attrs expr2
735 pure (\x -> do
716 pure (\x -> do
736 ev1 <- expr1v x
717 ev1 <- expr1v x
737 ev2 <- expr2v x
718 ev2 <- expr2v x
738 pure (ev1 || ev2))
719 pure (ev1 || ev2))
740−predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
721+predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
742−predicateRestrictionFilter attrs (NotPredicate expr) =
723+predicateRestrictionFilter attrs (NotPredicate expr) = do
744− exprv <- liftE (predicateRestrictionFilter attrs expr)
724+ exprv <- predicateRestrictionFilter attrs expr
745− pure (fmap not . exprv)
725+ pure (fmap not . exprv)
747--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
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
749predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
728predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
750− rstate <- ask
729+ renv <- askEnv
751− pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
730+ let eval :: RelationTuple -> Either RelationalError Relation
732+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
733+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
734+ pure (\tup -> case eval tup of
752 Left err -> Left err
735 Left err -> Left err
753 Right rel -> if arity rel /= 0 then
736 Right rel -> if arity rel /= 0 then
754 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
737 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
756− pure (rel == relationTrue)))
739+ pure (rel == relationTrue))
758predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
741predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
759− rstate <- ask
742+ env <- askEnv
760− let attrs' = stateAttributes rstate
743+ let attrs' = A.union attrs (envAttributes env)
761− ctxtup' = stateTuple rstate
744+ ctxtup' = envTuple env
763− atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
745+ atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
764− attr <- either throwE pure $ case A.attributeForName attrName attrs of
746+ attr <- lift $ except $ case A.attributeForName attrName attrs of
765 Right attr -> Right attr
747 Right attr -> Right attr
766 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
748 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
767 Right ctxattr -> Right ctxattr
749 Right ctxattr -> Right ctxattr
768 Left err2@(NoSuchAttributeNamesError _) -> Left err2
750 Left err2@(NoSuchAttributeNamesError _) -> Left err2
769 Left err -> Left err
751 Left err -> Left err
770 Left err -> Left err
752 Left err -> Left err
771− if atomExprType /= A.atomType attr then
753+ if atomExprType /= A.atomType attr then
772− throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
754+ throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
774 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
756 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
775 Right atomCmp -> atomCmp == atomIn
757 Right atomCmp -> atomCmp == atomIn
776 Left _ -> False
758 Left _ -> False
777− atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
759+ atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
779 pure $ case atomForAttributeName attrName tupleIn of
761 pure $ case atomForAttributeName attrName tupleIn of
780 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
762 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -785,267 +767,322 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
785-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
767-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
786predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
768predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
787 --merge attrs into the state attributes
769 --merge attrs into the state attributes
788− rstate <- ask
770+ renv <- askEnv
790− aType <- liftE (typeFromAtomExpr attrs atomExpr)
771+ aType <- typeForGraphRefAtomExpr attrs atomExpr
791− if aType /= BoolAtomType then
772+ if aType /= BoolAtomType then
792− throwE (AtomTypeMismatchError aType BoolAtomType)
773+ throwError (AtomTypeMismatchError aType BoolAtomType)
794 pure (\tupleIn ->
775 pure (\tupleIn ->
795− case runReader (evalAtomExpr tupleIn atomExpr) rstate of
776+ case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
796− Left err -> Left err
777+ Left err -> Left err
797− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
778+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
799tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
780tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
800tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
781tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
801 Left (AttributeNameInUseError attrName)
782 Left (AttributeNameInUseError attrName)
803 Right rel
784 Right rel
805−extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
786+extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
806−extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
787+extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
807− rstate <- ask
788+-- renv <- askEnv
808 -- check that the attribute name is not in use
789 -- check that the attribute name is not in use
809 case tupleExprCheckNewAttrName newAttrName relIn of
790 case tupleExprCheckNewAttrName newAttrName relIn of
810− Left err -> pure (Left err)
791+ Left err -> throwError err
811− Right _ -> runExceptT $ do
792+ Right _ -> do
812− atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
793+ atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
813− atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
794+ atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
814 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
795 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
815 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
796 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
816− pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in
798+ pure (newAndOldAttrs, \tup -> do
817− case unimplemented {-runReader (evalAtomExpr tup atomExpr) substate-} of
799+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
818− Left err -> Left err
800+ atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
819− Right atom -> Right (tupleAtomExtend newAttrName atom tup)
801+ Right (tupleAtomExtend newAttrName atom tup)
822−
804+evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
823−evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
805+evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
824−evalAtomExpr = undefined
827−evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
806+ case atomForAttributeName attrName tupIn of
828− Right atom -> pure (Right atom)
807+ Right atom -> pure atom
829− err@(Left (NoSuchAttributeNamesError _)) -> do
808+ Left err@(NoSuchAttributeNamesError _) -> do
830− rstate <- ask
809+ env <- askEnv
831− let stateTup = stateTuple rstate
810+ case gre_extra env of
811+ Nothing -> throwError err
832− pure (atomForAttributeName attrName stateTup)
812+ Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
813+ Just (Right _) -> throwError err
833− Left err -> pure (Left err)
814+ Left err -> throwError err
834−evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
815+evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
835−evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
816+evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
836− argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
817+ argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
837− context <- fmap stateElemsContext ask
818+ context <- gfDatabaseContextForMarker tid
839− let functions = atomFunctions context
819+ let functions = atomFunctions context
840− func <- either throwE pure (atomFunctionForName funcName functions)
820+ func <- lift $ except (atomFunctionForName funcName functions)
841− let expectedArgCount = length (atomFuncType func) - 1
821+ let expectedArgCount = length (atomFuncType func) - 1
842− actualArgCount = length argTypes
822+ actualArgCount = length argTypes
843− safeInit [] = [] -- different behavior from normal init
823+ safeInit [] = [] -- different behavior from normal init
844− safeInit xs = init xs
824+ safeInit xs = init xs
845− if expectedArgCount /= actualArgCount then
825+ if expectedArgCount /= actualArgCount then
846− throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
826+ throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
848 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
828 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
849− mapM_ (\(expType, eActType) -> do
829+ mapM_ (\(expType, actType) ->
850− actType <- either throwE pure eActType
851− either throwE pure (atomTypeVerify expType actType)) zippedArgs
830+ lift $ except (atomTypeVerify expType actType)) zippedArgs
852− evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
831+ evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
853 case evalAtomFunction func evaldArgs of
832 case evalAtomFunction func evaldArgs of
854− Left err -> throwE (AtomFunctionUserError err)
833+ Left err -> throwError (AtomFunctionUserError err)
855 Right result -> do
834 Right result -> do
856 --validate that the result matches the expected type
835 --validate that the result matches the expected type
857− _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
836+ _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
858 pure result
837 pure result
859−evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
838+evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
860 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
839 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
861− rstate <- ask
840+ env <- ask
862− runExceptT $ do
841+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
863− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
842+ relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
864− relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
865− pure (RelationAtom relAtom)
843+ pure (RelationAtom relAtom)
866−evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
844+evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
867− rstate <- lift ask
845+ let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
868− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
869− aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
846+ aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
870− argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
847+ argAtoms <- local mergeEnv $
848+ mapM (evalGraphRefAtomExpr tupIn) dConsArgs
871 pure (ConstructedAtom dConsName aType argAtoms)
849 pure (ConstructedAtom dConsName aType argAtoms)
873−typeFromAtomExpr :: Attributes -> AtomExpr -> RelationalExprState (Either RelationalError AtomType)
851+typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
874−typeFromAtomExpr attrs (AttributeAtomExpr attrName) = do
852+typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
875− rstate <- ask
853+ renv <- askEnv
876 case A.atomTypeForAttributeName attrName attrs of
854 case A.atomTypeForAttributeName attrName attrs of
877− Right aType -> pure (Right aType)
855+ Right aType -> pure aType
878 Left err@(NoSuchAttributeNamesError _) ->
856 Left err@(NoSuchAttributeNamesError _) ->
879− let stateTup = stateTuple rstate
857+ let envTup = envTuple renv
880− stateAttrs = stateAttributes rstate in
858+ envAttrs = envAttributes renv in
881− case A.attributeForName attrName stateAttrs of
859+ case A.attributeForName attrName envAttrs of
882− Right attr -> pure (Right (A.atomType attr))
860+ Right attr -> pure (A.atomType attr)
883− Left _ -> case atomForAttributeName attrName stateTup of
861+ Left _ -> case atomForAttributeName attrName envTup of
884− Right atom -> pure (Right (atomTypeForAtom atom))
862+ Right atom -> pure (atomTypeForAtom atom)
885− Left _ -> pure (Left err)
863+ Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
865+ Left err -> throwError err
887−typeFromAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
867+typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
888−typeFromAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
868+typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
889− context <- fmap stateElemsContext ask
890− let funcs = atomFunctions context
869+ funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
891 case atomFunctionForName funcName funcs of
870 case atomFunctionForName funcName funcs of
892− Left err -> pure (Left err)
871+ Left err -> throwError err
893 Right func -> do
872 Right func -> do
894 let funcRetType = last (atomFuncType func)
873 let funcRetType = last (atomFuncType func)
895 funcArgTypes = init (atomFuncType func)
874 funcArgTypes = init (atomFuncType func)
896− eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
875+ argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
897− case lefts eArgTypes of
898− errs@(_:_) -> pure (Left (someErrors errs))
900− let eTvMap = resolveTypeVariables funcArgTypes argTypes
876+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
901− argTypes = rights eArgTypes
902− case eTvMap of
877+ case eTvMap of
903− Left err -> pure (Left err)
878+ Left err -> throwError err
904− Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
879+ Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
905−typeFromAtomExpr attrs (RelationAtomExpr relExpr) = do
880+typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
906− relType <- local (mergeAttributesIntoRelationalExprState attrs) (typeForRelationalExpr relExpr)
881+ relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
908− Left err -> pure (Left err)
910− pure (pure (RelationAtomType (attributes relType')))
882+ pure (RelationAtomType (attributes relType))
911-- grab the type of the data constructor, then validate that the args match the expected types
883-- grab the type of the data constructor, then validate that the args match the expected types
912−typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
884+typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
913− runExceptT $ do
885+ do
914− argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
886+ argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
915− context <- fmap stateElemsContext (lift ask)
887+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
916− either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
888+ lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
918-- | Validate that the type of the AtomExpr matches the expected type.
890-- | Validate that the type of the AtomExpr matches the expected type.
919−verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
891+verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
920−verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
892+verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
921− rstate <- lift ask
893+ env <- askEnv
922 case A.atomTypeForAttributeName attrName (attributes relIn) of
894 case A.atomTypeForAttributeName attrName (attributes relIn) of
923− Right aType -> either throwE pure (atomTypeVerify expectedType aType)
895+ Right aType -> lift $ except $ atomTypeVerify expectedType aType
924 (Left err@(NoSuchAttributeNamesError _)) ->
896 (Left err@(NoSuchAttributeNamesError _)) ->
925− let attrs' = stateAttributes rstate in
897+ let attrs' = envAttributes env in
926 if attrs' == emptyAttributes then
898 if attrs' == emptyAttributes then
927− throwE err
899+ throwError err
929 case A.attributeForName attrName attrs' of
901 case A.attributeForName attrName attrs' of
930− Left err' -> throwE err'
902+ Left err' -> throwError err'
931− Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
903+ Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
904+ Left err -> throwError err
906+verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
932−verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
907+ lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
933−verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
908+verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
934− rstate <- ask
909+ context <- gfDatabaseContextForMarker tid
935 let functions = atomFunctions context
910 let functions = atomFunctions context
936− context = stateElemsContext rstate
938− func <- either throwE pure (atomFunctionForName funcName functions)
911+ func <- lift $ except $ atomFunctionForName funcName functions
939− let expectedArgTypes = atomFuncType func
912+ let expectedArgTypes = atomFuncType func
940− funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
913+ funcArgVerifier (atomExpr, expectedType2, argCount) = do
914+ let handler :: RelationalError -> GraphRefRelationalExprM AtomType
941− Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
915+ handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
942− Left err -> throwE err
916+ handler err = throwError err
943− Right x -> pure x
917+ verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
944− ) $ zip3 funcArgExprs expectedArgTypes [1..]
918+ funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
945− if length funcArgTypes /= length expectedArgTypes - 1 then
919+ if length funcArgTypes /= length expectedArgTypes - 1 then
946− throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
920+ throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
948− either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
922+ lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
949−verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
923+verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
950− rstate <- lift ask
924+ do
951− relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
925+ let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
926+ relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
952− either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
927+ lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
953−verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
928+verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
954− cType <- liftE (typeFromAtomExpr (attributes rel) cons)
929+ cType <- typeForGraphRefAtomExpr (attributes rel) cons
955− either throwE pure (atomTypeVerify expectedType cType)
930+ lift $ except $ atomTypeVerify expectedType cType
957-- | Look up the type's name and create a new attribute.
932-- | Look up the type's name and create a new attribute.
958−evalAttrExpr :: TypeConstructorMapping -> AttributeExpr -> Either RelationalError Attribute
933+evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
959−evalAttrExpr aTypes (AttributeAndTypeNameExpr attrName tCons ()) = do
934+evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
935+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
960− aType <- atomTypeForTypeConstructorValidate True tCons aTypes M.empty
936+ aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
961− validateAtomType aType aTypes
937+ lift $ except $ validateAtomType aType tConsMap
962− Right (Attribute attrName aType)
938+ pure $ Attribute attrName aType
964−evalAttrExpr _ (NakedAttributeExpr attr) = Right attr
940+evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
966−evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
942+-- for tuple type concrete resolution (Nothing ==> Maybe Int) when the attributes hint is Nothing, we need to first process all the tuples, then extract the concrete types on a per-attribute basis, then reprocess the tuples to include the concrete types
943+evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
944+evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
945+evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
946+ tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
947+ finalAttrs <- case mAttrs of
948+ Just attrs -> pure attrs
951+ [] -> pure emptyAttributes
952+ (headTuple:tailTuples) -> do
953+ --gather up resolved atom types or throw an error if an attribute cannot be made concrete from the inferred types- this could still fail if the type cannot be inferred (e.g. from [Nothing, Nothing])
955+ processTupleAttrs (tupAttr, accAttr) =
956+ --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
957+ if isResolvedAttribute accAttr && tupAttr == accAttr then
960+ lift $ except $ resolveAttributes accAttr tupAttr
961+ mostResolvedTypes <-
962+ foldM (\acc tup -> do
963+ let zipped = zip (V.toList . attributesVec $ tupleAttributes tup) acc
964+ accNames = S.fromList $ map A.attributeName acc
965+ tupNames = A.attributeNameSet (tupleAttributes tup)
966+ attrNamesDiff = S.union (S.difference accNames tupNames) (S.difference tupNames accNames)
967+ unless (null attrNamesDiff) (throwError (AttributeNamesMismatchError attrNamesDiff))
968+ nextTupleAttrs <- mapM processTupleAttrs zipped
969+ let diff = A.attributesDifference (A.attributesFromList nextTupleAttrs) (A.attributesFromList acc)
970+ if diff == A.emptyAttributes then
973+ throwError (TupleAttributeTypeMismatchError diff)
974+ ) (V.toList . attributesVec $ tupleAttributes headTuple) tailTuples
975+ pure (A.attributesFromList mostResolvedTypes)
976+ --strategy: if all the tuple expr transaction markers refer to one location, then we can pass the type constructor mapping from that location, otherwise, we cannot assume that the types are the same
977+ tConsMap <- case singularTransactions tupleExprL of
978+ SingularTransactionRef commonTransId ->
979+ typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
980+ NoTransactionsRef ->
981+ typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
982+ -- if there are multiple transaction markers in the TupleExprs, then we can't assume a single type constructor mapping- this could be improved in the future, but if all the tuples are fully resolved, then we don't need further resolution
983+ _ -> throwError TupleExprsReferenceMultipleMarkersError
984+ lift $ except $ validateAttributes tConsMap finalAttrs
985+ mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
988+--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
990+evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
967−evalTupleExpr mAttrs (TupleExpr tupMap) = do
991+evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
968− context <- fmap stateElemsContext ask
970 -- it's not possible for AtomExprs in tuple constructors to reference other Attributes' atoms due to the necessary order-of-operations (need a tuple to pass to evalAtomExpr)- it may be possible with some refactoring of type usage or delayed evaluation- needs more thought, but not a priority
992 -- it's not possible for AtomExprs in tuple constructors to reference other Attributes' atoms due to the necessary order-of-operations (need a tuple to pass to evalAtomExpr)- it may be possible with some refactoring of type usage or delayed evaluation- needs more thought, but not a priority
971 -- 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
993 -- 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
972− let attrs = fromMaybe A.emptyAttributes mAttrs
994+ let attrs = fromMaybe A.emptyAttributes mAttrs
973− attrAtoms <- mapM (\(attrName, aExpr) -> do
995+ resolveOneAtom (attrName, aExpr) =
974− --provided when the relation header is available
997+ --provided when the relation header is available
975− let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
998+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
976− unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
999+ unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
977− resolvedType <- case eExpectedAtomType of
1000+ resolvedType <- case eExpectedAtomType of
978 Left _ -> pure unresolvedType
1001 Left _ -> pure unresolvedType
979− Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
1002+ Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
980 --resolve atom typevars based on resolvedType?
1003 --resolve atom typevars based on resolvedType?
981− newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
1004+ newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
982− pure (attrName, newAtom, resolvedType)
1005+ pure (attrName, newAtom, resolvedType)
983− ) (M.toList tupMap)
1006+ attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
984− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1007+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
985− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1008+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
986− tup = mkRelationTuple tupAttrs atoms
1009+ tup = mkRelationTuple tupAttrs atoms
987− tConss = typeConstructorMapping context
988− finalAttrs = fromMaybe tupAttrs mAttrs
1010+ finalAttrs = fromMaybe tupAttrs mAttrs
989 --verify that the attributes match
1011 --verify that the attributes match
990− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
1012+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1013+ --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
991− tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1014+ --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1015+ let tup' = reorderTuple finalAttrs tup
1016+ --TODO: restore type resolution
992− _ <- either throwE pure (validateTuple tup' tConss)
1017+-- _ <- lift $ except (validateTuple tup' tConss)
993− pure tup'
1018+ pure tup'
995−evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
1020+--temporary implementation until we have a proper planner+executor
996−evalAttributeNames attrNames expr = do
1021+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
997− eExprType <- typeForRelationalExpr expr
1022+evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
998− case eExprType of
1023+ mAttrs <- case mAttrExprs of
999− Left err -> pure (Left err)
1024+ Just _ ->
1000− Right exprTyp -> do
1025+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1001− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1026+ Nothing -> pure Nothing
1002− case attrNames of
1027+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1003− AttributeNames names ->
1028+ let attrs = fromMaybe firstTupleAttrs mAttrs
1004− case A.projectionAttributesForNames names (attributes exprTyp) of
1029+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1005− Left err -> pure (Left err)
1030+ lift $ except $ mkRelation attrs (RelationTupleSet tuples)
1006− Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1031+evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
1007−
1032+ lift $ except $ mkRelation attributeSet tupleSet
1008− InvertedAttributeNames names -> do
1033+evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1009− let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1010− if not (S.null nonExistentAttributeNames) then
1011− pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1013− pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
1015− UnionAttributeNames namesA namesB -> do
1016− eNameSetA <- evalAttributeNames namesA expr
1018− Left err -> pure (Left err)
1019− Right nameSetA -> do
1020− eNameSetB <- evalAttributeNames namesB expr
1022− Left err -> pure (Left err)
1024− pure (Right (S.union nameSetA nameSetB))
1026− IntersectAttributeNames namesA namesB -> do
1027− eNameSetA <- evalAttributeNames namesA expr
1029− Left err -> pure (Left err)
1030− Right nameSetA -> do
1031− eNameSetB <- evalAttributeNames namesB expr
1033− Left err -> pure (Left err)
1035− pure (Right (S.intersection nameSetA nameSetB))
1037− RelationalExprAttributeNames attrExpr -> do
1038− eAttrExprType <- typeForRelationalExpr attrExpr
1039− case eAttrExprType of
1040− Left err -> pure (Left err)
1041− Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1043−evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError Relation
1044−evalGraphRefRelationalExpr (RelationVariable name tid) graph = do
1034+evalGraphRefRelationalExpr (RelationVariable name tid) = do
1045− ctx <- dbContextForTransId tid graph
1035+ ctx <- gfDatabaseContextForMarker tid
1046 case M.lookup name (relationVariables ctx) of
1036 case M.lookup name (relationVariables ctx) of
1047− Nothing -> Left (RelVarNotDefinedError name)
1037+ Nothing -> throwError (RelVarNotDefinedError name)
1048− Just rv -> evalGraphRefRelationalExpr rv graph
1038+ Just rv -> evalGraphRefRelationalExpr rv
1039+evalGraphRefRelationalExpr (Project attrNames expr) = do
1040+ attrNameSet <- evalGraphRefAttributeNames attrNames expr
1041+ rel <- evalGraphRefRelationalExpr expr
1042+ lift $ except $ project attrNameSet rel
1043+evalGraphRefRelationalExpr (Union exprA exprB) = do
1044+ relA <- evalGraphRefRelationalExpr exprA
1045+ relB <- evalGraphRefRelationalExpr exprB
1046+ lift $ except $ union relA relB
1047+evalGraphRefRelationalExpr (Join exprA exprB) = do
1048+ relA <- evalGraphRefRelationalExpr exprA
1049+ relB <- evalGraphRefRelationalExpr exprB
1050+ lift $ except $ join relA relB
1051+evalGraphRefRelationalExpr (Rename oldName newName expr) = do
1052+ rel <- evalGraphRefRelationalExpr expr
1053+ lift $ except $ rename oldName newName rel
1054+evalGraphRefRelationalExpr (Difference exprA exprB) = do
1055+ relA <- evalGraphRefRelationalExpr exprA
1056+ relB <- evalGraphRefRelationalExpr exprB
1057+ lift $ except $ difference relA relB
1058+evalGraphRefRelationalExpr (Group groupAttrNames newAttrName expr) = do
1059+ groupNames <- evalGraphRefAttributeNames groupAttrNames expr
1060+ rel <- evalGraphRefRelationalExpr expr
1061+ lift $ except $ group groupNames newAttrName rel
1062+evalGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1063+ rel <- evalGraphRefRelationalExpr expr
1064+ lift $ except $ ungroup groupAttrName rel
1065+evalGraphRefRelationalExpr (Restrict predExpr expr) = do
1066+ rel <- evalGraphRefRelationalExpr expr
1067+ filt <- predicateRestrictionFilter (attributes rel) predExpr
1068+ lift $ except $ restrict filt rel
1069+evalGraphRefRelationalExpr (Equals exprA exprB) = do
1070+ relA <- evalGraphRefRelationalExpr exprA
1071+ relB <- evalGraphRefRelationalExpr exprB
1072+ pure $ if relA == relB then relationTrue else relationFalse
1073+evalGraphRefRelationalExpr (NotEquals exprA exprB) = do
1074+ relA <- evalGraphRefRelationalExpr exprA
1075+ relB <- evalGraphRefRelationalExpr exprB
1076+ pure $ if relA == relB then relationFalse else relationTrue
1077+evalGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1078+ rel <- evalGraphRefRelationalExpr expr
1079+ (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1080+ lift $ except $ relMogrify tupProc newAttrs rel
1081+evalGraphRefRelationalExpr expr@With{} =
1082+ --strategy A: add relation variables to the contexts in the graph
1083+ --strategy B: drop in macros in place (easier programmatically)
1084+ --strategy B implementation
1085+ evalGraphRefRelationalExpr (substituteWithNameMacros [] expr)
1050dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1087dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1051dbContextForTransId tid graph = do
1088dbContextForTransId tid graph = do
@@ -1063,167 +1100,293 @@ transactionForId tid graph
1064 matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
1101 matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
1066−processRestrictionPredicateExpr :: RestrictionPredicateExpr -> RelationalExprState (Either RelationalError GraphRefRestrictionPredicateExpr)
1103+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1067−processRestrictionPredicateExpr TruePredicate = pure (Right TruePredicate)
1104+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1068−processRestrictionPredicateExpr (AndPredicate a b) = do
1105+typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1069− a' <- processRestrictionPredicateExpr a
1106+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1070− b' <- processRestrictionPredicateExpr b
1107+ mAttrs <- case mAttrExprs of
1071− case a' of
1108+ Just attrExprs -> do
1072− Left err -> pure (Left err)
1109+ attrs <- mapM evalGraphRefAttributeExpr attrExprs
1073− Right a'' -> case b' of
1110+ pure (Just (attributesFromList attrs))
1074− Left err -> pure (Left err)
1111+ Nothing -> pure Nothing
1075− Right b'' ->
1112+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1076− pure (Right (AndPredicate a'' b''))
1113+ let retAttrs = case tuples of
1077−processRestrictionPredicateExpr (OrPredicate a b) = do
1114+ (tup:_) -> tupleAttributes tup
1078− a' <- processRestrictionPredicateExpr a
1115+ [] -> fromMaybe A.emptyAttributes mAttrs
1079− b' <- processRestrictionPredicateExpr b
1116+ pure $ emptyRelationWithAttrs retAttrs
1081− Left err -> pure (Left err)
1082− Right a'' -> case b' of
1083− Left err -> pure (Left err)
1085− pure (Right (OrPredicate a'' b''))
1086−processRestrictionPredicateExpr (NotPredicate a) = do
1087− a' <- processRestrictionPredicateExpr a
1089− Left err -> pure (Left err)
1091− pure (Right (NotPredicate a''))
1092−processRestrictionPredicateExpr (RelationalExprPredicate expr) = do
1093− e <- evalRelationalExpr expr
1095− Left err -> Left err
1096− Right e' -> Right (RelationalExprPredicate e')
1097−processRestrictionPredicateExpr (AtomExprPredicate expr) = do
1098− e <- processAtomExpr expr
1099− pure (Right (AtomExprPredicate e))
1100−processRestrictionPredicateExpr (AttributeEqualityPredicate nam expr) = do
1101− e <- processAtomExpr expr
1102− pure (Right (AttributeEqualityPredicate nam e))
1104−processExtendTupleExpr :: ExtendTupleExpr -> RelationalExprState (Either RelationalError GraphRefExtendTupleExpr)
1105−processExtendTupleExpr (AttributeExtendTupleExpr nam atomExpr) = do
1106− e <- processAtomExpr atomExpr
1107− pure (Right (AttributeExtendTupleExpr nam e))
1109−typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> RelationalExprState (Either RelationalError Relation)
1110−typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = pure $ mkRelation attrs emptyTupleSet
1111−typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (Right (emptyRelationWithAttrs (attributes rel)))
1112−typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) =
1114− Just attrExprs -> do
1115− eAttrs <- mapM (\e -> evalGraphRefAttributeExpr e) attrExprs
1116− case lefts eAttrs of
1117− [] -> pure (Right (emptyRelationWithAttrs (attributesFromList (rights eAttrs))))
1118− _ -> pure (Left (someErrors (lefts eAttrs)))
1119typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1118typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1120− eTrans <- currentTrans
1119+ relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1122− Left err -> pure (Left err)
1124− let relVars = relationVariables (concreteDatabaseContext trans)
1125− case M.lookup rvName relVars of
1120+ case M.lookup rvName relVars of
1126− Nothing -> pure (Left (RelVarNotDefinedError rvName))
1121+ Nothing -> throwError (RelVarNotDefinedError rvName)
1127− Just rvExpr -> typeForGraphRefRelationalExpr rvExpr
1123+ typeForGraphRefRelationalExpr rvExpr
1128typeForGraphRefRelationalExpr (Project attrNames expr) = do
1124typeForGraphRefRelationalExpr (Project attrNames expr) = do
1129− eExprType <- typeForGraphRefRelationalExpr expr
1125+ exprType' <- typeForGraphRefRelationalExpr expr
1131− Left err -> pure (Left err)
1132− Right exprType -> do
1133− eProjectionAttrs <- evalGraphRefAttributeNames attrNames expr
1126+ projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1134− pure $ case eProjectionAttrs of
1135− Left err -> Left err
1136− Right projectionAttrs -> project projectionAttrs exprType
1127+ lift $ except $ project projectionAttrs exprType'
1137−
1128+typeForGraphRefRelationalExpr (Union exprA exprB) = do
1129+ exprA' <- typeForGraphRefRelationalExpr exprA
1130+ exprB' <- typeForGraphRefRelationalExpr exprB
1131+ lift $ except $ union exprA' exprB'
1132+typeForGraphRefRelationalExpr (Join exprA exprB) = do
1133+ exprA' <- typeForGraphRefRelationalExpr exprA
1134+ exprB' <- typeForGraphRefRelationalExpr exprB
1135+ lift $ except $ join exprA' exprB'
1136+typeForGraphRefRelationalExpr (Rename oldAttr newAttr expr) = do
1137+ expr' <- typeForGraphRefRelationalExpr expr
1138+ lift $ except $ rename oldAttr newAttr expr'
1139+typeForGraphRefRelationalExpr (Difference exprA exprB) = do
1140+ exprA' <- typeForGraphRefRelationalExpr exprA
1141+ exprB' <- typeForGraphRefRelationalExpr exprB
1142+ lift $ except $ difference exprA' exprB'
1143+typeForGraphRefRelationalExpr (Group groupNames attrName expr) = do
1144+ expr' <- typeForGraphRefRelationalExpr expr
1145+ groupNames' <- evalGraphRefAttributeNames groupNames expr
1146+ lift $ except $ group groupNames' attrName expr'
1147+typeForGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1148+ expr' <- typeForGraphRefRelationalExpr expr
1149+ lift $ except $ ungroup groupAttrName expr'
1150+typeForGraphRefRelationalExpr (Restrict pred' expr) = do
1151+ expr' <- typeForGraphRefRelationalExpr expr
1152+ filt <- predicateRestrictionFilter (attributes expr') pred'
1153+ lift $ except $ restrict filt expr'
1154+typeForGraphRefRelationalExpr Equals{} =
1156+typeForGraphRefRelationalExpr NotEquals{} =
1158+typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1159+ rel <- typeForGraphRefRelationalExpr expr
1160+ evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1161+typeForGraphRefRelationalExpr expr@(With withs _) = do
1162+ let expr' = substituteWithNameMacros [] expr
1163+ checkMacroName (WithNameExpr macroName tid) = do
1164+ rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1165+ case M.lookup macroName rvs of
1166+ Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1168+ mapM_ (checkMacroName . fst) withs
1169+ typeForGraphRefRelationalExpr expr'
1138−evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
1171+evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1139evalGraphRefAttributeNames attrNames expr = do
1172evalGraphRefAttributeNames attrNames expr = do
1140− eExprType <- typeForGraphRefRelationalExpr expr
1173+ exprType' <- typeForGraphRefRelationalExpr expr
1142− Left err -> pure (Left err)
1143− Right exprTyp -> do
1144− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1174+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1145− case attrNames of
1175+ case attrNames of
1146− AttributeNames names ->
1176+ AttributeNames names ->
1147− case A.projectionAttributesForNames names (attributes exprTyp) of
1177+ case A.projectionAttributesForNames names (attributes exprType') of
1148− Left err -> pure (Left err)
1178+ Left err -> throwError err
1149− Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1179+ Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1151− InvertedAttributeNames names -> do
1181+ InvertedAttributeNames names -> do
1152 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1182 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1153 if not (S.null nonExistentAttributeNames) then
1183 if not (S.null nonExistentAttributeNames) then
1154− pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1184+ throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1156− pure (pure (A.nonMatchingAttributeNameSet names typeNameSet))
1186+ pure (A.nonMatchingAttributeNameSet names typeNameSet)
1158− UnionAttributeNames namesA namesB -> do
1188+ UnionAttributeNames namesA namesB -> do
1159− eNameSetA <- evalGraphRefAttributeNames namesA expr
1189+ nameSetA <- evalGraphRefAttributeNames namesA expr
1161− Left err -> pure (Left err)
1162− Right nameSetA -> do
1163− eNameSetB <- evalGraphRefAttributeNames namesB expr
1190+ nameSetB <- evalGraphRefAttributeNames namesB expr
1165− Left err -> pure (Left err)
1167− pure (Right (S.union nameSetA nameSetB))
1191+ pure (S.union nameSetA nameSetB)
1169− IntersectAttributeNames namesA namesB -> do
1170− eNameSetA <- evalGraphRefAttributeNames namesA expr
1172− Left err -> pure (Left err)
1173− Right nameSetA -> do
1174− eNameSetB <- evalGraphRefAttributeNames namesB expr
1176− Left err -> pure (Left err)
1178− pure (Right (S.intersection nameSetA nameSetB))
1180− RelationalExprAttributeNames attrExpr -> do
1193+ IntersectAttributeNames namesA namesB -> do
1181− eAttrExprType <- typeForGraphRefRelationalExpr attrExpr
1194+ nameSetA <- evalGraphRefAttributeNames namesA expr
1182− case eAttrExprType of
1195+ nameSetB <- evalGraphRefAttributeNames namesB expr
1183− Left err -> pure (Left err)
1196+ pure (S.intersection nameSetA nameSetB)
1184− Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1198+ RelationalExprAttributeNames attrExpr -> do
1199+ attrExprType <- typeForGraphRefRelationalExpr attrExpr
1200+ pure (A.attributeNameSet (attributes attrExprType))
1202+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1203+evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1204+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1205+ case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1206+ Left err -> throwError err
1208+ case validateAtomType aType tConsMap of
1209+ Left err -> throwError err
1210+ Right _ -> pure (Attribute attrName aType)
1211+evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1213+mkEmptyRelVars :: RelationVariables -> RelationVariables
1214+mkEmptyRelVars = M.map mkEmptyRelVar
1216+ mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1217+ mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1218+ mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1219+ mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
1220+ mkEmptyRelVar (Project attrNames expr) = Project attrNames (mkEmptyRelVar expr)
1221+ mkEmptyRelVar (Union exprA exprB) = Union (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1222+ mkEmptyRelVar (Join exprA exprB) = Join (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1223+ mkEmptyRelVar (Rename nameA nameB expr) = Rename nameA nameB (mkEmptyRelVar expr)
1224+ mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1225+ mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1226+ mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1227+ mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1228+ mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1229+ mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1230+ mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1231+ mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1234+dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1235+dbErr err = lift (except (Left err))
1237+-- | Return a Relation describing the relation variables.
1238+relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1239+relationVariablesAsRelation ctx graph = do
1240+ let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1241+ attrs = A.attributesFromList [Attribute "name" TextAtomType,
1242+ Attribute "attributes" (RelationAtomType subrelAttrs)]
1243+ relVars = relationVariables ctx
1244+ mkRvDesc (rvName, gfExpr) = do
1245+ let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1246+ gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1247+ pure (rvName, gfType)
1248+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributesVec (attributes rel))]
1249+ attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1250+ attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1251+ Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1252+ Right rel -> RelationAtom rel
1253+ rvs <- mapM mkRvDesc (M.toList relVars)
1254+ let tups = map relVarToAtomList rvs
1255+ mkRelationFromList attrs tups
1257+-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1258+evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1259+evalRelationalExpr expr = do
1261+ context <- reContext
1262+ let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1263+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1264+ case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1265+ Left err -> throwError err
1266+ Right rel -> pure rel
1268+class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1269+ getContext :: m DatabaseContext
1271+instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1272+ getContext = gfDatabaseContextForMarker UncommittedContextMarker
1189−processAtomExpr :: AtomExpr -> RelationalExprState GraphRefAtomExpr
1274+instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1190−processAtomExpr (AttributeAtomExpr nam) = pure $ AttributeAtomExpr nam
1275+ getContext = getStateContext
1191−processAtomExpr (NakedAtomExpr atom) = pure $ NakedAtomExpr atom
1276+
1192−processAtomExpr (FunctionAtomExpr fName atomExprs ()) = do
1277+relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1193− tid <- elems_currentTransId <$> ask
1278+relVarByName rvName = do
1194− FunctionAtomExpr fName <$> mapM processAtomExpr atomExprs <*> pure tid
1279+ relvars <- relationVariables <$> getContext
1195−processAtomExpr (RelationAtomExpr expr) = RelationAtomExpr <$> processRelationalExpr expr
1280+ case M.lookup rvName relvars of
1196−processAtomExpr (ConstructedAtomExpr dConsName atomExprs ()) = ConstructedAtomExpr dConsName <$> mapM processAtomExpr atomExprs <*> (elems_currentTransId <$> ask)
1281+ Nothing -> throwError (RelVarNotDefinedError rvName)
1197−
1282+ Just gfexpr -> pure gfexpr
1198−processTupleExpr :: TupleExpr -> RelationalExprState GraphRefTupleExpr
1283+
1199−processTupleExpr (TupleExpr tMap) =
1284+-- | resolve UncommittedTransactionMarker whenever possible- this is important in the DatabaseContext in order to mitigate self-referencing loops for updates
1200− TupleExpr . M.fromList <$> mapM (\(k,v) -> (,) k <$> processAtomExpr v) (M.toList tMap)
1285+class ResolveGraphRefTransactionMarker a where
1201−
1286+ resolve :: a -> DatabaseContextEvalMonad a
1202−evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> RelationalExprState (Either RelationalError Attribute)
1287+
1203−evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1288+-- s := s union t
1204− graph <- elems_graph <$> ask
1289+instance ResolveGraphRefTransactionMarker GraphRefRelationalExpr where
1205− case transactionForId tid graph of
1290+ resolve (MakeRelationFromExprs mAttrs tupleExprs) =
1206− Left err -> pure (Left err)
1291+ MakeRelationFromExprs mAttrs <$> resolve tupleExprs
1207− Right trans -> do
1292+ resolve orig@MakeStaticRelation{} = pure orig
1208− let tConsMap = typeConstructorMapping (concreteDatabaseContext trans)
1293+ resolve orig@ExistingRelation{} = pure orig
1209− case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1294+ resolve orig@(RelationVariable rvName UncommittedContextMarker) = do
1210− Left err -> pure (Left err)
1295+ rvMap <- relationVariables <$> getStateContext
1211− Right aType -> do
1296+ case M.lookup rvName rvMap of
1212− case validateAtomType aType tConsMap of
1297+ Nothing -> pure orig
1213− Left err -> pure (Left err)
1298+ Just resolvedRv -> resolve resolvedRv
1214− Right _ -> pure (Right (Attribute attrName aType))
1299+ resolve orig@RelationVariable{} = pure orig
1215−
1300+ resolve (Project attrNames relExpr) = Project <$> resolve attrNames <*> resolve relExpr
1216−--convert AttributeExpr to GraphRefAttributeExpr
1301+ resolve (Union exprA exprB) = Union <$> resolve exprA <*> resolve exprB
1217−processAttributeExpr :: AttributeExpr -> RelationalExprState GraphRefAttributeExpr
1302+ resolve (Join exprA exprB) = Join <$> resolve exprA <*> resolve exprB
1218−processAttributeExpr (AttributeAndTypeNameExpr nam tCons ()) = do
1303+ resolve (Rename attrA attrB expr) = Rename attrA attrB <$> resolve expr
1219− tid <- elems_currentTransId <$> ask
1304+ resolve (Difference exprA exprB) = Difference <$> resolve exprA <*> resolve exprB
1220− pure $ AttributeAndTypeNameExpr nam tCons tid
1305+ resolve (Group namesA nameB expr) = Group <$> resolve namesA <*> pure nameB <*> resolve expr
1221−processAttributeExpr (NakedAttributeExpr attr) = pure $ NakedAttributeExpr attr
1306+ resolve (Ungroup nameA expr) = Ungroup nameA <$> resolve expr
1222−
1307+ resolve (Restrict restrictExpr relExpr) = Restrict <$> resolve restrictExpr <*> resolve relExpr
1223−-- convert a RelationalExpr into a GraphRefRelationalExpr
1308+ resolve (Equals exprA exprB) = Equals <$> resolve exprA <*> resolve exprB
1224−processRelationalExpr :: RelationalExpr -> RelationalExprState GraphRefRelationalExpr
1309+ resolve (NotEquals exprA exprB) = NotEquals <$> resolve exprA <*> resolve exprB
1225−processRelationalExpr (MakeRelationFromExprs mAttrs tupleExprs) = do
1310+ resolve (Extend extendExpr relExpr) = Extend <$> resolve extendExpr <*> resolve relExpr
1311+ resolve (With withExprs relExpr) = With <$> mapM (\(nam, expr) -> (,) <$> resolve nam <*> resolve expr) withExprs <*> resolve relExpr
1313+instance ResolveGraphRefTransactionMarker GraphRefTupleExprs where
1314+ resolve (TupleExprs marker tupleExprs) =
1315+ TupleExprs marker <$> mapM resolve tupleExprs
1317+instance ResolveGraphRefTransactionMarker GraphRefTupleExpr where
1318+ resolve (TupleExpr tupMap) = do
1319+ tupMap' <- mapM (\(attrName, expr) -> (,) attrName <$> resolve expr ) (M.toList tupMap)
1320+ pure (TupleExpr (M.fromList tupMap'))
1322+instance ResolveGraphRefTransactionMarker GraphRefAttributeNames where
1323+ resolve orig@AttributeNames{} = pure orig
1324+ resolve orig@InvertedAttributeNames{} = pure orig
1325+ resolve (UnionAttributeNames namesA namesB) = UnionAttributeNames <$> resolve namesA <*> resolve namesB
1326+ resolve (IntersectAttributeNames namesA namesB) = IntersectAttributeNames <$> resolve namesA <*> resolve namesB
1327+ resolve (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> resolve expr
1329+instance ResolveGraphRefTransactionMarker GraphRefRestrictionPredicateExpr where
1330+ resolve TruePredicate = pure TruePredicate
1331+ resolve (AndPredicate exprA exprB) = AndPredicate <$> resolve exprA <*> resolve exprB
1332+ resolve (OrPredicate exprA exprB) = OrPredicate <$> resolve exprA <*> resolve exprB
1333+ resolve (NotPredicate expr) = NotPredicate <$> resolve expr
1334+ resolve (RelationalExprPredicate expr) = RelationalExprPredicate <$> resolve expr
1335+ resolve (AtomExprPredicate expr) = AtomExprPredicate <$> resolve expr
1336+ resolve (AttributeEqualityPredicate nam expr)= AttributeEqualityPredicate nam <$> resolve expr
1338+instance ResolveGraphRefTransactionMarker GraphRefExtendTupleExpr where
1339+ resolve (AttributeExtendTupleExpr nam atomExpr) = AttributeExtendTupleExpr nam <$> resolve atomExpr
1341+instance ResolveGraphRefTransactionMarker GraphRefWithNameExpr where
1342+ resolve orig@WithNameExpr{} = pure orig -- match uncommitted marker?
1344+instance ResolveGraphRefTransactionMarker GraphRefAtomExpr where
1345+ resolve orig@AttributeAtomExpr{} = pure orig
1346+ resolve orig@NakedAtomExpr{} = pure orig
1347+ resolve (FunctionAtomExpr nam atomExprs marker) =
1348+ FunctionAtomExpr nam <$> mapM resolve atomExprs <*> pure marker
1349+ resolve (RelationAtomExpr expr) = RelationAtomExpr <$> resolve expr
1350+ resolve (ConstructedAtomExpr dConsName atomExprs marker) =
1351+ ConstructedAtomExpr dConsName <$> mapM resolve atomExprs <*> pure marker
1353+--convert series of simple Union queries into MakeStaticRelation
1354+-- this is especially useful for long, nested applications of Union with simple tuples
1355+-- Union (MakeRelation x y) (MakeRelation x y') -> MakeRelation x (y + y')
1357+--MakeRelationFromExprs Nothing (TupleExprs UncommittedContextMarker [TupleExpr (fromList [("name", NakedAtomExpr (TextAtom "steve"))])])
1359+applyUnionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1360+applyUnionCollapse = Fold.cata opt
1362+ opt :: RelationalExprBaseF GraphRefTransactionMarker GraphRefRelationalExpr -> GraphRefRelationalExpr
1363+ opt (UnionF exprA exprB) | exprA == exprB = exprA
1365+ exprA@(MakeRelationFromExprs mAttrs1 tupExprs1)
1366+ exprB@(MakeRelationFromExprs mAttrs2 tupExprs2)) | tupExprs1 == tupExprs2 = MakeRelationFromExprs (mAttrs1 <|> mAttrs2) tupExprs1
1367+ | tupExprsNull tupExprs1 = exprB
1368+ | tupExprsNull tupExprs2 = exprA
1369+ opt x = Fold.embed x
1370+ tupExprsNull (TupleExprs _ []) = True
1371+ tupExprsNull _ = False
1374+--UPDATE optimization- find matching where clause in "lower" levels of renaming
1375+--update x where y=1 set (x:=5,z:=10); update x where y=1 set(x:=6,z:=11)
1377+-- update x where y=1 set (x:=6,z:=11)
1378+-- future opt: match individual attributes update x where y=1 set (x:=5); update x where y=1 set (z:=11) => update x where y=1 set (x:=5,z:=11)
1380+--strategy: try to collapse the top-level update (union (restrict pred MakeRelationFromExpr) expr) if it contains the same predicate and resultant relation
1382+--DELETE optimization
1383+-- if a restriction matches a previous restriction, combine them
1384+-- O(1) since it only scans at the top level, critical in benchmarks generating redundant deletions
1385+applyRestrictionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1386+applyRestrictionCollapse orig@(Restrict npred@(NotPredicate _) expr) =
1226− mAttrs' <- case mAttrs of
1387+ case expr of
1227− Nothing -> pure Nothing
1388+ orig'@(Restrict npred'@(NotPredicate _) _) | npred == npred' -> orig'
1228− Just mAttrs'' -> Just <$> mapM processAttributeExpr mAttrs''
1389+ _ -> orig
1229− MakeRelationFromExprs mAttrs' <$> mapM processTupleExpr tupleExprs
1390+applyRestrictionCollapse expr = expr