@@ -1,4 +1,7 @@
1{-# LANGUAGE ScopedTypeVariables #-}
1{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE OverloadedStrings #-}
2module ProjectM36.RelationalExpression where
5module ProjectM36.RelationalExpression where
3import ProjectM36.Relation
6import ProjectM36.Relation
4import ProjectM36.Tuple
7import ProjectM36.Tuple
@@ -13,32 +16,38 @@ import ProjectM36.DataTypes.Primitive
13import ProjectM36.AtomFunction
16import ProjectM36.AtomFunction
14import ProjectM36.DatabaseContextFunction
17import ProjectM36.DatabaseContextFunction
15import ProjectM36.Arbitrary
18import ProjectM36.Arbitrary
19+import ProjectM36.GraphRefRelationalExpr
16import ProjectM36.Transaction
20import ProjectM36.Transaction
17import qualified ProjectM36.Attribute as A
21import qualified ProjectM36.Attribute as A
18import qualified Data.Map as M
22import qualified Data.Map as M
19import qualified Data.HashSet as HS
23import qualified Data.HashSet as HS
20import qualified Data.Set as S
24import qualified Data.Set as S
21−import Control.Monad.RWS.Strict as RWS hiding (join)
25+import Control.Monad.State hiding (join)
22−import Control.Monad.Trans.Class (lift)
26+import Data.Bifunctor (second)
23−import Control.Exception
24import Data.Maybe
27import Data.Maybe
25import Data.Either
28import Data.Either
26import Data.Char (isUpper)
29import Data.Char (isUpper)
31+import qualified Data.List.NonEmpty as NE
32+import Data.Functor.Identity
27import qualified Data.Text as T
33import qualified Data.Text as T
28import qualified Data.Vector as V
34import qualified Data.Vector as V
29import qualified ProjectM36.TypeConstructorDef as TCD
35import qualified ProjectM36.TypeConstructorDef as TCD
36+import qualified Control.Monad.RWS.Strict as RWS
37+import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
30import Control.Monad.Except hiding (join)
38import Control.Monad.Except hiding (join)
31import Control.Monad.Trans.Except (except)
39import Control.Monad.Trans.Except (except)
32import Control.Monad.Reader as R hiding (join)
40import Control.Monad.Reader as R hiding (join)
33import ProjectM36.NormalizeExpr
41import ProjectM36.NormalizeExpr
34import ProjectM36.WithNameExpr
42import ProjectM36.WithNameExpr
35import Test.QuickCheck
43import Test.QuickCheck
36−import GHC
44+import qualified Data.Functor.Foldable as Fold
45+import Control.Applicative
46+#ifdef PM36_HASKELL_SCRIPTING
47+import GHC hiding (getContext)
48+import Control.Exception
37import GHC.Paths
49import GHC.Paths
38−import Data.Time.Clock
50+#endif
39−import Data.Time.Calendar
40−import qualified Data.List.NonEmpty as NE
41−import Data.Functor.Identity
43data DatabaseContextExprDetails = CountUpdatedTuples
52data DatabaseContextExprDetails = CountUpdatedTuples
@@ -66,7 +75,6 @@ mkDatabaseContextEvalState context = DatabaseContextEvalState {
66data RelationalExprEnv = RelationalExprEnv {
75data RelationalExprEnv = RelationalExprEnv {
67 re_context :: DatabaseContext,
76 re_context :: DatabaseContext,
68 re_graph :: TransactionGraph,
77 re_graph :: TransactionGraph,
69− re_currentTransId :: TransactionId,
70 re_extra :: Maybe (Either RelationTuple Attributes)
78 re_extra :: Maybe (Either RelationTuple Attributes)
@@ -86,36 +94,29 @@ runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either Relationa
86runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
94runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
88reGraph :: RelationalExprM TransactionGraph
96reGraph :: RelationalExprM TransactionGraph
89−reGraph = re_graph <$> R.ask
91−currentTrans :: RelationalExprM Transaction
93− tid <- re_currentTransId <$> R.ask
94− graph <- re_graph <$> R.ask
97+reGraph = asks re_graph
95− lift $ except $ transactionForId tid graph
97−reTransId :: RelationalExprM TransactionId
99+reContext :: RelationalExprM DatabaseContext
98−reTransId = re_currentTransId <$> R.ask
100+reContext = asks re_context
100−mkRelationalExprEnv :: DatabaseContext -> TransactionId -> TransactionGraph -> RelationalExprEnv
102+mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
101−mkRelationalExprEnv ctx currentTransId graph =
103+mkRelationalExprEnv ctx graph =
102 RelationalExprEnv
104 RelationalExprEnv
103 { re_context = ctx,
105 { re_context = ctx,
104 re_graph = graph,
106 re_graph = graph,
105− re_currentTransId = currentTransId,
106 re_extra = Nothing }
107 re_extra = Nothing }
108askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
109askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
109askEnv = R.ask
110askEnv = R.ask
111mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
112mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
112−mergeTuplesIntoGraphRefRelationalExprEnv tupIn e =
113+mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
113− e{ gre_extra = new_elems }
114+ env { gre_extra = new_elems }
115 new_elems = Just (Left newTuple)
116 new_elems = Just (Left newTuple)
116− mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple e))
117+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
117 newTuple = mkRelationTupleFromMap mergedTupMap
118 newTuple = mkRelationTupleFromMap mergedTupMap
119mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
120mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
120mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
121mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
@@ -141,12 +142,12 @@ data DatabaseContextEvalEnv = DatabaseContextEvalEnv
143mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
144mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
144−mkDatabaseContextEvalEnv tid graph = DatabaseContextEvalEnv tid graph
145+mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
146type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
147type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
148runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
149runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
149−runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> (execRWST m env freshEnv)))
150+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
151 freshEnv = mkDatabaseContextEvalState ctx
152 freshEnv = mkDatabaseContextEvalState ctx
@@ -159,18 +160,20 @@ dbcGraph = dce_graph <$> RWS.ask
160dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
161dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
161dbcRelationalExprEnv =
162dbcRelationalExprEnv =
162− mkRelationalExprEnv <$> getStateContext <*> dbcTransId <*> dbcGraph
163+ mkRelationalExprEnv <$> getStateContext <*> dbcGraph
164getStateContext :: DatabaseContextEvalMonad DatabaseContext
165getStateContext :: DatabaseContextEvalMonad DatabaseContext
165−getStateContext = dbc_context <$> get
166+getStateContext = gets dbc_context
167putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
168putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
168putStateContext ctx' = do
169putStateContext ctx' = do
170− put (s {dbc_context = ctx'})
171+ put (s {dbc_context = ctx', dbc_dirty = True})
173+-- | The context is optionally passed down along in cases where the current context is uncommitted.
172data GraphRefRelationalExprEnv =
174data GraphRefRelationalExprEnv =
173 GraphRefRelationalExprEnv {
175 GraphRefRelationalExprEnv {
176+ gre_context :: Maybe DatabaseContext,
174 gre_graph :: TransactionGraph,
177 gre_graph :: TransactionGraph,
175 gre_extra :: Maybe (Either RelationTuple Attributes)
178 gre_extra :: Maybe (Either RelationTuple Attributes)
@@ -182,17 +185,26 @@ gfTransForId tid = do
182 graph <- gfGraph
185 graph <- gfGraph
183 lift $ except $ transactionForId tid graph
186 lift $ except $ transactionForId tid graph
188+gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
189+gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
190+gfDatabaseContextForMarker UncommittedContextMarker = do
191+ mctx <- gre_context <$> askEnv
193+ Nothing -> throwError NoUncommittedContextInEvalError
194+ Just ctx -> pure ctx
185runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
196runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
186runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
197runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
188−freshGraphRefRelationalExprEnv :: TransactionGraph -> GraphRefRelationalExprEnv
199+freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
189−freshGraphRefRelationalExprEnv graph = GraphRefRelationalExprEnv {
200+freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
190 gre_graph = graph,
202 gre_graph = graph,
191 gre_extra = Nothing
203 gre_extra = Nothing
194gfGraph :: GraphRefRelationalExprM TransactionGraph
206gfGraph :: GraphRefRelationalExprM TransactionGraph
195−gfGraph = gre_graph <$> R.ask
207+gfGraph = asks gre_graph
197envContext :: RelationalExprEnv -> DatabaseContext
209envContext :: RelationalExprEnv -> DatabaseContext
198envContext = re_context
210envContext = re_context
@@ -200,173 +212,27 @@ envContext = re_context
200setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
212setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
201setEnvContext e ctx = e { re_context = ctx }
213setEnvContext e ctx = e { re_context = ctx }
204−--full evaluation down the graph
205−eval :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
208− eGfExpr <- processRelationalExpr expr
210− Left err -> pure (Left err)
211− Right gfExpr -> pure $ evalGraphRefRelationalExpr gfExpr (re_graph env)
214−--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
215−evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
216−evalRelationalExpr (RelationVariable name _) = do
217− relvarTable <- fmap (relationVariables . envContext) askEnv
218− return $ case M.lookup name relvarTable of
219− Just res -> Right res
220− Nothing -> Left $ RelVarNotDefinedError name
222−evalRelationalExpr (Project attrNames expr) = do
223− eAttrNameSet <- evalAttributeNames attrNames expr
224− case eAttrNameSet of
225− Left err -> pure (Left err)
226− Right attrNameSet -> do
227− rel <- evalRelationalExpr expr
229− Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
230− Left err -> pure $ Left err
232−evalRelationalExpr (Union exprA exprB) = do
233− relA <- evalRelationalExpr exprA
234− relB <- evalRelationalExpr exprB
236− Left err -> return $ Left err
237− Right relA2 -> case relB of
238− Left err -> return $ Left err
239− Right relB2 -> return $ Right (Union relA2 relB2)
241−evalRelationalExpr (Join exprA exprB) = do
242− relA <- evalRelationalExpr exprA
243− relB <- evalRelationalExpr exprB
245− Left err -> return $ Left err
246− Right relA2 -> case relB of
247− Left err -> return $ Left err
248− Right relB2 -> return $ Right (Join relA2 relB2)
250−evalRelationalExpr (Difference exprA exprB) = do
251− relA <- evalRelationalExpr exprA
252− relB <- evalRelationalExpr exprB
254− Left err -> return $ Left err
255− Right relA2 -> case relB of
256− Left err -> return $ Left err
257− Right relB2 -> return $ Right (Difference relA2 relB2)
259−evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
260− case mkRelation attributeSet tupleSet of
261− Right rel -> return $ Right (ExistingRelation rel)
262− Left err -> return $ Left err
264−evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
265− currentContext <- fmap envContext askEnv
266− let tConss = typeConstructorMapping currentContext
267− -- 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
269− mAttrs <- case mAttrExprs of
271− Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
272− Nothing -> pure Nothing
273− tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
274− let attrs = fromMaybe firstTupleAttrs mAttrs
275− firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
276− expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
277− pure (ExistingRelation expr)
279−evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
281−evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
282− evald <- evalRelationalExpr relExpr
284− Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
285− Left err -> return $ Left err
287−evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
288− eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
289− case eOldAttrNameSet of
290− Left err -> pure (Left err)
291− Right oldAttrNameSet -> do
292− evald <- evalRelationalExpr relExpr
294− Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
295− Left err -> return $ Left err
297−evalRelationalExpr (Ungroup attrName relExpr) = do
298− evald <- evalRelationalExpr relExpr
300− Right expr -> return $ Right (Ungroup attrName expr)
301− Left err -> return $ Left err
303−evalRelationalExpr (Restrict predicateExpr relExpr) = do
304− evald <- evalRelationalExpr relExpr
305− pred <- processRestrictionPredicateExpr predicateExpr
307− Left err -> return $ Left err
309− pure $ Right (Restrict pred expr)
311−evalRelationalExpr (Equals relExprA relExprB) = do
312− evaldA <- evalRelationalExpr relExprA
313− evaldB <- evalRelationalExpr relExprB
315− Left err -> return $ Left err
316− Right exprA -> case evaldB of
317− Left err -> return $ Left err
318− Right exprB -> return $ Right (Equals exprA exprB)
320−evalRelationalExpr (With views mainExpr) = do
323− let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
324− Left (RelVarAlreadyDefinedError vname)
326− case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
327− (Left err,_) -> Left err
328− (Right (), (ctx',_,_)) -> Right ctx'
330− case foldM addScopedView (stateElemsContext rstate) views of
331− Left err -> return $ Left err
333− let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprEnv ctx'')
334− case evalMainExpr mainExpr of
335− Left err -> return $ Left err
336− Right rel -> return $ Right rel
338−--warning: copy-pasta from above- refactor
339−evalRelationalExpr (NotEquals relExprA relExprB) = do
340− evaldA <- evalRelationalExpr relExprA
341− evaldB <- evalRelationalExpr relExprB
343− Left err -> return $ Left err
344− Right exprA -> case evaldB of
345− Left err -> return $ Left err
346− Right exprB -> return $ Right (NotEquals exprA exprB)
348−-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
349−evalRelationalExpr (Extend tupleExpression relExpr) = do
350− eExpr <- evalRelationalExpr relExpr
352− Left err -> pure (Left err)
354− tupProc <- processExtendTupleExpr tupleExpression
355− pure (Right (Extend tupProc expr))
357--helper function to process relation variable creation/assignment
215--helper function to process relation variable creation/assignment
358setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
216setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
359setRelVar relVarName relExpr = do
217setRelVar relVarName relExpr = do
361 currentContext <- getStateContext
218 currentContext <- getStateContext
219+ --prevent recursive relvar definition by resolving references to relvars in previous states
220+ relExpr' <- resolve relExpr
362− let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
221+ let newRelVars = M.insert relVarName relExpr' $ relationVariables currentContext
363 potentialContext = currentContext { relationVariables = newRelVars }
222 potentialContext = currentContext { relationVariables = newRelVars }
223+ --optimization: if the relexpr is unchanged, skip the update
224+ if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
364− --determine when to check constraints
227+ --determine when to check constraints
365− graph <- dbcGraph
228+ graph <- dbcGraph
366− tid <- dbcTransId
229+ tid <- dbcTransId
367− case checkConstraints potentialContext tid graph of
230+ case checkConstraints potentialContext tid graph of
368− Left err -> dbErr err
231+ Left err -> dbErr err
369− Right _ -> putStateContext potentialContext
232+ Right _ -> putStateContext potentialContext
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 ()
371-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
237-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
372deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
238deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
@@ -385,19 +251,17 @@ evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContex
385evalGraphRefDatabaseContextExpr NoOperation = pure ()
251evalGraphRefDatabaseContextExpr NoOperation = pure ()
387evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
253evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
254+ context <- getStateContext
388 relvars <- fmap relationVariables getStateContext
255 relvars <- fmap relationVariables getStateContext
389 tConss <- fmap typeConstructorMapping getStateContext
256 tConss <- fmap typeConstructorMapping getStateContext
390 graph <- dbcGraph
257 graph <- dbcGraph
391 let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
258 let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
392− gfEnv = freshGraphRefRelationalExprEnv graph
259+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
393 case eAttrs of
260 case eAttrs of
394− Left err -> dbErr err
261+ Left err -> dbErr err
395 Right attrsList -> do
262 Right attrsList -> do
396− let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
263+ lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
397− if not (null atomTypeErrs) then
398− dbErr (someErrors atomTypeErrs)
400− case M.member relVarName relvars of
264+ case M.member relVarName relvars of
401 True -> dbErr (RelVarAlreadyDefinedError relVarName)
265 True -> dbErr (RelVarAlreadyDefinedError relVarName)
402 False -> setRelVar relVarName (ExistingRelation emptyRelation)
266 False -> setRelVar relVarName (ExistingRelation emptyRelation)
@@ -410,13 +274,17 @@ evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
410 graph <- re_graph <$> dbcRelationalExprEnv
274 graph <- re_graph <$> dbcRelationalExprEnv
411 context <- getStateContext
275 context <- getStateContext
412 let existingRelVar = M.lookup relVarName (relationVariables context)
276 let existingRelVar = M.lookup relVarName (relationVariables context)
277+ reEnv = freshGraphRefRelationalExprEnv (Just context) graph
278+ eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
413 case existingRelVar of
279 case existingRelVar of
414 Nothing -> do
280 Nothing -> do
281+ case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
282+ Left err -> dbErr err
284+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
415− setRelVar relVarName expr
285+ setRelVar relVarName expr
416 Just existingRel -> do
286 Just existingRel -> do
417 let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
287 let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
418− eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
419− reEnv = freshGraphRefRelationalExprEnv graph
420 case eExpectedType of
288 case eExpectedType of
421 Left err -> dbErr err
289 Left err -> dbErr err
422 Right expectedType ->
290 Right expectedType ->
@@ -424,44 +292,53 @@ evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
424 Left err -> dbErr err
292 Left err -> dbErr err
425 Right newExprType -> do
293 Right newExprType -> do
426 if newExprType == expectedType then do
294 if newExprType == expectedType then do
295+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
427 setRelVar relVarName expr
296 setRelVar relVarName expr
429 dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
298 dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
431evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
300evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
432− transId <- dbcTransId
301+ gfExpr <- relVarByName relVarName
433− evalGraphRefDatabaseContextExpr (Assign relVarName
302+ let optExpr = applyUnionCollapse (Union
435− (RelationVariable relVarName transId)
436− relExpr))
303+ relExpr
305+ evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
438evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
307evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
439− transId <- dbcTransId
308+ gfExpr <- relVarByName relVarName
440− let rv = RelationVariable relVarName transId
441− setRelVar relVarName (Restrict (NotPredicate predicate) rv)
309+ let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
310+ setRelVar relVarName optExpr
443--union of restricted+updated portion and the unrestricted+unupdated portion
312--union of restricted+updated portion and the unrestricted+unupdated portion
444evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
313evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
314+ rvExpr <- relVarByName relVarName
315+ graph <- re_graph <$> dbcRelationalExprEnv
445 context <- getStateContext
316 context <- getStateContext
446− transId <- dbcTransId
317+ let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
447− graph <- dbcGraph
318+ --get the current attributes name in the relvar to ensure that we don't conflict when renaming
448− let relVarMap = relationVariables context
319+ eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
449− case M.lookup relVarName relVarMap of
320+ exprType' <- case eExprType of
450− Nothing -> dbErr (RelVarNotDefinedError relVarName)
321+ Left err -> throwError err
451− Just _ -> do
322+ Right t -> pure t
452− let unrestrictedPortion = Restrict (NotPredicate pred') rv
323+ let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
453− rv = RelationVariable relVarName transId
324+ tmpAttr = tmpAttrC 1
454− tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
325+ tmpAttrC :: Int -> AttributeName -> AttributeName
327+ let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
328+ if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
455− updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
332+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
456− projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
333+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
457− --TODO restrictedPortion = Restrict pred'
334+ restrictedPortion = Restrict pred' rvExpr
458− updated = foldr (\(oldname, atomExpr) accum ->
335+ updated = foldr (\(oldname, atomExpr) accum ->
459− let procAtomExpr = runProcessExprM transId graph (processAtomExpr atomExpr) in
336+ let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
460 updateAttr oldname procAtomExpr accum
337 updateAttr oldname procAtomExpr accum
461− ) rv (M.toList atomExprMap)
338+ ) restrictedPortion (M.toList atomExprMap)
462 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
339 -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
463− updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
340+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
464− setRelVar relVarName (Union unrestrictedPortion updatedPortion)
341+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
466evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
343evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
467 currContext <- getStateContext
344 currContext <- getStateContext
@@ -473,6 +350,8 @@ evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
473 dbErr (InclusionDependencyNameInUseError newDepName)
350 dbErr (InclusionDependencyNameInUseError newDepName)
475 let potentialContext = currContext { inclusionDependencies = newDeps }
352 let potentialContext = currContext { inclusionDependencies = newDeps }
353+ -- if the potential context passes all constraints, then save it
354+ -- potential optimization: validate only the new constraint- all old constraints must already hold
476 case checkConstraints potentialContext transId graph of
355 case checkConstraints potentialContext transId graph of
477 Left err -> dbErr err
356 Left err -> dbErr err
478 Right _ ->
357 Right _ ->
@@ -517,9 +396,9 @@ evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
517 let oldTypes = typeConstructorMapping currentContext
396 let oldTypes = typeConstructorMapping currentContext
518 tConsName = TCD.name tConsDef
397 tConsName = TCD.name tConsDef
519 -- validate that the constructor's types exist
398 -- validate that the constructor's types exist
520− case validateTypeConstructorDef tConsDef dConsDefList of
399+ case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
521− errs@(_:_) -> dbErr (someErrors errs)
400+ Left err -> throwError err
522− [] | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
401+ Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
523 | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
402 | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
524 | otherwise -> do
403 | otherwise -> do
525 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
404 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
@@ -535,15 +414,10 @@ evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
535 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
414 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
536 putStateContext $ currentContext { typeConstructorMapping = newTypes }
415 putStateContext $ currentContext { typeConstructorMapping = newTypes }
538−evalGraphRefDatabaseContextExpr (MultipleExpr _) = do
417+evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
539 --the multiple expressions must pass the same context around- not the old unmodified context
418 --the multiple expressions must pass the same context around- not the old unmodified context
541−{- evald <- forM exprs (\expr -> evalGraphRefDatabaseContextExpr expr)
419+ mapM_ evalGraphRefDatabaseContextExpr exprs
542− --some lifting magic needed here
420+
545− errs -> dbErr (someErrors errs)
547evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
421evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
548 currentContext <- getStateContext
422 currentContext <- getStateContext
549 let atomFuncs = atomFunctions currentContext
423 let atomFuncs = atomFunctions currentContext
@@ -572,9 +446,9 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
572 context <- getStateContext
446 context <- getStateContext
573 graph <- dbcGraph
447 graph <- dbcGraph
574 --resolve atom arguments
448 --resolve atom arguments
575− let eAtomTypes = mapM (\atomExpr -> runGraphRefRelationalExprM gfEnv (typeForGraphRefAtomExpr emptyAttributes atomExpr)) atomArgExprs
449+ let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
576 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
450 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
577− gfEnv = freshGraphRefRelationalExprEnv graph
451+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
578 case eFunc of
452 case eFunc of
579 Left err -> dbErr err
453 Left err -> dbErr err
580 Right func -> do
454 Right func -> do
@@ -587,12 +461,13 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
587 case eAtomTypes of
461 case eAtomTypes of
588 Left err -> dbErr err
462 Left err -> dbErr err
589 Right atomTypes -> do
463 Right atomTypes -> do
464+ let mValidTypes = zipWith (\ expType actType
590− let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
465+ -> case atomTypeVerify expType actType of
591− Left err -> Just err
466+ Left err -> Just err
592− Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
468+ (dbcFuncType func) atomTypes
593 typeErrors = catMaybes mValidTypes
469 typeErrors = catMaybes mValidTypes
594− eAtomArgs = unimplemented
470+ eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
595− --eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
596 if length (lefts eAtomArgs) > 1 then
471 if length (lefts eAtomArgs) > 1 then
597 dbErr (someErrors (lefts eAtomArgs))
472 dbErr (someErrors (lefts eAtomArgs))
598 else if not (null typeErrors) then
473 else if not (null typeErrors) then
@@ -601,7 +476,6 @@ evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArg
601 case evalDatabaseContextFunction func (rights eAtomArgs) context of
476 case evalDatabaseContextFunction func (rights eAtomArgs) context of
602 Left err -> dbErr err
477 Left err -> dbErr err
603 Right newContext -> putStateContext newContext
478 Right newContext -> putStateContext newContext
605data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
479data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
606 { dbcio_transId :: TransactionId,
480 { dbcio_transId :: TransactionId,
607 dbcio_graph :: TransactionGraph,
481 dbcio_graph :: TransactionGraph,
@@ -637,10 +511,15 @@ getDBCIOContext = dbc_context <$> RWS.get
637getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
511getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
638getDBCIORelationalExprEnv = do
512getDBCIORelationalExprEnv = do
639 context <- getDBCIOContext
513 context <- getDBCIOContext
641− pure $ mkRelationalExprEnv context (dbcio_transId env) (dbcio_graph env)
514+ mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
643evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
516evalGraphRefDatabaseContextIOExpr :: 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))
644evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
523evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
645 eScriptSession <- requireScriptSession
524 eScriptSession <- requireScriptSession
646 currentContext <- getDBCIOContext
525 currentContext <- getDBCIOContext
@@ -674,7 +553,6 @@ evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = d
674 Right eContext -> case eContext of
553 Right eContext -> case eContext of
675 Left err -> pure (Left err)
554 Left err -> pure (Left err)
676 Right context' -> putDBCIOContext context'
555 Right context' -> putDBCIOContext context'
678evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
556evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
679 eScriptSession <- requireScriptSession
557 eScriptSession <- requireScriptSession
680 currentContext <- getDBCIOContext
558 currentContext <- getDBCIOContext
@@ -716,7 +594,6 @@ evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType
716 Right eContext -> case eContext of
594 Right eContext -> case eContext of
717 Left err -> pure (Left err)
595 Left err -> pure (Left err)
718 Right context' -> putDBCIOContext context'
596 Right context' -> putDBCIOContext context'
720evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
597evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
721 currentContext <- getDBCIOContext
598 currentContext <- getDBCIOContext
722 eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
599 eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
@@ -733,7 +610,7 @@ evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName
733 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
610 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
734 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
611 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
735 in putDBCIOContext newContext
612 in putDBCIOContext newContext
737evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
614evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
739 currentContext <- getDBCIOContext
616 currentContext <- getDBCIOContext
@@ -751,7 +628,7 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
751 case existingRelVar of
628 case existingRelVar of
752 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
753 Just existingRel -> do
630 Just existingRel -> do
754− let gfEnv = freshGraphRefRelationalExprEnv graph
631+ let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
755 case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
632 case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
756 Left err -> pure (Left err)
633 Left err -> pure (Left err)
757 Right relType -> do
634 Right relType -> do
@@ -765,44 +642,36 @@ evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs
765 Left err -> pure (Left err)
642 Left err -> pure (Left err)
766 Right dbstate' -> putDBCIOContext (dbc_context dbstate')
643 Right dbstate' -> putDBCIOContext (dbc_context dbstate')
769−updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
770−updateTupleWithAtomExprs exprMap context graph tupIn = do
771− --resolve all atom exprs
773− atomsAssoc <- mapM (\(attrName, atomExpr) -> do
774− let atom = unimplemented
775− --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
776− pure (attrName, atom)
777− ) (M.toList exprMap)
778− pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
780--run verification on all constraints
645--run verification on all constraints
781checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
646checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
782−checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
647+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
783 mapM_ (uncurry checkIncDep) (M.toList deps)
648 mapM_ (uncurry checkIncDep) (M.toList deps)
785 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
650 potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
786 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
651 tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
787 utctDayTime = secondsToDiffTime 0 }
652 utctDayTime = secondsToDiffTime 0 }
788 tempSchemas = Schemas context M.empty
653 tempSchemas = Schemas context M.empty
654+ tempTrans = Transaction U.nil tempTransInfo tempSchemas
789− tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
655+ tempTransInfo = TransactionInfo { parents = transId NE.:| [],
791 deps = inclusionDependencies context
660 deps = inclusionDependencies context
792 -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
661 -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
793 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
662 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
794− let process = runProcessExprM transId graph
663+ let process = runProcessExprM UncommittedContextMarker
795 gfSubsetExpr = process (processRelationalExpr subsetExpr)
664 gfSubsetExpr = process (processRelationalExpr subsetExpr)
796 gfSupersetExpr = process (processRelationalExpr supersetExpr)
665 gfSupersetExpr = process (processRelationalExpr supersetExpr)
797 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
666 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
798− let gfEnv = freshGraphRefRelationalExprEnv graph
667+ let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
799 runGfRel = runGraphRefRelationalExprM gfEnv
668 runGfRel = runGraphRefRelationalExprM gfEnv
800 typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
669 typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
801 typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
670 typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
802 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
671 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
803 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
672 let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
804 gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
673 gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
805− gfEnv' = freshGraphRefRelationalExprEnv potentialGraph
674+ gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
806 case gfEvald of
675 case gfEvald of
807 Left err -> Left err
676 Left err -> Left err
808 Right resultRel -> if resultRel == relationTrue then
677 Right resultRel -> if resultRel == relationTrue then
@@ -818,20 +687,11 @@ typeForRelationalExpr expr = do
818 --replace the relationVariables context element with a cloned set of relation devoid of tuples
687 --replace the relationVariables context element with a cloned set of relation devoid of tuples
819 --evalRelationalExpr could still return an existing relation with tuples, so strip them
688 --evalRelationalExpr could still return an existing relation with tuples, so strip them
820 graph <- reGraph
689 graph <- reGraph
821− transId <- reTransId
690+ context <- reContext
822− let gfExpr = runProcessExprM transId graph (processRelationalExpr expr)
691+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
823− gfEnv = freshGraphRefRelationalExprEnv graph
692+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
824 runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
693 runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
825− lift $ except $ runGf
694+ lift $ except runGf
827−--returns a database context with all tuples removed
828−--this is useful for type checking and optimization
830−contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
831−contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
833− relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
836liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
696liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
837liftE v = do
697liftE v = do
@@ -880,7 +740,7 @@ predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
881predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
741predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
882 env <- askEnv
742 env <- askEnv
883− let attrs' = envAttributes env
743+ let attrs' = A.union attrs (envAttributes env)
884 ctxtup' = envTuple env
744 ctxtup' = envTuple env
885 atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
745 atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
886 attr <- lift $ except $ case A.attributeForName attrName attrs of
746 attr <- lift $ except $ case A.attributeForName attrName attrs of
@@ -924,7 +784,7 @@ tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName r
924 Right rel
784 Right rel
926extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
786extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
927−extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
787+extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
928-- renv <- askEnv
788-- renv <- askEnv
929 -- check that the attribute name is not in use
789 -- check that the attribute name is not in use
930 case tupleExprCheckNewAttrName newAttrName relIn of
790 case tupleExprCheckNewAttrName newAttrName relIn of
@@ -934,66 +794,60 @@ extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrNa
934 atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
794 atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
935 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
795 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
936 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
796 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
937− pure (newAndOldAttrs, \tup ->
798+ pure (newAndOldAttrs, \tup -> do
938− --let substate = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
799+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
939− case unimplemented {-runReader (evalAtomExpr tup atomExpr) substate-} of
800+ atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
940− Left err -> Left err
941− Right atom -> Right (tupleAtomExtend newAttrName atom tup)
801+ Right (tupleAtomExtend newAttrName atom tup)
944evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
804evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
945−evalGraphRefAtomExpr = unimplemented
805+evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
947−evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprM Atom
948−evalAtomExpr = unimplemented
951−evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
806+ case atomForAttributeName attrName tupIn of
952− Right atom -> pure (Right atom)
807+ Right atom -> pure atom
953− err@(Left (NoSuchAttributeNamesError _)) -> do
808+ Left err@(NoSuchAttributeNamesError _) -> do
954− rstate <- ask
809+ env <- askEnv
955− let stateTup = stateTuple rstate
810+ case gre_extra env of
811+ Nothing -> throwError err
956− pure (atomForAttributeName attrName stateTup)
812+ Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
813+ Just (Right _) -> throwError err
957− Left err -> pure (Left err)
814+ Left err -> throwError err
958−evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
815+evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
959−evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
816+evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
960− argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
817+ argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
961− context <- fmap stateElemsContext ask
818+ context <- gfDatabaseContextForMarker tid
963− let functions = atomFunctions context
819+ let functions = atomFunctions context
964− func <- either throwE pure (atomFunctionForName funcName functions)
820+ func <- lift $ except (atomFunctionForName funcName functions)
965− let expectedArgCount = length (atomFuncType func) - 1
821+ let expectedArgCount = length (atomFuncType func) - 1
966− actualArgCount = length argTypes
822+ actualArgCount = length argTypes
967− safeInit [] = [] -- different behavior from normal init
823+ safeInit [] = [] -- different behavior from normal init
968− safeInit xs = init xs
824+ safeInit xs = init xs
969− if expectedArgCount /= actualArgCount then
825+ if expectedArgCount /= actualArgCount then
970− throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
826+ throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
972 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
828 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
973− mapM_ (\(expType, eActType) -> do
829+ mapM_ (\(expType, actType) ->
974− actType <- either throwE pure eActType
975− either throwE pure (atomTypeVerify expType actType)) zippedArgs
830+ lift $ except (atomTypeVerify expType actType)) zippedArgs
976− evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
831+ evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
977 case evalAtomFunction func evaldArgs of
832 case evalAtomFunction func evaldArgs of
978− Left err -> throwE (AtomFunctionUserError err)
833+ Left err -> throwError (AtomFunctionUserError err)
979 Right result -> do
834 Right result -> do
980 --validate that the result matches the expected type
835 --validate that the result matches the expected type
981− _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
836+ _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
982 pure result
837 pure result
983−evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
838+evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
984 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
839 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
985− rstate <- ask
840+ env <- ask
986− runExceptT $ do
841+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
987− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
842+ relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
988− relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
989− pure (RelationAtom relAtom)
843+ pure (RelationAtom relAtom)
990−evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
844+evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
991− rstate <- lift ask
845+ let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
992− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
993− aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
846+ aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
994− argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
847+ argAtoms <- local mergeEnv $
848+ mapM (evalGraphRefAtomExpr tupIn) dConsArgs
995 pure (ConstructedAtom dConsName aType argAtoms)
849 pure (ConstructedAtom dConsName aType argAtoms)
997typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
851typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
998typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
852typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
999 renv <- askEnv
853 renv <- askEnv
@@ -1006,12 +860,13 @@ typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
1006 Right attr -> pure (A.atomType attr)
860 Right attr -> pure (A.atomType attr)
1007 Left _ -> case atomForAttributeName attrName envTup of
861 Left _ -> case atomForAttributeName attrName envTup of
1008 Right atom -> pure (atomTypeForAtom atom)
862 Right atom -> pure (atomTypeForAtom atom)
863+ Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
1009− Left _ -> throwError err
864+ throwError err
1010 Left err -> throwError err
865 Left err -> throwError err
1012typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
867typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
1013typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
868typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
1014− funcs <- atomFunctions . concreteDatabaseContext <$> gfTransForId transId
869+ funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
1015 case atomFunctionForName funcName funcs of
870 case atomFunctionForName funcName funcs of
1016 Left err -> throwError err
871 Left err -> throwError err
1017 Right func -> do
872 Right func -> do
@@ -1029,7 +884,7 @@ typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
1029typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
884typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
1031 argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
886 argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
1032− tConsMap <- typeConstructorMapping . concreteDatabaseContext <$> gfTransForId tid
887+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1033 lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
888 lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
1035-- | Validate that the type of the AtomExpr matches the expected type.
890-- | Validate that the type of the AtomExpr matches the expected type.
@@ -1051,7 +906,7 @@ verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
1051verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
906verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
1052 lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
907 lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
1053verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
908verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
1054− context <- concreteDatabaseContext <$> gfTransForId tid
909+ context <- gfDatabaseContextForMarker tid
1055 let functions = atomFunctions context
910 let functions = atomFunctions context
1056 func <- lift $ except $ atomFunctionForName funcName functions
911 func <- lift $ except $ atomFunctionForName funcName functions
1057 let expectedArgTypes = atomFuncType func
912 let expectedArgTypes = atomFuncType func
@@ -1059,7 +914,7 @@ verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) e
1059 let handler :: RelationalError -> GraphRefRelationalExprM AtomType
914 let handler :: RelationalError -> GraphRefRelationalExprM AtomType
1060 handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
915 handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
1061 handler err = throwError err
916 handler err = throwError err
1062− verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
917+ verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
1063 funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
918 funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
1064 if length funcArgTypes /= length expectedArgTypes - 1 then
919 if length funcArgTypes /= length expectedArgTypes - 1 then
1065 throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
920 throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
@@ -1077,13 +932,61 @@ verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
1077-- | Look up the type's name and create a new attribute.
932-- | Look up the type's name and create a new attribute.
1078evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
933evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1079evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
934evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
1080− tConsMap <- typeConstructorMapping . concreteDatabaseContext <$> gfTransForId transId
935+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
1081 aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
936 aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
1082 lift $ except $ validateAtomType aType tConsMap
937 lift $ except $ validateAtomType aType tConsMap
1083 pure $ Attribute attrName aType
938 pure $ Attribute attrName aType
1085evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
940evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
942+-- for tuple type concrete resolution (Nothing ==> Maybe Int) when the attributes hint is Nothing, we need to first process all the tuples, then extract the concrete types on a per-attribute basis, then reprocess the tuples to include the concrete types
943+evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
944+evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
945+evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
946+ tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
947+ finalAttrs <- case mAttrs of
948+ Just attrs -> pure attrs
951+ [] -> pure emptyAttributes
952+ (headTuple:tailTuples) -> do
953+ --gather up resolved atom types or throw an error if an attribute cannot be made concrete from the inferred types- this could still fail if the type cannot be inferred (e.g. from [Nothing, Nothing])
955+ processTupleAttrs (tupAttr, accAttr) =
956+ --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
957+ if isResolvedAttribute accAttr && tupAttr == accAttr then
960+ lift $ except $ resolveAttributes accAttr tupAttr
961+ mostResolvedTypes <-
962+ foldM (\acc tup -> do
963+ let zipped = zip (V.toList . attributesVec $ tupleAttributes tup) acc
964+ accNames = S.fromList $ map A.attributeName acc
965+ tupNames = A.attributeNameSet (tupleAttributes tup)
966+ attrNamesDiff = S.union (S.difference accNames tupNames) (S.difference tupNames accNames)
967+ unless (null attrNamesDiff) (throwError (AttributeNamesMismatchError attrNamesDiff))
968+ nextTupleAttrs <- mapM processTupleAttrs zipped
969+ let diff = A.attributesDifference (A.attributesFromList nextTupleAttrs) (A.attributesFromList acc)
970+ if diff == A.emptyAttributes then
973+ throwError (TupleAttributeTypeMismatchError diff)
974+ ) (V.toList . attributesVec $ tupleAttributes headTuple) tailTuples
975+ pure (A.attributesFromList mostResolvedTypes)
976+ --strategy: if all the tuple expr transaction markers refer to one location, then we can pass the type constructor mapping from that location, otherwise, we cannot assume that the types are the same
977+ tConsMap <- case singularTransactions tupleExprL of
978+ SingularTransactionRef commonTransId ->
979+ typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
980+ NoTransactionsRef ->
981+ typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
982+ -- if there are multiple transaction markers in the TupleExprs, then we can't assume a single type constructor mapping- this could be improved in the future, but if all the tuples are fully resolved, then we don't need further resolution
983+ _ -> throwError TupleExprsReferenceMultipleMarkersError
984+ lift $ except $ validateAttributes tConsMap finalAttrs
985+ mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
988+--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
1087evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
990evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
1088evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
991evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
1089 -- it's not possible for AtomExprs in tuple constructors to reference other Attributes' atoms due to the necessary order-of-operations (need a tuple to pass to evalAtomExpr)- it may be possible with some refactoring of type usage or delayed evaluation- needs more thought, but not a priority
992 -- it's not possible for AtomExprs in tuple constructors to reference other Attributes' atoms due to the necessary order-of-operations (need a tuple to pass to evalAtomExpr)- it may be possible with some refactoring of type usage or delayed evaluation- needs more thought, but not a priority
@@ -1108,62 +1011,12 @@ evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
1108 --verify that the attributes match
1011 --verify that the attributes match
1109 when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1012 when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1110 --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1013 --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1111−-- tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1014+ --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1112 let tup' = reorderTuple finalAttrs tup
1015 let tup' = reorderTuple finalAttrs tup
1113 --TODO: restore type resolution
1016 --TODO: restore type resolution
1114-- _ <- lift $ except (validateTuple tup' tConss)
1017-- _ <- lift $ except (validateTuple tup' tConss)
1115 pure tup'
1018 pure tup'
1118−evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprM (Either RelationalError (S.Set AttributeName))
1119−evalAttributeNames attrNames expr = do
1120− eExprType <- typeForRelationalExpr expr
1122− Left err -> throwError err
1123− Right exprTyp -> do
1124− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1126− AttributeNames names ->
1127− case A.projectionAttributesForNames names (attributes exprTyp) of
1128− Left err -> pure (Left err)
1129− Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1131− InvertedAttributeNames names -> do
1132− let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1133− if not (S.null nonExistentAttributeNames) then
1134− pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1136− pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
1138− UnionAttributeNames namesA namesB -> do
1139− eNameSetA <- evalAttributeNames namesA expr
1141− Left err -> pure (Left err)
1142− Right nameSetA -> do
1143− eNameSetB <- evalAttributeNames namesB expr
1145− Left err -> pure (Left err)
1147− pure (Right (S.union nameSetA nameSetB))
1149− IntersectAttributeNames namesA namesB -> do
1150− eNameSetA <- evalAttributeNames namesA expr
1152− Left err -> pure (Left err)
1153− Right nameSetA -> do
1154− eNameSetB <- evalAttributeNames namesB expr
1156− Left err -> pure (Left err)
1158− pure (Right (S.intersection nameSetA nameSetB))
1160− RelationalExprAttributeNames attrExpr -> do
1161− eAttrExprType <- typeForRelationalExpr attrExpr
1162− case eAttrExprType of
1163− Left err -> pure (Left err)
1164− Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1167--temporary implementation until we have a proper planner+executor
1020--temporary implementation until we have a proper planner+executor
1168evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1021evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1169evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1022evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
@@ -1171,7 +1024,7 @@ evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1171 Just _ ->
1024 Just _ ->
1172 Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1025 Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1173 Nothing -> pure Nothing
1026 Nothing -> pure Nothing
1174− tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprs
1027+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1175 let attrs = fromMaybe firstTupleAttrs mAttrs
1028 let attrs = fromMaybe firstTupleAttrs mAttrs
1176 firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1029 firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1177 lift $ except $ mkRelation attrs (RelationTupleSet tuples)
1030 lift $ except $ mkRelation attrs (RelationTupleSet tuples)
@@ -1179,7 +1032,7 @@ evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
1179 lift $ except $ mkRelation attributeSet tupleSet
1032 lift $ except $ mkRelation attributeSet tupleSet
1180evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1033evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1181evalGraphRefRelationalExpr (RelationVariable name tid) = do
1034evalGraphRefRelationalExpr (RelationVariable name tid) = do
1182− ctx <- concreteDatabaseContext <$> gfTransForId tid
1035+ ctx <- gfDatabaseContextForMarker tid
1183 case M.lookup name (relationVariables ctx) of
1036 case M.lookup name (relationVariables ctx) of
1184 Nothing -> throwError (RelVarNotDefinedError name)
1037 Nothing -> throwError (RelVarNotDefinedError name)
1185 Just rv -> evalGraphRefRelationalExpr rv
1038 Just rv -> evalGraphRefRelationalExpr rv
@@ -1225,7 +1078,7 @@ evalGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1225 rel <- evalGraphRefRelationalExpr expr
1078 rel <- evalGraphRefRelationalExpr expr
1226 (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1079 (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1227 lift $ except $ relMogrify tupProc newAttrs rel
1080 lift $ except $ relMogrify tupProc newAttrs rel
1228−evalGraphRefRelationalExpr expr@With{} = do
1081+evalGraphRefRelationalExpr expr@With{} =
1229 --strategy A: add relation variables to the contexts in the graph
1082 --strategy A: add relation variables to the contexts in the graph
1230 --strategy B: drop in macros in place (easier programmatically)
1083 --strategy B: drop in macros in place (easier programmatically)
1231 --strategy B implementation
1084 --strategy B implementation
@@ -1253,20 +1106,21 @@ typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAt
1253typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1106typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1254 mAttrs <- case mAttrExprs of
1107 mAttrs <- case mAttrExprs of
1255 Just attrExprs -> do
1108 Just attrExprs -> do
1256− attrs <- mapM (\e -> evalGraphRefAttributeExpr e) attrExprs
1109+ attrs <- mapM evalGraphRefAttributeExpr attrExprs
1257 pure (Just (attributesFromList attrs))
1110 pure (Just (attributesFromList attrs))
1258 Nothing -> pure Nothing
1111 Nothing -> pure Nothing
1259− tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprs
1112+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1260 let retAttrs = case tuples of
1113 let retAttrs = case tuples of
1261 (tup:_) -> tupleAttributes tup
1114 (tup:_) -> tupleAttributes tup
1262 [] -> fromMaybe A.emptyAttributes mAttrs
1115 [] -> fromMaybe A.emptyAttributes mAttrs
1263 pure $ emptyRelationWithAttrs retAttrs
1116 pure $ emptyRelationWithAttrs retAttrs
1265typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1118typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1266− relVars <- relationVariables . concreteDatabaseContext <$> gfTransForId tid
1119+ relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1267 case M.lookup rvName relVars of
1120 case M.lookup rvName relVars of
1268 Nothing -> throwError (RelVarNotDefinedError rvName)
1121 Nothing -> throwError (RelVarNotDefinedError rvName)
1269− Just rvExpr -> typeForGraphRefRelationalExpr rvExpr
1123+ typeForGraphRefRelationalExpr rvExpr
1270typeForGraphRefRelationalExpr (Project attrNames expr) = do
1124typeForGraphRefRelationalExpr (Project attrNames expr) = do
1271 exprType' <- typeForGraphRefRelationalExpr expr
1125 exprType' <- typeForGraphRefRelationalExpr expr
1272 projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1126 projectionAttrs <- evalGraphRefAttributeNames attrNames expr
@@ -1297,15 +1151,21 @@ typeForGraphRefRelationalExpr (Restrict pred' expr) = do
1297 expr' <- typeForGraphRefRelationalExpr expr
1151 expr' <- typeForGraphRefRelationalExpr expr
1298 filt <- predicateRestrictionFilter (attributes expr') pred'
1152 filt <- predicateRestrictionFilter (attributes expr') pred'
1299 lift $ except $ restrict filt expr'
1153 lift $ except $ restrict filt expr'
1300−typeForGraphRefRelationalExpr Equals{} = do
1154+typeForGraphRefRelationalExpr Equals{} =
1301 pure relationFalse
1155 pure relationFalse
1302−typeForGraphRefRelationalExpr NotEquals{} = do
1156+typeForGraphRefRelationalExpr NotEquals{} =
1303 pure relationFalse
1157 pure relationFalse
1304typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1158typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1305 rel <- typeForGraphRefRelationalExpr expr
1159 rel <- typeForGraphRefRelationalExpr expr
1306 evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1160 evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1307−typeForGraphRefRelationalExpr expr@With{} = do
1161+typeForGraphRefRelationalExpr expr@(With withs _) = do
1308 let expr' = substituteWithNameMacros [] expr
1162 let expr' = substituteWithNameMacros [] expr
1163+ checkMacroName (WithNameExpr macroName tid) = do
1164+ rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1165+ case M.lookup macroName rvs of
1166+ Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1168+ mapM_ (checkMacroName . fst) withs
1309 typeForGraphRefRelationalExpr expr'
1169 typeForGraphRefRelationalExpr expr'
1311evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1171evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
@@ -1321,7 +1181,7 @@ evalGraphRefAttributeNames attrNames expr = do
1321 InvertedAttributeNames names -> do
1181 InvertedAttributeNames names -> do
1322 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1182 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1323 if not (S.null nonExistentAttributeNames) then
1183 if not (S.null nonExistentAttributeNames) then
1324− throwError (AttributeNamesMismatchError nonExistentAttributeNames)
1184+ throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1326 pure (A.nonMatchingAttributeNameSet names typeNameSet)
1186 pure (A.nonMatchingAttributeNameSet names typeNameSet)
@@ -1341,7 +1201,7 @@ evalGraphRefAttributeNames attrNames expr = do
1342evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1202evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1343evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1203evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1344− tConsMap <- typeConstructorMapping . concreteDatabaseContext <$> gfTransForId tid
1204+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1345 case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1205 case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1346 Left err -> throwError err
1206 Left err -> throwError err
1347 Right aType -> do
1207 Right aType -> do
@@ -1351,9 +1211,9 @@ evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1351evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1211evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1353mkEmptyRelVars :: RelationVariables -> RelationVariables
1213mkEmptyRelVars :: RelationVariables -> RelationVariables
1354−mkEmptyRelVars rvMap = M.map mkEmptyRelVar rvMap
1214+mkEmptyRelVars = M.map mkEmptyRelVar
1356− mkEmptyRelVar (MakeRelationFromExprs mAttrs _) = MakeRelationFromExprs mAttrs []
1216+ mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1357 mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1217 mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1358 mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1218 mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1359 mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
1219 mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
@@ -1368,28 +1228,165 @@ mkEmptyRelVars rvMap = M.map mkEmptyRelVar rvMap
1368 mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1228 mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1369 mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1229 mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1370 mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1230 mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1371− mkEmptyRelVar (With macros expr) = With (map (\(rv, expr') -> (rv, mkEmptyRelVar expr')) macros) (mkEmptyRelVar expr)
1231+ mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1374dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1234dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1375dbErr err = lift (except (Left err))
1235dbErr err = lift (except (Left err))
1377-- | Return a Relation describing the relation variables.
1237-- | Return a Relation describing the relation variables.
1378−relationVariablesAsRelation :: RelationVariables -> TransactionGraph -> Either RelationalError Relation
1238+relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1379−relationVariablesAsRelation relVarMap graph = do
1239+relationVariablesAsRelation ctx graph = do
1380 let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1240 let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1381 attrs = A.attributesFromList [Attribute "name" TextAtomType,
1241 attrs = A.attributesFromList [Attribute "name" TextAtomType,
1382 Attribute "attributes" (RelationAtomType subrelAttrs)]
1242 Attribute "attributes" (RelationAtomType subrelAttrs)]
1243+ relVars = relationVariables ctx
1383 mkRvDesc (rvName, gfExpr) = do
1244 mkRvDesc (rvName, gfExpr) = do
1384− let gfEnv = freshGraphRefRelationalExprEnv graph
1245+ let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1385 gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1246 gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1386 pure (rvName, gfType)
1247 pure (rvName, gfType)
1387− relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributes rel)]
1248+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributesVec (attributes rel))]
1388 attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1249 attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1389 attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1250 attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1390 Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1251 Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1391 Right rel -> RelationAtom rel
1252 Right rel -> RelationAtom rel
1392− rvs <- mapM mkRvDesc (M.toList relVarMap)
1253+ rvs <- mapM mkRvDesc (M.toList relVars)
1393 let tups = map relVarToAtomList rvs
1254 let tups = map relVarToAtomList rvs
1394 mkRelationFromList attrs tups
1255 mkRelationFromList attrs tups
1257+-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1258+evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1259+evalRelationalExpr expr = do
1261+ context <- reContext
1262+ let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1263+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1264+ case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1265+ Left err -> throwError err
1266+ Right rel -> pure rel
1268+class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1269+ getContext :: m DatabaseContext
1271+instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1272+ getContext = gfDatabaseContextForMarker UncommittedContextMarker
1274+instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1275+ getContext = getStateContext
1277+relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1278+relVarByName rvName = do
1279+ relvars <- relationVariables <$> getContext
1280+ case M.lookup rvName relvars of
1281+ Nothing -> throwError (RelVarNotDefinedError rvName)
1282+ Just gfexpr -> pure gfexpr
1284+-- | resolve UncommittedTransactionMarker whenever possible- this is important in the DatabaseContext in order to mitigate self-referencing loops for updates
1285+class ResolveGraphRefTransactionMarker a where
1286+ resolve :: a -> DatabaseContextEvalMonad a
1289+instance ResolveGraphRefTransactionMarker GraphRefRelationalExpr where
1290+ resolve (MakeRelationFromExprs mAttrs tupleExprs) =
1291+ MakeRelationFromExprs mAttrs <$> resolve tupleExprs
1292+ resolve orig@MakeStaticRelation{} = pure orig
1293+ resolve orig@ExistingRelation{} = pure orig
1294+ resolve orig@(RelationVariable rvName UncommittedContextMarker) = do
1295+ rvMap <- relationVariables <$> getStateContext
1296+ case M.lookup rvName rvMap of
1297+ Nothing -> pure orig
1298+ Just resolvedRv -> resolve resolvedRv
1299+ resolve orig@RelationVariable{} = pure orig
1300+ resolve (Project attrNames relExpr) = Project <$> resolve attrNames <*> resolve relExpr
1301+ resolve (Union exprA exprB) = Union <$> resolve exprA <*> resolve exprB
1302+ resolve (Join exprA exprB) = Join <$> resolve exprA <*> resolve exprB
1303+ resolve (Rename attrA attrB expr) = Rename attrA attrB <$> resolve expr
1304+ resolve (Difference exprA exprB) = Difference <$> resolve exprA <*> resolve exprB
1305+ resolve (Group namesA nameB expr) = Group <$> resolve namesA <*> pure nameB <*> resolve expr
1306+ resolve (Ungroup nameA expr) = Ungroup nameA <$> resolve expr
1307+ resolve (Restrict restrictExpr relExpr) = Restrict <$> resolve restrictExpr <*> resolve relExpr
1308+ resolve (Equals exprA exprB) = Equals <$> resolve exprA <*> resolve exprB
1309+ resolve (NotEquals exprA exprB) = NotEquals <$> resolve exprA <*> resolve exprB
1310+ resolve (Extend extendExpr relExpr) = Extend <$> resolve extendExpr <*> resolve relExpr
1311+ resolve (With withExprs relExpr) = With <$> mapM (\(nam, expr) -> (,) <$> resolve nam <*> resolve expr) withExprs <*> resolve relExpr
1313+instance ResolveGraphRefTransactionMarker GraphRefTupleExprs where
1314+ resolve (TupleExprs marker tupleExprs) =
1315+ TupleExprs marker <$> mapM resolve tupleExprs
1317+instance ResolveGraphRefTransactionMarker GraphRefTupleExpr where
1318+ resolve (TupleExpr tupMap) = do
1319+ tupMap' <- mapM (\(attrName, expr) -> (,) attrName <$> resolve expr ) (M.toList tupMap)
1320+ pure (TupleExpr (M.fromList tupMap'))
1322+instance ResolveGraphRefTransactionMarker GraphRefAttributeNames where
1323+ resolve orig@AttributeNames{} = pure orig
1324+ resolve orig@InvertedAttributeNames{} = pure orig
1325+ resolve (UnionAttributeNames namesA namesB) = UnionAttributeNames <$> resolve namesA <*> resolve namesB
1326+ resolve (IntersectAttributeNames namesA namesB) = IntersectAttributeNames <$> resolve namesA <*> resolve namesB
1327+ resolve (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> resolve expr
1329+instance ResolveGraphRefTransactionMarker GraphRefRestrictionPredicateExpr where
1330+ resolve TruePredicate = pure TruePredicate
1331+ resolve (AndPredicate exprA exprB) = AndPredicate <$> resolve exprA <*> resolve exprB
1332+ resolve (OrPredicate exprA exprB) = OrPredicate <$> resolve exprA <*> resolve exprB
1333+ resolve (NotPredicate expr) = NotPredicate <$> resolve expr
1334+ resolve (RelationalExprPredicate expr) = RelationalExprPredicate <$> resolve expr
1335+ resolve (AtomExprPredicate expr) = AtomExprPredicate <$> resolve expr
1336+ resolve (AttributeEqualityPredicate nam expr)= AttributeEqualityPredicate nam <$> resolve expr
1338+instance ResolveGraphRefTransactionMarker GraphRefExtendTupleExpr where
1339+ resolve (AttributeExtendTupleExpr nam atomExpr) = AttributeExtendTupleExpr nam <$> resolve atomExpr
1341+instance ResolveGraphRefTransactionMarker GraphRefWithNameExpr where
1342+ resolve orig@WithNameExpr{} = pure orig -- match uncommitted marker?
1344+instance ResolveGraphRefTransactionMarker GraphRefAtomExpr where
1345+ resolve orig@AttributeAtomExpr{} = pure orig
1346+ resolve orig@NakedAtomExpr{} = pure orig
1347+ resolve (FunctionAtomExpr nam atomExprs marker) =
1348+ FunctionAtomExpr nam <$> mapM resolve atomExprs <*> pure marker
1349+ resolve (RelationAtomExpr expr) = RelationAtomExpr <$> resolve expr
1350+ resolve (ConstructedAtomExpr dConsName atomExprs marker) =
1351+ ConstructedAtomExpr dConsName <$> mapM resolve atomExprs <*> pure marker
1353+--convert series of simple Union queries into MakeStaticRelation
1354+-- this is especially useful for long, nested applications of Union with simple tuples
1355+-- Union (MakeRelation x y) (MakeRelation x y') -> MakeRelation x (y + y')
1357+--MakeRelationFromExprs Nothing (TupleExprs UncommittedContextMarker [TupleExpr (fromList [("name", NakedAtomExpr (TextAtom "steve"))])])
1359+applyUnionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1360+applyUnionCollapse = Fold.cata opt
1362+ opt :: RelationalExprBaseF GraphRefTransactionMarker GraphRefRelationalExpr -> GraphRefRelationalExpr
1363+ opt (UnionF exprA exprB) | exprA == exprB = exprA
1365+ exprA@(MakeRelationFromExprs mAttrs1 tupExprs1)
1366+ exprB@(MakeRelationFromExprs mAttrs2 tupExprs2)) | tupExprs1 == tupExprs2 = MakeRelationFromExprs (mAttrs1 <|> mAttrs2) tupExprs1
1367+ | tupExprsNull tupExprs1 = exprB
1368+ | tupExprsNull tupExprs2 = exprA
1369+ opt x = Fold.embed x
1370+ tupExprsNull (TupleExprs _ []) = True
1371+ tupExprsNull _ = False
1374+--UPDATE optimization- find matching where clause in "lower" levels of renaming
1375+--update x where y=1 set (x:=5,z:=10); update x where y=1 set(x:=6,z:=11)
1377+-- update x where y=1 set (x:=6,z:=11)
1378+-- future opt: match individual attributes update x where y=1 set (x:=5); update x where y=1 set (z:=11) => update x where y=1 set (x:=5,z:=11)
1380+--strategy: try to collapse the top-level update (union (restrict pred MakeRelationFromExpr) expr) if it contains the same predicate and resultant relation
1382+--DELETE optimization
1383+-- if a restriction matches a previous restriction, combine them
1384+-- O(1) since it only scans at the top level, critical in benchmarks generating redundant deletions
1385+applyRestrictionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1386+applyRestrictionCollapse orig@(Restrict npred@(NotPredicate _) expr) =
1388+ orig'@(Restrict npred'@(NotPredicate _) _) | npred == npred' -> orig'
1390+applyRestrictionCollapse expr = expr