Commit e45402a4 authored by Hugo Beauzée-Luyssen's avatar Hugo Beauzée-Luyssen

SqliteConnection: Ensure no connection is left behind

parent 8cfdd93a
......@@ -2,8 +2,6 @@
#include "database/SqliteTools.h"
thread_local sqlite3* dbConnection;
SqliteConnection::SqliteConnection( const std::string &dbPath )
: m_dbPath( dbPath )
{
......@@ -15,7 +13,10 @@ SqliteConnection::SqliteConnection( const std::string &dbPath )
sqlite3 *SqliteConnection::getConn()
{
if ( dbConnection == nullptr )
std::unique_lock<std::mutex> lock( m_connMutex );
sqlite3* dbConnection;
auto it = m_conns.find( std::this_thread::get_id() );
if ( it == end( m_conns ) )
{
auto res = sqlite3_open( m_dbPath.c_str(), &dbConnection );
if ( res != SQLITE_OK )
......@@ -23,17 +24,17 @@ sqlite3 *SqliteConnection::getConn()
res = sqlite3_busy_timeout( dbConnection, 500 );
if ( res != SQLITE_OK )
LOG_WARN( "Failed to enable sqlite busy timeout" );
m_conns.emplace(std::this_thread::get_id(), ConnPtr( dbConnection, &sqlite3_close ) );
lock.unlock();
if ( sqlite::Tools::executeRequest( this, "PRAGMA foreign_keys = ON" ) == false )
throw std::runtime_error( "Failed to enable foreign keys" );
std::unique_lock<std::mutex> lock( m_connMutex );
m_conns.emplace(std::this_thread::get_id(), ConnPtr( dbConnection, &sqlite3_close ) );
return dbConnection;
}
return dbConnection;
return it->second.get();
}
void SqliteConnection::release()
{
std::unique_lock<std::mutex> lock( m_connMutex );
m_conns.erase( std::this_thread::get_id() );
dbConnection = nullptr;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment