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