#9 TI-1: Use Transaction and UndoAction in Database

- Add toString-Methods to Transaction and UndoAction
This commit is contained in:
Thomas Lauf 2018-07-18 21:09:07 +02:00
parent 2fdc3eba4a
commit f031bd9d22
6 changed files with 35 additions and 8 deletions

View file

@ -176,7 +176,9 @@ void Database::modifyInterval (const Interval& from, const Interval& to)
void Database::undoTxnStart ()
{
if (_txn == 0)
_undo.push_back ("txn:");
{
_currentTransaction = std::make_shared <Transaction> ();
}
++_txn;
}
@ -191,18 +193,20 @@ void Database::undoTxnEnd ()
if (_txn == 0)
{
File undo (_location + "/undo.data");
if (undo.open ())
{
for (auto& line : _undo)
undo.append (line + "\n");
undo.append (_currentTransaction->toString());
undo.close ();
_undo.clear ();
_currentTransaction.reset ();
}
else
{
throw format ("Unable to write the undo transaction to {1}", undo._data);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Record undoable transactions. There are several types:
@ -213,9 +217,7 @@ void Database::undoTxn (
const std::string& before,
const std::string& after)
{
_undo.push_back (" type: " + type);
_undo.push_back (" before: " + before);
_undo.push_back (" after: " + after);
_currentTransaction->addUndoAction (type, before, after);
}
////////////////////////////////////////////////////////////////////////////////

View file

@ -30,6 +30,7 @@
#include <Datafile.h>
#include <Interval.h>
#include <Range.h>
#include <Transaction.h>
#include <vector>
#include <string>
@ -62,8 +63,9 @@ private:
private:
std::string _location {"~/.timewarrior/data"};
std::vector <Datafile> _files {};
std::vector <std::string> _undo {};
int _txn {0};
std::shared_ptr <Transaction> _currentTransaction = nullptr;
};
#endif

View file

@ -34,3 +34,15 @@ void Transaction::addUndoAction (
{
_actions.emplace_back (type, before, after);
}
std::string Transaction::toString ()
{
std::string output = "txn:\n";
for (auto& action : _actions)
{
output += action.toString ();
}
return output;
}

View file

@ -35,6 +35,8 @@ class Transaction
public:
void addUndoAction(const std::string&, const std::string&, const std::string&);
std::string toString();
private:
std::vector<UndoAction> _actions {};
};

View file

@ -35,3 +35,10 @@ UndoAction::UndoAction (
_before = before;
_after = after;
}
std::string UndoAction::toString ()
{
return " type: " + _type + "\n" +
" before: " + _before + "\n" +
" after: " + _after + "\n";
}

View file

@ -34,6 +34,8 @@ class UndoAction
public:
UndoAction(const std::string&, const std::string&, const std::string&);
std::string toString ();
private:
std::string _type;
std::string _before;