Zserio C++17 runtime library 1.3.0
Built for Zserio 2.20.0
Loading...
Searching...
No Matches
SqliteConnection.h
Go to the documentation of this file.
1#ifndef ZSERIO_SQL_CONNECTION_H_INC
2#define ZSERIO_SQL_CONNECTION_H_INC
3
4#include <memory>
5#include <string_view>
6
9
10#include "sqlite3.h"
11
12namespace zserio
13{
14
21{
22public:
31
38 explicit SqliteConnection(
40
45
52
63 void reset(sqlite3* connection = nullptr, ConnectionType connectionType = INTERNAL_CONNECTION);
64
73
80
86 void executeUpdate(std::string_view sqlQuery);
87
97 sqlite3_stmt* prepareStatement(std::string_view sqlQuery);
98
104 bool startTransaction();
105
123
124private:
125 sqlite3* m_connection;
126 ConnectionType m_connectionType;
127};
128
130 m_connection(connection),
131 m_connectionType(connectionType)
132{}
133
138
140{
141 // close connection only if it is internal
142 if (m_connectionType == INTERNAL_CONNECTION)
143 {
144 sqlite3_close_v2(m_connection); // sqlite3_close_v2(NULL) is a harmless no-op
145 }
146
147 m_connection = connection;
148 m_connectionType = connectionType;
149}
150
152{
153 return m_connectionType;
154}
155
157{
158 return m_connection;
159}
160
161inline void SqliteConnection::executeUpdate(std::string_view sqlQuery)
162{
163 std::unique_ptr<sqlite3_stmt, SqliteFinalizer> statement(prepareStatement(sqlQuery));
164 int result = sqlite3_step(statement.get());
165 if (result != SQLITE_DONE)
166 {
167 throw SqliteException("SqliteConnection::executeUpdate(): sqlite3_step failed: ")
169 }
170}
171
173{
174 sqlite3_stmt* statement = nullptr;
175 const int result = sqlite3_prepare_v2(
176 m_connection, sqlQuery.data(), static_cast<int>(sqlQuery.size()), &statement, nullptr);
177 if (result != SQLITE_OK)
178 {
179 throw SqliteException("SqliteConnection::prepareStatement(): sqlite3_prepare_v2() failed: ")
181 }
182
183 return statement;
184}
185
187{
188 bool wasTransactionStarted = false;
189 if (sqlite3_get_autocommit(m_connection) != 0)
190 {
191 executeUpdate("BEGIN;");
193 }
194
196}
197
199{
201 {
202 executeUpdate("COMMIT;");
203 }
204}
205
206} // namespace zserio
207
208#endif // ZSERIO_SQL_CONNECTION_H_INC
SqliteConnection & operator=(const SqliteConnection &)=delete
SqliteConnection(SqliteConnection &&)=delete
SqliteConnection(const SqliteConnection &)=delete
SqliteConnection & operator=(SqliteConnection &&)=delete
SqliteConnection(sqlite3 *connection=nullptr, ConnectionType connectionType=INTERNAL_CONNECTION)
sqlite3_stmt * prepareStatement(std::string_view sqlQuery)
ConnectionType getConnectionType() const
void endTransaction(bool wasTransactionStarted)
void executeUpdate(std::string_view sqlQuery)
void reset(sqlite3 *connection=nullptr, ConnectionType connectionType=INTERNAL_CONNECTION)