src/Connection.cpp
branchv_0
changeset 27 9441a517fa1f
parent 26 49919a60c747
child 29 b0ef1e1dc9c8
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Connection.cpp	Wed Dec 25 01:07:41 2019 +0100
@@ -0,0 +1,69 @@
+/**
+ * Relational pipes
+ * Copyright © 2019 František Kučera (Frantovo.cz, GlobalCode.info)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, version 3.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "Connection.h"
+
+namespace relpipe {
+namespace tr {
+namespace sql {
+
+void Connection::begin() {
+	sqlite3_exec(db, "BEGIN", nullptr, nullptr, nullptr);
+}
+
+Connection::Connection(const char* filename) {
+	int result = sqlite3_open(filename, &db);
+	if (result != SQLITE_OK) {
+		sqlite3_close(db);
+		throw SqlException(L"Unable to open SQLite database.");
+	}
+	begin();
+}
+
+Connection::~Connection() {
+	sqlite3_close(db);
+}
+
+PreparedStatement* Connection::prepareStatement(const char* sql) {
+	const char* remaining;
+	sqlite3_stmt *stmt;
+	int result = sqlite3_prepare(db, sql, -1, &stmt, &remaining);
+	if (result == SQLITE_OK) return new PreparedStatement(stmt);
+	else throw SqlException(L"Unable to prepare SQLite statement.");
+}
+
+bool Connection::getAutoCommit() {
+	return sqlite3_get_autocommit(db);
+}
+
+void Connection::setAutoCommit(bool autoCommit) {
+	bool autoCommitOld = getAutoCommit();
+	if (autoCommit && !autoCommitOld) commit();
+	else if (!autoCommit && autoCommitOld) begin();
+}
+
+void Connection::commit() {
+	sqlite3_exec(db, "COMMIT", nullptr, nullptr, nullptr);
+}
+
+void Connection::rollback() {
+	sqlite3_exec(db, "ROLLBACK", nullptr, nullptr, nullptr);
+}
+
+}
+}
+}