Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions sqlwriter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,16 @@ void MiniSQLite::cycle()
exec("commit;begin");
}

MiniSQLite::lock_guard::lock_guard(MiniSQLite& dt) : d_target(dt)
{
sqlite3_mutex_enter(sqlite3_db_mutex(d_target.d_sqlite));
}

MiniSQLite::lock_guard::~lock_guard()
{
sqlite3_mutex_leave(sqlite3_db_mutex(d_target.d_sqlite));
}

bool MiniSQLite::haveTable(const string& table)
{
return !getSchema(table).empty();
Expand Down Expand Up @@ -269,7 +279,7 @@ void SQLiteWriter::commitThread()
while(!d_pleasequit) {
usleep(50000);
if(!(n%20)) {
std::lock_guard<std::mutex> lock(d_mutex);
MiniSQLite::lock_guard lock(d_db);
d_db.cycle();
}
n++;
Expand Down Expand Up @@ -322,7 +332,7 @@ void SQLiteWriter::addValueGeneric(const std::string& table, const T& values, bo
if(d_flag == SQLWFlag::ReadOnly)
throw std::runtime_error("Attempting to write to a read-only database instance");

std::lock_guard<std::mutex> lock(d_mutex);
MiniSQLite::lock_guard lock(d_db);
if(!d_db.isPrepared(table) || d_lastreplace[table] != replace || !equal(values.begin(), values.end(),
d_lastsig[table].cbegin(), d_lastsig[table].cend(),
[](const auto& a, const auto& b)
Expand Down Expand Up @@ -418,7 +428,7 @@ vector<std::unordered_map<string, MiniSQLite::outvar_t>> SQLiteWriter::queryGen(
if(msec && d_flag != SQLWFlag::ReadOnly)
throw std::runtime_error("Timeout only possible for read-only connections");

std::lock_guard<std::mutex> lock(d_mutex);
MiniSQLite::lock_guard lock(d_db);
d_db.prepare("", q); // we use an empty table name so as not to collide with other things
int n = 1;
for(const auto& p : values) {
Expand Down
9 changes: 7 additions & 2 deletions sqlwriter.hh
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
#include <vector>
#include <unordered_map>
#include <variant>
#include <mutex>
#include <thread>
#include <iostream>
#include <map>
Expand Down Expand Up @@ -50,6 +49,13 @@ public:
return iter->second != nullptr;
}

struct lock_guard {
lock_guard(MiniSQLite&);
~lock_guard();
private:
MiniSQLite& d_target;
};

private:
sqlite3* d_sqlite;
std::unordered_map<std::string, sqlite3_stmt*> d_stmts;
Expand Down Expand Up @@ -112,7 +118,6 @@ private:
void commitThread();
bool d_pleasequit{false};
std::optional<std::thread> d_thread;
std::mutex d_mutex;
MiniSQLite d_db;
SQLWFlag d_flag{SQLWFlag::NoFlag};
std::unordered_map<std::string, std::vector<std::pair<std::string, std::string>>> d_columns;
Expand Down