@@ -1,53 +1,34 @@
1{-# LANGUAGE ScopedTypeVariables #-}
1{-# LANGUAGE ScopedTypeVariables #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE OverloadedStrings #-}
5module ProjectM36.RelationalExpression where
2module ProjectM36.RelationalExpression where
6import ProjectM36.Relation
3import ProjectM36.Relation
7import ProjectM36.Tuple
4import ProjectM36.Tuple
8import ProjectM36.TupleSet
5import ProjectM36.TupleSet
9import ProjectM36.Base
6import ProjectM36.Base
10−import qualified Data.UUID as U
11import ProjectM36.Error
7import ProjectM36.Error
12import ProjectM36.AtomType
8import ProjectM36.AtomType
13−import ProjectM36.Attribute (emptyAttributes, attributesFromList)
9+import ProjectM36.Attribute (emptyAttributes)
14import ProjectM36.ScriptSession
10import ProjectM36.ScriptSession
15import ProjectM36.DataTypes.Primitive
11import ProjectM36.DataTypes.Primitive
16import ProjectM36.AtomFunction
12import ProjectM36.AtomFunction
17import ProjectM36.DatabaseContextFunction
13import ProjectM36.DatabaseContextFunction
18import ProjectM36.Arbitrary
14import ProjectM36.Arbitrary
19−import ProjectM36.GraphRefRelationalExpr
20−import ProjectM36.Transaction
21import qualified ProjectM36.Attribute as A
15import qualified ProjectM36.Attribute as A
22import qualified Data.Map as M
16import qualified Data.Map as M
23import qualified Data.HashSet as HS
17import qualified Data.HashSet as HS
24import qualified Data.Set as S
18import qualified Data.Set as S
25import Control.Monad.State hiding (join)
19import Control.Monad.State hiding (join)
26−import Data.Bifunctor (second)
20+import Control.Exception
27import Data.Maybe
21import Data.Maybe
28import Data.Either
22import Data.Either
29import Data.Char (isUpper)
23import Data.Char (isUpper)
31−import qualified Data.List.NonEmpty as NE
32−import Data.Functor.Identity
33import qualified Data.Text as T
24import qualified Data.Text as T
34import qualified Data.Vector as V
25import qualified Data.Vector as V
35import qualified ProjectM36.TypeConstructorDef as TCD
26import qualified ProjectM36.TypeConstructorDef as TCD
36−import qualified Control.Monad.RWS.Strict as RWS
27+import Control.Monad.Trans.Except
37−import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
38−import Control.Monad.Except hiding (join)
39−import Control.Monad.Trans.Except (except)
28+import Control.Monad.Trans.Reader
40−import Control.Monad.Reader as R hiding (join)
41−import ProjectM36.NormalizeExpr
42−import ProjectM36.WithNameExpr
43import Test.QuickCheck
29import Test.QuickCheck
44−import qualified Data.Functor.Foldable as Fold
30+import GHC
45−import Control.Applicative
46−#ifdef PM36_HASKELL_SCRIPTING
47−import GHC hiding (getContext)
48−import Control.Exception
49import GHC.Paths
31import GHC.Paths
52data DatabaseContextExprDetails = CountUpdatedTuples
33data DatabaseContextExprDetails = CountUpdatedTuples
@@ -64,63 +45,32 @@ databaseContextExprDetailsFunc CountUpdatedTuples _ relIn = Relation attrs newTu
64 Right ts -> ts
45 Right ts -> ts
66-- | Used to start a fresh database state for a new database context expression.
47-- | Used to start a fresh database state for a new database context expression.
67−mkDatabaseContextEvalState :: DatabaseContext -> DatabaseContextEvalState
48+freshDatabaseState :: DatabaseContext -> DatabaseStateElems
68−mkDatabaseContextEvalState context = DatabaseContextEvalState {
69− dbc_context = context,
72− } --future work: propagate return accumulator
49+freshDatabaseState ctx = (ctx, M.empty, False) --future work: propagate return accumulator
74-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
51-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
75−data RelationalExprEnv = RelationalExprEnv {
52+data RelationalExprStateElems = RelationalExprStateTupleElems DatabaseContext RelationTuple | -- used when fully evaluating a relexpr
76− re_context :: DatabaseContext,
53+ RelationalExprStateAttrsElems DatabaseContext Attributes | --used when evaluating the type of a relexpr
77− re_graph :: TransactionGraph,
54+ RelationalExprStateElems DatabaseContext --used by default at the top level of evaluation
78− re_extra :: Maybe (Either RelationTuple Attributes)
55+
79− }
56+instance Show RelationalExprStateElems where
80−
57+ show (RelationalExprStateTupleElems _ tup) = "RelationalExprStateTupleElems " ++ show tup
81−envTuple :: GraphRefRelationalExprEnv -> RelationTuple
58+ show (RelationalExprStateAttrsElems _ attrs) = "RelationalExprStateAttrsElems" ++ show attrs
82−envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
59+ show (RelationalExprStateElems _) = "RelationalExprStateElems"
84−envAttributes :: GraphRefRelationalExprEnv -> Attributes
61+mkRelationalExprState :: DatabaseContext -> RelationalExprStateElems
85−envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
62+mkRelationalExprState = RelationalExprStateElems
64+mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprStateElems -> RelationalExprStateElems
65+mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateElems ctx) = RelationalExprStateTupleElems ctx tupIn
66+mergeTuplesIntoRelationalExprState _ st@(RelationalExprStateAttrsElems _ _) = st
67+mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateTupleElems ctx existingTuple) = let mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap existingTuple) in
68+ RelationalExprStateTupleElems ctx (mkRelationTupleFromMap mergedTupMap)
87−instance Show RelationalExprEnv where
70+mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprStateElems -> RelationalExprStateElems
88− show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
71+mergeAttributesIntoRelationalExprState attrs (RelationalExprStateElems ctx) = RelationalExprStateAttrsElems ctx attrs
89−
72+mergeAttributesIntoRelationalExprState _ st@(RelationalExprStateTupleElems _ _) = st
90−--used to eval relationalexpr
73+mergeAttributesIntoRelationalExprState attrsIn (RelationalExprStateAttrsElems ctx attrs) = RelationalExprStateAttrsElems ctx (A.union attrsIn attrs)
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)))
125type ResultAccumName = StringType
75type ResultAccumName = StringType
@@ -130,403 +80,447 @@ data ResultAccum = ResultAccum { resultAccumFunc :: ResultAccumFunc,
130 resultAccumResult :: Relation
80 resultAccumResult :: Relation
133−data DatabaseContextEvalState = DatabaseContextEvalState {
134− dbc_context :: DatabaseContext, --new, alterable context for a new transaction
135− dbc_accum :: M.Map ResultAccumName ResultAccum,
83+type DatabaseStateElems = (DatabaseContext, M.Map ResultAccumName ResultAccum, DirtyFlag)
136− dbc_dirty :: DirtyFlag
139−data DatabaseContextEvalEnv = DatabaseContextEvalEnv
140− { dce_transId :: TransactionId,
141− dce_graph :: TransactionGraph
144−mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
145−mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
147−type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
85+type DatabaseState a = State DatabaseStateElems a
149−runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
87+getStateContext :: DatabaseState DatabaseContext
150−runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
88+getStateContext = do
151− where
89+ (ctx,_, _) <- get
152− freshEnv = mkDatabaseContextEvalState ctx
90+ pure ctx
92+putStateContext :: DatabaseContext -> DatabaseState ()
93+putStateContext ctx = do
95+ put (ctx, accum, True)
97+type RelationalExprState a = Reader RelationalExprStateElems a
99+stateElemsContext :: RelationalExprStateElems -> DatabaseContext
100+stateElemsContext (RelationalExprStateTupleElems ctx _) = ctx
101+stateElemsContext (RelationalExprStateElems ctx) = ctx
102+stateElemsContext (RelationalExprStateAttrsElems ctx _) = ctx
104+setStateElemsContext :: RelationalExprStateElems -> DatabaseContext -> RelationalExprStateElems
105+setStateElemsContext (RelationalExprStateTupleElems _ tup) ctx = RelationalExprStateTupleElems ctx tup
106+setStateElemsContext (RelationalExprStateElems _) ctx = RelationalExprStateElems ctx
107+setStateElemsContext (RelationalExprStateAttrsElems _ attrs) ctx = RelationalExprStateAttrsElems ctx attrs
109+--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
110+evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
111+evalRelationalExpr (RelationVariable name _) = do
112+ relvarTable <- fmap (relationVariables . stateElemsContext) ask
113+ return $ case M.lookup name relvarTable of
114+ Just res -> Right res
115+ Nothing -> Left $ RelVarNotDefinedError name
117+evalRelationalExpr (Project attrNames expr) = do
118+ eAttrNameSet <- evalAttributeNames attrNames expr
119+ case eAttrNameSet of
120+ Left err -> pure (Left err)
121+ Right attrNameSet -> do
122+ rel <- evalRelationalExpr expr
124+ Right rel2 -> pure $ project attrNameSet rel2
125+ Left err -> pure $ Left err
127+evalRelationalExpr (Union exprA exprB) = do
128+ relA <- evalRelationalExpr exprA
129+ relB <- evalRelationalExpr exprB
131+ Left err -> return $ Left err
132+ Right relA2 -> case relB of
133+ Left err -> return $ Left err
134+ Right relB2 -> return $ union relA2 relB2
136+evalRelationalExpr (Join exprA exprB) = do
137+ relA <- evalRelationalExpr exprA
138+ relB <- evalRelationalExpr exprB
140+ Left err -> return $ Left err
141+ Right relA2 -> case relB of
142+ Left err -> return $ Left err
143+ Right relB2 -> return $ join relA2 relB2
145+evalRelationalExpr (Difference exprA exprB) = do
146+ relA <- evalRelationalExpr exprA
147+ relB <- evalRelationalExpr exprB
149+ Left err -> return $ Left err
150+ Right relA2 -> case relB of
151+ Left err -> return $ Left err
152+ Right relB2 -> return $ difference relA2 relB2
154+evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
155+ case mkRelation attributeSet tupleSet of
156+ Right rel -> return $ Right rel
157+ Left err -> return $ Left err
154−
159+evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
155−dbcTransId :: DatabaseContextEvalMonad TransactionId
160+ currentContext <- fmap stateElemsContext ask
156−dbcTransId = dce_transId <$> RWS.ask
161+ let tConss = typeConstructorMapping currentContext
157−
162+ -- 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
158−dbcGraph :: DatabaseContextEvalMonad TransactionGraph
163+ runExceptT $ do
159−dbcGraph = dce_graph <$> RWS.ask
164+ mAttrs <- case mAttrExprs of
161−dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
166+ Just . A.attributesFromList <$> mapM (either throwE pure . evalAttrExpr tConss) (fromMaybe [] mAttrExprs)
162−dbcRelationalExprEnv =
167+ Nothing -> pure Nothing
163− mkRelationalExprEnv <$> getStateContext <*> dbcGraph
168+ tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
164−
169+ let attrs = fromMaybe firstTupleAttrs mAttrs
165−getStateContext :: DatabaseContextEvalMonad DatabaseContext
170+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
166−getStateContext = gets dbc_context
171+ either throwE pure (mkRelation attrs (RelationTupleSet tuples))
168−putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
169−putStateContext ctx' = do
171− put (s {dbc_context = ctx', dbc_dirty = True})
173−-- | The context is optionally passed down along in cases where the current context is uncommitted.
174−data GraphRefRelationalExprEnv =
175− GraphRefRelationalExprEnv {
176− gre_context :: Maybe DatabaseContext,
177− gre_graph :: TransactionGraph,
178− gre_extra :: Maybe (Either RelationTuple Attributes)
181−type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
173+evalRelationalExpr (ExistingRelation rel) = pure (Right rel)
183−gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
184−gfTransForId tid = do
186− lift $ except $ transactionForId tid graph
188−gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
189−gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
190−gfDatabaseContextForMarker UncommittedContextMarker = do
191− mctx <- gre_context <$> askEnv
193− Nothing -> throwError NoUncommittedContextInEvalError
194− Just ctx -> pure ctx
196−runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
175+evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
197−runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
176+ evald <- evalRelationalExpr relExpr
178+ Right rel -> return $ rename oldAttrName newAttrName rel
179+ Left err -> return $ Left err
199−freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
181+evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
200−freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
182+ eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
201− gre_context = mctx,
183+ case eOldAttrNameSet of
202− gre_graph = graph,
184+ Left err -> pure (Left err)
203− gre_extra = Nothing
185+ Right oldAttrNameSet -> do
204− }
186+ evald <- evalRelationalExpr relExpr
206−gfGraph :: GraphRefRelationalExprM TransactionGraph
188+ Right rel -> return $ group oldAttrNameSet newAttrName rel
207−gfGraph = asks gre_graph
189+ Left err -> return $ Left err
209−envContext :: RelationalExprEnv -> DatabaseContext
191+evalRelationalExpr (Ungroup attrName relExpr) = do
210−envContext = re_context
192+ evald <- evalRelationalExpr relExpr
212−setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
194+ Right rel -> return $ ungroup attrName rel
213−setEnvContext e ctx = e { re_context = ctx }
195+ Left err -> return $ Left err
197+evalRelationalExpr (Restrict predicateExpr relExpr) = do
198+ evald <- evalRelationalExpr relExpr
200+ Left err -> return $ Left err
202+ eFilterFunc <- predicateRestrictionFilter (attributes rel) predicateExpr
204+ Left err -> return $ Left err
206+ pure (restrict filterfunc rel)
208+evalRelationalExpr (Equals relExprA relExprB) = do
209+ evaldA <- evalRelationalExpr relExprA
210+ evaldB <- evalRelationalExpr relExprB
212+ Left err -> return $ Left err
213+ Right relA -> case evaldB of
214+ Left err -> return $ Left err
215+ Right relB -> return $ Right $ if relA == relB then relationTrue else relationFalse
217+evalRelationalExpr (With views mainExpr) = do
220+ let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
221+ Left (RelVarAlreadyDefinedError vname)
223+ case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
224+ (Left err,_) -> Left err
225+ (Right (), (ctx',_,_)) -> Right ctx'
227+ case foldM addScopedView (stateElemsContext rstate) views of
228+ Left err -> return $ Left err
230+ let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprStateElems ctx'')
231+ case evalMainExpr mainExpr of
232+ Left err -> return $ Left err
233+ Right rel -> return $ Right rel
235+--warning: copy-pasta from above- refactor
236+evalRelationalExpr (NotEquals relExprA relExprB) = do
237+ evaldA <- evalRelationalExpr relExprA
238+ evaldB <- evalRelationalExpr relExprB
240+ Left err -> return $ Left err
241+ Right relA -> case evaldB of
242+ Left err -> return $ Left err
243+ Right relB -> return $ Right $ if relA /= relB then relationTrue else relationFalse
245+-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
246+evalRelationalExpr (Extend tupleExpression relExpr) = do
248+ let evald = runReader (evalRelationalExpr relExpr) rstate
250+ Left err -> pure (Left err)
252+ tupProc <- extendTupleExpressionProcessor rel tupleExpression
254+ Left err -> pure (Left err)
255+ Right (newAttrs, tupProc') -> pure $ relMogrify tupProc' newAttrs rel
215--helper function to process relation variable creation/assignment
257--helper function to process relation variable creation/assignment
216−setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
258+setRelVar :: RelVarName -> Relation -> DatabaseState (Either RelationalError ())
217−setRelVar relVarName relExpr = do
259+setRelVar relVarName rel = do
218 currentContext <- getStateContext
260 currentContext <- getStateContext
219− --prevent recursive relvar definition by resolving references to relvars in previous states
220− relExpr' <- resolve relExpr
221− let newRelVars = M.insert relVarName relExpr' $ relationVariables currentContext
261+ let newRelVars = M.insert relVarName rel $ relationVariables currentContext
222 potentialContext = currentContext { relationVariables = newRelVars }
262 potentialContext = currentContext { relationVariables = newRelVars }
223− --optimization: if the relexpr is unchanged, skip the update
263+
224− if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
227− --determine when to check constraints
230− case checkConstraints potentialContext tid graph of
264+ case checkConstraints potentialContext of
231− Left err -> dbErr err
265+ Left err -> pure (Left err)
232− Right _ -> putStateContext potentialContext
267+ putStateContext potentialContext
233−
268+ return (Right ())
234−--fast-path insertion- we already know that the previous relvar validated correctly, so we can validate just the relation that is being inserted for attribute matches- without this, even a single tuple relation inserted causes the entire relation to be re-validated unnecessarily
235−--insertIntoRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
237-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
270-- 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
238−deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
271+deleteRelVar :: RelVarName -> DatabaseState (Either RelationalError ())
239deleteRelVar relVarName = do
272deleteRelVar relVarName = do
240 currContext <- getStateContext
273 currContext <- getStateContext
241 let relVars = relationVariables currContext
274 let relVars = relationVariables currContext
242 if M.notMember relVarName relVars then
275 if M.notMember relVarName relVars then
243− pure ()
276+ pure (Right ())
245 let newRelVars = M.delete relVarName relVars
278 let newRelVars = M.delete relVarName relVars
246 newContext = currContext { relationVariables = newRelVars }
279 newContext = currContext { relationVariables = newRelVars }
247 putStateContext newContext
280 putStateContext newContext
248− pure ()
281+ pure (Right ())
250−evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContextEvalMonad ()
283+evalDatabaseContextExpr :: DatabaseContextExpr -> DatabaseState (Either RelationalError ())
251−evalGraphRefDatabaseContextExpr NoOperation = pure ()
284+evalDatabaseContextExpr NoOperation = pure (Right ())
253−evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
286+evalDatabaseContextExpr (Define relVarName attrExprs) = do
254− context <- getStateContext
255 relvars <- fmap relationVariables getStateContext
287 relvars <- fmap relationVariables getStateContext
256 tConss <- fmap typeConstructorMapping getStateContext
288 tConss <- fmap typeConstructorMapping getStateContext
257− graph <- dbcGraph
289+ let eAttrs = map (evalAttrExpr tConss) attrExprs
258− let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
290+ attrErrs = lefts eAttrs
259− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
291+ attrsList = rights eAttrs
260− case eAttrs of
292+ if not (null attrErrs) then
261− Left err -> dbErr err
293+ pure (Left (someErrors attrErrs))
262− Right attrsList -> do
294+ else do
263− lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
295+ let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
296+ if not (null atomTypeErrs) then
297+ pure (Left (someErrors atomTypeErrs))
264− case M.member relVarName relvars of
299+ case M.member relVarName relvars of
265− True -> dbErr (RelVarAlreadyDefinedError relVarName)
300+ True -> pure (Left (RelVarAlreadyDefinedError relVarName))
266− False -> setRelVar relVarName (ExistingRelation emptyRelation)
301+ False -> setRelVar relVarName emptyRelation >> pure (Right ())
268 attrs = A.attributesFromList attrsList
303 attrs = A.attributesFromList attrsList
269 emptyRelation = Relation attrs emptyTupleSet
304 emptyRelation = Relation attrs emptyTupleSet
271−evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
306+evalDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
273−evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
308+evalDatabaseContextExpr (Assign relVarName expr) = do
274− graph <- re_graph <$> dbcRelationalExprEnv
309+ -- in the future, it would be nice to get types from the RelationalExpr instead of needing to evaluate it
275 context <- getStateContext
310 context <- getStateContext
276− let existingRelVar = M.lookup relVarName (relationVariables context)
311+ let existingRelVar = M.lookup relVarName relVarTable
277− reEnv = freshGraphRefRelationalExprEnv (Just context) graph
312+ relVarTable = relationVariables context
278− eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
313+ value = runReader (evalRelationalExpr expr) (RelationalExprStateElems context)
315+ Left err -> pure (Left err)
279− case existingRelVar of
316+ Right rel -> 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
317+ Nothing -> setRelVar relVarName rel
286− Just existingRel -> do
318+ Just existingRel -> let expectedAttributes = attributes existingRel
287− let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
319+ foundAttributes = attributes rel in
288− case eExpectedType of
320+ if A.attributesEqual expectedAttributes foundAttributes then
289− Left err -> dbErr err
290− Right expectedType ->
291− case eNewExprType of
292− Left err -> dbErr err
293− Right newExprType -> do
294− if newExprType == expectedType then do
295− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
296− setRelVar relVarName expr
321+ setRelVar relVarName rel
298− dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
323+ pure (Left (RelationTypeMismatchError expectedAttributes foundAttributes))
300−evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
325+evalDatabaseContextExpr (Insert relVarName relExpr) = do
301− gfExpr <- relVarByName relVarName
326+ context <- getStateContext
302− let optExpr = applyUnionCollapse (Union
327+ let unionexp = Union relExpr rv
303− relExpr
328+ rv = RelationVariable relVarName ()
304− gfExpr)
329+ unioned = runReader (evalRelationalExpr unionexp) (RelationalExprStateElems context)
305− evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
330+ origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
332+ Left err -> pure (Left err)
333+ Right unioned' -> case origRel of
334+ Left err -> pure (Left err)
335+ Right origRel' -> if cardinality unioned' == cardinality origRel' then --no tuples actually inserted
338+ evalDatabaseContextExpr $ Assign relVarName (ExistingRelation unioned')
340+evalDatabaseContextExpr (Delete relVarName predicate) = do
341+ context <- getStateContext
342+ let rv = RelationVariable relVarName ()
343+ let updatedRel = runReader (evalRelationalExpr (Restrict (NotPredicate predicate) rv)) (RelationalExprStateElems context)
344+ origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
346+ Left err -> pure (Left err)
347+ Right updatedRel' -> case origRel of
348+ Left err -> pure (Left err)
349+ Right origRel' -> if cardinality origRel' == cardinality updatedRel' then
352+ setRelVar relVarName updatedRel'
307−evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
308− gfExpr <- relVarByName relVarName
309− let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
310− setRelVar relVarName optExpr
312--union of restricted+updated portion and the unrestricted+unupdated portion
354--union of restricted+updated portion and the unrestricted+unupdated portion
313−evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
355+evalDatabaseContextExpr (Update relVarName atomExprMap restrictionPredicateExpr) = do
314− rvExpr <- relVarByName relVarName
315− graph <- re_graph <$> dbcRelationalExprEnv
316 context <- getStateContext
356 context <- getStateContext
317− let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
357+ let relVarTable = relationVariables context
318− --get the current attributes name in the relvar to ensure that we don't conflict when renaming
358+ case M.lookup relVarName relVarTable of
319− eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
359+ Nothing -> pure (Left (RelVarNotDefinedError relVarName))
320− exprType' <- case eExprType of
360+ Just rel ->
321− Left err -> throwError err
361+ case runReader (predicateRestrictionFilter (attributes rel) restrictionPredicateExpr) (RelationalExprStateElems context) of
322− Right t -> pure t
362+ Left err -> pure (Left err)
323− let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
363+ Right predicateFunc -> do
324− tmpAttr = tmpAttrC 1
364+ let ret = do
325− tmpAttrC :: Int -> AttributeName -> AttributeName
365+ restrictedPortion <- restrict predicateFunc rel
326− tmpAttrC c attr =
366+ if cardinality restrictedPortion == Finite 0 then
327− let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
367+ pure Nothing
328− if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
331− tmpAttrName
369+ unrestrictedPortion <- restrict (predicateFunc >=> (pure . not)) rel
332− updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
370+ updatedPortion <- relMap (updateTupleWithAtomExprs atomExprMap context) restrictedPortion
333− projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
371+ updatedRel <- updatedPortion `union` unrestrictedPortion
334− restrictedPortion = Restrict pred' rvExpr
372+ pure (Just updatedRel)
335− updated = foldr (\(oldname, atomExpr) accum ->
373+ case ret of
336− let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
374+ Left err -> pure (Left err)
337− updateAttr oldname procAtomExpr accum
375+ Right Nothing -> pure (Right ())
338− ) restrictedPortion (M.toList atomExprMap)
376+ Right (Just updatedRel) -> setRelVar relVarName updatedRel
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)
343−evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
378+evalDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
344 currContext <- getStateContext
379 currContext <- getStateContext
345− transId <- dbcTransId
347 let currDeps = inclusionDependencies currContext
380 let currDeps = inclusionDependencies currContext
348 newDeps = M.insert newDepName newDep currDeps
381 newDeps = M.insert newDepName newDep currDeps
349 if M.member newDepName currDeps then
382 if M.member newDepName currDeps then
350− dbErr (InclusionDependencyNameInUseError newDepName)
383+ pure (Left (InclusionDependencyNameInUseError newDepName))
352 let potentialContext = currContext { inclusionDependencies = newDeps }
385 let potentialContext = currContext { inclusionDependencies = newDeps }
353− -- if the potential context passes all constraints, then save it
354− -- potential optimization: validate only the new constraint- all old constraints must already hold
355− case checkConstraints potentialContext transId graph of
386+ case checkConstraints potentialContext of
356− Left err -> dbErr err
387+ Left err -> pure (Left err)
357− Right _ ->
388+ Right _ -> do
358 putStateContext potentialContext
389 putStateContext potentialContext
360−evalGraphRefDatabaseContextExpr (RemoveInclusionDependency depName) = do
392+evalDatabaseContextExpr (RemoveInclusionDependency depName) = do
361 currContext <- getStateContext
393 currContext <- getStateContext
362 let currDeps = inclusionDependencies currContext
394 let currDeps = inclusionDependencies currContext
363 newDeps = M.delete depName currDeps
395 newDeps = M.delete depName currDeps
364 if M.notMember depName currDeps then
396 if M.notMember depName currDeps then
365− dbErr (InclusionDependencyNameNotInUseError depName)
397+ pure (Left (InclusionDependencyNameNotInUseError depName))
367 putStateContext $ currContext {inclusionDependencies = newDeps }
399 putStateContext $ currContext {inclusionDependencies = newDeps }
369-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
402-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
370−evalGraphRefDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
403+evalDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
371 currentContext <- getStateContext
404 currentContext <- getStateContext
372 let nots = notifications currentContext
405 let nots = notifications currentContext
373 if M.member notName nots then
406 if M.member notName nots then
374− dbErr (NotificationNameInUseError notName)
407+ pure (Left (NotificationNameInUseError notName))
376 let newNotifications = M.insert notName newNotification nots
409 let newNotifications = M.insert notName newNotification nots
377 newNotification = Notification { changeExpr = triggerExpr,
410 newNotification = Notification { changeExpr = triggerExpr,
378 reportOldExpr = resultOldExpr,
411 reportOldExpr = resultOldExpr,
379 reportNewExpr = resultNewExpr}
412 reportNewExpr = resultNewExpr}
380 putStateContext $ currentContext { notifications = newNotifications }
413 putStateContext $ currentContext { notifications = newNotifications }
382−evalGraphRefDatabaseContextExpr (RemoveNotification notName) = do
416+evalDatabaseContextExpr (RemoveNotification notName) = do
383 currentContext <- getStateContext
417 currentContext <- getStateContext
384 let nots = notifications currentContext
418 let nots = notifications currentContext
385 if M.notMember notName nots then
419 if M.notMember notName nots then
386− dbErr (NotificationNameNotInUseError notName)
420+ pure (Left (NotificationNameNotInUseError notName))
388 let newNotifications = M.delete notName nots
422 let newNotifications = M.delete notName nots
389 putStateContext $ currentContext { notifications = newNotifications }
423 putStateContext $ currentContext { notifications = newNotifications }
392-- | Adds type and data constructors to the database context.
426-- | Adds type and data constructors to the database context.
393-- validate that the type *and* constructor names are unique! not yet implemented!
427-- validate that the type *and* constructor names are unique! not yet implemented!
394−evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
428+evalDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
395 currentContext <- getStateContext
429 currentContext <- getStateContext
396 let oldTypes = typeConstructorMapping currentContext
430 let oldTypes = typeConstructorMapping currentContext
397 tConsName = TCD.name tConsDef
431 tConsName = TCD.name tConsDef
398 -- validate that the constructor's types exist
432 -- validate that the constructor's types exist
399 case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
433 case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
400− Left err -> throwError err
434+ Left err -> pure (Left err)
401− Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
435+ Right _ | T.null tConsName || not (isUpper (T.head tConsName)) -> pure (Left (InvalidAtomTypeName tConsName))
402− | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
436+ | isJust (findTypeConstructor tConsName oldTypes) -> pure (Left (AtomTypeNameInUseError tConsName))
403− | otherwise -> do
437+ | otherwise -> do
404− let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
438+ let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
405− putStateContext $ currentContext { typeConstructorMapping = newTypes }
439+ putStateContext $ currentContext { typeConstructorMapping = newTypes }
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.
442-- | 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.
408−evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
443+evalDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
409 currentContext <- getStateContext
444 currentContext <- getStateContext
410 let oldTypes = typeConstructorMapping currentContext
445 let oldTypes = typeConstructorMapping currentContext
411 if isNothing (findTypeConstructor tConsName oldTypes) then
446 if isNothing (findTypeConstructor tConsName oldTypes) then
412− dbErr (AtomTypeNameNotInUseError tConsName)
447+ pure (Left (AtomTypeNameNotInUseError tConsName))
414 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
449 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
415 putStateContext $ currentContext { typeConstructorMapping = newTypes }
450 putStateContext $ currentContext { typeConstructorMapping = newTypes }
417−evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
453+evalDatabaseContextExpr (MultipleExpr exprs) = do
418 --the multiple expressions must pass the same context around- not the old unmodified context
454 --the multiple expressions must pass the same context around- not the old unmodified context
419− mapM_ evalGraphRefDatabaseContextExpr exprs
455+ evald <- forM exprs evalDatabaseContextExpr
420−
456+ --some lifting magic needed here
458+ [] -> pure (Right ())
459+ errs -> pure (Left (someErrors errs))
421−evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
461+evalDatabaseContextExpr (RemoveAtomFunction funcName) = do
422 currentContext <- getStateContext
462 currentContext <- getStateContext
423 let atomFuncs = atomFunctions currentContext
463 let atomFuncs = atomFunctions currentContext
424 case atomFunctionForName funcName atomFuncs of
464 case atomFunctionForName funcName atomFuncs of
425− Left err -> dbErr err
465+ Left err -> pure (Left err)
427− if isScriptedAtomFunction realFunc then do
466+ Right realFunc -> if isScriptedAtomFunction realFunc then do
428− let updatedFuncs = HS.delete realFunc atomFuncs
467+ let updatedFuncs = HS.delete realFunc atomFuncs
429− putStateContext (currentContext {atomFunctions = updatedFuncs })
468+ putStateContext (currentContext {atomFunctions = updatedFuncs })
431− dbErr (PrecompiledFunctionRemoveError funcName)
471+ pure (Left (PrecompiledFunctionRemoveError funcName))
433−evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
473+evalDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
434 context <- getStateContext
474 context <- getStateContext
435 let dbcFuncs = dbcFunctions context
475 let dbcFuncs = dbcFunctions context
436 case databaseContextFunctionForName funcName dbcFuncs of
476 case databaseContextFunctionForName funcName dbcFuncs of
437− Left err -> dbErr err
477+ Left err -> pure (Left err)
439− if isScriptedDatabaseContextFunction realFunc then do
478+ Right realFunc -> if isScriptedDatabaseContextFunction realFunc then do
440− let updatedFuncs = HS.delete realFunc dbcFuncs
479+ let updatedFuncs = HS.delete realFunc dbcFuncs
441− putStateContext (context { dbcFunctions = updatedFuncs })
480+ putStateContext (context { dbcFunctions = updatedFuncs })
443− dbErr (PrecompiledFunctionRemoveError funcName)
483+ pure (Left (PrecompiledFunctionRemoveError funcName))
445−evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
485+evalDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
446 context <- getStateContext
486 context <- getStateContext
448 --resolve atom arguments
487 --resolve atom arguments
449− let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
488+ let relExprState = mkRelationalExprState context
489+ eAtomTypes = map (\atomExpr -> runReader (typeFromAtomExpr emptyAttributes atomExpr) relExprState) atomArgExprs
450 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
490 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
451− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
452 case eFunc of
491 case eFunc of
453− Left err -> dbErr err
492+ Left err -> pure (Left err)
454 Right func -> do
493 Right func -> do
455 let expectedArgCount = length (dbcFuncType func)
494 let expectedArgCount = length (dbcFuncType func)
456 actualArgCount = length atomArgExprs
495 actualArgCount = length atomArgExprs
457 if expectedArgCount /= actualArgCount then
496 if expectedArgCount /= actualArgCount then
458− dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
497+ pure (Left (FunctionArgumentCountMismatchError expectedArgCount actualArgCount))
460 --check that the atom types are valid
499 --check that the atom types are valid
461− case eAtomTypes of
500+ case lefts eAtomTypes of
462− Left err -> dbErr err
501+ _:_ -> pure (Left (someErrors (lefts eAtomTypes)))
463− Right atomTypes -> do
502+ [] -> do
464− let mValidTypes = zipWith (\ expType actType
503+ let atomTypes = rights eAtomTypes
465− -> case atomTypeVerify expType actType of
504+ let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
466− Left err -> Just err
505+ Left err -> Just err
468− (dbcFuncType func) atomTypes
506+ Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
469− typeErrors = catMaybes mValidTypes
507+ typeErrors = catMaybes mValidTypes
470− eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
508+ eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
471 if length (lefts eAtomArgs) > 1 then
509 if length (lefts eAtomArgs) > 1 then
472− dbErr (someErrors (lefts eAtomArgs))
510+ pure (Left (someErrors (lefts eAtomArgs)))
473 else if not (null typeErrors) then
511 else if not (null typeErrors) then
474− dbErr (someErrors typeErrors)
512+ pure (Left (someErrors typeErrors))
476 case evalDatabaseContextFunction func (rights eAtomArgs) context of
514 case evalDatabaseContextFunction func (rights eAtomArgs) context of
477− Left err -> dbErr err
515+ Left err -> pure (Left err)
478− Right newContext -> putStateContext newContext
516+ Right newContext -> putStateContext newContext >> pure (Right ())
479−data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
517+
480− { dbcio_transId :: TransactionId,
518+evalDatabaseContextIOExpr :: Maybe ScriptSession -> DatabaseContext -> DatabaseContextIOExpr -> IO (Either RelationalError DatabaseContext)
481− dbcio_graph :: TransactionGraph,
482− dbcio_mScriptSession :: Maybe ScriptSession
485−type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
487−runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
488−runDatabaseContextIOEvalMonad env ctx m = do
489− res <- runRWST m env freshState
491− (Left err,_,_) -> pure (Left err)
492− (Right (),s,_) -> pure (Right s)
494− freshState = mkDatabaseContextEvalState ctx
496−requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
497−requireScriptSession = do
499− case dbcio_mScriptSession env of
500− Nothing -> pure $ Left $ ScriptError ScriptCompilationDisabledError
501− Just ss -> pure (Right ss)
503−putDBCIOContext :: DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ())
504−putDBCIOContext ctx = do
505− RWS.modify (\dbstate -> dbstate { dbc_context = ctx})
508−getDBCIOContext :: DatabaseContextIOEvalMonad DatabaseContext
509−getDBCIOContext = dbc_context <$> RWS.get
511−getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
512−getDBCIORelationalExprEnv = do
513− context <- getDBCIOContext
514− mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
516−evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
517−#if !defined(PM36_HASKELL_SCRIPTING)
518−evalGraphRefDatabaseContextIOExpr AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
519−evalGraphRefDatabaseContextIOExpr AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
520−evalGraphRefDatabaseContextIOExpr LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
521−evalGraphRefDatabaseContextIOExpr LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
523−evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
519+evalDatabaseContextIOExpr mScriptSession currentContext (AddAtomFunction funcName funcType script) =
524− eScriptSession <- requireScriptSession
520+ case mScriptSession of
525− currentContext <- getDBCIOContext
521+ Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
526− case eScriptSession of
527− Left err -> pure (Left err)
528− Right scriptSession -> do
522+ Just scriptSession -> do
529− res <- liftIO $ try $ runGhc (Just libdir) $ do
523+ res <- try $ runGhc (Just libdir) $ do
530 setSession (hscEnv scriptSession)
524 setSession (hscEnv scriptSession)
531 let atomFuncs = atomFunctions currentContext
525 let atomFuncs = atomFunctions currentContext
532 case extractAtomFunctionType funcType of
526 case extractAtomFunctionType funcType of
@@ -552,13 +546,12 @@ evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = d
552 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
546 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
553 Right eContext -> case eContext of
547 Right eContext -> case eContext of
554 Left err -> pure (Left err)
548 Left err -> pure (Left err)
555− Right context' -> putDBCIOContext context'
549+ Right context' -> pure (Right context')
556−evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
551+evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunction funcName funcType script) =
557− eScriptSession <- requireScriptSession
552+ case mScriptSession of
558− currentContext <- getDBCIOContext
553+ Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
559− case eScriptSession of
560− Left err -> pure (Left err)
561− Right scriptSession -> do
554+ Just scriptSession -> do
562 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
555 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
563 let last2Args = reverse (take 2 (reverse funcType))
556 let last2Args = reverse (take 2 (reverse funcType))
564 atomArgs = take (length funcType - 2) funcType
557 atomArgs = take (length funcType - 2) funcType
@@ -568,7 +561,7 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
568 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
561 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
569 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
562 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
571− res <- liftIO $ try $ runGhc (Just libdir) $ do
564+ res <- try $ runGhc (Just libdir) $ do
572 setSession (hscEnv scriptSession)
565 setSession (hscEnv scriptSession)
573 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
566 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
574 pure $ case eCompiledFunc of
567 pure $ case eCompiledFunc of
@@ -593,86 +586,67 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
593 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
586 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
594 Right eContext -> case eContext of
587 Right eContext -> case eContext of
595 Left err -> pure (Left err)
588 Left err -> pure (Left err)
596− Right context' -> putDBCIOContext context'
589+ Right context' -> pure (Right context')
597−evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
590+evalDatabaseContextIOExpr _ currentContext (LoadAtomFunctions modName funcName modPath) = do
598− currentContext <- getDBCIOContext
599− eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
591+ eLoadFunc <- loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
600 case eLoadFunc of
592 case eLoadFunc of
601 Left LoadSymbolError -> pure (Left LoadFunctionError)
593 Left LoadSymbolError -> pure (Left LoadFunctionError)
602 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
594 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
603 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
595 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
604− in putDBCIOContext newContext
596+ in pure (Right newContext)
605−evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName modPath) = do
597+evalDatabaseContextIOExpr _ currentContext (LoadDatabaseContextFunctions modName funcName modPath) = do
606− currentContext <- getDBCIOContext
607− eLoadFunc <- liftIO $ loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
598+ eLoadFunc <- loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
608 case eLoadFunc of
599 case eLoadFunc of
609 Left LoadSymbolError -> pure (Left LoadFunctionError)
600 Left LoadSymbolError -> pure (Left LoadFunctionError)
610 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
601 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
611 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
602 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
612− in putDBCIOContext newContext
603+ in pure (Right newContext)
614−evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
605+evalDatabaseContextIOExpr _ currentContext (CreateArbitraryRelation relVarName attrExprs range) =
616− currentContext <- getDBCIOContext
607+ case runState ( evalDatabaseContextExpr (Define relVarName attrExprs)) (freshDatabaseState currentContext) of
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)
608+ (Left err,_) -> pure (Left err)
624− Right dbstate -> do
609+ (Right (), elems@(ctx,_,_)) -> do
626 let existingRelVar = M.lookup relVarName relVarTable
611 let existingRelVar = M.lookup relVarName relVarTable
627− relVarTable = relationVariables (dbc_context dbstate)
612+ relVarTable = relationVariables ctx
628 case existingRelVar of
613 case existingRelVar of
629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
614 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
630 Just existingRel -> do
615 Just existingRel -> do
631− let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
616+ let expectedAttributes = attributes existingRel
632− case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
633− Left err -> pure (Left err)
635− let expectedAttributes = attributes relType
636− tcMap = typeConstructorMapping (dbc_context dbstate)
617+ let tcMap = typeConstructorMapping ctx
637− eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
618+ eitherRel <- generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
638− case eitherRel of
619+ case eitherRel of
639− Left err -> pure $ Left err
620+ Left err -> pure $ Left err
640− Right rel ->
621+ Right rel ->
641− case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
622+ case runState (setRelVar relVarName rel) elems of
642− Left err -> pure (Left err)
623+ (Left err,_) -> pure (Left err)
643− Right dbstate' -> putDBCIOContext (dbc_context dbstate')
624+ (Right (), (ctx',_,_)) -> pure $ Right ctx'
626+updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> RelationTuple -> Either RelationalError RelationTuple
627+updateTupleWithAtomExprs exprMap context tupIn = do
628+ --resolve all atom exprs
629+ atomsAssoc <- mapM (\(attrName, atomExpr) -> do
630+ atom <- runReader (evalAtomExpr tupIn atomExpr) (RelationalExprStateElems context)
631+ pure (attrName, atom)
632+ ) (M.toList exprMap)
633+ pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
645--run verification on all constraints
635--run verification on all constraints
646−checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
636+checkConstraints :: DatabaseContext -> Either RelationalError ()
647−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
637+checkConstraints context =
648 mapM_ (uncurry checkIncDep) (M.toList deps)
638 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.:| [],
660 deps = inclusionDependencies context
640 deps = inclusionDependencies context
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
641+ eval expr = evalReader (evalRelationalExpr expr)
642+ evalReader f = runReader f (RelationalExprStateElems context)
662 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
643 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
663− let process = runProcessExprM UncommittedContextMarker
664− gfSubsetExpr = process (processRelationalExpr subsetExpr)
665− gfSupersetExpr = process (processRelationalExpr supersetExpr)
666 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
644 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
667− let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
645+ typeSub <- evalReader (typeForRelationalExpr subsetExpr)
668− runGfRel = runGraphRefRelationalExprM gfEnv
646+ typeSuper <- evalReader (typeForRelationalExpr supersetExpr)
669− typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
670− typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
671 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
647 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
672− let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
648+ let checkExpr = Equals supersetExpr (Union subsetExpr supersetExpr)
673− gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
649+ case eval checkExpr of
674− gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
676 Left err -> Left err
650 Left err -> Left err
677 Right resultRel -> if resultRel == relationTrue then
651 Right resultRel -> if resultRel == relationTrue then
@@ -682,81 +656,91 @@ checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
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
656-- 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
683-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
657-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
685−typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
659+typeForRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
686typeForRelationalExpr expr = do
660typeForRelationalExpr expr = do
662+ let context = stateElemsContext rstate
687 --replace the relationVariables context element with a cloned set of relation devoid of tuples
663 --replace the relationVariables context element with a cloned set of relation devoid of tuples
664+ let context' = contextWithEmptyTupleSets context
665+ rstate' = setStateElemsContext rstate context'
688 --evalRelationalExpr could still return an existing relation with tuples, so strip them
666 --evalRelationalExpr could still return an existing relation with tuples, so strip them
689− graph <- reGraph
667+ pure $ case runReader (evalRelationalExpr expr) rstate' of
690− context <- reContext
668+ Left err -> Left err
691− let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
669+ Right typeRel -> Right (relationWithEmptyTupleSet typeRel)
692− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
670+
693− runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
671+--returns a database context with all tuples removed
694− lift $ except runGf
672+--this is useful for type checking and optimization
673+contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
674+contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
676+ relVars = M.map (\rel -> Relation (attributes rel) emptyTupleSet) (relationVariables contextIn)
696liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
678liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
697liftE v = do
679liftE v = do
698 y <- lift v
680 y <- lift v
699 case y of
681 case y of
700− Left err -> throwError err
682+ Left err -> throwE err
701 Right val -> pure val
683 Right val -> pure val
703{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
685{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
704−predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
686+predicateRestrictionFilter :: Attributes -> RestrictionPredicateExpr -> RelationalExprState (Either RelationalError RestrictionFilter)
705−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
687+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
706− expr1v <- predicateRestrictionFilter attrs expr1
689+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
707− expr2v <- predicateRestrictionFilter attrs expr2
690+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
708− pure (\x -> do
691+ pure (\x -> do
709− ev1 <- expr1v x
692+ ev1 <- expr1v x
710− ev2 <- expr2v x
693+ ev2 <- expr2v x
711− pure (ev1 && ev2))
694+ pure (ev1 && ev2))
713−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
696+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
714− expr1v <- predicateRestrictionFilter attrs expr1
698+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
715− expr2v <- predicateRestrictionFilter attrs expr2
699+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
716 pure (\x -> do
700 pure (\x -> do
717 ev1 <- expr1v x
701 ev1 <- expr1v x
718 ev2 <- expr2v x
702 ev2 <- expr2v x
719 pure (ev1 || ev2))
703 pure (ev1 || ev2))
721−predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
705+predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
723−predicateRestrictionFilter attrs (NotPredicate expr) = do
707+predicateRestrictionFilter attrs (NotPredicate expr) =
724− exprv <- predicateRestrictionFilter attrs expr
709+ exprv <- liftE (predicateRestrictionFilter attrs expr)
725− pure (fmap not . exprv)
710+ 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
712--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
713predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
729− renv <- askEnv
714+ rstate <- ask
730− let eval :: RelationTuple -> Either RelationalError Relation
715+ pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
732− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
733− runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
734− pure (\tup -> case eval tup of
735 Left err -> Left err
716 Left err -> Left err
736 Right rel -> if arity rel /= 0 then
717 Right rel -> if arity rel /= 0 then
737 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
718 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
739− pure (rel == relationTrue))
720+ pure (rel == relationTrue)))
741predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
722predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
742− env <- askEnv
723+ rstate <- ask
743− let attrs' = A.union attrs (envAttributes env)
724+ let (attrs', ctxtup') = case rstate of
744− ctxtup' = envTuple env
725+ RelationalExprStateElems _ -> (attrs, emptyTuple)
726+ RelationalExprStateAttrsElems _ _ -> (attrs, emptyTuple)
727+ RelationalExprStateTupleElems _ ctxtup -> (A.union attrs (tupleAttributes ctxtup), ctxtup)
745− atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
729+ atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
746− attr <- lift $ except $ case A.attributeForName attrName attrs of
730+ attr <- either throwE pure $ case A.attributeForName attrName attrs of
747 Right attr -> Right attr
731 Right attr -> Right attr
748 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
732 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
749 Right ctxattr -> Right ctxattr
733 Right ctxattr -> Right ctxattr
750 Left err2@(NoSuchAttributeNamesError _) -> Left err2
734 Left err2@(NoSuchAttributeNamesError _) -> Left err2
751 Left err -> Left err
735 Left err -> Left err
752 Left err -> Left err
736 Left err -> Left err
753− if atomExprType /= A.atomType attr then
737+ if atomExprType /= A.atomType attr then
754− throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
738+ throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
756 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
740 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
757 Right atomCmp -> atomCmp == atomIn
741 Right atomCmp -> atomCmp == atomIn
758 Left _ -> False
742 Left _ -> False
759− atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
743+ atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
761 pure $ case atomForAttributeName attrName tupleIn of
745 pure $ case atomForAttributeName attrName tupleIn of
762 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
746 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -767,15 +751,16 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
767-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
751-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
768predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
752predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
769 --merge attrs into the state attributes
753 --merge attrs into the state attributes
770− renv <- askEnv
754+ rstate <- ask
771− aType <- typeForGraphRefAtomExpr attrs atomExpr
756+ aType <- liftE (typeFromAtomExpr attrs atomExpr)
772− if aType /= BoolAtomType then
757+ if aType /= BoolAtomType then
773− throwError (AtomTypeMismatchError aType BoolAtomType)
758+ throwE (AtomTypeMismatchError aType BoolAtomType)
775 pure (\tupleIn ->
760 pure (\tupleIn ->
776− case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
761+ case runReader (evalAtomExpr tupleIn atomExpr) rstate of
777− Left err -> Left err
762+ Left err -> Left err
778− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
763+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
780tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
765tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
781tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
766tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
@@ -783,610 +768,235 @@ tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName r
784 Right rel
769 Right rel
786−extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
771+extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
787−extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
772+extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
788−-- renv <- askEnv
773+ rstate <- ask
789 -- check that the attribute name is not in use
774 -- check that the attribute name is not in use
790 case tupleExprCheckNewAttrName newAttrName relIn of
775 case tupleExprCheckNewAttrName newAttrName relIn of
791− Left err -> throwError err
776+ Left err -> pure (Left err)
792− Right _ -> do
777+ Right _ -> runExceptT $ do
793− atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
778+ atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
794− atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
779+ atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
795 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
780 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
796 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
781 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
797− env <- ask
782+ pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in case runReader (evalAtomExpr tup atomExpr) substate of
798− pure (newAndOldAttrs, \tup -> do
783+ Left err -> Left err
799− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
800− atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
801− Right (tupleAtomExtend newAttrName atom tup)
784+ Right atom -> Right (tupleAtomExtend newAttrName atom tup)
804−evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
787+evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
805−evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
806− case atomForAttributeName attrName tupIn of
788+evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
807− Right atom -> pure atom
789+ Right atom -> pure (Right atom)
808− Left err@(NoSuchAttributeNamesError _) -> do
790+ err@(Left (NoSuchAttributeNamesError _)) -> do
809− env <- askEnv
791+ rstate <- ask
810− case gre_extra env of
792+ case rstate of
811− Nothing -> throwError err
793+ RelationalExprStateElems _ -> pure err
794+ RelationalExprStateAttrsElems _ _ -> pure err
812− Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
795+ RelationalExprStateTupleElems _ ctxtup -> pure (atomForAttributeName attrName ctxtup)
813− Just (Right _) -> throwError err
814− Left err -> throwError err
796+ Left err -> pure (Left err)
815−evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
797+evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
816−evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
798+evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
817− argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
799+ argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
818− context <- gfDatabaseContextForMarker tid
800+ context <- fmap stateElemsContext ask
819− let functions = atomFunctions context
802+ let functions = atomFunctions context
820− func <- lift $ except (atomFunctionForName funcName functions)
803+ func <- either throwE pure (atomFunctionForName funcName functions)
821− let expectedArgCount = length (atomFuncType func) - 1
804+ let expectedArgCount = length (atomFuncType func) - 1
822− actualArgCount = length argTypes
805+ actualArgCount = length argTypes
823− safeInit [] = [] -- different behavior from normal init
806+ safeInit [] = [] -- different behavior from normal init
824− safeInit xs = init xs
807+ safeInit xs = init xs
825− if expectedArgCount /= actualArgCount then
808+ if expectedArgCount /= actualArgCount then
826− throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
809+ throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
828 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
811 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
829− mapM_ (\(expType, actType) ->
812+ mapM_ (\(expType, eActType) -> do
813+ actType <- either throwE pure eActType
830− lift $ except (atomTypeVerify expType actType)) zippedArgs
814+ either throwE pure (atomTypeVerify expType actType)) zippedArgs
831− evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
815+ evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
832 case evalAtomFunction func evaldArgs of
816 case evalAtomFunction func evaldArgs of
833− Left err -> throwError (AtomFunctionUserError err)
817+ Left err -> throwE (AtomFunctionUserError err)
834 Right result -> do
818 Right result -> do
835 --validate that the result matches the expected type
819 --validate that the result matches the expected type
836− _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
820+ _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
837 pure result
821 pure result
838−evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
822+evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
839 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
823 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
840− env <- ask
824+ rstate <- ask
841− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
825+ runExceptT $ do
842− relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
826+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
827+ relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
843− pure (RelationAtom relAtom)
828+ pure (RelationAtom relAtom)
844−evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
829+evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
845− let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
830+ rstate <- lift ask
831+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
846− aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
832+ aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
847− argAtoms <- local mergeEnv $
833+ argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
848− mapM (evalGraphRefAtomExpr tupIn) dConsArgs
849 pure (ConstructedAtom dConsName aType argAtoms)
834 pure (ConstructedAtom dConsName aType argAtoms)
851−typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
836+typeFromAtomExpr :: Attributes -> AtomExpr -> RelationalExprState (Either RelationalError AtomType)
852−typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
837+typeFromAtomExpr attrs (AttributeAtomExpr attrName) = do
853− renv <- askEnv
838+ rstate <- ask
854 case A.atomTypeForAttributeName attrName attrs of
839 case A.atomTypeForAttributeName attrName attrs of
855− Right aType -> pure aType
840+ Right aType -> pure (Right aType)
856− Left err@(NoSuchAttributeNamesError _) ->
841+ Left err@(NoSuchAttributeNamesError _) -> case rstate of
857− let envTup = envTuple renv
858− envAttrs = envAttributes renv in
859− case A.attributeForName attrName envAttrs of
842+ RelationalExprStateAttrsElems _ attrs' -> case A.attributeForName attrName attrs' of
843+ Left err' -> pure (Left err')
860− Right attr -> pure (A.atomType attr)
844+ Right attr -> pure (Right (A.atomType attr))
845+ RelationalExprStateElems _ -> pure (Left err)
861− Left _ -> case atomForAttributeName attrName envTup of
846+ RelationalExprStateTupleElems _ tup -> case atomForAttributeName attrName tup of
862− Right atom -> pure (atomTypeForAtom atom)
847+ Left err' -> pure (Left err')
863− Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
848+ Right atom -> pure (Right (atomTypeForAtom atom))
865− Left err -> throwError err
849+ Left err -> pure (Left err)
867−typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
850+typeFromAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
868−typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
851+typeFromAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
852+ context <- fmap stateElemsContext ask
869− funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
853+ let funcs = atomFunctions context
870 case atomFunctionForName funcName funcs of
854 case atomFunctionForName funcName funcs of
871− Left err -> throwError err
855+ Left err -> pure (Left err)
872 Right func -> do
856 Right func -> do
873 let funcRetType = last (atomFuncType func)
857 let funcRetType = last (atomFuncType func)
874 funcArgTypes = init (atomFuncType func)
858 funcArgTypes = init (atomFuncType func)
875− argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
859+ eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
860+ case lefts eArgTypes of
861+ errs@(_:_) -> pure (Left (someErrors errs))
876− let eTvMap = resolveTypeVariables funcArgTypes argTypes
863+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
864+ argTypes = rights eArgTypes
877− case eTvMap of
865+ case eTvMap of
878− Left err -> throwError err
866+ Left err -> pure (Left err)
879− Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
867+ Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
880−typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
868+typeFromAtomExpr attrs (RelationAtomExpr relExpr) = runExceptT $ do
881− relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
869+ rstate <- lift ask
870+ relType <- either throwE pure (runReader (typeForRelationalExpr relExpr) (mergeAttributesIntoRelationalExprState attrs rstate))
882 pure (RelationAtomType (attributes relType))
871 pure (RelationAtomType (attributes relType))
883-- grab the type of the data constructor, then validate that the args match the expected types
872-- grab the type of the data constructor, then validate that the args match the expected types
884−typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
873+typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
885− do
874+ runExceptT $ do
886− argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
875+ argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
887− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
876+ context <- fmap stateElemsContext (lift ask)
888− lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
877+ either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
890-- | Validate that the type of the AtomExpr matches the expected type.
879-- | Validate that the type of the AtomExpr matches the expected type.
891−verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
880+verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
892−verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
881+verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
893− env <- askEnv
882+ rstate <- lift ask
894 case A.atomTypeForAttributeName attrName (attributes relIn) of
883 case A.atomTypeForAttributeName attrName (attributes relIn) of
895− Right aType -> lift $ except $ atomTypeVerify expectedType aType
884+ Right aType -> either throwE pure (atomTypeVerify expectedType aType)
896− (Left err@(NoSuchAttributeNamesError _)) ->
885+ (Left err@(NoSuchAttributeNamesError _)) -> case rstate of
897− let attrs' = envAttributes env in
886+ RelationalExprStateTupleElems _ _ -> throwE err
898− if attrs' == emptyAttributes then
887+ RelationalExprStateElems _ -> throwE err
901− case A.attributeForName attrName attrs' of
888+ RelationalExprStateAttrsElems _ attrs -> case A.attributeForName attrName attrs of
902− Left err' -> throwError err'
889+ Left err' -> throwE err'
903− Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
890+ Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
904− Left err -> throwError err
891+ Left err -> throwE err
906−verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
907− lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
892+verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
908−verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
893+verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
909− context <- gfDatabaseContextForMarker tid
894+ rstate <- ask
910 let functions = atomFunctions context
895 let functions = atomFunctions context
896+ context = stateElemsContext rstate
911− func <- lift $ except $ atomFunctionForName funcName functions
898+ func <- either throwE pure (atomFunctionForName funcName functions)
912− let expectedArgTypes = atomFuncType func
899+ let expectedArgTypes = atomFuncType func
913− funcArgVerifier (atomExpr, expectedType2, argCount) = do
900+ funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
914− let handler :: RelationalError -> GraphRefRelationalExprM AtomType
915− handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
901+ Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
916− handler err = throwError err
902+ Left err -> throwE err
917− verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
903+ Right x -> pure x
918− funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
904+ ) $ zip3 funcArgExprs expectedArgTypes [1..]
919− if length funcArgTypes /= length expectedArgTypes - 1 then
905+ if length funcArgTypes /= length expectedArgTypes - 1 then
920− throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
906+ throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
922− lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
908+ either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
923−verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
909+verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
924− do
910+ rstate <- lift ask
925− let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
911+ relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
926− relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
927− lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
912+ either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
928−verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
913+verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
929− cType <- typeForGraphRefAtomExpr (attributes rel) cons
914+ cType <- liftE (typeFromAtomExpr (attributes rel) cons)
930− lift $ except $ atomTypeVerify expectedType cType
915+ either throwE pure (atomTypeVerify expectedType cType)
932-- | Look up the type's name and create a new attribute.
917-- | Look up the type's name and create a new attribute.
933−evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
918+evalAttrExpr :: TypeConstructorMapping -> AttributeExpr -> Either RelationalError Attribute
934−evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
919+evalAttrExpr aTypes (AttributeAndTypeNameExpr attrName tCons ()) = do
935− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
936− aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
920+ aType <- atomTypeForTypeConstructorValidate True tCons aTypes M.empty
937− lift $ except $ validateAtomType aType tConsMap
921+ validateAtomType aType aTypes
938− pure $ Attribute attrName aType
922+ Right (Attribute attrName aType)
940−evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
924+evalAttrExpr _ (NakedAttributeExpr attr) = Right 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
926+evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
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
991−evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
927+evalTupleExpr mAttrs (TupleExpr tupMap) = do
928+ context <- fmap stateElemsContext ask
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
930 -- 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
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
931 -- 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
994− let attrs = fromMaybe A.emptyAttributes mAttrs
932+ let attrs = fromMaybe A.emptyAttributes mAttrs
995− resolveOneAtom (attrName, aExpr) =
933+ attrAtoms <- mapM (\(attrName, aExpr) -> do
997− --provided when the relation header is available
934+ --provided when the relation header is available
998− let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
935+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
999− unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
936+ unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
1000− resolvedType <- case eExpectedAtomType of
937+ resolvedType <- case eExpectedAtomType of
1001 Left _ -> pure unresolvedType
938 Left _ -> pure unresolvedType
1002− Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
939+ Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
1003 --resolve atom typevars based on resolvedType?
940 --resolve atom typevars based on resolvedType?
1004− newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
941+ newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
1005− pure (attrName, newAtom, resolvedType)
942+ pure (attrName, newAtom, resolvedType)
1006− attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
943+ ) (M.toList tupMap)
1007− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
944+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1008− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
945+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1009− tup = mkRelationTuple tupAttrs atoms
946+ tup = mkRelationTuple tupAttrs atoms
947+ tConss = typeConstructorMapping context
1010− finalAttrs = fromMaybe tupAttrs mAttrs
948+ finalAttrs = fromMaybe tupAttrs mAttrs
1011 --verify that the attributes match
949 --verify that the attributes match
1012− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
950+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
1013− --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1014− --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
951+ tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1015− let tup' = reorderTuple finalAttrs tup
1016− --TODO: restore type resolution
1017−-- _ <- lift $ except (validateTuple tup' tConss)
952+ _ <- either throwE pure (validateTuple tup' tConss)
1018− pure tup'
953+ pure tup'
1020−--temporary implementation until we have a proper planner+executor
955+evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
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)
1172−evalGraphRefAttributeNames attrNames expr = do
956+evalAttributeNames attrNames expr = do
1173− exprType' <- typeForGraphRefRelationalExpr expr
957+ eExprType <- typeForRelationalExpr expr
959+ Left err -> pure (Left err)
1174− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
961+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1175− case attrNames of
962+ case attrNames of
1176− AttributeNames names ->
963+ AttributeNames names ->
1177− case A.projectionAttributesForNames names (attributes exprType') of
964+ case A.projectionAttributesForNames names (attributes exprTyp) of
1178− Left err -> throwError err
965+ Left err -> pure (Left err)
1179− Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
966+ Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1181− InvertedAttributeNames names -> do
968+ InvertedAttributeNames names -> do
1182 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
969 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1183 if not (S.null nonExistentAttributeNames) then
970 if not (S.null nonExistentAttributeNames) then
1184− throwError $ AttributeNamesMismatchError nonExistentAttributeNames
971+ pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1186− pure (A.nonMatchingAttributeNameSet names typeNameSet)
973+ pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
1188− UnionAttributeNames namesA namesB -> do
975+ UnionAttributeNames namesA namesB -> do
1189− nameSetA <- evalGraphRefAttributeNames namesA expr
976+ eNameSetA <- evalAttributeNames namesA expr
1190− nameSetB <- evalGraphRefAttributeNames namesB expr
977+ case eNameSetA of
978+ Left err -> pure (Left err)
979+ Right nameSetA -> do
980+ eNameSetB <- evalAttributeNames namesB expr
982+ Left err -> pure (Left err)
1191− pure (S.union nameSetA nameSetB)
984+ pure (Right (S.union nameSetA nameSetB))
1193− IntersectAttributeNames namesA namesB -> do
986+ IntersectAttributeNames namesA namesB -> do
1194− nameSetA <- evalGraphRefAttributeNames namesA expr
987+ eNameSetA <- evalAttributeNames namesA expr
1195− nameSetB <- evalGraphRefAttributeNames namesB expr
988+ case eNameSetA of
989+ Left err -> pure (Left err)
990+ Right nameSetA -> do
991+ eNameSetB <- evalAttributeNames namesB expr
993+ Left err -> pure (Left err)
1196− pure (S.intersection nameSetA nameSetB)
995+ pure (Right (S.intersection nameSetA nameSetB))
1198− RelationalExprAttributeNames attrExpr -> do
997+ RelationalExprAttributeNames attrExpr -> do
1199− attrExprType <- typeForGraphRefRelationalExpr attrExpr
998+ eAttrExprType <- typeForRelationalExpr attrExpr
999+ case eAttrExprType of
1000+ Left err -> pure (Left err)
1200− pure (A.attributeNameSet (attributes attrExprType))
1001+ Right attrExprType -> pure (Right (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