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

sqlite: Flush precompiled statements cache when closing connection

parent 21f72b5a
......@@ -35,6 +35,11 @@ SqliteConnection::SqliteConnection( const std::string &dbPath )
throw std::runtime_error( "Failed to enable sqlite multithreaded mode" );
}
SqliteConnection::~SqliteConnection()
{
sqlite::Statement::FlushStatementCache();
}
SqliteConnection::Handle SqliteConnection::getConn()
{
std::unique_lock<std::mutex> lock( m_connMutex );
......
......@@ -45,6 +45,7 @@ public:
using Handle = sqlite3*;
explicit SqliteConnection( const std::string& dbPath );
~SqliteConnection();
// Returns the current thread's connection
// This will initiate a connection if required
Handle getConn();
......
......@@ -24,5 +24,8 @@
namespace sqlite
{
thread_local std::unordered_map<std::string, Statement::CachedStmtPtr> Statement::StatementsCache;
std::unordered_map<SqliteConnection::Handle,
std::unordered_map<std::string, Statement::CachedStmtPtr>> Statement::StatementsCache;
std::mutex Statement::StatementsCacheLock;
}
......@@ -107,8 +107,10 @@ public:
, m_req( req )
, m_bindIdx( 0 )
{
auto it = StatementsCache.find( req );
if ( it == end( StatementsCache ) )
std::lock_guard<std::mutex> lock( StatementsCacheLock );
auto& connMap = StatementsCache[ dbConnection ];
auto it = connMap.find( req );
if ( it == end( connMap ) )
{
sqlite3_stmt* stmt;
int res = sqlite3_prepare_v2( dbConnection, req.c_str(), -1, &stmt, NULL );
......@@ -118,7 +120,7 @@ public:
sqlite3_errmsg( dbConnection ) );
}
m_stmt.reset( stmt );
StatementsCache.emplace( req, CachedStmtPtr( stmt, &sqlite3_finalize ) );
connMap.emplace( req, CachedStmtPtr( stmt, &sqlite3_finalize ) );
}
else
{
......@@ -153,6 +155,12 @@ public:
}
}
static void FlushStatementCache()
{
std::lock_guard<std::mutex> lock( StatementsCacheLock );
StatementsCache.clear();
}
private:
template <typename T>
bool _bind( T&& value )
......@@ -171,7 +179,9 @@ private:
SqliteConnection::Handle m_dbConn;
std::string m_req;
unsigned int m_bindIdx;
static thread_local std::unordered_map<std::string, CachedStmtPtr> StatementsCache;
static std::mutex StatementsCacheLock;
static std::unordered_map<SqliteConnection::Handle,
std::unordered_map<std::string, CachedStmtPtr>> StatementsCache;
};
class Tools
......
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