on fc8cecc help sign in
project-m36/src/lib/ProjectM36/TransactionGraph.hs
545 lines 31 kB history raw
1{-# LANGUAGE DeriveAnyClass, DeriveGeneric #-}
2module ProjectM36.TransactionGraph where
3import ProjectM36.Base
4import ProjectM36.Error
5import ProjectM36.Transaction
6import ProjectM36.Relation
7import ProjectM36.TupleSet
8import ProjectM36.Tuple
9import ProjectM36.RelationalExpression
10import ProjectM36.TransactionGraph.Merge
11import qualified ProjectM36.DisconnectedTransaction as Discon
13import qualified Data.Vector as V
14import qualified ProjectM36.Attribute as A
15import qualified Data.UUID as U
16import qualified Data.Set as S
17import qualified Data.Map as M
18import Control.Monad
19import Data.Time.Clock
20import qualified Data.Text as T
21import GHC.Generics
22import Data.Binary
23import Data.Either (lefts, rights, isRight)
24import Data.Monoid
25import Control.Arrow
26import Data.Maybe
28{-
29--import Debug.Trace
30import Control.Monad.Reader
31import qualified ProjectM36.DisconnectedTransaction as D
32-}
34-- | Record a lookup for a specific transaction in the graph.
35data TransactionIdLookup = TransactionIdLookup TransactionId |
36 TransactionIdHeadNameLookup HeadName [TransactionIdHeadBacktrack]
37 deriving (Show, Eq, Binary, Generic)
39-- | Used for git-style head backtracking such as topic~3^2.
40data TransactionIdHeadBacktrack = TransactionIdHeadParentBacktrack Int | -- ^ git equivalent of ~: walk back n parents, arbitrarily choosing a parent when a choice must be made
41 TransactionIdHeadBranchBacktrack Int | -- ^ git equivalent of ^: walk back one parent level to the nth arbitrarily-chosen parent
42 TransactionStampHeadBacktrack UTCTime -- ^ git equivalent of 'git-rev-list -n 1 --before X' find the first transaction which was created before the timestamp
43 deriving (Show, Eq, Binary, Generic)
46-- | Operators which manipulate a transaction graph and which transaction the current 'Session' is based upon.
47data TransactionGraphOperator = JumpToHead HeadName |
48 JumpToTransaction TransactionId |
49 WalkBackToTime UTCTime |
50 Branch HeadName |
51 DeleteBranch HeadName |
52 MergeTransactions MergeStrategy HeadName HeadName |
53 Commit |
54 Rollback
55 deriving (Eq, Show, Binary, Generic)
57isCommit :: TransactionGraphOperator -> Bool
58isCommit Commit = True
59isCommit _ = False
61data ROTransactionGraphOperator = ShowGraph
62 deriving Show
64bootstrapTransactionGraph :: UTCTime -> TransactionId -> DatabaseContext -> TransactionGraph
65bootstrapTransactionGraph stamp freshId context = TransactionGraph bootstrapHeads bootstrapTransactions
66 where
67 bootstrapHeads = M.singleton "master" freshTransaction
68 newSchemas = Schemas context M.empty
69 freshTransaction = Transaction freshId (TransactionInfo U.nil S.empty stamp) newSchemas
70 bootstrapTransactions = S.singleton freshTransaction
72emptyTransactionGraph :: TransactionGraph
73emptyTransactionGraph = TransactionGraph M.empty S.empty
75transactionForHead :: HeadName -> TransactionGraph -> Maybe Transaction
76transactionForHead headName graph = M.lookup headName (transactionHeadsForGraph graph)
78headList :: TransactionGraph -> [(HeadName, TransactionId)]
79headList graph = map (second transactionId) (M.assocs (transactionHeadsForGraph graph))
81headNameForTransaction :: Transaction -> TransactionGraph -> Maybe HeadName
82headNameForTransaction transaction (TransactionGraph heads _) = if M.null matchingTrans then
83 Nothing
84 else
85 Just $ (head . M.keys) matchingTrans
86 where
87 matchingTrans = M.filter (transaction ==) heads
89transactionForId :: TransactionId -> TransactionGraph -> Either RelationalError Transaction
90transactionForId tid graph
91 | tid == U.nil =
92 Left RootTransactionTraversalError
93 | S.null matchingTrans =
94 Left $ NoSuchTransactionError tid
95 | otherwise =
96 Right $ head (S.toList matchingTrans)
97 where
98 matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
100transactionsForIds :: S.Set TransactionId -> TransactionGraph -> Either RelationalError (S.Set Transaction)
101transactionsForIds idSet graph =
102 S.fromList <$> forM (S.toList idSet) (`transactionForId` graph)
104isRootTransaction :: Transaction -> TransactionGraph -> Bool
105isRootTransaction (Transaction _ (TransactionInfo pId _ _) _) _ = U.null pId
106isRootTransaction (Transaction _ MergeTransactionInfo{} _) _ = False
108-- the first transaction has no parent - all other do have parents- merges have two parents
109parentTransactions :: Transaction -> TransactionGraph -> Either RelationalError (S.Set Transaction)
110parentTransactions (Transaction _ (TransactionInfo pId _ _) _) graph =
111 S.singleton <$> transactionForId pId graph
114parentTransactions (Transaction _ (MergeTransactionInfo pId1 pId2 _ _) _ ) graph = transactionsForIds (S.fromList [pId1, pId2]) graph
117childTransactions :: Transaction -> TransactionGraph -> Either RelationalError (S.Set Transaction)
118childTransactions (Transaction _ (TransactionInfo _ children _) _) = transactionsForIds children
119childTransactions (Transaction _ (MergeTransactionInfo _ _ children _) _) = transactionsForIds children
121-- create a new commit and add it to the heads
122-- technically, the new head could be added to an existing commit, but by adding a new commit, the new head is unambiguously linked to a new commit (with a context indentical to its parent)
123addBranch :: UTCTime -> TransactionId -> HeadName -> TransactionId -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
124addBranch stamp newId newBranchName branchPointId graph = do
125 parentTrans <- transactionForId branchPointId graph
126 let newTrans = Transaction newId (TransactionInfo branchPointId S.empty stamp) (schemas parentTrans)
127 addTransactionToGraph newBranchName newTrans graph
129--adds a disconnected transaction to a transaction graph at some head
130addDisconnectedTransaction :: UTCTime -> TransactionId -> HeadName -> DisconnectedTransaction -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
131addDisconnectedTransaction stamp newId headName (DisconnectedTransaction parentId schemas' _) = addTransactionToGraph headName (Transaction newId (TransactionInfo parentId S.empty stamp) schemas')
134addTransactionToGraph :: HeadName -> Transaction -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
135addTransactionToGraph headName newTrans graph = do
136 let parentIds = transactionParentIds newTrans
137 childIds = transactionChildIds newTrans
138 newId = transactionId newTrans
139 validateIds ids = mapM (`transactionForId` graph) (S.toList ids)
140 addChildTransaction trans = transactionSetChildren trans (S.insert newId (transactionChildIds trans))
141 --validate that the parent transactions are in the graph
142 _ <- validateIds parentIds
143 when (S.size parentIds < 1) (Left $ NewTransactionMissingParentError newId)
144 --if the headName already exists, ensure that it refers to a parent
145 case transactionForHead headName graph of
146 Nothing -> pure () -- any headName is OK
147 Just trans -> when (S.notMember (transactionId trans) parentIds) (Left (HeadNameSwitchingHeadProhibitedError headName))
148 --validate that the transaction has no children
149 unless (S.null childIds) (Left $ NewTransactionMayNotHaveChildrenError newId)
150 --validate that the trasaction's id is unique
151 when (isRight (transactionForId newId graph)) (Left (TransactionIdInUseError newId))
152 --update the parent transactions to point to the new transaction
153 parents <- mapM (`transactionForId` graph) (S.toList parentIds)
154 let updatedParents = S.map addChildTransaction (S.fromList parents)
155 updatedTransSet = S.insert newTrans (S.union updatedParents (transactionsForGraph graph))
156 updatedHeads = M.insert headName newTrans (transactionHeadsForGraph graph)
157 pure (newTrans, TransactionGraph updatedHeads updatedTransSet)
159validateGraph :: TransactionGraph -> Maybe [RelationalError]
160validateGraph graph@(TransactionGraph _ transSet) = do
161 --check that all transaction ids are unique in the graph
162 --FINISH ME!
163 --uuids = map transactionId transSet
164 --check that all heads appear in the transSet
165 --check that all forward and backward links are in place
166 mapM_ (walkParentTransactions S.empty graph) (S.toList transSet)
167 mapM (walkChildTransactions S.empty graph) (S.toList transSet)
169--verify that all parent links exist and that all children exist
170--maybe verify that all parents end at transaction id nil and all children end at leaves
171walkParentTransactions :: S.Set TransactionId -> TransactionGraph -> Transaction -> Maybe RelationalError
172walkParentTransactions seenTransSet graph trans =
173 let transId = transactionId trans in
174 if transId == U.nil then
175 Nothing
176 else if S.member transId seenTransSet then
177 Just $ TransactionGraphCycleError transId
178 else
179 let parentTransSetOrError = parentTransactions trans graph in
180 case parentTransSetOrError of
181 Left err -> Just err
182 Right parentTransSet -> do
183 walk <- mapM (walkParentTransactions (S.insert transId seenTransSet) graph) (S.toList parentTransSet)
184 case walk of
185 err:_ -> Just err
186 _ -> Nothing
188--refactor: needless duplication in these two functions
189walkChildTransactions :: S.Set TransactionId -> TransactionGraph -> Transaction -> Maybe RelationalError
190walkChildTransactions seenTransSet graph trans =
191 let transId = transactionId trans in
192 if childTransactions trans graph == Right S.empty then
193 Nothing
194 else if S.member transId seenTransSet then
195 Just $ TransactionGraphCycleError transId
196 else
197 let childTransSetOrError = childTransactions trans graph in
198 case childTransSetOrError of
199 Left err -> Just err
200 Right childTransSet -> do
201 walk <- mapM (walkChildTransactions (S.insert transId seenTransSet) graph) (S.toList childTransSet)
202 case walk of
203 err:_ -> Just err
204 _ -> Nothing
206-- returns the new "current" transaction, updated graph, and tutorial d result
207-- the current transaction is not part of the transaction graph until it is committed
208evalGraphOp :: UTCTime -> TransactionId -> DisconnectedTransaction -> TransactionGraph -> TransactionGraphOperator -> Either RelationalError (DisconnectedTransaction, TransactionGraph)
210evalGraphOp _ _ _ graph (JumpToTransaction jumpId) = case transactionForId jumpId graph of
211 Left err -> Left err
212 Right parentTrans -> Right (newTrans, graph)
213 where
214 newTrans = DisconnectedTransaction jumpId (schemas parentTrans) False
216-- switch from one head to another
217evalGraphOp _ _ _ graph (JumpToHead headName) =
218 case transactionForHead headName graph of
219 Just newHeadTransaction -> let disconnectedTrans = DisconnectedTransaction (transactionId newHeadTransaction) (schemas newHeadTransaction) False in
220 Right (disconnectedTrans, graph)
221 Nothing -> Left $ NoSuchHeadNameError headName
223evalGraphOp _ _ discon graph (WalkBackToTime backTime) = do
224 let startTransId = Discon.parentId discon
225 jumpDest <- backtrackGraph graph startTransId (TransactionStampHeadBacktrack backTime)
226 case transactionForId jumpDest graph of
227 Left err -> Left err
228 Right trans -> do
229 let disconnectedTrans = DisconnectedTransaction (transactionId trans) (schemas trans) False
230 Right (disconnectedTrans, graph)
232-- add new head pointing to branchPoint
233-- repoint the disconnected transaction to the new branch commit (with a potentially different disconnected context)
234-- affects transactiongraph and the disconnectedtransaction is recreated based off the branch
235 {-
236evalGraphOp newId discon@(DisconnectedTransaction parentId disconContext) graph (Branch newBranchName) = case transactionForId parentId graph of
237 Nothing -> (discon, graph, DisplayErrorResult "Failed to find parent transaction.")
238 Just parentTrans -> case addBranch newBranchName parentTrans graph of
239 Nothing -> (discon, graph, DisplayErrorResult "Failed to add branch.")
240 Just newGraph -> (newDiscon, newGraph, DisplayResult "Branched.")
241 where
242 newDiscon = DisconnectedTransaction (transactionId parentTrans) disconContext
243-}
245-- create a new commit and add it to the heads
246-- technically, the new head could be added to an existing commit, but by adding a new commit, the new head is unambiguously linked to a new commit (with a context indentical to its parent)
247evalGraphOp stamp newId (DisconnectedTransaction parentId schemas' _) graph (Branch newBranchName) = do
248 let newDiscon = DisconnectedTransaction newId schemas' False
249 case addBranch stamp newId newBranchName parentId graph of
250 Left err -> Left err
251 Right (_, newGraph) -> Right (newDiscon, newGraph)
253-- add the disconnected transaction to the graph
254-- affects graph and disconnectedtransaction- the new disconnectedtransaction's parent is the freshly committed transaction
255evalGraphOp stamp newTransId discon@(DisconnectedTransaction parentId schemas' _) graph Commit = case transactionForId parentId graph of
256 Left err -> Left err
257 Right parentTransaction -> case headNameForTransaction parentTransaction graph of
258 Nothing -> Left $ TransactionIsNotAHeadError parentId
259 Just headName -> case maybeUpdatedGraph of
260 Left err-> Left err
261 Right (_, updatedGraph) -> Right (newDisconnectedTrans, updatedGraph)
262 where
263 newDisconnectedTrans = DisconnectedTransaction newTransId schemas' False
264 maybeUpdatedGraph = addDisconnectedTransaction stamp newTransId headName discon graph
266-- refresh the disconnected transaction, return the same graph
267evalGraphOp _ _ (DisconnectedTransaction parentId _ _) graph Rollback = case transactionForId parentId graph of
268 Left err -> Left err
269 Right parentTransaction -> Right (newDiscon, graph)
270 where
271 newDiscon = DisconnectedTransaction parentId (schemas parentTransaction) False
273evalGraphOp stamp newId (DisconnectedTransaction parentId _ _) graph (MergeTransactions mergeStrategy headNameA headNameB) = mergeTransactions stamp newId parentId mergeStrategy (headNameA, headNameB) graph
275evalGraphOp _ _ discon graph@(TransactionGraph graphHeads transSet) (DeleteBranch branchName) = case transactionForHead branchName graph of
276 Nothing -> Left (NoSuchHeadNameError branchName)
277 Just _ -> Right (discon, TransactionGraph (M.delete branchName graphHeads) transSet)
279--present a transaction graph as a relation showing the uuids, parentuuids, and flag for the current location of the disconnected transaction
280graphAsRelation :: DisconnectedTransaction -> TransactionGraph -> Either RelationalError Relation
281graphAsRelation (DisconnectedTransaction parentId _ _) graph@(TransactionGraph _ transSet) = do
282 tupleMatrix <- mapM tupleGenerator (S.toList transSet)
283 mkRelationFromList attrs tupleMatrix
284 where
285 attrs = A.attributesFromList [Attribute "id" TextAtomType,
286 Attribute "stamp" DateTimeAtomType,
287 Attribute "parents" (RelationAtomType parentAttributes),
288 Attribute "current" BoolAtomType,
289 Attribute "head" TextAtomType
290 ]
291 parentAttributes = A.attributesFromList [Attribute "id" TextAtomType]
292 tupleGenerator transaction = case transactionParentsRelation transaction graph of
293 Left err -> Left err
294 Right parentTransRel -> Right [TextAtom $ T.pack $ show (transactionId transaction),
295 DateTimeAtom (transactionTimestamp transaction),
296 RelationAtom parentTransRel,
297 BoolAtom $ parentId == transactionId transaction,
298 TextAtom $ fromMaybe "" (headNameForTransaction transaction graph)
299 ]
301transactionParentsRelation :: Transaction -> TransactionGraph -> Either RelationalError Relation
302transactionParentsRelation trans graph =
303 if isRootTransaction trans graph then
304 mkRelation attrs emptyTupleSet
305 else do
306 parentTransSet <- parentTransactions trans graph
307 let tuples = map trans2tuple (S.toList parentTransSet)
308 mkRelationFromTuples attrs tuples
309 where
310 attrs = A.attributesFromList [Attribute "id" TextAtomType]
311 trans2tuple trans2 = mkRelationTuple attrs $ V.singleton (TextAtom (T.pack (show $ transactionId trans2)))
313{-
314--display transaction graph as relation
315evalROGraphOp :: DisconnectedTransaction -> TransactionGraph -> ROTransactionGraphOperator -> Either RelationalError Relation
316evalROGraphOp discon graph ShowGraph = do
317 graphRel <- graphAsRelation discon graph
318 return graphRel
319-}
321-- | Execute the merge strategy against the transactions, returning a new transaction which can be then added to the transaction graph
322createMergeTransaction :: UTCTime -> TransactionId -> MergeStrategy -> TransactionGraph -> (Transaction, Transaction) -> Either MergeError Transaction
323createMergeTransaction stamp newId (SelectedBranchMergeStrategy selectedBranch) graph t2@(trans1, trans2) = do
324 let selectedTrans = validateHeadName selectedBranch graph t2
325 Transaction newId (MergeTransactionInfo (transactionId trans1) (transactionId trans2) S.empty stamp) . schemas <$> selectedTrans
327-- merge functions, relvars, individually
328createMergeTransaction stamp newId strat@UnionMergeStrategy graph t2 = createUnionMergeTransaction stamp newId strat graph t2
330-- merge function, relvars, but, on error, just take the component from the preferred branch
331createMergeTransaction stamp newId strat@(UnionPreferMergeStrategy _) graph t2 = createUnionMergeTransaction stamp newId strat graph t2
333-- | Returns the correct Transaction for the branch name in the graph and ensures that it is one of the two transaction arguments in the tuple.
334validateHeadName :: HeadName -> TransactionGraph -> (Transaction, Transaction) -> Either MergeError Transaction
335validateHeadName headName graph (t1, t2) =
336 case transactionForHead headName graph of
337 Nothing -> Left SelectedHeadMismatchMergeError
338 Just trans -> if trans /= t1 && trans /= t2 then
339 Left SelectedHeadMismatchMergeError
340 else
341 Right trans
343-- Algorithm: start at one transaction and work backwards up the parents. If there is a node we have not yet visited as a child, then walk that up to its head. If that branch contains the goal transaction, then we have completed a valid subgraph traversal.
344subGraphOfFirstCommonAncestor :: TransactionGraph -> TransactionHeads -> Transaction -> Transaction -> S.Set Transaction -> Either RelationalError TransactionGraph
345subGraphOfFirstCommonAncestor origGraph resultHeads currentTrans goalTrans traverseSet = do
346 let currentid = transactionId currentTrans
347 goalid = transactionId goalTrans
348 if currentTrans == goalTrans then
349 Right (TransactionGraph resultHeads traverseSet) -- add filter
350 --catch root transaction to improve error?
351 else do
352 currentTransChildren <- S.fromList <$> mapM (`transactionForId` origGraph) (S.toList (transactionChildIds currentTrans))
353 let searchChildren = S.difference (S.insert currentTrans traverseSet) currentTransChildren
354 searchChild start = pathToTransaction origGraph start goalTrans (S.insert currentTrans traverseSet)
355 childSearches = map searchChild (S.toList searchChildren)
356 errors = lefts childSearches
357 pathsFound = rights childSearches
358 realErrors = filter (/= FailedToFindTransactionError goalid) errors
359 -- report any non-search-related errors
360 unless (null realErrors) (Left (head realErrors))
361 -- if no paths found, search the parent
362 if null pathsFound then
363 case oneParent currentTrans of
364 Left RootTransactionTraversalError -> Left (NoCommonTransactionAncestorError currentid goalid)
365 Left err -> Left err
366 Right currentTransParent ->
367 subGraphOfFirstCommonAncestor origGraph resultHeads currentTransParent goalTrans (S.insert currentTrans traverseSet)
368 else -- we found a path
369 Right (TransactionGraph resultHeads (S.unions (traverseSet : pathsFound)))
370 where
371 oneParent (Transaction _ (TransactionInfo parentId _ _) _) = transactionForId parentId origGraph
372 oneParent (Transaction _ (MergeTransactionInfo parentId _ _ _) _) = transactionForId parentId origGraph
374-- | Search from a past graph point to all following heads for a specific transaction. If found, return the transaction path, otherwise a RelationalError.
375pathToTransaction :: TransactionGraph -> Transaction -> Transaction -> S.Set Transaction -> Either RelationalError (S.Set Transaction)
376pathToTransaction graph currentTransaction targetTransaction accumTransSet = do
377 let targetId = transactionId targetTransaction
378 if transactionId targetTransaction == transactionId currentTransaction then
379 Right accumTransSet
380 else do
381 currentTransChildren <- mapM (`transactionForId` graph) (S.toList (transactionChildIds currentTransaction))
382 if null currentTransChildren then
383 Left (FailedToFindTransactionError targetId)
384 else do
385 let searches = map (\t -> pathToTransaction graph t targetTransaction (S.insert t accumTransSet)) currentTransChildren
386 let realErrors = filter (/= FailedToFindTransactionError targetId) (lefts searches)
387 paths = rights searches
388 if not (null realErrors) then -- found some real errors
389 Left (head realErrors)
390 else if null paths then -- failed to find transaction in all children
391 Left (FailedToFindTransactionError targetId)
392 else --we have some paths!
393 Right (S.unions paths)
395mergeTransactions :: UTCTime -> TransactionId -> TransactionId -> MergeStrategy -> (HeadName, HeadName) -> TransactionGraph -> Either RelationalError (DisconnectedTransaction, TransactionGraph)
396mergeTransactions stamp newId parentId mergeStrategy (headNameA, headNameB) graph = do
397 let transactionForHeadErr name = case transactionForHead name graph of
398 Nothing -> Left (NoSuchHeadNameError name)
399 Just t -> Right t
400 transA <- transactionForHeadErr headNameA
401 transB <- transactionForHeadErr headNameB
402 disconParent <- transactionForId parentId graph
403 let subHeads = M.filterWithKey (\k _ -> k `elem` [headNameA, headNameB]) (transactionHeadsForGraph graph)
404 subGraph <- subGraphOfFirstCommonAncestor graph subHeads transA transB S.empty
405 subGraph' <- filterSubGraph subGraph subHeads
406 case createMergeTransaction stamp newId mergeStrategy subGraph' (transA, transB) of
407 Left err -> Left (MergeTransactionError err)
408 Right mergedTrans -> case checkConstraints (concreteDatabaseContext mergedTrans) of
409 Left err -> Left err
410 Right _ -> case headNameForTransaction disconParent graph of
411 Nothing -> Left (TransactionIsNotAHeadError parentId)
412 Just headName -> do
413 (newTrans, newGraph) <- addTransactionToGraph headName mergedTrans graph
414 let newGraph' = TransactionGraph (transactionHeadsForGraph newGraph) (transactionsForGraph newGraph)
415 newDiscon = DisconnectedTransaction newId (schemas newTrans) False
416 pure (newDiscon, newGraph')
418--TEMPORARY COPY/PASTE
419showTransactionStructureX :: Transaction -> TransactionGraph -> String
420showTransactionStructureX trans graph = headInfo ++ " " ++ show (transactionId trans) ++ " " ++ parentTransactionsInfo
421 where
422 headInfo = maybe "" show (headNameForTransaction trans graph)
423 parentTransactionsInfo = if isRootTransaction trans graph then "root" else case parentTransactions trans graph of
424 Left err -> show err
425 Right parentTransSet -> concat $ S.toList $ S.map (show . transactionId) parentTransSet
427showGraphStructureX :: TransactionGraph -> String
428showGraphStructureX graph@(TransactionGraph heads transSet) = headsInfo ++ S.foldr folder "" transSet
429 where
430 folder trans acc = acc ++ showTransactionStructureX trans graph ++ "\n"
431 headsInfo = show $ M.map transactionId heads
433-- | After splicing out a subgraph, run it through this function to remove references to transactions which are not in the subgraph.
434filterSubGraph :: TransactionGraph -> TransactionHeads -> Either RelationalError TransactionGraph
435filterSubGraph graph heads = Right $ TransactionGraph newHeads newTransSet
436 where
437 validIds = S.map transactionId (transactionsForGraph graph)
438 newTransSet = S.map (filterTransaction validIds) (transactionsForGraph graph)
439 newHeads = M.map (filterTransaction validIds) heads
441--helper function for commonalities in union merge
442createUnionMergeTransaction :: UTCTime -> TransactionId -> MergeStrategy -> TransactionGraph -> (Transaction, Transaction) -> Either MergeError Transaction
443createUnionMergeTransaction stamp newId strategy graph (t1,t2) = do
444 let contextA = concreteDatabaseContext t1
445 contextB = concreteDatabaseContext t2
447 preference <- case strategy of
448 UnionMergeStrategy -> pure PreferNeither
449 UnionPreferMergeStrategy preferBranch ->
450 case transactionForHead preferBranch graph of
451 Nothing -> Left (PreferredHeadMissingMergeError preferBranch)
452 Just preferredTrans -> pure $ if t1 == preferredTrans then PreferFirst else PreferSecond
453 badStrat -> Left (InvalidMergeStrategyError badStrat)
455 incDeps <- unionMergeMaps preference (inclusionDependencies contextA) (inclusionDependencies contextB)
456 relVars <- unionMergeRelVars preference (relationVariables contextA) (relationVariables contextB)
457 atomFuncs <- unionMergeAtomFunctions preference (atomFunctions contextA) (atomFunctions contextB)
458 notifs <- unionMergeMaps preference (notifications contextA) (notifications contextB)
459 types <- unionMergeTypeConstructorMapping preference (typeConstructorMapping contextA) (typeConstructorMapping contextB)
460 dbcFuncs <- unionMergeDatabaseContextFunctions preference (dbcFunctions contextA) (dbcFunctions contextB)
461 -- TODO: add merge of subschemas
462 let newContext = DatabaseContext {
463 inclusionDependencies = incDeps,
464 relationVariables = relVars,
465 atomFunctions = atomFuncs,
466 dbcFunctions = dbcFuncs,
467 notifications = notifs,
468 typeConstructorMapping = types
469 }
470 newSchemas = Schemas newContext (subschemas t1)
471 pure (Transaction newId (MergeTransactionInfo (transactionId t1) (transactionId t2) S.empty stamp) newSchemas)
473lookupTransaction :: TransactionGraph -> TransactionIdLookup -> Either RelationalError Transaction
474lookupTransaction graph (TransactionIdLookup tid) = transactionForId tid graph
475lookupTransaction graph (TransactionIdHeadNameLookup headName backtracks) = case transactionForHead headName graph of
476 Nothing -> Left (NoSuchHeadNameError headName)
477 Just headTrans -> do
478 traversedId <- traverseGraph graph (transactionId headTrans) backtracks
479 transactionForId traversedId graph
481traverseGraph :: TransactionGraph -> TransactionId -> [TransactionIdHeadBacktrack] -> Either RelationalError TransactionId
482traverseGraph graph = foldM (backtrackGraph graph)
484backtrackGraph :: TransactionGraph -> TransactionId -> TransactionIdHeadBacktrack -> Either RelationalError TransactionId
485-- tilde, step back one parent link- if a choice must be made, choose the "first" link arbitrarily
486backtrackGraph graph currentTid (TransactionIdHeadParentBacktrack steps) = do
487 trans <- transactionForId currentTid graph
488 let parents = S.toAscList (transactionParentIds trans)
489 if length parents < 1 then
490 Left RootTransactionTraversalError
491 else do
492 parentTrans <- transactionForId (head parents) graph
493 if steps == 1 then
494 pure (transactionId parentTrans)
495 else
496 backtrackGraph graph (transactionId parentTrans) (TransactionIdHeadParentBacktrack (steps - 1))
498backtrackGraph graph currentTid (TransactionIdHeadBranchBacktrack steps) = do
499 trans <- transactionForId currentTid graph
500 let parents = transactionParentIds trans
501 if S.size parents < 1 then
502 Left RootTransactionTraversalError
503 else if S.size parents < steps then
504 Left (ParentCountTraversalError (S.size parents) steps)
505 else
506 pure (S.elemAt (steps - 1) parents)
508backtrackGraph graph currentTid btrack@(TransactionStampHeadBacktrack stamp) = do
509 trans <- transactionForId currentTid graph
510 let parents = transactionParentIds trans
511 if transactionTimestamp trans <= stamp then
512 pure currentTid
513 else if S.null parents then
514 Left RootTransactionTraversalError
515 else
516 let arbitraryParent = head (S.toList parents) in
517 backtrackGraph graph arbitraryParent btrack
519-- | Create a temporary branch for commit, merge the result to head, delete the temporary branch. This is useful to atomically commit a transaction, avoiding a TransactionIsNotHeadError but trading it for a potential MergeError.
520--this is not a GraphOp because it combines multiple graph operations
521autoMergeToHead :: UTCTime -> (TransactionId, TransactionId, TransactionId) -> DisconnectedTransaction -> HeadName -> MergeStrategy -> TransactionGraph -> Either RelationalError (DisconnectedTransaction, TransactionGraph)
522autoMergeToHead stamp (tempBranchTransId, tempCommitTransId, mergeTransId) discon mergeToHeadName strat graph = do
523 let tempBranchName = "mergebranch_" <> U.toText tempBranchTransId
524 --create the temp branch
525 (discon', graph') <- evalGraphOp stamp tempBranchTransId discon graph (Branch tempBranchName)
527 --commit to the new branch- possible future optimization: don't require fsync for this- create a temp commit type
528 (discon'', graph'') <- evalGraphOp stamp tempCommitTransId discon' graph' Commit
530 --jump to merge head
531 (discon''', graph''') <- evalGraphOp stamp tempBranchTransId discon'' graph'' (JumpToHead mergeToHeadName)
533 --create the merge
534 (discon'''', graph'''') <- evalGraphOp stamp mergeTransId discon''' graph''' (MergeTransactions strat tempBranchName mergeToHeadName)
536 --delete the temp branch
537 (discon''''', graph''''') <- evalGraphOp stamp tempBranchTransId discon'''' graph'''' (DeleteBranch tempBranchName)
538 {-
539 let rel = runReader (evalRelationalExpr (RelationVariable "s" ())) (mkRelationalExprState $ D.concreteDatabaseContext discon'''')
540 traceShowM rel
541-}
543 pure (discon''''', graph''''')