@@ -1,7 +1,4 @@
11{-# LANGUAGE ScopedTypeVariables #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE OverloadedStrings #-}
52module ProjectM36.RelationalExpression where
63import ProjectM36.Relation
74import ProjectM36.Tuple
@@ -16,38 +13,31 @@ import ProjectM36.DataTypes.Primitive
1613import ProjectM36.AtomFunction
1714import ProjectM36.DatabaseContextFunction
1815import ProjectM36.Arbitrary
19−import ProjectM36.GraphRefRelationalExpr
2016import ProjectM36.Transaction
2117import qualified ProjectM36.Attribute as A
2218import qualified Data.Map as M
2319import qualified Data.HashSet as HS
2420import qualified Data.Set as S
25−import Control.Monad.State hiding (join)
26−import Data.Bifunctor (second)
21+import Control.Monad.Trans.RWS.Strict as RWS
22+import Control.Monad.Trans.Class (lift)
23+import Control.Exception
2724import Data.Maybe
2825import Data.Either
2926import Data.Char (isUpper)
30−import Data.Time
31−import qualified Data.List.NonEmpty as NE
32−import Data.Functor.Identity
3327import qualified Data.Text as T
3428import qualified Data.Vector as V
3529import qualified ProjectM36.TypeConstructorDef as TCD
36−import qualified Control.Monad.RWS.Strict as RWS
37−import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
38−import Control.Monad.Except hiding (join)
39−import Control.Monad.Trans.Except (except)
40−import Control.Monad.Reader as R hiding (join)
41−import ProjectM36.NormalizeExpr
42−import ProjectM36.WithNameExpr
30+import Control.Monad.Trans.Except
31+import Control.Monad.Trans.Reader as R
4332import Test.QuickCheck
44−import qualified Data.Functor.Foldable as Fold
45−import Control.Applicative
46−#ifdef PM36_HASKELL_SCRIPTING
47−import GHC hiding (getContext)
48−import Control.Exception
33+import GHC
4934import GHC.Paths
50−#endif
35+import Data.Time.Clock
36+import Data.Time.Calendar
37+import qualified Data.List.NonEmpty as NE
38+import Data.Functor.Identity
39+import Control.Monad
40+import Control.Monad.IO.Class
5141
5242data DatabaseContextExprDetails = CountUpdatedTuples
5343
@@ -75,52 +65,48 @@ mkDatabaseContextEvalState context = DatabaseContextEvalState {
7565data RelationalExprEnv = RelationalExprEnv {
7666 re_context :: DatabaseContext,
7767 re_graph :: TransactionGraph,
68+ re_currentTransId :: TransactionId,
7869 re_extra :: Maybe (Either RelationTuple Attributes)
7970 }
8071
81−envTuple :: GraphRefRelationalExprEnv -> RelationTuple
82−envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
72+stateTuple :: RelationalExprEnv -> RelationTuple
73+stateTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (re_extra e))
8374
84−envAttributes :: GraphRefRelationalExprEnv -> Attributes
85−envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
75+stateAttributes :: RelationalExprEnv -> Attributes
76+stateAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (re_extra e))
8677
8778instance Show RelationalExprEnv where
8879 show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
8980
90−--used to eval relationalexpr
91−type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
92−
93−runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
94−runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
95−
96−reGraph :: RelationalExprM TransactionGraph
97−reGraph = asks re_graph
98−
99−reContext :: RelationalExprM DatabaseContext
100−reContext = asks re_context
101−
102−mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
103−mkRelationalExprEnv ctx graph =
81+mkRelationalExprEnv :: DatabaseContext -> TransactionId -> TransactionGraph -> RelationalExprEnv
82+mkRelationalExprEnv ctx currentTransId graph =
10483 RelationalExprEnv
10584 { re_context = ctx,
10685 re_graph = graph,
86+ re_currentTransId = currentTransId,
10787 re_extra = Nothing }
10888
109−askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
89+askEnv :: RelationalExprState RelationalExprEnv
11090askEnv = R.ask
11191
112−mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
113−mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
114− env { gre_extra = new_elems }
92+currentTrans :: RelationalExprState (Either RelationalError Transaction)
93+currentTrans = do
94+ tid <- re_currentTransId <$> R.ask
95+ graph <- re_graph <$> R.ask
96+ pure (transactionForId tid graph)
97+
98+mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprEnv -> RelationalExprEnv
99+mergeTuplesIntoRelationalExprState tupIn e@RelationalExprEnv{} =
100+ e{re_extra = new_elems }
115101 where
116102 new_elems = Just (Left newTuple)
117− mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
103+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (stateTuple e))
118104 newTuple = mkRelationTupleFromMap mergedTupMap
119−
120−mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
121−mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
105+
106+mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprEnv -> RelationalExprEnv
107+mergeAttributesIntoRelationalExprState attrsIn e@RelationalExprEnv{} = e{re_extra = newattrs }
122108 where
123− newattrs = Just (Right (A.union attrsIn (envAttributes e)))
109+ newattrs = Just (Right (A.union attrsIn (stateAttributes e)))
124110
125111type ResultAccumName = StringType
126112
@@ -142,12 +128,12 @@ data DatabaseContextEvalEnv = DatabaseContextEvalEnv
142128 }
143129
144130mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
145−mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
131+mkDatabaseContextEvalEnv tid graph = DatabaseContextEvalEnv tid graph
146132
147133type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
148134
149135runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
150−runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
136+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> (execRWST m env freshEnv)))
151137 where
152138 freshEnv = mkDatabaseContextEvalState ctx
153139
@@ -160,51 +146,19 @@ dbcGraph = dce_graph <$> RWS.ask
160146
161147dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
162148dbcRelationalExprEnv =
163− mkRelationalExprEnv <$> getStateContext <*> dbcGraph
149+ mkRelationalExprEnv <$> getStateContext <*> dbcTransId <*> dbcGraph
164150
165151getStateContext :: DatabaseContextEvalMonad DatabaseContext
166−getStateContext = gets dbc_context
152+getStateContext = dbc_context <$> get
167153
168154putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
169155putStateContext ctx' = do
170156 s <- get
171− put (s {dbc_context = ctx', dbc_dirty = True})
172−
173−-- | The context is optionally passed down along in cases where the current context is uncommitted.
174−data GraphRefRelationalExprEnv =
175− GraphRefRelationalExprEnv {
176− gre_context :: Maybe DatabaseContext,
177− gre_graph :: TransactionGraph,
178− gre_extra :: Maybe (Either RelationTuple Attributes)
179− }
157+ put (s {dbc_context = ctx'})
180158
181−type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
182−
183−gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
184−gfTransForId tid = do
185− graph <- gfGraph
186− lift $ except $ transactionForId tid graph
187−
188−gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
189−gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
190−gfDatabaseContextForMarker UncommittedContextMarker = do
191− mctx <- gre_context <$> askEnv
192− case mctx of
193− Nothing -> throwError NoUncommittedContextInEvalError
194− Just ctx -> pure ctx
195−
196−runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
197−runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
198−
199−freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
200−freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
201− gre_context = mctx,
202− gre_graph = graph,
203− gre_extra = Nothing
204− }
159+type RelationalExprState a = Reader RelationalExprEnv a
205160
206−gfGraph :: GraphRefRelationalExprM TransactionGraph
207−gfGraph = asks gre_graph
161+type GraphRefRelationalExprR a = Reader TransactionGraph a
208162
209163envContext :: RelationalExprEnv -> DatabaseContext
210164envContext = re_context
@@ -212,27 +166,173 @@ envContext = re_context
212166setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
213167setEnvContext e ctx = e { re_context = ctx }
214168
169+{-
170+--full evaluation down the graph
171+eval :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
172+eval expr = do
173+ env <- askEnv
174+ eGfExpr <- processRelationalExpr expr
175+ case eGfExpr of
176+ Left err -> pure (Left err)
177+ Right gfExpr -> pure $ evalGraphRefRelationalExpr gfExpr (re_graph env)
178+-}
179+{-
180+--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
181+evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
182+evalRelationalExpr (RelationVariable name _) = do
183+ relvarTable <- fmap (relationVariables . envContext) askEnv
184+ return $ case M.lookup name relvarTable of
185+ Just res -> Right res
186+ Nothing -> Left $ RelVarNotDefinedError name
187+
188+evalRelationalExpr (Project attrNames expr) = do
189+ eAttrNameSet <- evalAttributeNames attrNames expr
190+ case eAttrNameSet of
191+ Left err -> pure (Left err)
192+ Right attrNameSet -> do
193+ rel <- evalRelationalExpr expr
194+ case rel of
195+ Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
196+ Left err -> pure $ Left err
197+
198+evalRelationalExpr (Union exprA exprB) = do
199+ relA <- evalRelationalExpr exprA
200+ relB <- evalRelationalExpr exprB
201+ case relA of
202+ Left err -> return $ Left err
203+ Right relA2 -> case relB of
204+ Left err -> return $ Left err
205+ Right relB2 -> return $ Right (Union relA2 relB2)
206+
207+evalRelationalExpr (Join exprA exprB) = do
208+ relA <- evalRelationalExpr exprA
209+ relB <- evalRelationalExpr exprB
210+ case relA of
211+ Left err -> return $ Left err
212+ Right relA2 -> case relB of
213+ Left err -> return $ Left err
214+ Right relB2 -> return $ Right (Join relA2 relB2)
215+
216+evalRelationalExpr (Difference exprA exprB) = do
217+ relA <- evalRelationalExpr exprA
218+ relB <- evalRelationalExpr exprB
219+ case relA of
220+ Left err -> return $ Left err
221+ Right relA2 -> case relB of
222+ Left err -> return $ Left err
223+ Right relB2 -> return $ Right (Difference relA2 relB2)
224+
225+evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
226+ case mkRelation attributeSet tupleSet of
227+ Right rel -> return $ Right (ExistingRelation rel)
228+ Left err -> return $ Left err
229+
230+evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
231+ currentContext <- fmap envContext askEnv
232+ let tConss = typeConstructorMapping currentContext
233+ -- 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
234+ runExceptT $ do
235+ mAttrs <- case mAttrExprs of
236+ Just _ ->
237+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
238+ Nothing -> pure Nothing
239+ tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
240+ let attrs = fromMaybe firstTupleAttrs mAttrs
241+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
242+ expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
243+ pure (ExistingRelation expr)
244+
245+evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
246+
247+evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
248+ evald <- evalRelationalExpr relExpr
249+ case evald of
250+ Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
251+ Left err -> return $ Left err
252+
253+evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
254+ eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
255+ case eOldAttrNameSet of
256+ Left err -> pure (Left err)
257+ Right oldAttrNameSet -> do
258+ evald <- evalRelationalExpr relExpr
259+ case evald of
260+ Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
261+ Left err -> return $ Left err
262+
263+evalRelationalExpr (Ungroup attrName relExpr) = do
264+ evald <- evalRelationalExpr relExpr
265+ case evald of
266+ Right expr -> return $ Right (Ungroup attrName expr)
267+ Left err -> return $ Left err
268+
269+evalRelationalExpr (Restrict predicateExpr relExpr) = do
270+ evald <- evalRelationalExpr relExpr
271+ pred <- processRestrictionPredicateExpr predicateExpr
272+ case evald of
273+ Left err -> return $ Left err
274+ Right expr ->
275+ pure $ Right (Restrict pred expr)
276+
277+evalRelationalExpr (Equals relExprA relExprB) = do
278+ evaldA <- evalRelationalExpr relExprA
279+ evaldB <- evalRelationalExpr relExprB
280+ case evaldA of
281+ Left err -> return $ Left err
282+ Right exprA -> case evaldB of
283+ Left err -> return $ Left err
284+ Right exprB -> return $ Right (Equals exprA exprB)
285+{-
286+evalRelationalExpr (With views mainExpr) = do
287+ rstate <- ask
288+
289+ let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
290+ Left (RelVarAlreadyDefinedError vname)
291+ else
292+ case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
293+ (Left err,_) -> Left err
294+ (Right (), (ctx',_,_)) -> Right ctx'
295+
296+ case foldM addScopedView (stateElemsContext rstate) views of
297+ Left err -> return $ Left err
298+ Right ctx'' -> do
299+ let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprEnv ctx'')
300+ case evalMainExpr mainExpr of
301+ Left err -> return $ Left err
302+ Right rel -> return $ Right rel
303+-}
304+--warning: copy-pasta from above- refactor
305+evalRelationalExpr (NotEquals relExprA relExprB) = do
306+ evaldA <- evalRelationalExpr relExprA
307+ evaldB <- evalRelationalExpr relExprB
308+ case evaldA of
309+ Left err -> return $ Left err
310+ Right exprA -> case evaldB of
311+ Left err -> return $ Left err
312+ Right exprB -> return $ Right (NotEquals exprA exprB)
313+
314+-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
315+evalRelationalExpr (Extend tupleExpression relExpr) = do
316+ eExpr <- evalRelationalExpr relExpr
317+ case eExpr of
318+ Left err -> pure (Left err)
319+ Right expr -> do
320+ tupProc <- processExtendTupleExpr tupleExpression
321+ pure (Right (Extend tupProc expr))
322+-}
215323--helper function to process relation variable creation/assignment
216324setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
217325setRelVar relVarName relExpr = do
326+
218327 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
328+ let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
222329 potentialContext = currentContext { relationVariables = newRelVars }
223− --optimization: if the relexpr is unchanged, skip the update
224− if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
225− pure ()
226− else do
227− --determine when to check constraints
228− graph <- dbcGraph
229− tid <- dbcTransId
230− case checkConstraints potentialContext tid graph of
231− Left err -> dbErr err
232− Right _ -> putStateContext potentialContext
233−
234−--fast-path insertion- we already know that the previous relvar validated correctly, so we can validate just the relation that is being inserted for attribute matches- without this, even a single tuple relation inserted causes the entire relation to be re-validated unnecessarily
235−--insertIntoRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
330+ --determine when to check constraints
331+ graph <- dbcGraph
332+ tid <- dbcTransId
333+ case checkConstraints potentialContext tid graph of
334+ Left err -> dbErr err
335+ Right _ -> putStateContext potentialContext
236336
237337-- 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
238338deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
@@ -251,17 +351,20 @@ evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContex
251351evalGraphRefDatabaseContextExpr NoOperation = pure ()
252352
253353evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
254− context <- getStateContext
255354 relvars <- fmap relationVariables getStateContext
256355 tConss <- fmap typeConstructorMapping getStateContext
257− graph <- dbcGraph
258− let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
259− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
260− case eAttrs of
261− Left err -> dbErr err
262− Right attrsList -> do
263− lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
264− case M.member relVarName relvars of
356+ relEnv <- dbcRelationalExprEnv
357+ let eAttrs = runReader (mapM evalGraphRefAttrExpr attrExprs) relEnv
358+ attrErrs = lefts eAttrs
359+ attrsList = rights eAttrs
360+ if not (null attrErrs) then
361+ dbErr (someErrors attrErrs)
362+ else do
363+ let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
364+ if not (null atomTypeErrs) then
365+ dbErr (someErrors atomTypeErrs)
366+ else
367+ case M.member relVarName relvars of
265368 True -> dbErr (RelVarAlreadyDefinedError relVarName)
266369 False -> setRelVar relVarName (ExistingRelation emptyRelation)
267370 where
@@ -274,17 +377,12 @@ evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
274377 graph <- re_graph <$> dbcRelationalExprEnv
275378 context <- getStateContext
276379 let existingRelVar = M.lookup relVarName (relationVariables context)
277− reEnv = freshGraphRefRelationalExprEnv (Just context) graph
278− eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
279380 case existingRelVar of
280381 Nothing -> do
281− case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
282− Left err -> dbErr err
283− Right reltype -> do
284− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
285− setRelVar relVarName expr
382+ setRelVar relVarName expr
286383 Just existingRel -> do
287− let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
384+ let eExpectedType = runReader (typeForGraphRefRelationalExpr existingRel) graph
385+ eNewExprType = runReader (typeForGraphRefRelationalExpr expr) graph
288386 case eExpectedType of
289387 Left err -> dbErr err
290388 Right expectedType ->
@@ -292,53 +390,44 @@ evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
292390 Left err -> dbErr err
293391 Right newExprType -> do
294392 if newExprType == expectedType then do
295− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
296393 setRelVar relVarName expr
297394 else
298395 dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
299396
300397evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
301− gfExpr <- relVarByName relVarName
302− let optExpr = applyUnionCollapse (Union
303− relExpr
304− gfExpr)
305− evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
398+ transId <- dbcTransId
399+ evalGraphRefDatabaseContextExpr (Assign relVarName
400+ (Union
401+ (RelationVariable relVarName transId)
402+ relExpr))
306403
307404evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
308− gfExpr <- relVarByName relVarName
309− let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
310− setRelVar relVarName optExpr
405+ transId <- dbcTransId
406+ let rv = RelationVariable relVarName transId
407+ setRelVar relVarName (Restrict (NotPredicate predicate) rv)
311408
312409--union of restricted+updated portion and the unrestricted+unupdated portion
313410evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
314− rvExpr <- relVarByName relVarName
315− graph <- re_graph <$> dbcRelationalExprEnv
316411 context <- getStateContext
317− let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
318− --get the current attributes name in the relvar to ensure that we don't conflict when renaming
319− eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
320− exprType' <- case eExprType of
321− Left err -> throwError err
322− Right t -> pure t
323− let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
324− tmpAttr = tmpAttrC 1
325− tmpAttrC :: Int -> AttributeName -> AttributeName
326− tmpAttrC c attr =
327− let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
328− if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
329− tmpAttrC (c+1) attr
330− else
331− tmpAttrName
332− updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
333− projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
334− restrictedPortion = Restrict pred' rvExpr
335− updated = foldr (\(oldname, atomExpr) accum ->
336− let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
412+ transId <- dbcTransId
413+ reEnv <- dbcRelationalExprEnv
414+ let relVarMap = relationVariables context
415+ case M.lookup relVarName relVarMap of
416+ Nothing -> dbErr (RelVarNotDefinedError relVarName)
417+ Just _ -> do
418+ let unrestrictedPortion = Restrict (NotPredicate pred') rv
419+ rv = RelationVariable relVarName transId
420+ tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
421+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
422+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
423+ restrictedPortion = Restrict pred'
424+ updated = foldr (\(oldname, atomExpr) accum ->
425+ let procAtomExpr = runReader (processAtomExpr atomExpr) reEnv in
337426 updateAttr oldname procAtomExpr accum
338− ) restrictedPortion (M.toList atomExprMap)
427+ ) rv (M.toList atomExprMap)
339428 -- 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)
429+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
430+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
342431
343432evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
344433 currContext <- getStateContext
@@ -350,8 +439,6 @@ evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
350439 dbErr (InclusionDependencyNameInUseError newDepName)
351440 else do
352441 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
355442 case checkConstraints potentialContext transId graph of
356443 Left err -> dbErr err
357444 Right _ ->
@@ -396,9 +483,9 @@ evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
396483 let oldTypes = typeConstructorMapping currentContext
397484 tConsName = TCD.name tConsDef
398485 -- validate that the constructor's types exist
399− case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
400− Left err -> throwError err
401− Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
486+ case validateTypeConstructorDef tConsDef dConsDefList of
487+ errs@(_:_) -> dbErr (someErrors errs)
488+ [] | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
402489 | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
403490 | otherwise -> do
404491 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
@@ -414,10 +501,15 @@ evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
414501 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
415502 putStateContext $ currentContext { typeConstructorMapping = newTypes }
416503
417−evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
504+evalGraphRefDatabaseContextExpr (MultipleExpr _) = do
418505 --the multiple expressions must pass the same context around- not the old unmodified context
419− mapM_ evalGraphRefDatabaseContextExpr exprs
420−
506+ unimplemented
507+{- evald <- forM exprs (\expr -> evalGraphRefDatabaseContextExpr expr)
508+ --some lifting magic needed here
509+ case lefts evald of
510+ [] -> pure ()
511+ errs -> dbErr (someErrors errs)
512+ -}
421513evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
422514 currentContext <- getStateContext
423515 let atomFuncs = atomFunctions currentContext
@@ -444,11 +536,10 @@ evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
444536
445537evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
446538 context <- getStateContext
447− graph <- dbcGraph
539+ relExprEnv <- dbcRelationalExprEnv
448540 --resolve atom arguments
449− let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
541+ let eAtomTypes = map (\atomExpr -> runReader (typeForGraphRefAtomExpr emptyAttributes atomExpr) relExprEnv) atomArgExprs
450542 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
451− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
452543 case eFunc of
453544 Left err -> dbErr err
454545 Right func -> do
@@ -458,16 +549,16 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
458549 dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
459550 else
460551 --check that the atom types are valid
461− case eAtomTypes of
462− Left err -> dbErr err
463− Right atomTypes -> do
464− let mValidTypes = zipWith (\ expType actType
465− -> case atomTypeVerify expType actType of
466− Left err -> Just err
467− Right _ -> Nothing)
468− (dbcFuncType func) atomTypes
552+ case lefts eAtomTypes of
553+ _:_ -> dbErr (someErrors (lefts eAtomTypes))
554+ [] -> do
555+ let atomTypes = rights eAtomTypes
556+ let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
557+ Left err -> Just err
558+ Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
469559 typeErrors = catMaybes mValidTypes
470− eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
560+ eAtomArgs = unimplemented
561+ --eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
471562 if length (lefts eAtomArgs) > 1 then
472563 dbErr (someErrors (lefts eAtomArgs))
473564 else if not (null typeErrors) then
@@ -476,6 +567,7 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
476567 case evalDatabaseContextFunction func (rights eAtomArgs) context of
477568 Left err -> dbErr err
478569 Right newContext -> putStateContext newContext
570+
479571data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
480572 { dbcio_transId :: TransactionId,
481573 dbcio_graph :: TransactionGraph,
@@ -511,15 +603,10 @@ getDBCIOContext = dbc_context <$> RWS.get
511603getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
512604getDBCIORelationalExprEnv = do
513605 context <- getDBCIOContext
514− mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
606+ env <- RWS.ask
607+ pure $ mkRelationalExprEnv context (dbcio_transId env) (dbcio_graph env)
515608
516609evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
517−#if !defined(PM36_HASKELL_SCRIPTING)
518−evalGraphRefDatabaseContextIOExpr AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
519−evalGraphRefDatabaseContextIOExpr AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
520−evalGraphRefDatabaseContextIOExpr LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
521−evalGraphRefDatabaseContextIOExpr LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
522−#else
523610evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
524611 eScriptSession <- requireScriptSession
525612 currentContext <- getDBCIOContext
@@ -553,6 +640,7 @@ evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = d
553640 Right eContext -> case eContext of
554641 Left err -> pure (Left err)
555642 Right context' -> putDBCIOContext context'
643+
556644evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
557645 eScriptSession <- requireScriptSession
558646 currentContext <- getDBCIOContext
@@ -594,6 +682,7 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
594682 Right eContext -> case eContext of
595683 Left err -> pure (Left err)
596684 Right context' -> putDBCIOContext context'
685+
597686evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
598687 currentContext <- getDBCIOContext
599688 eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
@@ -610,7 +699,7 @@ evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName
610699 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
611700 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
612701 in putDBCIOContext newContext
613−#endif
702+
614703evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
615704 --Define
616705 currentContext <- getDBCIOContext
@@ -618,61 +707,63 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
618707 --create graph ref expr
619708 let gfExpr = Define relVarName attrExprs
620709 evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
710+ transId = dbcio_transId env
621711 graph = dbcio_graph env
622712 case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
623713 Left err -> pure (Left err)
624− Right dbstate -> do
714+ Right state -> do
625715 --Assign
626716 let existingRelVar = M.lookup relVarName relVarTable
627− relVarTable = relationVariables (dbc_context dbstate)
717+ relVarTable = relationVariables (dbc_context state)
628718 case existingRelVar of
629719 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
630720 Just existingRel -> do
631− let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
632− case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
721+ case runReader (typeForGraphRefRelationalExpr existingRel) graph of
633722 Left err -> pure (Left err)
634723 Right relType -> do
635724 let expectedAttributes = attributes relType
636− tcMap = typeConstructorMapping (dbc_context dbstate)
725+ tcMap = typeConstructorMapping (dbc_context state)
637726 eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
638727 case eitherRel of
639728 Left err -> pure $ Left err
640729 Right rel ->
641730 case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
642731 Left err -> pure (Left err)
643− Right dbstate' -> putDBCIOContext (dbc_context dbstate')
732+ Right state -> putDBCIOContext (dbc_context state)
733+
734+updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
735+updateTupleWithAtomExprs exprMap context graph tupIn = do
736+ --resolve all atom exprs
737+ atomsAssoc <- mapM (\(attrName, atomExpr) -> do
738+ let atom = unimplemented
739+ --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
740+ pure (attrName, atom)
741+ ) (M.toList exprMap)
742+ pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
644743
645744--run verification on all constraints
646745checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
647−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
746+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
648747 mapM_ (uncurry checkIncDep) (M.toList deps)
649748 where
650749 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
651750 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
652751 utctDayTime = secondsToDiffTime 0 }
653752 tempSchemas = Schemas context M.empty
654− tempTrans = Transaction U.nil tempTransInfo tempSchemas
655− tempTransInfo = TransactionInfo { parents = transId NE.:| [],
656− stamp = tempStamp,
657− merkleHash = mempty
658− }
753+ tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
659754
660755 deps = inclusionDependencies context
756+ reEnv = mkRelationalExprEnv context transId graph
661757 -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
662758 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
663− let process = runProcessExprM UncommittedContextMarker
664− gfSubsetExpr = process (processRelationalExpr subsetExpr)
665− gfSupersetExpr = process (processRelationalExpr supersetExpr)
759+ let gfSubsetExpr = runReader (processRelationalExpr subsetExpr) reEnv
760+ gfSupersetExpr = runReader (processRelationalExpr supersetExpr) reEnv
666761 --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
668− runGfRel = runGraphRefRelationalExprM gfEnv
669− typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
670− typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
762+ typeSub <- runReader (typeForRelationalExpr subsetExpr) reEnv
763+ typeSuper <- runReader (typeForRelationalExpr supersetExpr) reEnv
671764 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
672765 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
673− gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
674− gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
675− case gfEvald of
766+ case evalGraphRefRelationalExpr checkExpr potentialGraph of
676767 Left err -> Left err
677768 Right resultRel -> if resultRel == relationTrue then
678769 pure ()
@@ -682,81 +773,88 @@ checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
682773-- 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
683774-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
684775
685−typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
776+typeForRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
686777typeForRelationalExpr expr = do
687778 --replace the relationVariables context element with a cloned set of relation devoid of tuples
688779 --evalRelationalExpr could still return an existing relation with tuples, so strip them
689− graph <- reGraph
690− context <- reContext
691− let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
692− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
693− runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
694− lift $ except runGf
780+ gfExpr <- processRelationalExpr expr
781+ graph <- re_graph <$> askEnv
782+ pure $ runReader (typeForGraphRefRelationalExpr gfExpr) graph
783+
784+--returns a database context with all tuples removed
785+--this is useful for type checking and optimization
786+{-
787+contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
788+contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
789+ where
790+ relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
791+-}
695792
696793liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
697794liftE v = do
698795 y <- lift v
699796 case y of
700− Left err -> throwError err
797+ Left err -> throwE err
701798 Right val -> pure val
702799
703800{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
704−predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
705−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
706− expr1v <- predicateRestrictionFilter attrs expr1
707− expr2v <- predicateRestrictionFilter attrs expr2
708− pure (\x -> do
709− ev1 <- expr1v x
710− ev2 <- expr2v x
711− pure (ev1 && ev2))
712−
713−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
714− expr1v <- predicateRestrictionFilter attrs expr1
715− expr2v <- predicateRestrictionFilter attrs expr2
801+predicateRestrictionFilter :: Attributes -> RestrictionPredicateExprBase a -> RelationalExprState (Either RelationalError RestrictionFilter)
802+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
803+ runExceptT $ do
804+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
805+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
806+ pure (\x -> do
807+ ev1 <- expr1v x
808+ ev2 <- expr2v x
809+ pure (ev1 && ev2))
810+
811+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
812+ runExceptT $ do
813+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
814+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
716815 pure (\x -> do
717816 ev1 <- expr1v x
718817 ev2 <- expr2v x
719818 pure (ev1 || ev2))
720819
721−predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
820+predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
722821
723−predicateRestrictionFilter attrs (NotPredicate expr) = do
724− exprv <- predicateRestrictionFilter attrs expr
725− pure (fmap not . exprv)
822+predicateRestrictionFilter attrs (NotPredicate expr) =
823+ runExceptT $ do
824+ exprv <- liftE (predicateRestrictionFilter attrs expr)
825+ pure (fmap not . exprv)
726826
727827--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
828+{-
728829predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
729− renv <- askEnv
730− let eval :: RelationTuple -> Either RelationalError Relation
731− eval tup =
732− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
733− runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
734− pure (\tup -> case eval tup of
830+ rstate <- ask
831+ pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
735832 Left err -> Left err
736833 Right rel -> if arity rel /= 0 then
737834 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
738835 else
739− pure (rel == relationTrue))
836+ pure (rel == relationTrue)))
740837
741838predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
742− env <- askEnv
743− let attrs' = A.union attrs (envAttributes env)
744− ctxtup' = envTuple env
745− atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
746− attr <- lift $ except $ case A.attributeForName attrName attrs of
839+ rstate <- ask
840+ let attrs' = stateAttributes rstate
841+ ctxtup' = stateTuple rstate
842+ runExceptT $ do
843+ atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
844+ attr <- either throwE pure $ case A.attributeForName attrName attrs of
747845 Right attr -> Right attr
748846 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
749847 Right ctxattr -> Right ctxattr
750848 Left err2@(NoSuchAttributeNamesError _) -> Left err2
751849 Left err -> Left err
752850 Left err -> Left err
753− if atomExprType /= A.atomType attr then
754− throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
755− else
851+ if atomExprType /= A.atomType attr then
852+ throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
853+ else
756854 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
757855 Right atomCmp -> atomCmp == atomIn
758856 Left _ -> False
759− atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
857+ atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
760858 in
761859 pure $ case atomForAttributeName attrName tupleIn of
762860 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -767,322 +865,279 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
767865-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
768866predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
769867 --merge attrs into the state attributes
770− renv <- askEnv
771− aType <- typeForGraphRefAtomExpr attrs atomExpr
772− if aType /= BoolAtomType then
773− throwError (AtomTypeMismatchError aType BoolAtomType)
774− else
868+ rstate <- ask
869+ runExceptT $ do
870+ aType <- liftE (typeFromAtomExpr attrs atomExpr)
871+ if aType /= BoolAtomType then
872+ throwE (AtomTypeMismatchError aType BoolAtomType)
873+ else
775874 pure (\tupleIn ->
776− case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
777− Left err -> Left err
778− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
779−
875+ case runReader (evalAtomExpr tupleIn atomExpr) rstate of
876+ Left err -> Left err
877+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
878+-}
780879tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
781880tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
782881 Left (AttributeNameInUseError attrName)
783882 else
784883 Right rel
785884
786−extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
787−extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
788−-- renv <- askEnv
885+extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
886+extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
887+ rstate <- askEnv
789888 -- check that the attribute name is not in use
790889 case tupleExprCheckNewAttrName newAttrName relIn of
791− Left err -> throwError err
792− Right _ -> do
793− atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
794− atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
890+ Left err -> pure (Left err)
891+ Right _ -> runExceptT $ do
892+ atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
893+ atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
795894 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
796895 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
797− env <- ask
798− pure (newAndOldAttrs, \tup -> do
799− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
800− atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
801− Right (tupleAtomExtend newAttrName atom tup)
896+ pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in
897+ case unimplemented {-runReader (evalAtomExpr tup atomExpr) substate-} of
898+ Left err -> Left err
899+ Right atom -> Right (tupleAtomExtend newAttrName atom tup)
802900 )
803901
804−evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
805−evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
806− case atomForAttributeName attrName tupIn of
807− Right atom -> pure atom
808− Left err@(NoSuchAttributeNamesError _) -> do
809− env <- askEnv
810− case gre_extra env of
811− Nothing -> throwError err
812− Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
813− Just (Right _) -> throwError err
814− Left err -> throwError err
815−evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
816−evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
817− argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
818− context <- gfDatabaseContextForMarker tid
819− let functions = atomFunctions context
820− func <- lift $ except (atomFunctionForName funcName functions)
821− let expectedArgCount = length (atomFuncType func) - 1
822− actualArgCount = length argTypes
823− safeInit [] = [] -- different behavior from normal init
824− safeInit xs = init xs
825− if expectedArgCount /= actualArgCount then
826− throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
827− else do
902+
903+evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
904+evalAtomExpr = undefined
905+{-
906+
907+evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
908+ Right atom -> pure (Right atom)
909+ err@(Left (NoSuchAttributeNamesError _)) -> do
910+ rstate <- ask
911+ let stateTup = stateTuple rstate
912+ pure (atomForAttributeName attrName stateTup)
913+ Left err -> pure (Left err)
914+evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
915+evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
916+ argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
917+ context <- fmap stateElemsContext ask
918+ runExceptT $ do
919+ let functions = atomFunctions context
920+ func <- either throwE pure (atomFunctionForName funcName functions)
921+ let expectedArgCount = length (atomFuncType func) - 1
922+ actualArgCount = length argTypes
923+ safeInit [] = [] -- different behavior from normal init
924+ safeInit xs = init xs
925+ if expectedArgCount /= actualArgCount then
926+ throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
927+ else do
828928 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
829− mapM_ (\(expType, actType) ->
830− lift $ except (atomTypeVerify expType actType)) zippedArgs
831− evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
929+ mapM_ (\(expType, eActType) -> do
930+ actType <- either throwE pure eActType
931+ either throwE pure (atomTypeVerify expType actType)) zippedArgs
932+ evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
832933 case evalAtomFunction func evaldArgs of
833− Left err -> throwError (AtomFunctionUserError err)
934+ Left err -> throwE (AtomFunctionUserError err)
834935 Right result -> do
835936 --validate that the result matches the expected type
836− _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
937+ _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
837938 pure result
838−evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
939+evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
839940 --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
841− let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
842− relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
843− pure (RelationAtom relAtom)
844−evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
845− let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
846− aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
847− argAtoms <- local mergeEnv $
848− mapM (evalGraphRefAtomExpr tupIn) dConsArgs
941+ rstate <- ask
942+ runExceptT $ do
943+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
944+ relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
945+ pure (RelationAtom relAtom)
946+evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
947+ rstate <- lift ask
948+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
949+ aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
950+ argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
849951 pure (ConstructedAtom dConsName aType argAtoms)
850−
851−typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
952+-}
953+typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> RelationalExprState (Either RelationalError AtomType)
852954typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
853− renv <- askEnv
955+ rstate <- askEnv
854956 case A.atomTypeForAttributeName attrName attrs of
855− Right aType -> pure aType
957+ Right aType -> pure (Right aType)
856958 Left err@(NoSuchAttributeNamesError _) ->
857− let envTup = envTuple renv
858− envAttrs = envAttributes renv in
859− case A.attributeForName attrName envAttrs of
860− Right attr -> pure (A.atomType attr)
861− Left _ -> case atomForAttributeName attrName envTup of
862− Right atom -> pure (atomTypeForAtom atom)
863− Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
864− throwError err
865− Left err -> throwError err
866−
867−typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
868−typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
869− funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
959+ let stateTup = stateTuple rstate
960+ stateAttrs = stateAttributes rstate in
961+ case A.attributeForName attrName stateAttrs of
962+ Right attr -> pure (Right (A.atomType attr))
963+ Left _ -> case atomForAttributeName attrName stateTup of
964+ Right atom -> pure (Right (atomTypeForAtom atom))
965+ Left _ -> pure (Left err)
966+
967+typeForGraphAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
968+typeForGraphAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
969+ context <- fmap envContext askEnv
970+ let funcs = atomFunctions context
870971 case atomFunctionForName funcName funcs of
871− Left err -> throwError err
972+ Left err -> pure (Left err)
872973 Right func -> do
873974 let funcRetType = last (atomFuncType func)
874975 funcArgTypes = init (atomFuncType func)
875− argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
876− let eTvMap = resolveTypeVariables funcArgTypes argTypes
877− case eTvMap of
878− Left err -> throwError err
879− Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
880−typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
881− relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
882− pure (RelationAtomType (attributes relType))
976+ eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
977+ case lefts eArgTypes of
978+ errs@(_:_) -> pure (Left (someErrors errs))
979+ [] -> do
980+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
981+ argTypes = rights eArgTypes
982+ case eTvMap of
983+ Left err -> pure (Left err)
984+ Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
985+typeFromAtomExpr attrs (RelationAtomExpr relExpr) = do
986+ relType <- R.local (mergeAttributesIntoRelationalExprState attrs) (typeForRelationalExpr relExpr)
987+ case relType of
988+ Left err -> pure (Left err)
989+ Right relType' ->
990+ pure (pure (RelationAtomType (attributes relType')))
883991-- grab the type of the data constructor, then validate that the args match the expected types
884−typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
885− do
886− argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
887− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
888− lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
992+typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
993+ runExceptT $ do
994+ argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
995+ context <- fmap envContext (lift askEnv)
996+ either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
889997
890998-- | Validate that the type of the AtomExpr matches the expected type.
891−verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
892−verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
893− env <- askEnv
999+verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
1000+verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
1001+ rstate <- lift askEnv
8941002 case A.atomTypeForAttributeName attrName (attributes relIn) of
895− Right aType -> lift $ except $ atomTypeVerify expectedType aType
1003+ Right aType -> either throwE pure (atomTypeVerify expectedType aType)
8961004 (Left err@(NoSuchAttributeNamesError _)) ->
897− let attrs' = envAttributes env in
1005+ let attrs' = stateAttributes rstate in
8981006 if attrs' == emptyAttributes then
899− throwError err
1007+ throwE err
9001008 else
9011009 case A.attributeForName attrName attrs' of
902− Left err' -> throwError err'
903− Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
904− Left err -> throwError err
905−
906−verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
907− lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
908−verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
909− context <- gfDatabaseContextForMarker tid
1010+ Left err' -> throwE err'
1011+ Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
1012+verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
1013+verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
1014+ rstate <- askEnv
9101015 let functions = atomFunctions context
911− func <- lift $ except $ atomFunctionForName funcName functions
912− let expectedArgTypes = atomFuncType func
913− funcArgVerifier (atomExpr, expectedType2, argCount) = do
914− let handler :: RelationalError -> GraphRefRelationalExprM AtomType
915− handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
916− handler err = throwError err
917− verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
918− funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
919− if length funcArgTypes /= length expectedArgTypes - 1 then
920− throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
1016+ context = envContext rstate
1017+ runExceptT $ do
1018+ func <- either throwE pure (atomFunctionForName funcName functions)
1019+ let expectedArgTypes = atomFuncType func
1020+ funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
1021+ Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
1022+ Left err -> throwE err
1023+ Right x -> pure x
1024+ ) $ zip3 funcArgExprs expectedArgTypes [1..]
1025+ if length funcArgTypes /= length expectedArgTypes - 1 then
1026+ throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
9211027 else
922− lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
923−verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
924− do
925− let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
926− relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
927− lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
928−verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
929− cType <- typeForGraphRefAtomExpr (attributes rel) cons
930− lift $ except $ atomTypeVerify expectedType cType
1028+ either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
1029+verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
1030+ rstate <- lift askEnv
1031+ relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
1032+ either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
1033+verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
1034+ cType <- liftE (typeFromAtomExpr (attributes rel) cons)
1035+ either throwE pure (atomTypeVerify expectedType cType)
9311036
9321037-- | Look up the type's name and create a new attribute.
933−evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1038+evalGraphRefAttrExpr :: GraphRefAttributeExpr -> RelationalExprState (Either RelationalError Attribute)
9341039evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
935− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
936− aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
937− lift $ except $ validateAtomType aType tConsMap
938− pure $ Attribute attrName aType
1040+ graph <- re_graph <$> askEnv
1041+ case transactionForId transId graph of
1042+ Left err -> pure (Left err)
1043+ Right trans -> do
1044+ let tConsMap = typeConstructorMapping (concreteDatabaseContext trans)
1045+ validate = do
1046+ aType <- atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
1047+ validateAtomType aType tConsMap
1048+ pure aType
1049+ case validate of
1050+ Left err -> pure (Left err)
1051+ Right aType ->
1052+ pure $ Right (Attribute attrName aType)
1053+
1054+evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure $ Right attr
9391055
940−evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
941−
942−-- for tuple type concrete resolution (Nothing ==> Maybe Int) when the attributes hint is Nothing, we need to first process all the tuples, then extract the concrete types on a per-attribute basis, then reprocess the tuples to include the concrete types
943−evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
944−evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
945−evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
946− tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
947− finalAttrs <- case mAttrs of
948− Just attrs -> pure attrs
949− Nothing ->
950− case tuples of
951− [] -> pure emptyAttributes
952− (headTuple:tailTuples) -> do
953− --gather up resolved atom types or throw an error if an attribute cannot be made concrete from the inferred types- this could still fail if the type cannot be inferred (e.g. from [Nothing, Nothing])
954− let
955− processTupleAttrs (tupAttr, accAttr) =
956− --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
957− if isResolvedAttribute accAttr && tupAttr == accAttr then
958− pure accAttr
959− else
960− lift $ except $ resolveAttributes accAttr tupAttr
961− mostResolvedTypes <-
962− foldM (\acc tup -> do
963− let zipped = zip (V.toList . attributesVec $ tupleAttributes tup) acc
964− accNames = S.fromList $ map A.attributeName acc
965− tupNames = A.attributeNameSet (tupleAttributes tup)
966− attrNamesDiff = S.union (S.difference accNames tupNames) (S.difference tupNames accNames)
967− unless (null attrNamesDiff) (throwError (AttributeNamesMismatchError attrNamesDiff))
968− nextTupleAttrs <- mapM processTupleAttrs zipped
969− let diff = A.attributesDifference (A.attributesFromList nextTupleAttrs) (A.attributesFromList acc)
970− if diff == A.emptyAttributes then
971− pure nextTupleAttrs
972− else
973− throwError (TupleAttributeTypeMismatchError diff)
974− ) (V.toList . attributesVec $ tupleAttributes headTuple) tailTuples
975− pure (A.attributesFromList mostResolvedTypes)
976− --strategy: if all the tuple expr transaction markers refer to one location, then we can pass the type constructor mapping from that location, otherwise, we cannot assume that the types are the same
977− tConsMap <- case singularTransactions tupleExprL of
978− SingularTransactionRef commonTransId ->
979− typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
980− NoTransactionsRef ->
981− typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
982− -- if there are multiple transaction markers in the TupleExprs, then we can't assume a single type constructor mapping- this could be improved in the future, but if all the tuples are fully resolved, then we don't need further resolution
983− _ -> throwError TupleExprsReferenceMultipleMarkersError
984− lift $ except $ validateAttributes tConsMap finalAttrs
985− mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
986−
987−
988−--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
989−
990−evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
991−evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
1056+evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
1057+evalTupleExpr mAttrs (TupleExpr tupMap) = do
1058+ context <- fmap envContext askEnv
1059+ runExceptT $ do
9921060 -- 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
9931061 -- 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
995− resolveOneAtom (attrName, aExpr) =
996− do
997− --provided when the relation header is available
998− let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
999− unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
1000− resolvedType <- case eExpectedAtomType of
1062+ let attrs = fromMaybe A.emptyAttributes mAttrs
1063+ attrAtoms <- mapM (\(attrName, aExpr) -> do
1064+ --provided when the relation header is available
1065+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
1066+ unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
1067+ resolvedType <- case eExpectedAtomType of
10011068 Left _ -> pure unresolvedType
1002− Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
1069+ Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
10031070 --resolve atom typevars based on resolvedType?
1004− newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
1005− pure (attrName, newAtom, resolvedType)
1006− attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
1007− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1008− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1009− tup = mkRelationTuple tupAttrs atoms
1010− finalAttrs = fromMaybe tupAttrs mAttrs
1071+ newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
1072+ pure (attrName, newAtom, resolvedType)
1073+ ) (M.toList tupMap)
1074+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1075+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1076+ tup = mkRelationTuple tupAttrs atoms
1077+ tConss = typeConstructorMapping context
1078+ finalAttrs = fromMaybe tupAttrs mAttrs
10111079 --verify that the attributes match
1012− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1013− --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1014− --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1015− let tup' = reorderTuple finalAttrs tup
1016− --TODO: restore type resolution
1017−-- _ <- lift $ except (validateTuple tup' tConss)
1018− pure tup'
1019−
1020−--temporary implementation until we have a proper planner+executor
1021−evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1022−evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1023− mAttrs <- case mAttrExprs of
1024− Just _ ->
1025− Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1026− Nothing -> pure Nothing
1027− tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1028− let attrs = fromMaybe firstTupleAttrs mAttrs
1029− firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1030− lift $ except $ mkRelation attrs (RelationTupleSet tuples)
1031−evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
1032− lift $ except $ mkRelation attributeSet tupleSet
1033−evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1034−evalGraphRefRelationalExpr (RelationVariable name tid) = do
1035− ctx <- gfDatabaseContextForMarker tid
1080+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
1081+ tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1082+ _ <- either throwE pure (validateTuple tup' tConss)
1083+ pure tup'
1084+
1085+evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
1086+evalAttributeNames attrNames expr = do
1087+ eExprType <- typeForRelationalExpr expr
1088+ case eExprType of
1089+ Left err -> pure (Left err)
1090+ Right exprTyp -> do
1091+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1092+ case attrNames of
1093+ AttributeNames names ->
1094+ case A.projectionAttributesForNames names (attributes exprTyp) of
1095+ Left err -> pure (Left err)
1096+ Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1097+
1098+ InvertedAttributeNames names -> do
1099+ let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1100+ if not (S.null nonExistentAttributeNames) then
1101+ pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1102+ else
1103+ pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
1104+
1105+ UnionAttributeNames namesA namesB -> do
1106+ eNameSetA <- evalAttributeNames namesA expr
1107+ case eNameSetA of
1108+ Left err -> pure (Left err)
1109+ Right nameSetA -> do
1110+ eNameSetB <- evalAttributeNames namesB expr
1111+ case eNameSetB of
1112+ Left err -> pure (Left err)
1113+ Right nameSetB ->
1114+ pure (Right (S.union nameSetA nameSetB))
1115+
1116+ IntersectAttributeNames namesA namesB -> do
1117+ eNameSetA <- evalAttributeNames namesA expr
1118+ case eNameSetA of
1119+ Left err -> pure (Left err)
1120+ Right nameSetA -> do
1121+ eNameSetB <- evalAttributeNames namesB expr
1122+ case eNameSetB of
1123+ Left err -> pure (Left err)
1124+ Right nameSetB ->
1125+ pure (Right (S.intersection nameSetA nameSetB))
1126+
1127+ RelationalExprAttributeNames attrExpr -> do
1128+ eAttrExprType <- typeForRelationalExpr attrExpr
1129+ case eAttrExprType of
1130+ Left err -> pure (Left err)
1131+ Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1132+
1133+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError Relation
1134+--evalGraphRefRelationalExpr (MakeRelationaFromExprs
1135+evalGraphRefRelationalExpr (RelationVariable name tid) graph = do
1136+ ctx <- dbContextForTransId tid graph
10361137 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)
1138+ Nothing -> Left (RelVarNotDefinedError name)
1139+ Just rv -> evalGraphRefRelationalExpr rv graph
1140+
10861141
10871142dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
10881143dbContextForTransId tid graph = do
@@ -1100,120 +1155,170 @@ transactionForId tid graph
11001155 where
11011156 matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
11021157
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
1117−
1158+processRestrictionPredicateExpr :: RestrictionPredicateExpr -> RelationalExprState GraphRefRestrictionPredicateExpr
1159+processRestrictionPredicateExpr TruePredicate = pure TruePredicate
1160+processRestrictionPredicateExpr (AndPredicate a b) = AndPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
1161+processRestrictionPredicateExpr (OrPredicate a b) = OrPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
1162+processRestrictionPredicateExpr (NotPredicate a) = NotPredicate <$> processRestrictionPredicateExpr a
1163+processRestrictionPredicateExpr (RelationalExprPredicate expr) =
1164+ RelationalExprPredicate <$> processRelationalExpr expr
1165+processRestrictionPredicateExpr (AtomExprPredicate expr) =
1166+ AtomExprPredicate <$> processAtomExpr expr
1167+processRestrictionPredicateExpr (AttributeEqualityPredicate nam expr) =
1168+ AttributeEqualityPredicate nam <$> processAtomExpr expr
1169+
1170+processExtendTupleExpr :: ExtendTupleExpr -> RelationalExprState GraphRefExtendTupleExpr
1171+processExtendTupleExpr (AttributeExtendTupleExpr nam atomExpr) =
1172+ AttributeExtendTupleExpr nam <$> processAtomExpr atomExpr
1173+
1174+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprR (Either RelationalError Relation)
1175+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = pure $ mkRelation attrs emptyTupleSet
1176+typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (Right (emptyRelationWithAttrs (attributes rel)))
1177+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) =
1178+ case mAttrExprs of
1179+ Just attrExprs -> do
1180+ eAttrs <- mapM (\e -> evalGraphRefAttributeExpr e) attrExprs
1181+ case lefts eAttrs of
1182+ [] -> pure (Right (emptyRelationWithAttrs (attributesFromList (rights eAttrs))))
1183+ _ -> pure (Left (someErrors (lefts eAttrs)))
11181184typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1119− relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1120− case M.lookup rvName relVars of
1121− Nothing -> throwError (RelVarNotDefinedError rvName)
1122− Just rvExpr ->
1123− typeForGraphRefRelationalExpr rvExpr
1185+ graph <- R.ask
1186+ let eTrans = transactionForId tid graph
1187+ case eTrans of
1188+ Left err -> pure (Left err)
1189+ Right trans -> do
1190+ let relVars = relationVariables (concreteDatabaseContext trans)
1191+ case M.lookup rvName relVars of
1192+ Nothing -> pure (Left (RelVarNotDefinedError rvName))
1193+ Just rvExpr -> typeForGraphRefRelationalExpr rvExpr
11241194typeForGraphRefRelationalExpr (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{} =
1155− pure relationFalse
1156−typeForGraphRefRelationalExpr NotEquals{} =
1157− pure relationFalse
1158−typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1159− rel <- typeForGraphRefRelationalExpr expr
1160− evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1161−typeForGraphRefRelationalExpr expr@(With withs _) = do
1162− let expr' = substituteWithNameMacros [] expr
1163− checkMacroName (WithNameExpr macroName tid) = do
1164− rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1165− case M.lookup macroName rvs of
1166− Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1167− Nothing -> pure ()
1168− mapM_ (checkMacroName . fst) withs
1169− typeForGraphRefRelationalExpr expr'
1170−
1171−evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1195+ eExprType <- typeForGraphRefRelationalExpr expr
1196+ case eExprType of
1197+ Left err -> pure (Left err)
1198+ Right exprType -> do
1199+ eProjectionAttrs <- evalGraphRefAttributeNames attrNames expr
1200+ pure $ case eProjectionAttrs of
1201+ Left err -> Left err
1202+ Right projectionAttrs -> project projectionAttrs exprType
1203+
1204+evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprR (Either RelationalError (S.Set AttributeName))
11721205evalGraphRefAttributeNames attrNames expr = do
1173− exprType' <- typeForGraphRefRelationalExpr expr
1174− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1175− case attrNames of
1176− AttributeNames names ->
1177− case A.projectionAttributesForNames names (attributes exprType') of
1178− Left err -> throwError err
1179− Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1206+ eExprType <- typeForGraphRefRelationalExpr expr
1207+ case eExprType of
1208+ Left err -> pure (Left err)
1209+ Right exprTyp -> do
1210+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1211+ case attrNames of
1212+ AttributeNames names ->
1213+ case A.projectionAttributesForNames names (attributes exprTyp) of
1214+ Left err -> pure (Left err)
1215+ Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
11801216
1181− InvertedAttributeNames names -> do
1217+ InvertedAttributeNames names -> do
11821218 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
11831219 if not (S.null nonExistentAttributeNames) then
1184− throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1220+ pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
11851221 else
1186− pure (A.nonMatchingAttributeNameSet names typeNameSet)
1222+ pure (pure (A.nonMatchingAttributeNameSet names typeNameSet))
11871223
1188− UnionAttributeNames namesA namesB -> do
1189− nameSetA <- evalGraphRefAttributeNames namesA expr
1190− nameSetB <- evalGraphRefAttributeNames namesB expr
1191− pure (S.union nameSetA nameSetB)
1224+ UnionAttributeNames namesA namesB -> do
1225+ eNameSetA <- evalGraphRefAttributeNames namesA expr
1226+ case eNameSetA of
1227+ Left err -> pure (Left err)
1228+ Right nameSetA -> do
1229+ eNameSetB <- evalGraphRefAttributeNames namesB expr
1230+ case eNameSetB of
1231+ Left err -> pure (Left err)
1232+ Right nameSetB ->
1233+ pure (Right (S.union nameSetA nameSetB))
11921234
1193− IntersectAttributeNames namesA namesB -> do
1194− nameSetA <- evalGraphRefAttributeNames namesA expr
1195− nameSetB <- evalGraphRefAttributeNames namesB expr
1196− pure (S.intersection nameSetA nameSetB)
1235+ IntersectAttributeNames namesA namesB -> do
1236+ eNameSetA <- evalGraphRefAttributeNames namesA expr
1237+ case eNameSetA of
1238+ Left err -> pure (Left err)
1239+ Right nameSetA -> do
1240+ eNameSetB <- evalGraphRefAttributeNames namesB expr
1241+ case eNameSetB of
1242+ Left err -> pure (Left err)
1243+ Right nameSetB ->
1244+ pure (Right (S.intersection nameSetA nameSetB))
11971245
1198− RelationalExprAttributeNames attrExpr -> do
1199− attrExprType <- typeForGraphRefRelationalExpr attrExpr
1200− pure (A.attributeNameSet (attributes attrExprType))
1246+ RelationalExprAttributeNames attrExpr -> do
1247+ eAttrExprType <- typeForGraphRefRelationalExpr attrExpr
1248+ case eAttrExprType of
1249+ Left err -> pure (Left err)
1250+ Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1251+
1252+
1253+
12011254
1202−evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1255+processAtomExpr :: AtomExpr -> RelationalExprState GraphRefAtomExpr
1256+processAtomExpr (AttributeAtomExpr nam) = pure $ AttributeAtomExpr nam
1257+processAtomExpr (NakedAtomExpr atom) = pure $ NakedAtomExpr atom
1258+processAtomExpr (FunctionAtomExpr fName atomExprs ()) = do
1259+ tid <- re_currentTransId <$> askEnv
1260+ FunctionAtomExpr fName <$> mapM processAtomExpr atomExprs <*> pure tid
1261+processAtomExpr (RelationAtomExpr expr) = RelationAtomExpr <$> processRelationalExpr expr
1262+processAtomExpr (ConstructedAtomExpr dConsName atomExprs ()) = ConstructedAtomExpr dConsName <$> mapM processAtomExpr atomExprs <*> (re_currentTransId <$> askEnv)
1263+
1264+processTupleExpr :: TupleExpr -> RelationalExprState GraphRefTupleExpr
1265+processTupleExpr (TupleExpr tMap) =
1266+ TupleExpr . M.fromList <$> mapM (\(k,v) -> (,) k <$> processAtomExpr v) (M.toList tMap)
1267+
1268+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprR (Either RelationalError Attribute)
12031269evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1204− tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1205− case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1206− Left err -> throwError err
1207− Right aType -> do
1208− case validateAtomType aType tConsMap of
1209− Left err -> throwError err
1210− Right _ -> pure (Attribute attrName aType)
1211−evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1270+ graph <- R.ask
1271+ case transactionForId tid graph of
1272+ Left err -> pure (Left err)
1273+ Right trans -> do
1274+ let tConsMap = typeConstructorMapping (concreteDatabaseContext trans)
1275+ case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1276+ Left err -> pure (Left err)
1277+ Right aType -> do
1278+ case validateAtomType aType tConsMap of
1279+ Left err -> pure (Left err)
1280+ Right _ -> pure (Right (Attribute attrName aType))
1281+
1282+--convert AttributeExpr to GraphRefAttributeExpr
1283+processAttributeExpr :: AttributeExpr -> RelationalExprState GraphRefAttributeExpr
1284+processAttributeExpr (AttributeAndTypeNameExpr nam tCons ()) = do
1285+ tid <- re_currentTransId <$> askEnv
1286+ pure $ AttributeAndTypeNameExpr nam tCons tid
1287+processAttributeExpr (NakedAttributeExpr attr) = pure $ NakedAttributeExpr attr
1288+
1289+-- convert a RelationalExpr into a GraphRefRelationalExpr using the current trans Id
1290+-- can this be done without any RelationalErrors as opposed to evalRelationalExpr?
1291+processRelationalExpr :: RelationalExpr -> RelationalExprState GraphRefRelationalExpr
1292+processRelationalExpr (MakeRelationFromExprs mAttrs tupleExprs) = do
1293+ mAttrs' <- case mAttrs of
1294+ Nothing -> pure Nothing
1295+ Just mAttrs'' -> Just <$> mapM processAttributeExpr mAttrs''
1296+ MakeRelationFromExprs mAttrs' <$> mapM processTupleExpr tupleExprs
1297+processRelationalExpr (MakeStaticRelation attrs tupSet) = pure (MakeStaticRelation attrs tupSet)
1298+processRelationalExpr (ExistingRelation rel) = pure (ExistingRelation rel)
1299+processRelationalExpr (RelationVariable rv ()) = RelationVariable rv <$> fmap re_currentTransId askEnv
1300+processRelationalExpr (Project attrNames expr) = Project <$> processAttributeNames attrNames <*> processRelationalExpr expr
1301+processRelationalExpr (Union exprA exprB) = Union <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1302+processRelationalExpr (Join exprA exprB) = Join <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1303+processRelationalExpr (Rename attrA attrB expr) =
1304+ Rename attrA attrB <$> processRelationalExpr expr
1305+processRelationalExpr (Difference exprA exprB) = Difference <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1306+processRelationalExpr (Group attrNames attrName expr) = Group <$> processAttributeNames attrNames <*> pure attrName <*> processRelationalExpr expr
1307+processRelationalExpr (Ungroup attrName expr) = Ungroup attrName <$> processRelationalExpr expr
1308+processRelationalExpr (Restrict pred expr) = Restrict <$> processRestrictionPredicateExpr pred <*> processRelationalExpr expr
1309+processRelationalExpr (Equals exprA exprB) =
1310+ Equals <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1311+processRelationalExpr (NotEquals exprA exprB) =
1312+ NotEquals <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1313+processRelationalExpr (Extend extendExpr expr) =
1314+ Extend <$> processExtendTupleExpr extendExpr <*> processRelationalExpr expr
1315+processRelationalExpr (With macros expr) =
1316+ With <$> mapM (\(nam, wexpr) -> (,) nam <$> processRelationalExpr wexpr) macros <*> processRelationalExpr expr
12121317
12131318mkEmptyRelVars :: RelationVariables -> RelationVariables
1214−mkEmptyRelVars = M.map mkEmptyRelVar
1319+mkEmptyRelVars rvMap = M.map mkEmptyRelVar rvMap
12151320 where
1216− mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1321+ mkEmptyRelVar (MakeRelationFromExprs mAttrs _) = MakeRelationFromExprs mAttrs []
12171322 mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
12181323 mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
12191324 mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
@@ -1224,169 +1329,71 @@ mkEmptyRelVars = M.map mkEmptyRelVar
12241329 mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
12251330 mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
12261331 mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1227− mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1332+ mkEmptyRelVar (Restrict pred expr) = Restrict pred (mkEmptyRelVar expr)
12281333 mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
12291334 mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
12301335 mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1231− mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1336+ mkEmptyRelVar (With macros expr) = With (map (\(rv, expr) -> (rv, mkEmptyRelVar expr)) macros) (mkEmptyRelVar expr)
12321337
1338+processAttributeNames :: AttributeNames -> RelationalExprState GraphRefAttributeNames
1339+processAttributeNames (AttributeNames nameSet) = pure $ AttributeNames nameSet
1340+processAttributeNames (UnionAttributeNames attrNamesA attrNamesB) = UnionAttributeNames <$> processAttributeNames attrNamesA <*> processAttributeNames attrNamesB
1341+processAttributeNames (IntersectAttributeNames attrNamesA attrNamesB) = IntersectAttributeNames <$> processAttributeNames attrNamesA <*> processAttributeNames attrNamesB
1342+processAttributeNames (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> processRelationalExpr expr
1343+
1344+processDatabaseContextExpr :: DatabaseContextExpr -> RelationalExprState GraphRefDatabaseContextExpr
1345+processDatabaseContextExpr expr =
1346+ case expr of
1347+ NoOperation -> pure NoOperation
1348+ Define nam attrExprs -> Define nam <$> mapM processAttributeExpr attrExprs
1349+ Undefine nam -> pure (Undefine nam)
1350+ Assign nam rexpr -> Assign nam <$> processRelationalExpr rexpr
1351+ Insert nam rexpr -> Insert nam <$> processRelationalExpr rexpr
1352+ Delete nam pred -> Delete nam <$> processRestrictionPredicateExpr pred
1353+ Update nam attrMap pred -> Update nam attrMap <$> processRestrictionPredicateExpr pred
1354+
1355+ AddInclusionDependency nam dep -> pure (AddInclusionDependency nam dep)
1356+ RemoveInclusionDependency nam -> pure (RemoveInclusionDependency nam)
1357+ AddNotification nam exprA exprB exprC -> pure (AddNotification nam exprA exprB exprC)
1358+ RemoveNotification nam -> pure (RemoveNotification nam)
1359+ AddTypeConstructor tyDef consDefs -> pure (AddTypeConstructor tyDef consDefs)
1360+ RemoveTypeConstructor tyName -> pure (RemoveTypeConstructor tyName)
1361+
1362+ RemoveAtomFunction aFuncName -> pure (RemoveAtomFunction aFuncName)
1363+ RemoveDatabaseContextFunction funcName -> pure (RemoveDatabaseContextFunction funcName)
1364+ ExecuteDatabaseContextFunction funcName atomExprs -> ExecuteDatabaseContextFunction funcName <$> mapM processAtomExpr atomExprs
1365+ MultipleExpr exprs -> MultipleExpr <$> mapM processDatabaseContextExpr exprs
12331366
12341367dbErr :: RelationalError -> DatabaseContextEvalMonad ()
12351368dbErr err = lift (except (Left err))
12361369
1370+processDatabaseContextIOExpr :: DatabaseContextIOExpr -> RelationalExprState GraphRefDatabaseContextIOExpr
1371+processDatabaseContextIOExpr (AddAtomFunction f tcs sc) =
1372+ pure (AddAtomFunction f tcs sc)
1373+processDatabaseContextIOExpr (LoadAtomFunctions mod fun file) =
1374+ pure (LoadAtomFunctions mod fun file)
1375+processDatabaseContextIOExpr (AddDatabaseContextFunction mod fun path) =
1376+ pure (AddDatabaseContextFunction mod fun path)
1377+processDatabaseContextIOExpr (LoadDatabaseContextFunctions mod fun path) =
1378+ pure (LoadDatabaseContextFunctions mod fun path)
1379+processDatabaseContextIOExpr (CreateArbitraryRelation rvName attrExprs range) =
1380+ CreateArbitraryRelation rvName <$> mapM processAttributeExpr attrExprs <*> pure range
1381+
12371382-- | Return a Relation describing the relation variables.
1238−relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1239−relationVariablesAsRelation ctx graph = do
1383+relationVariablesAsRelation :: RelationVariables -> TransactionGraph -> Either RelationalError Relation
1384+relationVariablesAsRelation relVarMap graph = do
12401385 let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
12411386 attrs = A.attributesFromList [Attribute "name" TextAtomType,
12421387 Attribute "attributes" (RelationAtomType subrelAttrs)]
1243− relVars = relationVariables ctx
12441388 mkRvDesc (rvName, gfExpr) = do
1245− let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1246− gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1389+ gfType <- runReader (typeForGraphRefRelationalExpr gfExpr) graph
12471390 pure (rvName, gfType)
1248− relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributesVec (attributes rel))]
1391+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributes rel)]
12491392 attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
12501393 attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
12511394 Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
12521395 Right rel -> RelationAtom rel
1253− rvs <- mapM mkRvDesc (M.toList relVars)
1396+ rvs <- mapM mkRvDesc (M.toList relVarMap)
12541397 let tups = map relVarToAtomList rvs
12551398 mkRelationFromList attrs tups
12561399
1257−-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1258−evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1259−evalRelationalExpr expr = do
1260− graph <- reGraph
1261− context <- reContext
1262− let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1263− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1264− case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1265− Left err -> throwError err
1266− Right rel -> pure rel
1267−
1268−class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1269− getContext :: m DatabaseContext
1270−
1271−instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1272− getContext = gfDatabaseContextForMarker UncommittedContextMarker
1273−
1274−instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1275− getContext = getStateContext
1276−
1277−relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1278−relVarByName rvName = do
1279− relvars <- relationVariables <$> getContext
1280− case M.lookup rvName relvars of
1281− Nothing -> throwError (RelVarNotDefinedError rvName)
1282− Just gfexpr -> pure gfexpr
1283−
1284−-- | resolve UncommittedTransactionMarker whenever possible- this is important in the DatabaseContext in order to mitigate self-referencing loops for updates
1285−class ResolveGraphRefTransactionMarker a where
1286− resolve :: a -> DatabaseContextEvalMonad a
1287−
1288−-- s := s union t
1289−instance ResolveGraphRefTransactionMarker GraphRefRelationalExpr where
1290− resolve (MakeRelationFromExprs mAttrs tupleExprs) =
1291− MakeRelationFromExprs mAttrs <$> resolve tupleExprs
1292− resolve orig@MakeStaticRelation{} = pure orig
1293− resolve orig@ExistingRelation{} = pure orig
1294− resolve orig@(RelationVariable rvName UncommittedContextMarker) = do
1295− rvMap <- relationVariables <$> getStateContext
1296− case M.lookup rvName rvMap of
1297− Nothing -> pure orig
1298− Just resolvedRv -> resolve resolvedRv
1299− resolve orig@RelationVariable{} = pure orig
1300− resolve (Project attrNames relExpr) = Project <$> resolve attrNames <*> resolve relExpr
1301− resolve (Union exprA exprB) = Union <$> resolve exprA <*> resolve exprB
1302− resolve (Join exprA exprB) = Join <$> resolve exprA <*> resolve exprB
1303− resolve (Rename attrA attrB expr) = Rename attrA attrB <$> resolve expr
1304− resolve (Difference exprA exprB) = Difference <$> resolve exprA <*> resolve exprB
1305− resolve (Group namesA nameB expr) = Group <$> resolve namesA <*> pure nameB <*> resolve expr
1306− resolve (Ungroup nameA expr) = Ungroup nameA <$> resolve expr
1307− resolve (Restrict restrictExpr relExpr) = Restrict <$> resolve restrictExpr <*> resolve relExpr
1308− resolve (Equals exprA exprB) = Equals <$> resolve exprA <*> resolve exprB
1309− resolve (NotEquals exprA exprB) = NotEquals <$> resolve exprA <*> resolve exprB
1310− resolve (Extend extendExpr relExpr) = Extend <$> resolve extendExpr <*> resolve relExpr
1311− resolve (With withExprs relExpr) = With <$> mapM (\(nam, expr) -> (,) <$> resolve nam <*> resolve expr) withExprs <*> resolve relExpr
1312−
1313−instance ResolveGraphRefTransactionMarker GraphRefTupleExprs where
1314− resolve (TupleExprs marker tupleExprs) =
1315− TupleExprs marker <$> mapM resolve tupleExprs
1316−
1317−instance ResolveGraphRefTransactionMarker GraphRefTupleExpr where
1318− resolve (TupleExpr tupMap) = do
1319− tupMap' <- mapM (\(attrName, expr) -> (,) attrName <$> resolve expr ) (M.toList tupMap)
1320− pure (TupleExpr (M.fromList tupMap'))
1321−
1322−instance ResolveGraphRefTransactionMarker GraphRefAttributeNames where
1323− resolve orig@AttributeNames{} = pure orig
1324− resolve orig@InvertedAttributeNames{} = pure orig
1325− resolve (UnionAttributeNames namesA namesB) = UnionAttributeNames <$> resolve namesA <*> resolve namesB
1326− resolve (IntersectAttributeNames namesA namesB) = IntersectAttributeNames <$> resolve namesA <*> resolve namesB
1327− resolve (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> resolve expr
1328−
1329−instance ResolveGraphRefTransactionMarker GraphRefRestrictionPredicateExpr where
1330− resolve TruePredicate = pure TruePredicate
1331− resolve (AndPredicate exprA exprB) = AndPredicate <$> resolve exprA <*> resolve exprB
1332− resolve (OrPredicate exprA exprB) = OrPredicate <$> resolve exprA <*> resolve exprB
1333− resolve (NotPredicate expr) = NotPredicate <$> resolve expr
1334− resolve (RelationalExprPredicate expr) = RelationalExprPredicate <$> resolve expr
1335− resolve (AtomExprPredicate expr) = AtomExprPredicate <$> resolve expr
1336− resolve (AttributeEqualityPredicate nam expr)= AttributeEqualityPredicate nam <$> resolve expr
1337−
1338−instance ResolveGraphRefTransactionMarker GraphRefExtendTupleExpr where
1339− resolve (AttributeExtendTupleExpr nam atomExpr) = AttributeExtendTupleExpr nam <$> resolve atomExpr
1340−
1341−instance ResolveGraphRefTransactionMarker GraphRefWithNameExpr where
1342− resolve orig@WithNameExpr{} = pure orig -- match uncommitted marker?
1343−
1344−instance ResolveGraphRefTransactionMarker GraphRefAtomExpr where
1345− resolve orig@AttributeAtomExpr{} = pure orig
1346− resolve orig@NakedAtomExpr{} = pure orig
1347− resolve (FunctionAtomExpr nam atomExprs marker) =
1348− FunctionAtomExpr nam <$> mapM resolve atomExprs <*> pure marker
1349− resolve (RelationAtomExpr expr) = RelationAtomExpr <$> resolve expr
1350− resolve (ConstructedAtomExpr dConsName atomExprs marker) =
1351− ConstructedAtomExpr dConsName <$> mapM resolve atomExprs <*> pure marker
1352−
1353−--convert series of simple Union queries into MakeStaticRelation
1354−-- this is especially useful for long, nested applications of Union with simple tuples
1355−-- Union (MakeRelation x y) (MakeRelation x y') -> MakeRelation x (y + y')
1356−
1357−--MakeRelationFromExprs Nothing (TupleExprs UncommittedContextMarker [TupleExpr (fromList [("name", NakedAtomExpr (TextAtom "steve"))])])
1358−
1359−applyUnionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1360−applyUnionCollapse = Fold.cata opt
1361− where
1362− opt :: RelationalExprBaseF GraphRefTransactionMarker GraphRefRelationalExpr -> GraphRefRelationalExpr
1363− opt (UnionF exprA exprB) | exprA == exprB = exprA
1364− opt (UnionF
1365− exprA@(MakeRelationFromExprs mAttrs1 tupExprs1)
1366− exprB@(MakeRelationFromExprs mAttrs2 tupExprs2)) | tupExprs1 == tupExprs2 = MakeRelationFromExprs (mAttrs1 <|> mAttrs2) tupExprs1
1367− | tupExprsNull tupExprs1 = exprB
1368− | tupExprsNull tupExprs2 = exprA
1369− opt x = Fold.embed x
1370− tupExprsNull (TupleExprs _ []) = True
1371− tupExprsNull _ = False
1372−
1373−
1374−--UPDATE optimization- find matching where clause in "lower" levels of renaming
1375−--update x where y=1 set (x:=5,z:=10); update x where y=1 set(x:=6,z:=11)
1376−-- =>
1377−-- update x where y=1 set (x:=6,z:=11)
1378−-- future opt: match individual attributes update x where y=1 set (x:=5); update x where y=1 set (z:=11) => update x where y=1 set (x:=5,z:=11)
1379−
1380−--strategy: try to collapse the top-level update (union (restrict pred MakeRelationFromExpr) expr) if it contains the same predicate and resultant relation
1381−
1382−--DELETE optimization
1383−-- if a restriction matches a previous restriction, combine them
1384−-- O(1) since it only scans at the top level, critical in benchmarks generating redundant deletions
1385−applyRestrictionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1386−applyRestrictionCollapse orig@(Restrict npred@(NotPredicate _) expr) =
1387− case expr of
1388− orig'@(Restrict npred'@(NotPredicate _) _) | npred == npred' -> orig'
1389− _ -> orig
1390−applyRestrictionCollapse expr = expr
1391−
1392−