@@ -1,39 +1,51 @@
11{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE FlexibleContexts #-}
24module ProjectM36.RelationalExpression where
35import ProjectM36.Relation
46import ProjectM36.Tuple
57import ProjectM36.TupleSet
68import ProjectM36.Base
9+import qualified Data.UUID as U
710import ProjectM36.Error
811import ProjectM36.AtomType
9−import ProjectM36.Attribute (emptyAttributes)
12+import ProjectM36.Attribute (emptyAttributes, attributesFromList)
1013import ProjectM36.ScriptSession
1114import ProjectM36.DataTypes.Primitive
1215import ProjectM36.AtomFunction
1316import ProjectM36.DatabaseContextFunction
1417import ProjectM36.Arbitrary
18+import ProjectM36.GraphRefRelationalExpr
19+import ProjectM36.Transaction
1520import qualified ProjectM36.Attribute as A
1621import qualified Data.Map as M
1722import qualified Data.HashSet as HS
1823import qualified Data.Set as S
1924import Control.Monad.State hiding (join)
25+import Data.Bifunctor (second)
2026import Data.Maybe
2127import Data.Either
2228import Data.Char (isUpper)
29+import Data.Time
30+import qualified Data.List.NonEmpty as NE
31+import Data.Functor.Identity
2332import qualified Data.Text as T
2433import qualified Data.Vector as V
2534import qualified ProjectM36.TypeConstructorDef as TCD
26−import Control.Monad.Trans.Except
27−import Control.Monad.Trans.Reader
35+import qualified Control.Monad.RWS.Strict as RWS
36+import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
37+import Control.Monad.Except hiding (join)
38+import Control.Monad.Trans.Except (except)
39+import Control.Monad.Reader as R hiding (join)
40+import ProjectM36.NormalizeExpr
41+import ProjectM36.WithNameExpr
2842import Test.QuickCheck
29−
3043#ifdef PM36_HASKELL_SCRIPTING
31−import GHC
44+import GHC hiding (getContext)
3245import Control.Exception
3346import GHC.Paths
3447#endif
3548
36−
3749data DatabaseContextExprDetails = CountUpdatedTuples
3850
3951databaseContextExprDetailsFunc :: DatabaseContextExprDetails -> ResultAccumFunc
@@ -49,32 +61,63 @@ databaseContextExprDetailsFunc CountUpdatedTuples _ relIn = Relation attrs newTu
4961 Right ts -> ts
5062
5163-- | Used to start a fresh database state for a new database context expression.
52−freshDatabaseState :: DatabaseContext -> DatabaseStateElems
53−freshDatabaseState ctx = (ctx, M.empty, False) --future work: propagate return accumulator
64+mkDatabaseContextEvalState :: DatabaseContext -> DatabaseContextEvalState
65+mkDatabaseContextEvalState context = DatabaseContextEvalState {
66+ dbc_context = context,
67+ dbc_accum = M.empty,
68+ dbc_dirty = False
69+ } --future work: propagate return accumulator
5470
5571-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
56−data RelationalExprStateElems = RelationalExprStateTupleElems DatabaseContext RelationTuple | -- used when fully evaluating a relexpr
57− RelationalExprStateAttrsElems DatabaseContext Attributes | --used when evaluating the type of a relexpr
58− RelationalExprStateElems DatabaseContext --used by default at the top level of evaluation
59−
60−instance Show RelationalExprStateElems where
61− show (RelationalExprStateTupleElems _ tup) = "RelationalExprStateTupleElems " ++ show tup
62− show (RelationalExprStateAttrsElems _ attrs) = "RelationalExprStateAttrsElems" ++ show attrs
63− show (RelationalExprStateElems _) = "RelationalExprStateElems"
64−
65−mkRelationalExprState :: DatabaseContext -> RelationalExprStateElems
66−mkRelationalExprState = RelationalExprStateElems
67−
68−mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprStateElems -> RelationalExprStateElems
69−mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateElems ctx) = RelationalExprStateTupleElems ctx tupIn
70−mergeTuplesIntoRelationalExprState _ st@(RelationalExprStateAttrsElems _ _) = st
71−mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateTupleElems ctx existingTuple) = let mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap existingTuple) in
72− RelationalExprStateTupleElems ctx (mkRelationTupleFromMap mergedTupMap)
72+data RelationalExprEnv = RelationalExprEnv {
73+ re_context :: DatabaseContext,
74+ re_graph :: TransactionGraph,
75+ re_extra :: Maybe (Either RelationTuple Attributes)
76+ }
77+
78+envTuple :: GraphRefRelationalExprEnv -> RelationTuple
79+envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
80+
81+envAttributes :: GraphRefRelationalExprEnv -> Attributes
82+envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
7383
74−mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprStateElems -> RelationalExprStateElems
75−mergeAttributesIntoRelationalExprState attrs (RelationalExprStateElems ctx) = RelationalExprStateAttrsElems ctx attrs
76−mergeAttributesIntoRelationalExprState _ st@(RelationalExprStateTupleElems _ _) = st
77−mergeAttributesIntoRelationalExprState attrsIn (RelationalExprStateAttrsElems ctx attrs) = RelationalExprStateAttrsElems ctx (A.union attrsIn attrs)
84+instance Show RelationalExprEnv where
85+ show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
86+
87+--used to eval relationalexpr
88+type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
89+
90+runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
91+runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
92+
93+reGraph :: RelationalExprM TransactionGraph
94+reGraph = asks re_graph
95+
96+reContext :: RelationalExprM DatabaseContext
97+reContext = asks re_context
98+
99+mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
100+mkRelationalExprEnv ctx graph =
101+ RelationalExprEnv
102+ { re_context = ctx,
103+ re_graph = graph,
104+ re_extra = Nothing }
105+
106+askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
107+askEnv = R.ask
108+
109+mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
110+mergeTuplesIntoGraphRefRelationalExprEnv tupIn e =
111+ e{ gre_extra = new_elems }
112+ where
113+ new_elems = Just (Left newTuple)
114+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple e))
115+ newTuple = mkRelationTupleFromMap mergedTupMap
116+
117+mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
118+mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
119+ where
120+ newattrs = Just (Right (A.union attrsIn (envAttributes e)))
78121
79122type ResultAccumName = StringType
80123
@@ -84,36 +127,103 @@ data ResultAccum = ResultAccum { resultAccumFunc :: ResultAccumFunc,
84127 resultAccumResult :: Relation
85128 }
86129
87−type DatabaseStateElems = (DatabaseContext, M.Map ResultAccumName ResultAccum, DirtyFlag)
130+data DatabaseContextEvalState = DatabaseContextEvalState {
131+ dbc_context :: DatabaseContext, --new, alterable context for a new transaction
132+ dbc_accum :: M.Map ResultAccumName ResultAccum,
133+ dbc_dirty :: DirtyFlag
134+ }
88135
89−type DatabaseState a = State DatabaseStateElems a
136+data DatabaseContextEvalEnv = DatabaseContextEvalEnv
137+ { dce_transId :: TransactionId,
138+ dce_graph :: TransactionGraph
139+ }
90140
91−getStateContext :: DatabaseState DatabaseContext
92−getStateContext = do
93− (ctx,_, _) <- get
94− pure ctx
95−
96−putStateContext :: DatabaseContext -> DatabaseState ()
97−putStateContext ctx = do
98− (_, accum, _) <- get
99− put (ctx, accum, True)
141+mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
142+mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
143+
144+type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
145+
146+runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
147+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
148+ where
149+ freshEnv = mkDatabaseContextEvalState ctx
150+
151+
152+dbcTransId :: DatabaseContextEvalMonad TransactionId
153+dbcTransId = dce_transId <$> RWS.ask
154+
155+dbcGraph :: DatabaseContextEvalMonad TransactionGraph
156+dbcGraph = dce_graph <$> RWS.ask
157+
158+dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
159+dbcRelationalExprEnv =
160+ mkRelationalExprEnv <$> getStateContext <*> dbcGraph
161+
162+getStateContext :: DatabaseContextEvalMonad DatabaseContext
163+getStateContext = gets dbc_context
164+
165+putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
166+putStateContext ctx' = do
167+ s <- get
168+ put (s {dbc_context = ctx', dbc_dirty = True})
169+
170+-- | The context is optionally passed down along in cases where the current context is uncommitted.
171+data GraphRefRelationalExprEnv =
172+ GraphRefRelationalExprEnv {
173+ gre_context :: Maybe DatabaseContext,
174+ gre_graph :: TransactionGraph,
175+ gre_extra :: Maybe (Either RelationTuple Attributes)
176+ }
100177
101−type RelationalExprState a = Reader RelationalExprStateElems a
178+type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
179+
180+gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
181+gfTransForId tid = do
182+ graph <- gfGraph
183+ lift $ except $ transactionForId tid graph
184+
185+gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
186+gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
187+gfDatabaseContextForMarker UncommittedContextMarker = do
188+ mctx <- gre_context <$> askEnv
189+ case mctx of
190+ Nothing -> throwError NoUncommittedContextInEvalError
191+ Just ctx -> pure ctx
192+
193+runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
194+runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
195+
196+freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
197+freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
198+ gre_context = mctx,
199+ gre_graph = graph,
200+ gre_extra = Nothing
201+ }
202+
203+gfGraph :: GraphRefRelationalExprM TransactionGraph
204+gfGraph = asks gre_graph
102205
103−stateElemsContext :: RelationalExprStateElems -> DatabaseContext
104−stateElemsContext (RelationalExprStateTupleElems ctx _) = ctx
105−stateElemsContext (RelationalExprStateElems ctx) = ctx
106−stateElemsContext (RelationalExprStateAttrsElems ctx _) = ctx
206+envContext :: RelationalExprEnv -> DatabaseContext
207+envContext = re_context
107208
108−setStateElemsContext :: RelationalExprStateElems -> DatabaseContext -> RelationalExprStateElems
109−setStateElemsContext (RelationalExprStateTupleElems _ tup) ctx = RelationalExprStateTupleElems ctx tup
110−setStateElemsContext (RelationalExprStateElems _) ctx = RelationalExprStateElems ctx
111−setStateElemsContext (RelationalExprStateAttrsElems _ attrs) ctx = RelationalExprStateAttrsElems ctx attrs
209+setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
210+setEnvContext e ctx = e { re_context = ctx }
112211
212+{-
213+--full evaluation down the graph
214+eval :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
215+eval expr = do
216+ env <- askEnv
217+ eGfExpr <- processRelationalExpr expr
218+ case eGfExpr of
219+ Left err -> pure (Left err)
220+ Right gfExpr -> pure $ evalGraphRefRelationalExpr gfExpr (re_graph env)
221+-}
222+{-
113223--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
114−evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
224+evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
115225evalRelationalExpr (RelationVariable name _) = do
116− relvarTable <- fmap (relationVariables . stateElemsContext) ask
226+ relvarTable <- fmap (relationVariables . envContext) askEnv
117227 return $ case M.lookup name relvarTable of
118228 Just res -> Right res
119229 Nothing -> Left $ RelVarNotDefinedError name
@@ -125,7 +235,7 @@ evalRelationalExpr (Project attrNames expr) = do
125235 Right attrNameSet -> do
126236 rel <- evalRelationalExpr expr
127237 case rel of
128− Right rel2 -> pure $ project attrNameSet rel2
238+ Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
129239 Left err -> pure $ Left err
130240
131241evalRelationalExpr (Union exprA exprB) = do
@@ -135,7 +245,7 @@ evalRelationalExpr (Union exprA exprB) = do
135245 Left err -> return $ Left err
136246 Right relA2 -> case relB of
137247 Left err -> return $ Left err
138− Right relB2 -> return $ union relA2 relB2
248+ Right relB2 -> return $ Right (Union relA2 relB2)
139249
140250evalRelationalExpr (Join exprA exprB) = do
141251 relA <- evalRelationalExpr exprA
@@ -144,7 +254,7 @@ evalRelationalExpr (Join exprA exprB) = do
144254 Left err -> return $ Left err
145255 Right relA2 -> case relB of
146256 Left err -> return $ Left err
147− Right relB2 -> return $ join relA2 relB2
257+ Right relB2 -> return $ Right (Join relA2 relB2)
148258
149259evalRelationalExpr (Difference exprA exprB) = do
150260 relA <- evalRelationalExpr exprA
@@ -153,33 +263,34 @@ evalRelationalExpr (Difference exprA exprB) = do
153263 Left err -> return $ Left err
154264 Right relA2 -> case relB of
155265 Left err -> return $ Left err
156− Right relB2 -> return $ difference relA2 relB2
266+ Right relB2 -> return $ Right (Difference relA2 relB2)
157267
158268evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
159269 case mkRelation attributeSet tupleSet of
160− Right rel -> return $ Right rel
270+ Right rel -> return $ Right (ExistingRelation rel)
161271 Left err -> return $ Left err
162272
163273evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
164− currentContext <- fmap stateElemsContext ask
274+ currentContext <- fmap envContext askEnv
165275 let tConss = typeConstructorMapping currentContext
166276 -- 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
167277 runExceptT $ do
168278 mAttrs <- case mAttrExprs of
169279 Just _ ->
170− Just . A.attributesFromList <$> mapM (either throwE pure . evalAttrExpr tConss) (fromMaybe [] mAttrExprs)
280+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
171281 Nothing -> pure Nothing
172282 tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
173283 let attrs = fromMaybe firstTupleAttrs mAttrs
174284 firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
175− either throwE pure (mkRelation attrs (RelationTupleSet tuples))
285+ expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
286+ pure (ExistingRelation expr)
176287
177−evalRelationalExpr (ExistingRelation rel) = pure (Right rel)
288+evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
178289
179290evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
180291 evald <- evalRelationalExpr relExpr
181292 case evald of
182− Right rel -> return $ rename oldAttrName newAttrName rel
293+ Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
183294 Left err -> return $ Left err
184295
185296evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
@@ -189,35 +300,32 @@ evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
189300 Right oldAttrNameSet -> do
190301 evald <- evalRelationalExpr relExpr
191302 case evald of
192− Right rel -> return $ group oldAttrNameSet newAttrName rel
303+ Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
193304 Left err -> return $ Left err
194305
195306evalRelationalExpr (Ungroup attrName relExpr) = do
196307 evald <- evalRelationalExpr relExpr
197308 case evald of
198− Right rel -> return $ ungroup attrName rel
309+ Right expr -> return $ Right (Ungroup attrName expr)
199310 Left err -> return $ Left err
200311
201312evalRelationalExpr (Restrict predicateExpr relExpr) = do
202313 evald <- evalRelationalExpr relExpr
314+ pred <- processRestrictionPredicateExpr predicateExpr
203315 case evald of
204316 Left err -> return $ Left err
205− Right rel -> do
206− eFilterFunc <- predicateRestrictionFilter (attributes rel) predicateExpr
207− case eFilterFunc of
208− Left err -> return $ Left err
209− Right filterfunc ->
210− pure (restrict filterfunc rel)
317+ Right expr ->
318+ pure $ Right (Restrict pred expr)
211319
212320evalRelationalExpr (Equals relExprA relExprB) = do
213321 evaldA <- evalRelationalExpr relExprA
214322 evaldB <- evalRelationalExpr relExprB
215323 case evaldA of
216324 Left err -> return $ Left err
217− Right relA -> case evaldB of
325+ Right exprA -> case evaldB of
218326 Left err -> return $ Left err
219− Right relB -> return $ Right $ if relA == relB then relationTrue else relationFalse
220−
327+ Right exprB -> return $ Right (Equals exprA exprB)
328+{-
221329evalRelationalExpr (With views mainExpr) = do
222330 rstate <- ask
223331
@@ -231,310 +339,325 @@ evalRelationalExpr (With views mainExpr) = do
231339 case foldM addScopedView (stateElemsContext rstate) views of
232340 Left err -> return $ Left err
233341 Right ctx'' -> do
234− let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprStateElems ctx'')
342+ let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprEnv ctx'')
235343 case evalMainExpr mainExpr of
236344 Left err -> return $ Left err
237345 Right rel -> return $ Right rel
238−
346+-}
239347--warning: copy-pasta from above- refactor
240348evalRelationalExpr (NotEquals relExprA relExprB) = do
241349 evaldA <- evalRelationalExpr relExprA
242350 evaldB <- evalRelationalExpr relExprB
243351 case evaldA of
244352 Left err -> return $ Left err
245− Right relA -> case evaldB of
353+ Right exprA -> case evaldB of
246354 Left err -> return $ Left err
247− Right relB -> return $ Right $ if relA /= relB then relationTrue else relationFalse
355+ Right exprB -> return $ Right (NotEquals exprA exprB)
248356
249357-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
250358evalRelationalExpr (Extend tupleExpression relExpr) = do
251− rstate <- ask
252− let evald = runReader (evalRelationalExpr relExpr) rstate
253− case evald of
359+ eExpr <- evalRelationalExpr relExpr
360+ case eExpr of
254361 Left err -> pure (Left err)
255− Right rel -> do
256− tupProc <- extendTupleExpressionProcessor rel tupleExpression
257− case tupProc of
258− Left err -> pure (Left err)
259− Right (newAttrs, tupProc') -> pure $ relMogrify tupProc' newAttrs rel
260−
362+ Right expr -> do
363+ tupProc <- processExtendTupleExpr tupleExpression
364+ pure (Right (Extend tupProc expr))
365+-}
261366--helper function to process relation variable creation/assignment
262−setRelVar :: RelVarName -> Relation -> DatabaseState (Either RelationalError ())
263−setRelVar relVarName rel = do
367+setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
368+setRelVar relVarName relExpr = do
264369 currentContext <- getStateContext
265− let newRelVars = M.insert relVarName rel $ relationVariables currentContext
370+ --prevent recursive relvar definition
371+ let newRelVars = M.insert relVarName relExpr $ relationVariables currentContext
266372 potentialContext = currentContext { relationVariables = newRelVars }
267−
268− case checkConstraints potentialContext of
269− Left err -> pure (Left err)
270− Right _ -> do
271− putStateContext potentialContext
272− return (Right ())
373+ --optimization: if the relexpr is unchanged, skip the update
374+ if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
375+ pure ()
376+ else do
377+ --determine when to check constraints
378+ graph <- dbcGraph
379+ tid <- dbcTransId
380+ case checkConstraints potentialContext tid graph of
381+ Left err -> dbErr err
382+ Right _ -> putStateContext potentialContext
273383
274384-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
275−deleteRelVar :: RelVarName -> DatabaseState (Either RelationalError ())
385+deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
276386deleteRelVar relVarName = do
277387 currContext <- getStateContext
278388 let relVars = relationVariables currContext
279389 if M.notMember relVarName relVars then
280− pure (Right ())
390+ pure ()
281391 else do
282392 let newRelVars = M.delete relVarName relVars
283393 newContext = currContext { relationVariables = newRelVars }
284394 putStateContext newContext
285− pure (Right ())
395+ pure ()
286396
287−evalDatabaseContextExpr :: DatabaseContextExpr -> DatabaseState (Either RelationalError ())
288−evalDatabaseContextExpr NoOperation = pure (Right ())
397+evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContextEvalMonad ()
398+evalGraphRefDatabaseContextExpr NoOperation = pure ()
289399
290−evalDatabaseContextExpr (Define relVarName attrExprs) = do
400+evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
401+ context <- getStateContext
291402 relvars <- fmap relationVariables getStateContext
292403 tConss <- fmap typeConstructorMapping getStateContext
293− let eAttrs = map (evalAttrExpr tConss) attrExprs
294− attrErrs = lefts eAttrs
295− attrsList = rights eAttrs
296− if not (null attrErrs) then
297− pure (Left (someErrors attrErrs))
298− else do
299− let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
300− if not (null atomTypeErrs) then
301− pure (Left (someErrors atomTypeErrs))
302− else
303− case M.member relVarName relvars of
304− True -> pure (Left (RelVarAlreadyDefinedError relVarName))
305− False -> setRelVar relVarName emptyRelation >> pure (Right ())
404+ graph <- dbcGraph
405+ let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
406+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
407+ case eAttrs of
408+ Left err -> dbErr err
409+ Right attrsList -> do
410+ lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
411+ case M.member relVarName relvars of
412+ True -> dbErr (RelVarAlreadyDefinedError relVarName)
413+ False -> setRelVar relVarName (ExistingRelation emptyRelation)
306414 where
307415 attrs = A.attributesFromList attrsList
308416 emptyRelation = Relation attrs emptyTupleSet
309417
310−evalDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
418+evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
311419
312−evalDatabaseContextExpr (Assign relVarName expr) = do
313− -- in the future, it would be nice to get types from the RelationalExpr instead of needing to evaluate it
420+evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
421+ graph <- re_graph <$> dbcRelationalExprEnv
314422 context <- getStateContext
315− let existingRelVar = M.lookup relVarName relVarTable
316− relVarTable = relationVariables context
317− value = runReader (evalRelationalExpr expr) (RelationalExprStateElems context)
318− case value of
319− Left err -> pure (Left err)
320− Right rel -> case existingRelVar of
321− Nothing -> setRelVar relVarName rel
322− Just existingRel -> let expectedAttributes = attributes existingRel
323− foundAttributes = attributes rel in
324− if A.attributesEqual expectedAttributes foundAttributes then
325− setRelVar relVarName rel
326− else
327− pure (Left (RelationTypeMismatchError expectedAttributes foundAttributes))
328−
329−evalDatabaseContextExpr (Insert relVarName relExpr) = do
330− context <- getStateContext
331− let unionexp = Union relExpr rv
332− rv = RelationVariable relVarName ()
333− unioned = runReader (evalRelationalExpr unionexp) (RelationalExprStateElems context)
334− origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
335− case unioned of
336− Left err -> pure (Left err)
337− Right unioned' -> case origRel of
338− Left err -> pure (Left err)
339− Right origRel' -> if cardinality unioned' == cardinality origRel' then --no tuples actually inserted
340− pure (Right ())
341− else
342− evalDatabaseContextExpr $ Assign relVarName (ExistingRelation unioned')
423+ let existingRelVar = M.lookup relVarName (relationVariables context)
424+ reEnv = freshGraphRefRelationalExprEnv (Just context) graph
425+ eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
426+ case existingRelVar of
427+ Nothing -> do
428+ case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
429+ Left err -> dbErr err
430+ Right reltype -> do
431+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
432+ setRelVar relVarName expr
433+ Just existingRel -> do
434+ let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
435+ case eExpectedType of
436+ Left err -> dbErr err
437+ Right expectedType ->
438+ case eNewExprType of
439+ Left err -> dbErr err
440+ Right newExprType -> do
441+ if newExprType == expectedType then do
442+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
443+ setRelVar relVarName expr
444+ else
445+ dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
343446
344−evalDatabaseContextExpr (Delete relVarName predicate) = do
345− context <- getStateContext
346− let rv = RelationVariable relVarName ()
347− let updatedRel = runReader (evalRelationalExpr (Restrict (NotPredicate predicate) rv)) (RelationalExprStateElems context)
348− origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
349− case updatedRel of
350− Left err -> pure (Left err)
351− Right updatedRel' -> case origRel of
352− Left err -> pure (Left err)
353− Right origRel' -> if cardinality origRel' == cardinality updatedRel' then
354− pure (Right ())
355− else
356− setRelVar relVarName updatedRel'
447+evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
448+ gfExpr <- relVarByName relVarName
449+ evalGraphRefDatabaseContextExpr (Assign relVarName
450+ (Union
451+ gfExpr
452+ relExpr))
357453
454+evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
455+ gfExpr <- relVarByName relVarName
456+ setRelVar relVarName (Restrict (NotPredicate predicate) gfExpr)
457+
358458--union of restricted+updated portion and the unrestricted+unupdated portion
359−evalDatabaseContextExpr (Update relVarName atomExprMap restrictionPredicateExpr) = do
360− context <- getStateContext
361− let relVarTable = relationVariables context
362− case M.lookup relVarName relVarTable of
363− Nothing -> pure (Left (RelVarNotDefinedError relVarName))
364− Just rel ->
365− case runReader (predicateRestrictionFilter (attributes rel) restrictionPredicateExpr) (RelationalExprStateElems context) of
366− Left err -> pure (Left err)
367− Right predicateFunc -> do
368− let ret = do
369− restrictedPortion <- restrict predicateFunc rel
370− if cardinality restrictedPortion == Finite 0 then
371− pure Nothing
372− else do
373− unrestrictedPortion <- restrict (predicateFunc >=> (pure . not)) rel
374− updatedPortion <- relMap (updateTupleWithAtomExprs atomExprMap context) restrictedPortion
375− updatedRel <- updatedPortion `union` unrestrictedPortion
376− pure (Just updatedRel)
377− case ret of
378− Left err -> pure (Left err)
379− Right Nothing -> pure (Right ())
380− Right (Just updatedRel) -> setRelVar relVarName updatedRel
459+evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
460+ rvExpr <- relVarByName relVarName
461+ let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
462+ tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
463+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
464+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
465+ restrictedPortion = Restrict pred' rvExpr
466+ updated = foldr (\(oldname, atomExpr) accum ->
467+ let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
468+ updateAttr oldname procAtomExpr accum
469+ ) restrictedPortion (M.toList atomExprMap)
470+ -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
471+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
472+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
381473
382−evalDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
474+evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
383475 currContext <- getStateContext
476+ transId <- dbcTransId
477+ graph <- dbcGraph
384478 let currDeps = inclusionDependencies currContext
385479 newDeps = M.insert newDepName newDep currDeps
386480 if M.member newDepName currDeps then
387− pure (Left (InclusionDependencyNameInUseError newDepName))
481+ dbErr (InclusionDependencyNameInUseError newDepName)
388482 else do
389483 let potentialContext = currContext { inclusionDependencies = newDeps }
390− case checkConstraints potentialContext of
391− Left err -> pure (Left err)
392− Right _ -> do
484+ -- if the potential context passes all constraints, then save it
485+ -- potential optimization: validate only the new constraint- all old constraints must already hold
486+ case checkConstraints potentialContext transId graph of
487+ Left err -> dbErr err
488+ Right _ ->
393489 putStateContext potentialContext
394− return (Right ())
395490
396−evalDatabaseContextExpr (RemoveInclusionDependency depName) = do
491+evalGraphRefDatabaseContextExpr (RemoveInclusionDependency depName) = do
397492 currContext <- getStateContext
398493 let currDeps = inclusionDependencies currContext
399494 newDeps = M.delete depName currDeps
400495 if M.notMember depName currDeps then
401− pure (Left (InclusionDependencyNameNotInUseError depName))
402− else do
496+ dbErr (InclusionDependencyNameNotInUseError depName)
497+ else
403498 putStateContext $ currContext {inclusionDependencies = newDeps }
404− return (Right ())
405499
406500-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
407−evalDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
501+evalGraphRefDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
408502 currentContext <- getStateContext
409503 let nots = notifications currentContext
410504 if M.member notName nots then
411− pure (Left (NotificationNameInUseError notName))
505+ dbErr (NotificationNameInUseError notName)
412506 else do
413507 let newNotifications = M.insert notName newNotification nots
414508 newNotification = Notification { changeExpr = triggerExpr,
415509 reportOldExpr = resultOldExpr,
416510 reportNewExpr = resultNewExpr}
417511 putStateContext $ currentContext { notifications = newNotifications }
418− return (Right ())
419512
420−evalDatabaseContextExpr (RemoveNotification notName) = do
513+evalGraphRefDatabaseContextExpr (RemoveNotification notName) = do
421514 currentContext <- getStateContext
422515 let nots = notifications currentContext
423516 if M.notMember notName nots then
424− pure (Left (NotificationNameNotInUseError notName))
517+ dbErr (NotificationNameNotInUseError notName)
425518 else do
426519 let newNotifications = M.delete notName nots
427520 putStateContext $ currentContext { notifications = newNotifications }
428− pure (Right ())
521+
429522
430523-- | Adds type and data constructors to the database context.
431524-- validate that the type *and* constructor names are unique! not yet implemented!
432−evalDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
525+evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
433526 currentContext <- getStateContext
434527 let oldTypes = typeConstructorMapping currentContext
435528 tConsName = TCD.name tConsDef
436529 -- validate that the constructor's types exist
437530 case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
438− Left err -> pure (Left err)
439− Right _ | T.null tConsName || not (isUpper (T.head tConsName)) -> pure (Left (InvalidAtomTypeName tConsName))
440− | isJust (findTypeConstructor tConsName oldTypes) -> pure (Left (AtomTypeNameInUseError tConsName))
441− | otherwise -> do
442− let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
443− putStateContext $ currentContext { typeConstructorMapping = newTypes }
444− pure (Right ())
531+ Left err -> throwError err
532+ Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
533+ | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
534+ | otherwise -> do
535+ let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
536+ putStateContext $ currentContext { typeConstructorMapping = newTypes }
445537
446538-- | Removing the atom constructor prevents new atoms of the type from being created. Existing atoms of the type remain. Thus, the atomTypes list in the DatabaseContext need not be all-inclusive.
447−evalDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
539+evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
448540 currentContext <- getStateContext
449541 let oldTypes = typeConstructorMapping currentContext
450542 if isNothing (findTypeConstructor tConsName oldTypes) then
451− pure (Left (AtomTypeNameNotInUseError tConsName))
543+ dbErr (AtomTypeNameNotInUseError tConsName)
452544 else do
453545 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
454546 putStateContext $ currentContext { typeConstructorMapping = newTypes }
455− pure (Right ())
456547
457−evalDatabaseContextExpr (MultipleExpr exprs) = do
548+evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
458549 --the multiple expressions must pass the same context around- not the old unmodified context
459− evald <- forM exprs evalDatabaseContextExpr
460− --some lifting magic needed here
461− case lefts evald of
462− [] -> pure (Right ())
463− errs -> pure (Left (someErrors errs))
464−
465−evalDatabaseContextExpr (RemoveAtomFunction funcName) = do
550+ mapM_ evalGraphRefDatabaseContextExpr exprs
551+
552+evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
466553 currentContext <- getStateContext
467554 let atomFuncs = atomFunctions currentContext
468555 case atomFunctionForName funcName atomFuncs of
469− Left err -> pure (Left err)
470− Right realFunc -> if isScriptedAtomFunction realFunc then do
471− let updatedFuncs = HS.delete realFunc atomFuncs
472− putStateContext (currentContext {atomFunctions = updatedFuncs })
473− pure (Right ())
474− else
475− pure (Left (PrecompiledFunctionRemoveError funcName))
556+ Left err -> dbErr err
557+ Right realFunc ->
558+ if isScriptedAtomFunction realFunc then do
559+ let updatedFuncs = HS.delete realFunc atomFuncs
560+ putStateContext (currentContext {atomFunctions = updatedFuncs })
561+ else
562+ dbErr (PrecompiledFunctionRemoveError funcName)
476563
477−evalDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
564+evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
478565 context <- getStateContext
479566 let dbcFuncs = dbcFunctions context
480567 case databaseContextFunctionForName funcName dbcFuncs of
481− Left err -> pure (Left err)
482− Right realFunc -> if isScriptedDatabaseContextFunction realFunc then do
483− let updatedFuncs = HS.delete realFunc dbcFuncs
484− putStateContext (context { dbcFunctions = updatedFuncs })
485− pure (Right ())
486− else
487− pure (Left (PrecompiledFunctionRemoveError funcName))
568+ Left err -> dbErr err
569+ Right realFunc ->
570+ if isScriptedDatabaseContextFunction realFunc then do
571+ let updatedFuncs = HS.delete realFunc dbcFuncs
572+ putStateContext (context { dbcFunctions = updatedFuncs })
573+ else
574+ dbErr (PrecompiledFunctionRemoveError funcName)
488575
489−evalDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
576+evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
490577 context <- getStateContext
578+ graph <- dbcGraph
491579 --resolve atom arguments
492− let relExprState = mkRelationalExprState context
493− eAtomTypes = map (\atomExpr -> runReader (typeFromAtomExpr emptyAttributes atomExpr) relExprState) atomArgExprs
580+ let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
494581 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
582+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
495583 case eFunc of
496− Left err -> pure (Left err)
584+ Left err -> dbErr err
497585 Right func -> do
498586 let expectedArgCount = length (dbcFuncType func)
499587 actualArgCount = length atomArgExprs
500588 if expectedArgCount /= actualArgCount then
501− pure (Left (FunctionArgumentCountMismatchError expectedArgCount actualArgCount))
589+ dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
502590 else
503591 --check that the atom types are valid
504− case lefts eAtomTypes of
505− _:_ -> pure (Left (someErrors (lefts eAtomTypes)))
506− [] -> do
507− let atomTypes = rights eAtomTypes
508− let mValidTypes = zipWith
509− (\expType actType
510− -> case atomTypeVerify expType actType of
511− Left err -> Just err
512− Right _ -> Nothing)
513− (dbcFuncType func)
514− atomTypes
515− typeErrors = catMaybes mValidTypes
516− eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
592+ case eAtomTypes of
593+ Left err -> dbErr err
594+ Right atomTypes -> do
595+ let mValidTypes = zipWith (\ expType actType
596+ -> case atomTypeVerify expType actType of
597+ Left err -> Just err
598+ Right _ -> Nothing)
599+ (dbcFuncType func) atomTypes
600+ typeErrors = catMaybes mValidTypes
601+ eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
517602 if length (lefts eAtomArgs) > 1 then
518− pure (Left (someErrors (lefts eAtomArgs)))
603+ dbErr (someErrors (lefts eAtomArgs))
519604 else if not (null typeErrors) then
520− pure (Left (someErrors typeErrors))
605+ dbErr (someErrors typeErrors)
521606 else
522607 case evalDatabaseContextFunction func (rights eAtomArgs) context of
523− Left err -> pure (Left err)
524− Right newContext -> putStateContext newContext >> pure (Right ())
525−
526−evalDatabaseContextIOExpr :: Maybe ScriptSession -> DatabaseContext -> DatabaseContextIOExpr -> IO (Either RelationalError DatabaseContext)
527−#if !defined(PM36_HASKELL_SCRIPTING)
528−evalDatabaseContextIOExpr _ _ AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
529−evalDatabaseContextIOExpr _ _ AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
530−evalDatabaseContextIOExpr _ _ LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
531−evalDatabaseContextIOExpr _ _ LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
608+ Left err -> dbErr err
609+ Right newContext -> putStateContext newContext
610+data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
611+ { dbcio_transId :: TransactionId,
612+ dbcio_graph :: TransactionGraph,
613+ dbcio_mScriptSession :: Maybe ScriptSession
614+ }
615+
616+type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
617+
618+runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
619+runDatabaseContextIOEvalMonad env ctx m = do
620+ res <- runRWST m env freshState
621+ case res of
622+ (Left err,_,_) -> pure (Left err)
623+ (Right (),s,_) -> pure (Right s)
624+ where
625+ freshState = mkDatabaseContextEvalState ctx
626+
627+requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
628+requireScriptSession = do
629+ env <- RWS.ask
630+ case dbcio_mScriptSession env of
631+ Nothing -> pure $ Left $ ScriptError ScriptCompilationDisabledError
632+ Just ss -> pure (Right ss)
633+
634+putDBCIOContext :: DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ())
635+putDBCIOContext ctx = do
636+ RWS.modify (\dbstate -> dbstate { dbc_context = ctx})
637+ pure (Right ())
638+
639+getDBCIOContext :: DatabaseContextIOEvalMonad DatabaseContext
640+getDBCIOContext = dbc_context <$> RWS.get
641+
642+getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
643+getDBCIORelationalExprEnv = do
644+ context <- getDBCIOContext
645+ mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
646+
647+evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
648+#if !defined(PM36_HASKELL_SCRIPTING)
649+evalGraphRefDatabaseContextIOExpr AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
650+evalGraphRefDatabaseContextIOExpr AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
651+evalGraphRefDatabaseContextIOExpr LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
652+evalGraphRefDatabaseContextIOExpr LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
532653#else
533−evalDatabaseContextIOExpr mScriptSession currentContext (AddAtomFunction funcName funcType script) =
534− case mScriptSession of
535− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
536− Just scriptSession -> do
537− res <- try $ runGhc (Just libdir) $ do
654+evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
655+ eScriptSession <- requireScriptSession
656+ currentContext <- getDBCIOContext
657+ case eScriptSession of
658+ Left err -> pure (Left err)
659+ Right scriptSession -> do
660+ res <- liftIO $ try $ runGhc (Just libdir) $ do
538661 setSession (hscEnv scriptSession)
539662 let atomFuncs = atomFunctions currentContext
540663 case extractAtomFunctionType funcType of
@@ -560,12 +683,13 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddAtomFunction funcNam
560683 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
561684 Right eContext -> case eContext of
562685 Left err -> pure (Left err)
563− Right context' -> pure (Right context')
564−
565−evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunction funcName funcType script) =
566− case mScriptSession of
567− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
568− Just scriptSession -> do
686+ Right context' -> putDBCIOContext context'
687+evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
688+ eScriptSession <- requireScriptSession
689+ currentContext <- getDBCIOContext
690+ case eScriptSession of
691+ Left err -> pure (Left err)
692+ Right scriptSession -> do
569693 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
570694 let last2Args = reverse (take 2 (reverse funcType))
571695 atomArgs = take (length funcType - 2) funcType
@@ -575,7 +699,7 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunct
575699 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
576700 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
577701 else do
578− res <- try $ runGhc (Just libdir) $ do
702+ res <- liftIO $ try $ runGhc (Just libdir) $ do
579703 setSession (hscEnv scriptSession)
580704 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
581705 pure $ case eCompiledFunc of
@@ -600,68 +724,93 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunct
600724 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
601725 Right eContext -> case eContext of
602726 Left err -> pure (Left err)
603− Right context' -> pure (Right context')
604−evalDatabaseContextIOExpr _ currentContext (LoadAtomFunctions modName funcName modPath) = do
605− eLoadFunc <- loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
727+ Right context' -> putDBCIOContext context'
728+evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
729+ currentContext <- getDBCIOContext
730+ eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
606731 case eLoadFunc of
607732 Left LoadSymbolError -> pure (Left LoadFunctionError)
608733 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
609734 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
610− in pure (Right newContext)
611−evalDatabaseContextIOExpr _ currentContext (LoadDatabaseContextFunctions modName funcName modPath) = do
612− eLoadFunc <- loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
735+ in putDBCIOContext newContext
736+evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName modPath) = do
737+ currentContext <- getDBCIOContext
738+ eLoadFunc <- liftIO $ loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
613739 case eLoadFunc of
614740 Left LoadSymbolError -> pure (Left LoadFunctionError)
615741 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
616742 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
617− in pure (Right newContext)
618−#endif
619−
620−evalDatabaseContextIOExpr _ currentContext (CreateArbitraryRelation relVarName attrExprs range) =
743+ in putDBCIOContext newContext
744+evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
621745 --Define
622− case runState ( evalDatabaseContextExpr (Define relVarName attrExprs)) (freshDatabaseState currentContext) of
623− (Left err,_) -> pure (Left err)
624− (Right (), elems@(ctx,_,_)) -> do
746+ currentContext <- getDBCIOContext
747+ env <- RWS.ask
748+ --create graph ref expr
749+ let gfExpr = Define relVarName attrExprs
750+ evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
751+ graph = dbcio_graph env
752+ case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
753+ Left err -> pure (Left err)
754+ Right dbstate -> do
625755 --Assign
626756 let existingRelVar = M.lookup relVarName relVarTable
627− relVarTable = relationVariables ctx
757+ relVarTable = relationVariables (dbc_context dbstate)
628758 case existingRelVar of
629759 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
630760 Just existingRel -> do
631− let expectedAttributes = attributes existingRel
632− let tcMap = typeConstructorMapping ctx
633− eitherRel <- generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
634− case eitherRel of
635− Left err -> pure $ Left err
636− Right rel ->
637− case runState (setRelVar relVarName rel) elems of
638− (Left err,_) -> pure (Left err)
639− (Right (), (ctx',_,_)) -> pure $ Right ctx'
640−
641−updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> RelationTuple -> Either RelationalError RelationTuple
642−updateTupleWithAtomExprs exprMap context tupIn = do
761+ let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
762+ case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
763+ Left err -> pure (Left err)
764+ Right relType -> do
765+ let expectedAttributes = attributes relType
766+ tcMap = typeConstructorMapping (dbc_context dbstate)
767+ eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
768+ case eitherRel of
769+ Left err -> pure $ Left err
770+ Right rel ->
771+ case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
772+ Left err -> pure (Left err)
773+ Right dbstate' -> putDBCIOContext (dbc_context dbstate')
774+#endif
775+{-
776+updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
777+updateTupleWithAtomExprs exprMap context graph tupIn = do
643778 --resolve all atom exprs
779+ let
644780 atomsAssoc <- mapM (\(attrName, atomExpr) -> do
645− atom <- runReader (evalAtomExpr tupIn atomExpr) (RelationalExprStateElems context)
781+ let atom = unimplemented
782+ --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
646783 pure (attrName, atom)
647784 ) (M.toList exprMap)
648785 pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
649−
786+-}
650787--run verification on all constraints
651−checkConstraints :: DatabaseContext -> Either RelationalError ()
652−checkConstraints context =
788+checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
789+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
653790 mapM_ (uncurry checkIncDep) (M.toList deps)
654791 where
792+ potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
793+ tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
794+ utctDayTime = secondsToDiffTime 0 }
795+ tempSchemas = Schemas context M.empty
796+ tempTrans = Transaction U.nil (TransactionInfo (transId NE.:| []) tempStamp) tempSchemas
797+
655798 deps = inclusionDependencies context
656− eval expr = evalReader (evalRelationalExpr expr)
657− evalReader f = runReader f (RelationalExprStateElems context)
799+ -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
658800 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
801+ let process = runProcessExprM UncommittedContextMarker
802+ gfSubsetExpr = process (processRelationalExpr subsetExpr)
803+ gfSupersetExpr = process (processRelationalExpr supersetExpr)
659804 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
660− typeSub <- evalReader (typeForRelationalExpr subsetExpr)
661− typeSuper <- evalReader (typeForRelationalExpr supersetExpr)
805+ let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
806+ runGfRel = runGraphRefRelationalExprM gfEnv
807+ typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
808+ typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
662809 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
663− let checkExpr = Equals supersetExpr (Union subsetExpr supersetExpr)
664− case eval checkExpr of
810+ let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
811+ gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
812+ gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
813+ case gfEvald of
665814 Left err -> Left err
666815 Right resultRel -> if resultRel == relationTrue then
667816 pure ()
@@ -671,91 +820,90 @@ checkConstraints context =
671820-- 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
672821-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
673822
674−typeForRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
823+typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
675824typeForRelationalExpr expr = do
676− rstate <- ask
677− let context = stateElemsContext rstate
678825 --replace the relationVariables context element with a cloned set of relation devoid of tuples
679− let context' = contextWithEmptyTupleSets context
680− rstate' = setStateElemsContext rstate context'
681826 --evalRelationalExpr could still return an existing relation with tuples, so strip them
682− pure $ case runReader (evalRelationalExpr expr) rstate' of
683− Left err -> Left err
684− Right typeRel -> Right (relationWithEmptyTupleSet typeRel)
827+ graph <- reGraph
828+ context <- reContext
829+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
830+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
831+ runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
832+ lift $ except runGf
685833
686834--returns a database context with all tuples removed
687835--this is useful for type checking and optimization
836+{-
688837contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
689838contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
690839 where
691− relVars = M.map (\rel -> Relation (attributes rel) emptyTupleSet) (relationVariables contextIn)
840+ relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
841+-}
692842
693843liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
694844liftE v = do
695845 y <- lift v
696846 case y of
697− Left err -> throwE err
847+ Left err -> throwError err
698848 Right val -> pure val
699849
700850{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
701−predicateRestrictionFilter :: Attributes -> RestrictionPredicateExpr -> RelationalExprState (Either RelationalError RestrictionFilter)
702−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
703− runExceptT $ do
704− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
705− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
706− pure (\x -> do
707− ev1 <- expr1v x
708− ev2 <- expr2v x
709− pure (ev1 && ev2))
851+predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
852+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
853+ expr1v <- predicateRestrictionFilter attrs expr1
854+ expr2v <- predicateRestrictionFilter attrs expr2
855+ pure (\x -> do
856+ ev1 <- expr1v x
857+ ev2 <- expr2v x
858+ pure (ev1 && ev2))
710859
711−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
712− runExceptT $ do
713− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
714− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
860+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
861+ expr1v <- predicateRestrictionFilter attrs expr1
862+ expr2v <- predicateRestrictionFilter attrs expr2
715863 pure (\x -> do
716864 ev1 <- expr1v x
717865 ev2 <- expr2v x
718866 pure (ev1 || ev2))
719867
720−predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
868+predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
721869
722−predicateRestrictionFilter attrs (NotPredicate expr) =
723− runExceptT $ do
724− exprv <- liftE (predicateRestrictionFilter attrs expr)
725− pure (fmap not . exprv)
870+predicateRestrictionFilter attrs (NotPredicate expr) = do
871+ exprv <- predicateRestrictionFilter attrs expr
872+ pure (fmap not . exprv)
726873
727874--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
728875predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
729− rstate <- ask
730− pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
876+ renv <- askEnv
877+ let eval :: RelationTuple -> Either RelationalError Relation
878+ eval tup =
879+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
880+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
881+ pure (\tup -> case eval tup of
731882 Left err -> Left err
732883 Right rel -> if arity rel /= 0 then
733884 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
734885 else
735− pure (rel == relationTrue)))
886+ pure (rel == relationTrue))
736887
737888predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
738− rstate <- ask
739− let (attrs', ctxtup') = case rstate of
740− RelationalExprStateElems _ -> (attrs, emptyTuple)
741− RelationalExprStateAttrsElems _ _ -> (attrs, emptyTuple)
742− RelationalExprStateTupleElems _ ctxtup -> (A.union attrs (tupleAttributes ctxtup), ctxtup)
743− runExceptT $ do
744− atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
745− attr <- either throwE pure $ case A.attributeForName attrName attrs of
889+ env <- askEnv
890+ let attrs' = A.union attrs (envAttributes env)
891+ ctxtup' = envTuple env
892+ atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
893+ attr <- lift $ except $ case A.attributeForName attrName attrs of
746894 Right attr -> Right attr
747895 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
748896 Right ctxattr -> Right ctxattr
749897 Left err2@(NoSuchAttributeNamesError _) -> Left err2
750898 Left err -> Left err
751899 Left err -> Left err
752− if atomExprType /= A.atomType attr then
753− throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
754− else
900+ if atomExprType /= A.atomType attr then
901+ throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
902+ else
755903 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
756904 Right atomCmp -> atomCmp == atomIn
757905 Left _ -> False
758− atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
906+ atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
759907 in
760908 pure $ case atomForAttributeName attrName tupleIn of
761909 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -766,16 +914,15 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
766914-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
767915predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
768916 --merge attrs into the state attributes
769− rstate <- ask
770− runExceptT $ do
771− aType <- liftE (typeFromAtomExpr attrs atomExpr)
772− if aType /= BoolAtomType then
773− throwE (AtomTypeMismatchError aType BoolAtomType)
774− else
917+ renv <- askEnv
918+ aType <- typeForGraphRefAtomExpr attrs atomExpr
919+ if aType /= BoolAtomType then
920+ throwError (AtomTypeMismatchError aType BoolAtomType)
921+ else
775922 pure (\tupleIn ->
776− case runReader (evalAtomExpr tupleIn atomExpr) rstate of
777− Left err -> Left err
778− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
923+ case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
924+ Left err -> Left err
925+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
779926
780927tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
781928tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
@@ -783,31 +930,83 @@ tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName r
783930 else
784931 Right rel
785932
786−extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
787−extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
788− rstate <- ask
933+extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
934+extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
935+-- renv <- askEnv
789936 -- check that the attribute name is not in use
790937 case tupleExprCheckNewAttrName newAttrName relIn of
791− Left err -> pure (Left err)
792− Right _ -> runExceptT $ do
793− atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
794− atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
938+ Left err -> throwError err
939+ Right _ -> do
940+ atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
941+ atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
795942 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
796943 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
797− pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in case runReader (evalAtomExpr tup atomExpr) substate of
798− Left err -> Left err
799− Right atom -> Right (tupleAtomExtend newAttrName atom tup)
944+ env <- ask
945+ pure (newAndOldAttrs, \tup -> do
946+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
947+ atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
948+ Right (tupleAtomExtend newAttrName atom tup)
800949 )
801950
802−evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
951+evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
952+evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
953+ case atomForAttributeName attrName tupIn of
954+ Right atom -> pure atom
955+ Left err@(NoSuchAttributeNamesError _) -> do
956+ env <- askEnv
957+ case gre_extra env of
958+ Nothing -> throwError err
959+ Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
960+ Just (Right _) -> throwError err
961+ Left err -> throwError err
962+evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
963+evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
964+ argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
965+ context <- gfDatabaseContextForMarker tid
966+ let functions = atomFunctions context
967+ func <- lift $ except (atomFunctionForName funcName functions)
968+ let expectedArgCount = length (atomFuncType func) - 1
969+ actualArgCount = length argTypes
970+ safeInit [] = [] -- different behavior from normal init
971+ safeInit xs = init xs
972+ if expectedArgCount /= actualArgCount then
973+ throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
974+ else do
975+ let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
976+ mapM_ (\(expType, actType) ->
977+ lift $ except (atomTypeVerify expType actType)) zippedArgs
978+ evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
979+ case evalAtomFunction func evaldArgs of
980+ Left err -> throwError (AtomFunctionUserError err)
981+ Right result -> do
982+ --validate that the result matches the expected type
983+ _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
984+ pure result
985+evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
986+ --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
987+ env <- ask
988+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
989+ relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
990+ pure (RelationAtom relAtom)
991+evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
992+ let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
993+ aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
994+ argAtoms <- local mergeEnv $
995+ mapM (evalGraphRefAtomExpr tupIn) dConsArgs
996+ pure (ConstructedAtom dConsName aType argAtoms)
997+
998+{-
999+evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprM Atom
1000+evalAtomExpr tupIn expr =
1001+ -}
1002+{-
1003+
8031004evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
8041005 Right atom -> pure (Right atom)
8051006 err@(Left (NoSuchAttributeNamesError _)) -> do
8061007 rstate <- ask
807− case rstate of
808− RelationalExprStateElems _ -> pure err
809− RelationalExprStateAttrsElems _ _ -> pure err
810− RelationalExprStateTupleElems _ ctxtup -> pure (atomForAttributeName attrName ctxtup)
1008+ let stateTup = stateTuple rstate
1009+ pure (atomForAttributeName attrName stateTup)
8111010 Left err -> pure (Left err)
8121011evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
8131012evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
@@ -847,131 +1046,170 @@ evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExcept
8471046 aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
8481047 argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
8491048 pure (ConstructedAtom dConsName aType argAtoms)
850−
851−typeFromAtomExpr :: Attributes -> AtomExpr -> RelationalExprState (Either RelationalError AtomType)
852−typeFromAtomExpr attrs (AttributeAtomExpr attrName) = do
853− rstate <- ask
1049+-}
1050+typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
1051+typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
1052+ renv <- askEnv
8541053 case A.atomTypeForAttributeName attrName attrs of
855− Right aType -> pure (Right aType)
856− Left err@(NoSuchAttributeNamesError _) -> case rstate of
857− RelationalExprStateAttrsElems _ attrs' -> case A.attributeForName attrName attrs' of
858− Left err' -> pure (Left err')
859− Right attr -> pure (Right (A.atomType attr))
860− RelationalExprStateElems _ -> pure (Left err)
861− RelationalExprStateTupleElems _ tup -> case atomForAttributeName attrName tup of
862− Left err' -> pure (Left err')
863− Right atom -> pure (Right (atomTypeForAtom atom))
864− Left err -> pure (Left err)
865−typeFromAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
866−typeFromAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
867− context <- fmap stateElemsContext ask
868− let funcs = atomFunctions context
1054+ Right aType -> pure aType
1055+ Left err@(NoSuchAttributeNamesError _) ->
1056+ let envTup = envTuple renv
1057+ envAttrs = envAttributes renv in
1058+ case A.attributeForName attrName envAttrs of
1059+ Right attr -> pure (A.atomType attr)
1060+ Left _ -> case atomForAttributeName attrName envTup of
1061+ Right atom -> pure (atomTypeForAtom atom)
1062+ Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
1063+ throwError err
1064+ Left err -> throwError err
1065+
1066+typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
1067+typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
1068+ funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
8691069 case atomFunctionForName funcName funcs of
870− Left err -> pure (Left err)
1070+ Left err -> throwError err
8711071 Right func -> do
8721072 let funcRetType = last (atomFuncType func)
8731073 funcArgTypes = init (atomFuncType func)
874− eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
875− case lefts eArgTypes of
876− errs@(_:_) -> pure (Left (someErrors errs))
877− [] -> do
878− let eTvMap = resolveTypeVariables funcArgTypes argTypes
879− argTypes = rights eArgTypes
880− case eTvMap of
881− Left err -> pure (Left err)
882− Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
883−typeFromAtomExpr attrs (RelationAtomExpr relExpr) = runExceptT $ do
884− rstate <- lift ask
885− relType <- either throwE pure (runReader (typeForRelationalExpr relExpr) (mergeAttributesIntoRelationalExprState attrs rstate))
1074+ argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
1075+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
1076+ case eTvMap of
1077+ Left err -> throwError err
1078+ Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
1079+typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
1080+ relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
8861081 pure (RelationAtomType (attributes relType))
8871082-- grab the type of the data constructor, then validate that the args match the expected types
888−typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
889− runExceptT $ do
890− argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
891− context <- fmap stateElemsContext (lift ask)
892− either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
1083+typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
1084+ do
1085+ argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
1086+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1087+ lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
8931088
8941089-- | Validate that the type of the AtomExpr matches the expected type.
895−verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
896−verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
897− rstate <- lift ask
1090+verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
1091+verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
1092+ env <- askEnv
8981093 case A.atomTypeForAttributeName attrName (attributes relIn) of
899− Right aType -> either throwE pure (atomTypeVerify expectedType aType)
900− (Left err@(NoSuchAttributeNamesError _)) -> case rstate of
901− RelationalExprStateTupleElems _ _ -> throwE err
902− RelationalExprStateElems _ -> throwE err
903− RelationalExprStateAttrsElems _ attrs -> case A.attributeForName attrName attrs of
904− Left err' -> throwE err'
905− Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
906− Left err -> throwE err
907−verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
908−verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
909− rstate <- ask
1094+ Right aType -> lift $ except $ atomTypeVerify expectedType aType
1095+ (Left err@(NoSuchAttributeNamesError _)) ->
1096+ let attrs' = envAttributes env in
1097+ if attrs' == emptyAttributes then
1098+ throwError err
1099+ else
1100+ case A.attributeForName attrName attrs' of
1101+ Left err' -> throwError err'
1102+ Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
1103+ Left err -> throwError err
1104+
1105+verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
1106+ lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
1107+verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
1108+ context <- gfDatabaseContextForMarker tid
9101109 let functions = atomFunctions context
911− context = stateElemsContext rstate
912− runExceptT $ do
913− func <- either throwE pure (atomFunctionForName funcName functions)
914− let expectedArgTypes = atomFuncType func
915− funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
916− Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
917− Left err -> throwE err
918− Right x -> pure x
919− ) $ zip3 funcArgExprs expectedArgTypes [1..]
920− if length funcArgTypes /= length expectedArgTypes - 1 then
921− throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
1110+ func <- lift $ except $ atomFunctionForName funcName functions
1111+ let expectedArgTypes = atomFuncType func
1112+ funcArgVerifier (atomExpr, expectedType2, argCount) = do
1113+ let handler :: RelationalError -> GraphRefRelationalExprM AtomType
1114+ handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
1115+ handler err = throwError err
1116+ verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
1117+ funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
1118+ if length funcArgTypes /= length expectedArgTypes - 1 then
1119+ throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
9221120 else
923− either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
924−verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
925− rstate <- lift ask
926− relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
927− either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
928−verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
929− cType <- liftE (typeFromAtomExpr (attributes rel) cons)
930− either throwE pure (atomTypeVerify expectedType cType)
1121+ lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
1122+verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
1123+ do
1124+ let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
1125+ relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
1126+ lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
1127+verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
1128+ cType <- typeForGraphRefAtomExpr (attributes rel) cons
1129+ lift $ except $ atomTypeVerify expectedType cType
9311130
9321131-- | Look up the type's name and create a new attribute.
933−evalAttrExpr :: TypeConstructorMapping -> AttributeExpr -> Either RelationalError Attribute
934−evalAttrExpr aTypes (AttributeAndTypeNameExpr attrName tCons ()) = do
935− aType <- atomTypeForTypeConstructorValidate True tCons aTypes M.empty
936− validateAtomType aType aTypes
937− Right (Attribute attrName aType)
1132+evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1133+evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
1134+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
1135+ aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
1136+ lift $ except $ validateAtomType aType tConsMap
1137+ pure $ Attribute attrName aType
9381138
939−evalAttrExpr _ (NakedAttributeExpr attr) = Right attr
940−
941−evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
942−evalTupleExpr mAttrs (TupleExpr tupMap) = do
943− context <- fmap stateElemsContext ask
944− runExceptT $ do
1139+evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
1140+
1141+-- 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
1142+evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
1143+evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
1144+evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
1145+ tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
1146+ finalAttrs <- case mAttrs of
1147+ Just attrs -> pure attrs
1148+ Nothing ->
1149+ case tuples of
1150+ [] -> pure emptyAttributes
1151+ (headTuple:tailTuples) -> do
1152+ --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])
1153+ let mostResolvedTypes =
1154+ foldr (\tup acc ->
1155+ fmap (\(tupAttr,accAttr) -> --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
1156+ if isResolvedAttribute accAttr then
1157+ accAttr
1158+ else
1159+ case resolveAttributes accAttr tupAttr of
1160+ Left _ -> accAttr
1161+ Right val -> val) (zip (V.toList $ tupleAttributes tup) acc)) (V.toList $ tupleAttributes headTuple) tailTuples
1162+ pure (A.attributesFromList mostResolvedTypes)
1163+ --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
1164+ tConsMap <- case singularTransactions tupleExprL of
1165+ SingularTransactionRef commonTransId ->
1166+ typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
1167+ NoTransactionsRef ->
1168+ typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
1169+ -- 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
1170+ _ -> throwError TupleExprsReferenceMultipleMarkersError
1171+ lift $ except $ validateAttributes tConsMap finalAttrs
1172+ mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
1173+
1174+
1175+--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
1176+
1177+evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
1178+evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
9451179 -- 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
9461180 -- I could adjust this logic so that when the attributes are not specified (Nothing), then I can attempt to extract the attributes from the tuple- the type resolution will blow up if an ambiguous data constructor is used (Left 4) and this should allow simple cases to "relation{tuple{a 4}}" to be processed
947− let attrs = fromMaybe A.emptyAttributes mAttrs
948− attrAtoms <- mapM (\(attrName, aExpr) -> do
949− --provided when the relation header is available
950− let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
951− unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
952− resolvedType <- case eExpectedAtomType of
1181+ let attrs = fromMaybe A.emptyAttributes mAttrs
1182+ resolveOneAtom (attrName, aExpr) =
1183+ do
1184+ --provided when the relation header is available
1185+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
1186+ unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
1187+ resolvedType <- case eExpectedAtomType of
9531188 Left _ -> pure unresolvedType
954− Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
1189+ Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
9551190 --resolve atom typevars based on resolvedType?
956− newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
957− pure (attrName, newAtom, resolvedType)
958− ) (M.toList tupMap)
959− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
960− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
961− tup = mkRelationTuple tupAttrs atoms
962− tConss = typeConstructorMapping context
963− finalAttrs = fromMaybe tupAttrs mAttrs
1191+ newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
1192+ pure (attrName, newAtom, resolvedType)
1193+ attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
1194+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1195+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1196+ tup = mkRelationTuple tupAttrs atoms
1197+ finalAttrs = fromMaybe tupAttrs mAttrs
9641198 --verify that the attributes match
965− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
966− tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
967− _ <- either throwE pure (validateTuple tup' tConss)
968− pure tup'
1199+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1200+ --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1201+ --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1202+ let tup' = reorderTuple finalAttrs tup
1203+ --TODO: restore type resolution
1204+-- _ <- lift $ except (validateTuple tup' tConss)
1205+ pure tup'
9691206
970−evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
1207+{-
1208+evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprM (Either RelationalError (S.Set AttributeName))
9711209evalAttributeNames attrNames expr = do
9721210 eExprType <- typeForRelationalExpr expr
9731211 case eExprType of
974− Left err -> pure (Left err)
1212+ Left err -> throwError err
9751213 Right exprTyp -> do
9761214 let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
9771215 case attrNames of
@@ -1014,4 +1252,278 @@ evalAttributeNames attrNames expr = do
10141252 case eAttrExprType of
10151253 Left err -> pure (Left err)
10161254 Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1017−
1255+-}
1256+
1257+--temporary implementation until we have a proper planner+executor
1258+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1259+evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1260+ mAttrs <- case mAttrExprs of
1261+ Just _ ->
1262+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1263+ Nothing -> pure Nothing
1264+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1265+ let attrs = fromMaybe firstTupleAttrs mAttrs
1266+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1267+ lift $ except $ mkRelation attrs (RelationTupleSet tuples)
1268+evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
1269+ lift $ except $ mkRelation attributeSet tupleSet
1270+evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1271+evalGraphRefRelationalExpr (RelationVariable name tid) = do
1272+ ctx <- gfDatabaseContextForMarker tid
1273+ case M.lookup name (relationVariables ctx) of
1274+ Nothing -> throwError (RelVarNotDefinedError name)
1275+ Just rv -> evalGraphRefRelationalExpr rv
1276+evalGraphRefRelationalExpr (Project attrNames expr) = do
1277+ attrNameSet <- evalGraphRefAttributeNames attrNames expr
1278+ rel <- evalGraphRefRelationalExpr expr
1279+ lift $ except $ project attrNameSet rel
1280+evalGraphRefRelationalExpr (Union exprA exprB) = do
1281+ relA <- evalGraphRefRelationalExpr exprA
1282+ relB <- evalGraphRefRelationalExpr exprB
1283+ lift $ except $ union relA relB
1284+evalGraphRefRelationalExpr (Join exprA exprB) = do
1285+ relA <- evalGraphRefRelationalExpr exprA
1286+ relB <- evalGraphRefRelationalExpr exprB
1287+ lift $ except $ join relA relB
1288+evalGraphRefRelationalExpr (Rename oldName newName expr) = do
1289+ rel <- evalGraphRefRelationalExpr expr
1290+ lift $ except $ rename oldName newName rel
1291+evalGraphRefRelationalExpr (Difference exprA exprB) = do
1292+ relA <- evalGraphRefRelationalExpr exprA
1293+ relB <- evalGraphRefRelationalExpr exprB
1294+ lift $ except $ difference relA relB
1295+evalGraphRefRelationalExpr (Group groupAttrNames newAttrName expr) = do
1296+ groupNames <- evalGraphRefAttributeNames groupAttrNames expr
1297+ rel <- evalGraphRefRelationalExpr expr
1298+ lift $ except $ group groupNames newAttrName rel
1299+evalGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1300+ rel <- evalGraphRefRelationalExpr expr
1301+ lift $ except $ ungroup groupAttrName rel
1302+evalGraphRefRelationalExpr (Restrict predExpr expr) = do
1303+ rel <- evalGraphRefRelationalExpr expr
1304+ filt <- predicateRestrictionFilter (attributes rel) predExpr
1305+ lift $ except $ restrict filt rel
1306+evalGraphRefRelationalExpr (Equals exprA exprB) = do
1307+ relA <- evalGraphRefRelationalExpr exprA
1308+ relB <- evalGraphRefRelationalExpr exprB
1309+ pure $ if relA == relB then relationTrue else relationFalse
1310+evalGraphRefRelationalExpr (NotEquals exprA exprB) = do
1311+ relA <- evalGraphRefRelationalExpr exprA
1312+ relB <- evalGraphRefRelationalExpr exprB
1313+ pure $ if relA == relB then relationFalse else relationTrue
1314+evalGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1315+ rel <- evalGraphRefRelationalExpr expr
1316+ (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1317+ lift $ except $ relMogrify tupProc newAttrs rel
1318+evalGraphRefRelationalExpr expr@With{} =
1319+ --strategy A: add relation variables to the contexts in the graph
1320+ --strategy B: drop in macros in place (easier programmatically)
1321+ --strategy B implementation
1322+ evalGraphRefRelationalExpr (substituteWithNameMacros [] expr)
1323+
1324+dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1325+dbContextForTransId tid graph = do
1326+ trans <- transactionForId tid graph
1327+ pure (concreteDatabaseContext trans)
1328+
1329+transactionForId :: TransactionId -> TransactionGraph -> Either RelationalError Transaction
1330+transactionForId tid graph
1331+ | tid == U.nil =
1332+ Left RootTransactionTraversalError
1333+ | S.null matchingTrans =
1334+ Left $ NoSuchTransactionError tid
1335+ | otherwise =
1336+ Right $ head (S.toList matchingTrans)
1337+ where
1338+ matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
1339+
1340+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1341+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1342+typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1343+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1344+ mAttrs <- case mAttrExprs of
1345+ Just attrExprs -> do
1346+ attrs <- mapM evalGraphRefAttributeExpr attrExprs
1347+ pure (Just (attributesFromList attrs))
1348+ Nothing -> pure Nothing
1349+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1350+ let retAttrs = case tuples of
1351+ (tup:_) -> tupleAttributes tup
1352+ [] -> fromMaybe A.emptyAttributes mAttrs
1353+ pure $ emptyRelationWithAttrs retAttrs
1354+
1355+typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1356+ relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1357+ case M.lookup rvName relVars of
1358+ Nothing -> throwError (RelVarNotDefinedError rvName)
1359+ Just rvExpr ->
1360+ typeForGraphRefRelationalExpr rvExpr
1361+typeForGraphRefRelationalExpr (Project attrNames expr) = do
1362+ exprType' <- typeForGraphRefRelationalExpr expr
1363+ projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1364+ lift $ except $ project projectionAttrs exprType'
1365+typeForGraphRefRelationalExpr (Union exprA exprB) = do
1366+ exprA' <- typeForGraphRefRelationalExpr exprA
1367+ exprB' <- typeForGraphRefRelationalExpr exprB
1368+ lift $ except $ union exprA' exprB'
1369+typeForGraphRefRelationalExpr (Join exprA exprB) = do
1370+ exprA' <- typeForGraphRefRelationalExpr exprA
1371+ exprB' <- typeForGraphRefRelationalExpr exprB
1372+ lift $ except $ join exprA' exprB'
1373+typeForGraphRefRelationalExpr (Rename oldAttr newAttr expr) = do
1374+ expr' <- typeForGraphRefRelationalExpr expr
1375+ lift $ except $ rename oldAttr newAttr expr'
1376+typeForGraphRefRelationalExpr (Difference exprA exprB) = do
1377+ exprA' <- typeForGraphRefRelationalExpr exprA
1378+ exprB' <- typeForGraphRefRelationalExpr exprB
1379+ lift $ except $ difference exprA' exprB'
1380+typeForGraphRefRelationalExpr (Group groupNames attrName expr) = do
1381+ expr' <- typeForGraphRefRelationalExpr expr
1382+ groupNames' <- evalGraphRefAttributeNames groupNames expr
1383+ lift $ except $ group groupNames' attrName expr'
1384+typeForGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1385+ expr' <- typeForGraphRefRelationalExpr expr
1386+ lift $ except $ ungroup groupAttrName expr'
1387+typeForGraphRefRelationalExpr (Restrict pred' expr) = do
1388+ expr' <- typeForGraphRefRelationalExpr expr
1389+ filt <- predicateRestrictionFilter (attributes expr') pred'
1390+ lift $ except $ restrict filt expr'
1391+typeForGraphRefRelationalExpr Equals{} =
1392+ pure relationFalse
1393+typeForGraphRefRelationalExpr NotEquals{} =
1394+ pure relationFalse
1395+typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1396+ rel <- typeForGraphRefRelationalExpr expr
1397+ evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1398+typeForGraphRefRelationalExpr expr@(With withs _) = do
1399+ let expr' = substituteWithNameMacros [] expr
1400+ checkMacroName (WithNameExpr macroName tid) = do
1401+ rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1402+ case M.lookup macroName rvs of
1403+ Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1404+ Nothing -> pure ()
1405+ mapM_ (checkMacroName . fst) withs
1406+ typeForGraphRefRelationalExpr expr'
1407+
1408+evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1409+evalGraphRefAttributeNames attrNames expr = do
1410+ exprType' <- typeForGraphRefRelationalExpr expr
1411+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1412+ case attrNames of
1413+ AttributeNames names ->
1414+ case A.projectionAttributesForNames names (attributes exprType') of
1415+ Left err -> throwError err
1416+ Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1417+
1418+ InvertedAttributeNames names -> do
1419+ let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1420+ if not (S.null nonExistentAttributeNames) then
1421+ throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1422+ else
1423+ pure (A.nonMatchingAttributeNameSet names typeNameSet)
1424+
1425+ UnionAttributeNames namesA namesB -> do
1426+ nameSetA <- evalGraphRefAttributeNames namesA expr
1427+ nameSetB <- evalGraphRefAttributeNames namesB expr
1428+ pure (S.union nameSetA nameSetB)
1429+
1430+ IntersectAttributeNames namesA namesB -> do
1431+ nameSetA <- evalGraphRefAttributeNames namesA expr
1432+ nameSetB <- evalGraphRefAttributeNames namesB expr
1433+ pure (S.intersection nameSetA nameSetB)
1434+
1435+ RelationalExprAttributeNames attrExpr -> do
1436+ attrExprType <- typeForGraphRefRelationalExpr attrExpr
1437+ pure (A.attributeNameSet (attributes attrExprType))
1438+
1439+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1440+evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1441+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1442+ case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1443+ Left err -> throwError err
1444+ Right aType -> do
1445+ case validateAtomType aType tConsMap of
1446+ Left err -> throwError err
1447+ Right _ -> pure (Attribute attrName aType)
1448+evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1449+
1450+mkEmptyRelVars :: RelationVariables -> RelationVariables
1451+mkEmptyRelVars = M.map mkEmptyRelVar
1452+ where
1453+ mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1454+ mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1455+ mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1456+ mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
1457+ mkEmptyRelVar (Project attrNames expr) = Project attrNames (mkEmptyRelVar expr)
1458+ mkEmptyRelVar (Union exprA exprB) = Union (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1459+ mkEmptyRelVar (Join exprA exprB) = Join (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1460+ mkEmptyRelVar (Rename nameA nameB expr) = Rename nameA nameB (mkEmptyRelVar expr)
1461+ mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1462+ mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1463+ mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1464+ mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1465+ mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1466+ mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1467+ mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1468+ mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1469+
1470+
1471+dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1472+dbErr err = lift (except (Left err))
1473+
1474+-- | Return a Relation describing the relation variables.
1475+relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1476+relationVariablesAsRelation ctx graph = do
1477+ let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1478+ attrs = A.attributesFromList [Attribute "name" TextAtomType,
1479+ Attribute "attributes" (RelationAtomType subrelAttrs)]
1480+ relVars = relationVariables ctx
1481+ mkRvDesc (rvName, gfExpr) = do
1482+ let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1483+ gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1484+ pure (rvName, gfType)
1485+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributes rel)]
1486+ attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1487+ attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1488+ Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1489+ Right rel -> RelationAtom rel
1490+ rvs <- mapM mkRvDesc (M.toList relVars)
1491+ let tups = map relVarToAtomList rvs
1492+ mkRelationFromList attrs tups
1493+
1494+-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1495+evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1496+evalRelationalExpr expr = do
1497+ graph <- reGraph
1498+ context <- reContext
1499+ let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1500+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1501+ case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1502+ Left err -> throwError err
1503+ Right rel -> pure rel
1504+
1505+{-
1506+relVarByName :: RelVarName -> GraphRefRelationalExprM GraphRefRelationalExpr
1507+relVarByName = do
1508+ relvars <- relationVariables <$> getStateContext
1509+ case M.lookup relVarName relvars of
1510+ Nothing -> dbErr (RelVarNotDefinedError relVarName)
1511+ Just gfexpr -> pure gfExpr
1512+-}
1513+
1514+class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1515+ getContext :: m DatabaseContext
1516+
1517+instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1518+ getContext = gfDatabaseContextForMarker UncommittedContextMarker
1519+
1520+instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1521+ getContext = getStateContext
1522+
1523+relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1524+relVarByName rvName = do
1525+ relvars <- relationVariables <$> getContext
1526+ case M.lookup rvName relvars of
1527+ Nothing -> throwError (RelVarNotDefinedError rvName)
1528+ Just gfexpr -> pure gfexpr
1529+