@@ -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,32 @@ 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 hiding (join)
22+import Control.Monad.Trans.Class (lift)
23+import Control.Monad (forM)
24+import Control.Exception
2725import Data.Maybe
2826import Data.Either
2927import Data.Char (isUpper)
30−import Data.Time
31−import qualified Data.List.NonEmpty as NE
32−import Data.Functor.Identity
3328import qualified Data.Text as T
3429import qualified Data.Vector as V
3530import 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
31+import Control.Monad.Trans.Except
32+import Control.Monad.Trans.Reader as R
4333import 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
34+import GHC
4935import GHC.Paths
50−#endif
36+import Data.Time.Clock
37+import Data.Time.Calendar
38+import qualified Data.List.NonEmpty as NE
39+import Data.Functor.Identity
40+import Control.Monad
41+import Control.Monad.IO.Class
5142
5243data DatabaseContextExprDetails = CountUpdatedTuples
5344
@@ -75,52 +66,48 @@ mkDatabaseContextEvalState context = DatabaseContextEvalState {
7566data RelationalExprEnv = RelationalExprEnv {
7667 re_context :: DatabaseContext,
7768 re_graph :: TransactionGraph,
69+ re_currentTransId :: TransactionId,
7870 re_extra :: Maybe (Either RelationTuple Attributes)
7971 }
8072
81−envTuple :: GraphRefRelationalExprEnv -> RelationTuple
82−envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
73+stateTuple :: RelationalExprEnv -> RelationTuple
74+stateTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (re_extra e))
8375
84−envAttributes :: GraphRefRelationalExprEnv -> Attributes
85−envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
76+stateAttributes :: RelationalExprEnv -> Attributes
77+stateAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (re_extra e))
8678
8779instance Show RelationalExprEnv where
8880 show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
8981
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 =
82+mkRelationalExprEnv :: DatabaseContext -> TransactionId -> TransactionGraph -> RelationalExprEnv
83+mkRelationalExprEnv ctx currentTransId graph =
10484 RelationalExprEnv
10585 { re_context = ctx,
10686 re_graph = graph,
87+ re_currentTransId = currentTransId,
10788 re_extra = Nothing }
10889
109−askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
90+askEnv :: RelationalExprState RelationalExprEnv
11091askEnv = R.ask
11192
112−mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
113−mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
114− env { gre_extra = new_elems }
93+currentTrans :: RelationalExprState (Either RelationalError Transaction)
94+currentTrans = do
95+ tid <- re_currentTransId <$> R.ask
96+ graph <- re_graph <$> R.ask
97+ pure (transactionForId tid graph)
98+
99+mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprEnv -> RelationalExprEnv
100+mergeTuplesIntoRelationalExprState tupIn e@RelationalExprEnv{} =
101+ e{re_extra = new_elems }
115102 where
116103 new_elems = Just (Left newTuple)
117− mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
104+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (stateTuple e))
118105 newTuple = mkRelationTupleFromMap mergedTupMap
119−
120−mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
121−mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
106+
107+mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprEnv -> RelationalExprEnv
108+mergeAttributesIntoRelationalExprState attrsIn e@RelationalExprEnv{} = e{re_extra = newattrs }
122109 where
123− newattrs = Just (Right (A.union attrsIn (envAttributes e)))
110+ newattrs = Just (Right (A.union attrsIn (stateAttributes e)))
124111
125112type ResultAccumName = StringType
126113
@@ -142,12 +129,12 @@ data DatabaseContextEvalEnv = DatabaseContextEvalEnv
142129 }
143130
144131mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
145−mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
132+mkDatabaseContextEvalEnv tid graph = DatabaseContextEvalEnv tid graph
146133
147134type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
148135
149136runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
150−runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
137+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> (execRWST m env freshEnv)))
151138 where
152139 freshEnv = mkDatabaseContextEvalState ctx
153140
@@ -159,52 +146,20 @@ dbcGraph :: DatabaseContextEvalMonad TransactionGraph
159146dbcGraph = dce_graph <$> RWS.ask
160147
161148dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
162−dbcRelationalExprEnv =
163− mkRelationalExprEnv <$> getStateContext <*> dbcGraph
149+dbcRelationalExprEnv = do
150+ tid <- dbcTransId
151+ graph <- dbcGraph
152+ mkRelationalExprEnv <$> getStateContext <*> dbcTransId <*> dbcGraph
164153
165154getStateContext :: DatabaseContextEvalMonad DatabaseContext
166−getStateContext = gets dbc_context
155+getStateContext = dbc_context <$> get
167156
168157putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
169158putStateContext ctx' = do
170159 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− }
160+ put (s {dbc_context = ctx'})
180161
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− }
205−
206−gfGraph :: GraphRefRelationalExprM TransactionGraph
207−gfGraph = asks gre_graph
162+type RelationalExprState a = Reader RelationalExprEnv a
208163
209164envContext :: RelationalExprEnv -> DatabaseContext
210165envContext = re_context
@@ -212,27 +167,173 @@ envContext = re_context
212167setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
213168setEnvContext e ctx = e { re_context = ctx }
214169
170+{-
171+--full evaluation down the graph
172+eval :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
173+eval expr = do
174+ env <- askEnv
175+ eGfExpr <- processRelationalExpr expr
176+ case eGfExpr of
177+ Left err -> pure (Left err)
178+ Right gfExpr -> pure $ evalGraphRefRelationalExpr gfExpr (re_graph env)
179+-}
180+{-
181+--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
182+evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
183+evalRelationalExpr (RelationVariable name _) = do
184+ relvarTable <- fmap (relationVariables . envContext) askEnv
185+ return $ case M.lookup name relvarTable of
186+ Just res -> Right res
187+ Nothing -> Left $ RelVarNotDefinedError name
188+
189+evalRelationalExpr (Project attrNames expr) = do
190+ eAttrNameSet <- evalAttributeNames attrNames expr
191+ case eAttrNameSet of
192+ Left err -> pure (Left err)
193+ Right attrNameSet -> do
194+ rel <- evalRelationalExpr expr
195+ case rel of
196+ Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
197+ Left err -> pure $ Left err
198+
199+evalRelationalExpr (Union exprA exprB) = do
200+ relA <- evalRelationalExpr exprA
201+ relB <- evalRelationalExpr exprB
202+ case relA of
203+ Left err -> return $ Left err
204+ Right relA2 -> case relB of
205+ Left err -> return $ Left err
206+ Right relB2 -> return $ Right (Union relA2 relB2)
207+
208+evalRelationalExpr (Join exprA exprB) = do
209+ relA <- evalRelationalExpr exprA
210+ relB <- evalRelationalExpr exprB
211+ case relA of
212+ Left err -> return $ Left err
213+ Right relA2 -> case relB of
214+ Left err -> return $ Left err
215+ Right relB2 -> return $ Right (Join relA2 relB2)
216+
217+evalRelationalExpr (Difference exprA exprB) = do
218+ relA <- evalRelationalExpr exprA
219+ relB <- evalRelationalExpr exprB
220+ case relA of
221+ Left err -> return $ Left err
222+ Right relA2 -> case relB of
223+ Left err -> return $ Left err
224+ Right relB2 -> return $ Right (Difference relA2 relB2)
225+
226+evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
227+ case mkRelation attributeSet tupleSet of
228+ Right rel -> return $ Right (ExistingRelation rel)
229+ Left err -> return $ Left err
230+
231+evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
232+ currentContext <- fmap envContext askEnv
233+ let tConss = typeConstructorMapping currentContext
234+ -- 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
235+ runExceptT $ do
236+ mAttrs <- case mAttrExprs of
237+ Just _ ->
238+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
239+ Nothing -> pure Nothing
240+ tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
241+ let attrs = fromMaybe firstTupleAttrs mAttrs
242+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
243+ expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
244+ pure (ExistingRelation expr)
245+
246+evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
247+
248+evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
249+ evald <- evalRelationalExpr relExpr
250+ case evald of
251+ Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
252+ Left err -> return $ Left err
253+
254+evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
255+ eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
256+ case eOldAttrNameSet of
257+ Left err -> pure (Left err)
258+ Right oldAttrNameSet -> do
259+ evald <- evalRelationalExpr relExpr
260+ case evald of
261+ Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
262+ Left err -> return $ Left err
263+
264+evalRelationalExpr (Ungroup attrName relExpr) = do
265+ evald <- evalRelationalExpr relExpr
266+ case evald of
267+ Right expr -> return $ Right (Ungroup attrName expr)
268+ Left err -> return $ Left err
269+
270+evalRelationalExpr (Restrict predicateExpr relExpr) = do
271+ evald <- evalRelationalExpr relExpr
272+ pred <- processRestrictionPredicateExpr predicateExpr
273+ case evald of
274+ Left err -> return $ Left err
275+ Right expr ->
276+ pure $ Right (Restrict pred expr)
277+
278+evalRelationalExpr (Equals relExprA relExprB) = do
279+ evaldA <- evalRelationalExpr relExprA
280+ evaldB <- evalRelationalExpr relExprB
281+ case evaldA of
282+ Left err -> return $ Left err
283+ Right exprA -> case evaldB of
284+ Left err -> return $ Left err
285+ Right exprB -> return $ Right (Equals exprA exprB)
286+{-
287+evalRelationalExpr (With views mainExpr) = do
288+ rstate <- ask
289+
290+ let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
291+ Left (RelVarAlreadyDefinedError vname)
292+ else
293+ case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
294+ (Left err,_) -> Left err
295+ (Right (), (ctx',_,_)) -> Right ctx'
296+
297+ case foldM addScopedView (stateElemsContext rstate) views of
298+ Left err -> return $ Left err
299+ Right ctx'' -> do
300+ let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprEnv ctx'')
301+ case evalMainExpr mainExpr of
302+ Left err -> return $ Left err
303+ Right rel -> return $ Right rel
304+-}
305+--warning: copy-pasta from above- refactor
306+evalRelationalExpr (NotEquals relExprA relExprB) = do
307+ evaldA <- evalRelationalExpr relExprA
308+ evaldB <- evalRelationalExpr relExprB
309+ case evaldA of
310+ Left err -> return $ Left err
311+ Right exprA -> case evaldB of
312+ Left err -> return $ Left err
313+ Right exprB -> return $ Right (NotEquals exprA exprB)
314+
315+-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
316+evalRelationalExpr (Extend tupleExpression relExpr) = do
317+ eExpr <- evalRelationalExpr relExpr
318+ case eExpr of
319+ Left err -> pure (Left err)
320+ Right expr -> do
321+ tupProc <- processExtendTupleExpr tupleExpression
322+ pure (Right (Extend tupProc expr))
323+-}
215324--helper function to process relation variable creation/assignment
216325setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
217326setRelVar relVarName relExpr = do
327+
218328 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
329+ let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
222330 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 ()
331+ --determine when to check constraints
332+ graph <- dbcGraph
333+ tid <- dbcTransId
334+ case checkConstraints potentialContext tid graph of
335+ Left err -> dbErr err
336+ Right _ -> putStateContext potentialContext
236337
237338-- 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
238339deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
@@ -251,17 +352,20 @@ evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContex
251352evalGraphRefDatabaseContextExpr NoOperation = pure ()
252353
253354evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
254− context <- getStateContext
255355 relvars <- fmap relationVariables getStateContext
256356 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
357+ relEnv <- dbcRelationalExprEnv
358+ let eAttrs = runReader (mapM evalGraphRefAttrExpr attrExprs) relEnv
359+ attrErrs = lefts eAttrs
360+ attrsList = rights eAttrs
361+ if not (null attrErrs) then
362+ dbErr (someErrors attrErrs)
363+ else do
364+ let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
365+ if not (null atomTypeErrs) then
366+ dbErr (someErrors atomTypeErrs)
367+ else
368+ case M.member relVarName relvars of
265369 True -> dbErr (RelVarAlreadyDefinedError relVarName)
266370 False -> setRelVar relVarName (ExistingRelation emptyRelation)
267371 where
@@ -271,20 +375,15 @@ evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
271375evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
272376
273377evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
274− graph <- re_graph <$> dbcRelationalExprEnv
378+ relExprEnv <- dbcRelationalExprEnv
275379 context <- getStateContext
276380 let existingRelVar = M.lookup relVarName (relationVariables context)
277− reEnv = freshGraphRefRelationalExprEnv (Just context) graph
278− eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
279381 case existingRelVar of
280382 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
383+ setRelVar relVarName expr
286384 Just existingRel -> do
287− let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
385+ let eExpectedType = runReader (typeForGraphRefRelationalExpr existingRel) relExprEnv
386+ eNewExprType = runReader (typeForGraphRefRelationalExpr expr) relExprEnv
288387 case eExpectedType of
289388 Left err -> dbErr err
290389 Right expectedType ->
@@ -292,53 +391,44 @@ evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
292391 Left err -> dbErr err
293392 Right newExprType -> do
294393 if newExprType == expectedType then do
295− lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
296394 setRelVar relVarName expr
297395 else
298396 dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
299397
300398evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
301− gfExpr <- relVarByName relVarName
302− let optExpr = applyUnionCollapse (Union
303− relExpr
304− gfExpr)
305− evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
399+ transId <- dbcTransId
400+ evalGraphRefDatabaseContextExpr (Assign relVarName
401+ (Union
402+ (RelationVariable relVarName transId)
403+ relExpr))
306404
307405evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
308− gfExpr <- relVarByName relVarName
309− let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
310− setRelVar relVarName optExpr
406+ transId <- dbcTransId
407+ let rv = RelationVariable relVarName transId
408+ setRelVar relVarName (Restrict (NotPredicate predicate) rv)
311409
312410--union of restricted+updated portion and the unrestricted+unupdated portion
313−evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
314− rvExpr <- relVarByName relVarName
315− graph <- re_graph <$> dbcRelationalExprEnv
411+evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred) = do
316412 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
413+ transId <- dbcTransId
414+ reEnv <- dbcRelationalExprEnv
415+ let relVarMap = relationVariables context
416+ case M.lookup relVarName relVarMap of
417+ Nothing -> dbErr (RelVarNotDefinedError relVarName)
418+ Just existingRvExpr -> do
419+ let unrestrictedPortion = Restrict (NotPredicate pred) rv
420+ rv = RelationVariable relVarName transId
421+ tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
422+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
423+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
424+ restrictedPortion = Restrict pred
425+ updated = foldr (\(oldname, atomExpr) accum ->
426+ let procAtomExpr = runReader (processAtomExpr atomExpr) reEnv in
337427 updateAttr oldname procAtomExpr accum
338− ) restrictedPortion (M.toList atomExprMap)
428+ ) rv (M.toList atomExprMap)
339429 -- 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)
430+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
431+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
342432
343433evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
344434 currContext <- getStateContext
@@ -350,8 +440,6 @@ evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
350440 dbErr (InclusionDependencyNameInUseError newDepName)
351441 else do
352442 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
355443 case checkConstraints potentialContext transId graph of
356444 Left err -> dbErr err
357445 Right _ ->
@@ -396,9 +484,9 @@ evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
396484 let oldTypes = typeConstructorMapping currentContext
397485 tConsName = TCD.name tConsDef
398486 -- 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)
487+ case validateTypeConstructorDef tConsDef dConsDefList of
488+ errs@(_:_) -> dbErr (someErrors errs)
489+ [] | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
402490 | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
403491 | otherwise -> do
404492 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
@@ -414,10 +502,15 @@ evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
414502 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
415503 putStateContext $ currentContext { typeConstructorMapping = newTypes }
416504
417−evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
505+evalGraphRefDatabaseContextExpr (MultipleExpr exprs) = do
418506 --the multiple expressions must pass the same context around- not the old unmodified context
419− mapM_ evalGraphRefDatabaseContextExpr exprs
420−
507+ unimplemented
508+{- evald <- forM exprs (\expr -> evalGraphRefDatabaseContextExpr expr)
509+ --some lifting magic needed here
510+ case lefts evald of
511+ [] -> pure ()
512+ errs -> dbErr (someErrors errs)
513+ -}
421514evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
422515 currentContext <- getStateContext
423516 let atomFuncs = atomFunctions currentContext
@@ -444,11 +537,10 @@ evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
444537
445538evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
446539 context <- getStateContext
447− graph <- dbcGraph
540+ relExprEnv <- dbcRelationalExprEnv
448541 --resolve atom arguments
449− let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
542+ let eAtomTypes = map (\atomExpr -> runReader (typeForGraphRefAtomExpr emptyAttributes atomExpr) relExprEnv) atomArgExprs
450543 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
451− gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
452544 case eFunc of
453545 Left err -> dbErr err
454546 Right func -> do
@@ -458,16 +550,16 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
458550 dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
459551 else
460552 --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
553+ case lefts eAtomTypes of
554+ _:_ -> dbErr (someErrors (lefts eAtomTypes))
555+ [] -> do
556+ let atomTypes = rights eAtomTypes
557+ let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
558+ Left err -> Just err
559+ Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
469560 typeErrors = catMaybes mValidTypes
470− eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
561+ eAtomArgs = unimplemented
562+ --eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
471563 if length (lefts eAtomArgs) > 1 then
472564 dbErr (someErrors (lefts eAtomArgs))
473565 else if not (null typeErrors) then
@@ -476,6 +568,7 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
476568 case evalDatabaseContextFunction func (rights eAtomArgs) context of
477569 Left err -> dbErr err
478570 Right newContext -> putStateContext newContext
571+
479572data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
480573 { dbcio_transId :: TransactionId,
481574 dbcio_graph :: TransactionGraph,
@@ -484,15 +577,6 @@ data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
484577
485578type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
486579
487−runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
488−runDatabaseContextIOEvalMonad env ctx m = do
489− res <- runRWST m env freshState
490− case res of
491− (Left err,_,_) -> pure (Left err)
492− (Right (),s,_) -> pure (Right s)
493− where
494− freshState = mkDatabaseContextEvalState ctx
495−
496580requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
497581requireScriptSession = do
498582 env <- RWS.ask
@@ -511,15 +595,10 @@ getDBCIOContext = dbc_context <$> RWS.get
511595getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
512596getDBCIORelationalExprEnv = do
513597 context <- getDBCIOContext
514− mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
598+ env <- RWS.ask
599+ pure $ mkRelationalExprEnv context (dbcio_transId env) (dbcio_graph env)
515600
516601evalGraphRefDatabaseContextIOExpr :: 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
523602evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
524603 eScriptSession <- requireScriptSession
525604 currentContext <- getDBCIOContext
@@ -553,6 +632,7 @@ evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = d
553632 Right eContext -> case eContext of
554633 Left err -> pure (Left err)
555634 Right context' -> putDBCIOContext context'
635+
556636evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
557637 eScriptSession <- requireScriptSession
558638 currentContext <- getDBCIOContext
@@ -594,6 +674,7 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
594674 Right eContext -> case eContext of
595675 Left err -> pure (Left err)
596676 Right context' -> putDBCIOContext context'
677+
597678evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
598679 currentContext <- getDBCIOContext
599680 eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
@@ -610,7 +691,7 @@ evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName
610691 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
611692 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
612693 in putDBCIOContext newContext
613−#endif
694+
614695evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
615696 --Define
616697 currentContext <- getDBCIOContext
@@ -618,61 +699,63 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
618699 --create graph ref expr
619700 let gfExpr = Define relVarName attrExprs
620701 evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
702+ transId = dbcio_transId env
621703 graph = dbcio_graph env
622704 case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
623705 Left err -> pure (Left err)
624− Right dbstate -> do
706+ Right state -> do
625707 --Assign
626708 let existingRelVar = M.lookup relVarName relVarTable
627− relVarTable = relationVariables (dbc_context dbstate)
709+ relVarTable = relationVariables (dbc_context state)
628710 case existingRelVar of
629711 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
630712 Just existingRel -> do
631− let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
632− case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
713+ case runReader (typeForGraphRefRelationalExpr existingRel) (mkRelationalExprEnv currentContext transId graph) of
633714 Left err -> pure (Left err)
634715 Right relType -> do
635716 let expectedAttributes = attributes relType
636− tcMap = typeConstructorMapping (dbc_context dbstate)
717+ tcMap = typeConstructorMapping (dbc_context state)
637718 eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
638719 case eitherRel of
639720 Left err -> pure $ Left err
640721 Right rel ->
641722 case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
642723 Left err -> pure (Left err)
643− Right dbstate' -> putDBCIOContext (dbc_context dbstate')
724+ Right state -> putDBCIOContext (dbc_context state)
725+
726+updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
727+updateTupleWithAtomExprs exprMap context graph tupIn = do
728+ --resolve all atom exprs
729+ atomsAssoc <- mapM (\(attrName, atomExpr) -> do
730+ let atom = unimplemented
731+ --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
732+ pure (attrName, atom)
733+ ) (M.toList exprMap)
734+ pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
644735
645736--run verification on all constraints
646737checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
647−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
738+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
648739 mapM_ (uncurry checkIncDep) (M.toList deps)
649740 where
650741 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
651742 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
652743 utctDayTime = secondsToDiffTime 0 }
653744 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− }
745+ tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
659746
660747 deps = inclusionDependencies context
748+ reEnv = mkRelationalExprEnv context transId graph
661749 -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
662750 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
663− let process = runProcessExprM UncommittedContextMarker
664− gfSubsetExpr = process (processRelationalExpr subsetExpr)
665− gfSupersetExpr = process (processRelationalExpr supersetExpr)
751+ let gfSubsetExpr = runReader (processRelationalExpr subsetExpr) reEnv
752+ gfSupersetExpr = runReader (processRelationalExpr supersetExpr) reEnv
666753 --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)
754+ typeSub <- runReader (typeForRelationalExpr subsetExpr) reEnv
755+ typeSuper <- runReader (typeForRelationalExpr supersetExpr) reEnv
671756 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
672757 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
673− gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
674− gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
675− case gfEvald of
758+ case evalGraphRefRelationalExpr checkExpr potentialGraph of
676759 Left err -> Left err
677760 Right resultRel -> if resultRel == relationTrue then
678761 pure ()
@@ -682,81 +765,87 @@ checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
682765-- 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
683766-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
684767
685−typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
768+typeForRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
686769typeForRelationalExpr expr = do
687770 --replace the relationVariables context element with a cloned set of relation devoid of tuples
688771 --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
772+ gfExpr <- processRelationalExpr expr
773+ typeForGraphRefRelationalExpr gfExpr
774+
775+--returns a database context with all tuples removed
776+--this is useful for type checking and optimization
777+{-
778+contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
779+contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
780+ where
781+ relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
782+-}
695783
696784liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
697785liftE v = do
698786 y <- lift v
699787 case y of
700− Left err -> throwError err
788+ Left err -> throwE err
701789 Right val -> pure val
702790
703791{- 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
792+predicateRestrictionFilter :: Attributes -> RestrictionPredicateExprBase a -> RelationalExprState (Either RelationalError RestrictionFilter)
793+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
794+ runExceptT $ do
795+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
796+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
797+ pure (\x -> do
798+ ev1 <- expr1v x
799+ ev2 <- expr2v x
800+ pure (ev1 && ev2))
801+
802+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
803+ runExceptT $ do
804+ expr1v <- liftE (predicateRestrictionFilter attrs expr1)
805+ expr2v <- liftE (predicateRestrictionFilter attrs expr2)
716806 pure (\x -> do
717807 ev1 <- expr1v x
718808 ev2 <- expr2v x
719809 pure (ev1 || ev2))
720810
721−predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
811+predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
722812
723−predicateRestrictionFilter attrs (NotPredicate expr) = do
724− exprv <- predicateRestrictionFilter attrs expr
725− pure (fmap not . exprv)
813+predicateRestrictionFilter attrs (NotPredicate expr) =
814+ runExceptT $ do
815+ exprv <- liftE (predicateRestrictionFilter attrs expr)
816+ pure (fmap not . exprv)
726817
727818--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
819+{-
728820predicateRestrictionFilter _ (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
821+ rstate <- ask
822+ pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
735823 Left err -> Left err
736824 Right rel -> if arity rel /= 0 then
737825 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
738826 else
739− pure (rel == relationTrue))
827+ pure (rel == relationTrue)))
740828
741829predicateRestrictionFilter 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
830+ rstate <- ask
831+ let attrs' = stateAttributes rstate
832+ ctxtup' = stateTuple rstate
833+ runExceptT $ do
834+ atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
835+ attr <- either throwE pure $ case A.attributeForName attrName attrs of
747836 Right attr -> Right attr
748837 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
749838 Right ctxattr -> Right ctxattr
750839 Left err2@(NoSuchAttributeNamesError _) -> Left err2
751840 Left err -> Left err
752841 Left err -> Left err
753− if atomExprType /= A.atomType attr then
754− throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
755− else
842+ if atomExprType /= A.atomType attr then
843+ throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
844+ else
756845 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
757846 Right atomCmp -> atomCmp == atomIn
758847 Left _ -> False
759− atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
848+ atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
760849 in
761850 pure $ case atomForAttributeName attrName tupleIn of
762851 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -767,322 +856,277 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
767856-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
768857predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
769858 --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
859+ rstate <- ask
860+ runExceptT $ do
861+ aType <- liftE (typeFromAtomExpr attrs atomExpr)
862+ if aType /= BoolAtomType then
863+ throwE (AtomTypeMismatchError aType BoolAtomType)
864+ else
775865 pure (\tupleIn ->
776− case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
777− Left err -> Left err
778− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
779−
866+ case runReader (evalAtomExpr tupleIn atomExpr) rstate of
867+ Left err -> Left err
868+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
869+-}
780870tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
781871tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
782872 Left (AttributeNameInUseError attrName)
783873 else
784874 Right rel
785875
786−extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
787−extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
788−-- renv <- askEnv
876+extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
877+extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
878+ rstate <- askEnv
789879 -- check that the attribute name is not in use
790880 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
881+ Left err -> pure (Left err)
882+ Right _ -> runExceptT $ do
883+ atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
884+ atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
795885 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
796886 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)
887+ pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in
888+ case unimplemented {-runReader (evalAtomExpr tup atomExpr) substate-} of
889+ Left err -> Left err
890+ Right atom -> Right (tupleAtomExtend newAttrName atom tup)
802891 )
803892
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
893+
894+evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
895+evalAtomExpr = undefined
896+{-
897+
898+evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
899+ Right atom -> pure (Right atom)
900+ err@(Left (NoSuchAttributeNamesError _)) -> do
901+ rstate <- ask
902+ let stateTup = stateTuple rstate
903+ pure (atomForAttributeName attrName stateTup)
904+ Left err -> pure (Left err)
905+evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
906+evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
907+ argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
908+ context <- fmap stateElemsContext ask
909+ runExceptT $ do
910+ let functions = atomFunctions context
911+ func <- either throwE pure (atomFunctionForName funcName functions)
912+ let expectedArgCount = length (atomFuncType func) - 1
913+ actualArgCount = length argTypes
914+ safeInit [] = [] -- different behavior from normal init
915+ safeInit xs = init xs
916+ if expectedArgCount /= actualArgCount then
917+ throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
918+ else do
828919 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
829− mapM_ (\(expType, actType) ->
830− lift $ except (atomTypeVerify expType actType)) zippedArgs
831− evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
920+ mapM_ (\(expType, eActType) -> do
921+ actType <- either throwE pure eActType
922+ either throwE pure (atomTypeVerify expType actType)) zippedArgs
923+ evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
832924 case evalAtomFunction func evaldArgs of
833− Left err -> throwError (AtomFunctionUserError err)
925+ Left err -> throwE (AtomFunctionUserError err)
834926 Right result -> do
835927 --validate that the result matches the expected type
836− _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
928+ _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
837929 pure result
838−evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
930+evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
839931 --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
932+ rstate <- ask
933+ runExceptT $ do
934+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
935+ relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
936+ pure (RelationAtom relAtom)
937+evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
938+ rstate <- lift ask
939+ let newState = mergeTuplesIntoRelationalExprState tupIn rstate
940+ aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
941+ argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
849942 pure (ConstructedAtom dConsName aType argAtoms)
850−
851−typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
943+-}
944+typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> RelationalExprState (Either RelationalError AtomType)
852945typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
853− renv <- askEnv
946+ rstate <- askEnv
854947 case A.atomTypeForAttributeName attrName attrs of
855− Right aType -> pure aType
948+ Right aType -> pure (Right aType)
856949 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
950+ let stateTup = stateTuple rstate
951+ stateAttrs = stateAttributes rstate in
952+ case A.attributeForName attrName stateAttrs of
953+ Right attr -> pure (Right (A.atomType attr))
954+ Left _ -> case atomForAttributeName attrName stateTup of
955+ Right atom -> pure (Right (atomTypeForAtom atom))
956+ Left _ -> pure (Left err)
957+
958+typeForGraphAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
959+typeForGraphAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
960+ context <- fmap envContext askEnv
961+ let funcs = atomFunctions context
870962 case atomFunctionForName funcName funcs of
871− Left err -> throwError err
963+ Left err -> pure (Left err)
872964 Right func -> do
873965 let funcRetType = last (atomFuncType func)
874966 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))
967+ eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
968+ case lefts eArgTypes of
969+ errs@(_:_) -> pure (Left (someErrors errs))
970+ [] -> do
971+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
972+ argTypes = rights eArgTypes
973+ case eTvMap of
974+ Left err -> pure (Left err)
975+ Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
976+typeFromAtomExpr attrs (RelationAtomExpr relExpr) = do
977+ relType <- R.local (mergeAttributesIntoRelationalExprState attrs) (typeForRelationalExpr relExpr)
978+ case relType of
979+ Left err -> pure (Left err)
980+ Right relType' ->
981+ pure (pure (RelationAtomType (attributes relType')))
883982-- 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
983+typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
984+ runExceptT $ do
985+ argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
986+ context <- fmap envContext (lift askEnv)
987+ either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
889988
890989-- | 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
990+verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
991+verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
992+ rstate <- lift askEnv
894993 case A.atomTypeForAttributeName attrName (attributes relIn) of
895− Right aType -> lift $ except $ atomTypeVerify expectedType aType
994+ Right aType -> either throwE pure (atomTypeVerify expectedType aType)
896995 (Left err@(NoSuchAttributeNamesError _)) ->
897− let attrs' = envAttributes env in
996+ let attrs' = stateAttributes rstate in
898997 if attrs' == emptyAttributes then
899− throwError err
998+ throwE err
900999 else
9011000 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
1001+ Left err' -> throwE err'
1002+ Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
1003+verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
1004+verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
1005+ rstate <- askEnv
9101006 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)
1007+ context = envContext rstate
1008+ runExceptT $ do
1009+ func <- either throwE pure (atomFunctionForName funcName functions)
1010+ let expectedArgTypes = atomFuncType func
1011+ funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
1012+ Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
1013+ Left err -> throwE err
1014+ Right x -> pure x
1015+ ) $ zip3 funcArgExprs expectedArgTypes [1..]
1016+ if length funcArgTypes /= length expectedArgTypes - 1 then
1017+ throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
9211018 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
1019+ either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
1020+verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
1021+ rstate <- lift askEnv
1022+ relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
1023+ either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
1024+verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
1025+ cType <- liftE (typeFromAtomExpr (attributes rel) cons)
1026+ either throwE pure (atomTypeVerify expectedType cType)
9311027
9321028-- | Look up the type's name and create a new attribute.
933−evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1029+evalGraphRefAttrExpr :: GraphRefAttributeExpr -> RelationalExprState (Either RelationalError Attribute)
9341030evalGraphRefAttrExpr (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
1031+ graph <- re_graph <$> askEnv
1032+ case transactionForId transId graph of
1033+ Left err -> pure (Left err)
1034+ Right trans -> do
1035+ let tConsMap = typeConstructorMapping (concreteDatabaseContext trans)
1036+ validate = do
1037+ aType <- atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
1038+ validateAtomType aType tConsMap
1039+ pure aType
1040+ case validate of
1041+ Left err -> pure (Left err)
1042+ Right aType ->
1043+ pure $ Right (Attribute attrName aType)
1044+
1045+evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure $ Right attr
9391046
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
1047+evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
1048+evalTupleExpr mAttrs (TupleExpr tupMap) = do
1049+ context <- fmap envContext askEnv
1050+ runExceptT $ do
9921051 -- 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
9931052 -- 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
1053+ let attrs = fromMaybe A.emptyAttributes mAttrs
1054+ attrAtoms <- mapM (\(attrName, aExpr) -> do
1055+ --provided when the relation header is available
1056+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
1057+ unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
1058+ resolvedType <- case eExpectedAtomType of
10011059 Left _ -> pure unresolvedType
1002− Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
1060+ Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
10031061 --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
1062+ newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
1063+ pure (attrName, newAtom, resolvedType)
1064+ ) (M.toList tupMap)
1065+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1066+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1067+ tup = mkRelationTuple tupAttrs atoms
1068+ tConss = typeConstructorMapping context
1069+ finalAttrs = fromMaybe tupAttrs mAttrs
10111070 --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
1071+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
1072+ tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1073+ _ <- either throwE pure (validateTuple tup' tConss)
1074+ pure tup'
1075+
1076+evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
1077+evalAttributeNames attrNames expr = do
1078+ eExprType <- typeForRelationalExpr expr
1079+ case eExprType of
1080+ Left err -> pure (Left err)
1081+ Right exprTyp -> do
1082+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1083+ case attrNames of
1084+ AttributeNames names ->
1085+ case A.projectionAttributesForNames names (attributes exprTyp) of
1086+ Left err -> pure (Left err)
1087+ Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1088+
1089+ InvertedAttributeNames names -> do
1090+ let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1091+ if not (S.null nonExistentAttributeNames) then
1092+ pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1093+ else
1094+ pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
1095+
1096+ UnionAttributeNames namesA namesB -> do
1097+ eNameSetA <- evalAttributeNames namesA expr
1098+ case eNameSetA of
1099+ Left err -> pure (Left err)
1100+ Right nameSetA -> do
1101+ eNameSetB <- evalAttributeNames namesB expr
1102+ case eNameSetB of
1103+ Left err -> pure (Left err)
1104+ Right nameSetB ->
1105+ pure (Right (S.union nameSetA nameSetB))
1106+
1107+ IntersectAttributeNames namesA namesB -> do
1108+ eNameSetA <- evalAttributeNames namesA expr
1109+ case eNameSetA of
1110+ Left err -> pure (Left err)
1111+ Right nameSetA -> do
1112+ eNameSetB <- evalAttributeNames namesB expr
1113+ case eNameSetB of
1114+ Left err -> pure (Left err)
1115+ Right nameSetB ->
1116+ pure (Right (S.intersection nameSetA nameSetB))
1117+
1118+ RelationalExprAttributeNames attrExpr -> do
1119+ eAttrExprType <- typeForRelationalExpr attrExpr
1120+ case eAttrExprType of
1121+ Left err -> pure (Left err)
1122+ Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1123+
1124+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> TransactionGraph -> Either RelationalError Relation
1125+evalGraphRefRelationalExpr (RelationVariable name tid) graph = do
1126+ ctx <- dbContextForTransId tid graph
10361127 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)
1128+ Nothing -> Left (RelVarNotDefinedError name)
1129+ Just rv -> evalGraphRefRelationalExpr rv graph
10861130
10871131dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
10881132dbContextForTransId tid graph = do
@@ -1100,120 +1144,169 @@ transactionForId tid graph
11001144 where
11011145 matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
11021146
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−
1147+processRestrictionPredicateExpr :: RestrictionPredicateExpr -> RelationalExprState GraphRefRestrictionPredicateExpr
1148+processRestrictionPredicateExpr TruePredicate = pure TruePredicate
1149+processRestrictionPredicateExpr (AndPredicate a b) = AndPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
1150+processRestrictionPredicateExpr (OrPredicate a b) = OrPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
1151+processRestrictionPredicateExpr (NotPredicate a) = NotPredicate <$> processRestrictionPredicateExpr a
1152+processRestrictionPredicateExpr (RelationalExprPredicate expr) =
1153+ RelationalExprPredicate <$> processRelationalExpr expr
1154+processRestrictionPredicateExpr (AtomExprPredicate expr) =
1155+ AtomExprPredicate <$> processAtomExpr expr
1156+processRestrictionPredicateExpr (AttributeEqualityPredicate nam expr) =
1157+ AttributeEqualityPredicate nam <$> processAtomExpr expr
1158+
1159+processExtendTupleExpr :: ExtendTupleExpr -> RelationalExprState GraphRefExtendTupleExpr
1160+processExtendTupleExpr (AttributeExtendTupleExpr nam atomExpr) =
1161+ AttributeExtendTupleExpr nam <$> processAtomExpr atomExpr
1162+
1163+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> RelationalExprState (Either RelationalError Relation)
1164+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = pure $ mkRelation attrs emptyTupleSet
1165+typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (Right (emptyRelationWithAttrs (attributes rel)))
1166+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) =
1167+ case mAttrExprs of
1168+ Just attrExprs -> do
1169+ eAttrs <- mapM (\e -> evalGraphRefAttributeExpr e) attrExprs
1170+ case lefts eAttrs of
1171+ [] -> pure (Right (emptyRelationWithAttrs (attributesFromList (rights eAttrs))))
1172+ _ -> pure (Left (someErrors (lefts eAttrs)))
11181173typeForGraphRefRelationalExpr (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
1174+ eTrans <- currentTrans
1175+ case eTrans of
1176+ Left err -> pure (Left err)
1177+ Right trans -> do
1178+ let relVars = relationVariables (concreteDatabaseContext trans)
1179+ case M.lookup rvName relVars of
1180+ Nothing -> pure (Left (RelVarNotDefinedError rvName))
1181+ Just rvExpr -> typeForGraphRefRelationalExpr rvExpr
11241182typeForGraphRefRelationalExpr (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)
1183+ eExprType <- typeForGraphRefRelationalExpr expr
1184+ case eExprType of
1185+ Left err -> pure (Left err)
1186+ Right exprType -> do
1187+ eProjectionAttrs <- evalGraphRefAttributeNames attrNames expr
1188+ pure $ case eProjectionAttrs of
1189+ Left err -> Left err
1190+ Right projectionAttrs -> project projectionAttrs exprType
1191+
1192+evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
11721193evalGraphRefAttributeNames 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)))
1194+ eExprType <- typeForGraphRefRelationalExpr expr
1195+ case eExprType of
1196+ Left err -> pure (Left err)
1197+ Right exprTyp -> do
1198+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1199+ case attrNames of
1200+ AttributeNames names ->
1201+ case A.projectionAttributesForNames names (attributes exprTyp) of
1202+ Left err -> pure (Left err)
1203+ Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
11801204
1181− InvertedAttributeNames names -> do
1205+ InvertedAttributeNames names -> do
11821206 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
11831207 if not (S.null nonExistentAttributeNames) then
1184− throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1208+ pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
11851209 else
1186− pure (A.nonMatchingAttributeNameSet names typeNameSet)
1210+ pure (pure (A.nonMatchingAttributeNameSet names typeNameSet))
11871211
1188− UnionAttributeNames namesA namesB -> do
1189− nameSetA <- evalGraphRefAttributeNames namesA expr
1190− nameSetB <- evalGraphRefAttributeNames namesB expr
1191− pure (S.union nameSetA nameSetB)
1212+ UnionAttributeNames namesA namesB -> do
1213+ eNameSetA <- evalGraphRefAttributeNames namesA expr
1214+ case eNameSetA of
1215+ Left err -> pure (Left err)
1216+ Right nameSetA -> do
1217+ eNameSetB <- evalGraphRefAttributeNames namesB expr
1218+ case eNameSetB of
1219+ Left err -> pure (Left err)
1220+ Right nameSetB ->
1221+ pure (Right (S.union nameSetA nameSetB))
11921222
1193− IntersectAttributeNames namesA namesB -> do
1194− nameSetA <- evalGraphRefAttributeNames namesA expr
1195− nameSetB <- evalGraphRefAttributeNames namesB expr
1196− pure (S.intersection nameSetA nameSetB)
1223+ IntersectAttributeNames namesA namesB -> do
1224+ eNameSetA <- evalGraphRefAttributeNames namesA expr
1225+ case eNameSetA of
1226+ Left err -> pure (Left err)
1227+ Right nameSetA -> do
1228+ eNameSetB <- evalGraphRefAttributeNames namesB expr
1229+ case eNameSetB of
1230+ Left err -> pure (Left err)
1231+ Right nameSetB ->
1232+ pure (Right (S.intersection nameSetA nameSetB))
1233+
1234+ RelationalExprAttributeNames attrExpr -> do
1235+ eAttrExprType <- typeForGraphRefRelationalExpr attrExpr
1236+ case eAttrExprType of
1237+ Left err -> pure (Left err)
1238+ Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
11971239
1198− RelationalExprAttributeNames attrExpr -> do
1199− attrExprType <- typeForGraphRefRelationalExpr attrExpr
1200− pure (A.attributeNameSet (attributes attrExprType))
12011240
1202−evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1241+
1242+
1243+processAtomExpr :: AtomExpr -> RelationalExprState GraphRefAtomExpr
1244+processAtomExpr (AttributeAtomExpr nam) = pure $ AttributeAtomExpr nam
1245+processAtomExpr (NakedAtomExpr atom) = pure $ NakedAtomExpr atom
1246+processAtomExpr (FunctionAtomExpr fName atomExprs ()) = do
1247+ tid <- re_currentTransId <$> askEnv
1248+ FunctionAtomExpr fName <$> mapM processAtomExpr atomExprs <*> pure tid
1249+processAtomExpr (RelationAtomExpr expr) = RelationAtomExpr <$> processRelationalExpr expr
1250+processAtomExpr (ConstructedAtomExpr dConsName atomExprs ()) = ConstructedAtomExpr dConsName <$> mapM processAtomExpr atomExprs <*> (re_currentTransId <$> askEnv)
1251+
1252+processTupleExpr :: TupleExpr -> RelationalExprState GraphRefTupleExpr
1253+processTupleExpr (TupleExpr tMap) =
1254+ TupleExpr . M.fromList <$> mapM (\(k,v) -> (,) k <$> processAtomExpr v) (M.toList tMap)
1255+
1256+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> RelationalExprState (Either RelationalError Attribute)
12031257evalGraphRefAttributeExpr (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
1258+ graph <- re_graph <$> askEnv
1259+ case transactionForId tid graph of
1260+ Left err -> pure (Left err)
1261+ Right trans -> do
1262+ let tConsMap = typeConstructorMapping (concreteDatabaseContext trans)
1263+ case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1264+ Left err -> pure (Left err)
1265+ Right aType -> do
1266+ case validateAtomType aType tConsMap of
1267+ Left err -> pure (Left err)
1268+ Right _ -> pure (Right (Attribute attrName aType))
1269+
1270+--convert AttributeExpr to GraphRefAttributeExpr
1271+processAttributeExpr :: AttributeExpr -> RelationalExprState GraphRefAttributeExpr
1272+processAttributeExpr (AttributeAndTypeNameExpr nam tCons ()) = do
1273+ tid <- re_currentTransId <$> askEnv
1274+ pure $ AttributeAndTypeNameExpr nam tCons tid
1275+processAttributeExpr (NakedAttributeExpr attr) = pure $ NakedAttributeExpr attr
1276+
1277+-- convert a RelationalExpr into a GraphRefRelationalExpr using the current trans Id
1278+-- can this be done without any RelationalErrors as opposed to evalRelationalExpr?
1279+processRelationalExpr :: RelationalExpr -> RelationalExprState GraphRefRelationalExpr
1280+processRelationalExpr (MakeRelationFromExprs mAttrs tupleExprs) = do
1281+ mAttrs' <- case mAttrs of
1282+ Nothing -> pure Nothing
1283+ Just mAttrs'' -> Just <$> mapM processAttributeExpr mAttrs''
1284+ MakeRelationFromExprs mAttrs' <$> mapM processTupleExpr tupleExprs
1285+processRelationalExpr (MakeStaticRelation attrs tupSet) = pure (MakeStaticRelation attrs tupSet)
1286+processRelationalExpr (ExistingRelation rel) = pure (ExistingRelation rel)
1287+processRelationalExpr (RelationVariable rv ()) = RelationVariable rv <$> fmap re_currentTransId askEnv
1288+processRelationalExpr (Project attrNames expr) = Project <$> processAttributeNames attrNames <*> processRelationalExpr expr
1289+processRelationalExpr (Union exprA exprB) = Union <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1290+processRelationalExpr (Join exprA exprB) = Join <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1291+processRelationalExpr (Rename attrA attrB expr) =
1292+ Rename attrA attrB <$> processRelationalExpr expr
1293+processRelationalExpr (Difference exprA exprB) = Difference <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1294+processRelationalExpr (Group attrNames attrName expr) = Group <$> processAttributeNames attrNames <*> pure attrName <*> processRelationalExpr expr
1295+processRelationalExpr (Ungroup attrName expr) = Ungroup attrName <$> processRelationalExpr expr
1296+processRelationalExpr (Restrict pred expr) = Restrict <$> processRestrictionPredicateExpr pred <*> processRelationalExpr expr
1297+processRelationalExpr (Equals exprA exprB) =
1298+ Equals <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1299+processRelationalExpr (NotEquals exprA exprB) =
1300+ NotEquals <$> processRelationalExpr exprA <*> processRelationalExpr exprB
1301+processRelationalExpr (Extend extendExpr expr) =
1302+ Extend <$> processExtendTupleExpr extendExpr <*> processRelationalExpr expr
1303+processRelationalExpr (With macros expr) =
1304+ With <$> mapM (\(nam, wexpr) -> (,) nam <$> processRelationalExpr wexpr) macros <*> processRelationalExpr expr
12121305
12131306mkEmptyRelVars :: RelationVariables -> RelationVariables
1214−mkEmptyRelVars = M.map mkEmptyRelVar
1307+mkEmptyRelVars rvMap = M.map mkEmptyRelVar rvMap
12151308 where
1216− mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1309+ mkEmptyRelVar (MakeRelationFromExprs mAttrs _) = MakeRelationFromExprs mAttrs []
12171310 mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
12181311 mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
12191312 mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
@@ -1224,169 +1317,53 @@ mkEmptyRelVars = M.map mkEmptyRelVar
12241317 mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
12251318 mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
12261319 mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1227− mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1320+ mkEmptyRelVar (Restrict pred expr) = Restrict pred (mkEmptyRelVar expr)
12281321 mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
12291322 mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
12301323 mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1231− mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1324+ mkEmptyRelVar (With macros expr) = With (map (\(rv, expr) -> (rv, mkEmptyRelVar expr)) macros) (mkEmptyRelVar expr)
1325+
1326+processAttributeNames :: AttributeNames -> RelationalExprState GraphRefAttributeNames
1327+processAttributeNames (AttributeNames nameSet) = pure $ AttributeNames nameSet
1328+processAttributeNames (UnionAttributeNames attrNamesA attrNamesB) = UnionAttributeNames <$> processAttributeNames attrNamesA <*> processAttributeNames attrNamesB
1329+processAttributeNames (IntersectAttributeNames attrNamesA attrNamesB) = IntersectAttributeNames <$> processAttributeNames attrNamesA <*> processAttributeNames attrNamesB
1330+processAttributeNames (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> processRelationalExpr expr
12321331
1332+processDatabaseContextExpr :: DatabaseContextExpr -> RelationalExprState GraphRefDatabaseContextExpr
1333+processDatabaseContextExpr expr =
1334+ case expr of
1335+ NoOperation -> pure NoOperation
1336+ Define nam attrExprs -> Define nam <$> mapM processAttributeExpr attrExprs
1337+ Undefine nam -> pure (Undefine nam)
1338+ Assign nam rexpr -> Assign nam <$> processRelationalExpr rexpr
1339+ Insert nam rexpr -> Insert nam <$> processRelationalExpr rexpr
1340+ Delete nam pred -> Delete nam <$> processRestrictionPredicateExpr pred
1341+ Update nam attrMap pred -> Update nam attrMap <$> processRestrictionPredicateExpr pred
1342+
1343+ AddInclusionDependency nam dep -> pure (AddInclusionDependency nam dep)
1344+ RemoveInclusionDependency nam -> pure (RemoveInclusionDependency nam)
1345+ AddNotification nam exprA exprB exprC -> pure (AddNotification nam exprA exprB exprC)
1346+ RemoveNotification nam -> pure (RemoveNotification nam)
1347+ AddTypeConstructor tyDef consDefs -> pure (AddTypeConstructor tyDef consDefs)
1348+ RemoveTypeConstructor tyName -> pure (RemoveTypeConstructor tyName)
1349+
1350+ RemoveAtomFunction aFuncName -> pure (RemoveAtomFunction aFuncName)
1351+ RemoveDatabaseContextFunction funcName -> pure (RemoveDatabaseContextFunction funcName)
1352+ ExecuteDatabaseContextFunction funcName atomExprs -> ExecuteDatabaseContextFunction funcName <$> mapM processAtomExpr atomExprs
1353+ MultipleExpr exprs -> MultipleExpr <$> mapM processDatabaseContextExpr exprs
12331354
12341355dbErr :: RelationalError -> DatabaseContextEvalMonad ()
12351356dbErr err = lift (except (Left err))
12361357
1237−-- | Return a Relation describing the relation variables.
1238−relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1239−relationVariablesAsRelation ctx graph = do
1240− let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1241− attrs = A.attributesFromList [Attribute "name" TextAtomType,
1242− Attribute "attributes" (RelationAtomType subrelAttrs)]
1243− relVars = relationVariables ctx
1244− mkRvDesc (rvName, gfExpr) = do
1245− let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1246− gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1247− pure (rvName, gfType)
1248− relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributesVec (attributes rel))]
1249− attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1250− attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1251− Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1252− Right rel -> RelationAtom rel
1253− rvs <- mapM mkRvDesc (M.toList relVars)
1254− let tups = map relVarToAtomList rvs
1255− mkRelationFromList attrs tups
1256−
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
1358+processDatabaseContextIOExpr :: DatabaseContextIOExpr -> RelationalExprState GraphRefDatabaseContextIOExpr
1359+processDatabaseContextIOExpr (AddAtomFunction f tcs sc) =
1360+ pure (AddAtomFunction f tcs sc)
1361+processDatabaseContextIOExpr (LoadAtomFunctions mod fun file) =
1362+ pure (LoadAtomFunctions mod fun file)
1363+processDatabaseContextIOExpr (AddDatabaseContextFunction mod fun path) =
1364+ pure (AddDatabaseContextFunction mod fun path)
1365+processDatabaseContextIOExpr (LoadDatabaseContextFunctions mod fun path) =
1366+ pure (LoadDatabaseContextFunctions mod fun path)
1367+processDatabaseContextIOExpr (CreateArbitraryRelation rvName attrExprs range) =
1368+ CreateArbitraryRelation rvName <$> mapM processAttributeExpr attrExprs <*> pure range
12831369
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−