#include "stdafx.h"
#include "Transaction.h"
#include "SQL.h"

namespace sql {

	static const Transaction::End endDone = Transaction::End(-1); // Sentinel value.

	Transaction::Transaction(DBConnection *c) : state(new (c) State(c, endRollback)) {}

	Transaction::Transaction(DBConnection *c, End end) : state(new (c) State(c, end)) {}

	Transaction::~Transaction() {
		state->unref();
	}

	Transaction::Transaction(const Transaction &other) : state(other.state) {
		state->ref();
	}

	Transaction &Transaction::operator =(const Transaction &other) {
		other.state->ref();
		state->unref();
		state = other.state;
		return *this;
	}

	void Transaction::commit() {
		state->commit();
	}

	void Transaction::rollback() {
		state->rollback();
	}


	/**
	 * State.
	 */

	Transaction::State::State(DBConnection *c, End end) : connection(c), parent(c->transaction), end(end), refs(1) {
		c->transaction = this;
		if (parent == null)
			c->beginTransaction();
	}

	void Transaction::State::finish() {
		if (connection == null)
			return;

		if (connection->transaction == this) {
			connection->transaction = parent;

			if (parent == null && end != endNothing && end != endDone)
				connection->endTransaction(end);
		}

		connection = null;
		end = endDone;
	}

	void Transaction::State::commit() {
		if (end != endDone) {
			end = endDone;
			connection->endTransaction(endCommit);
		}
	}

	void Transaction::State::rollback() {
		if (end != endDone) {
			end = endDone;
			connection->endTransaction(endRollback);
		}
	}

}
