@@ -377,6 +377,12 @@ void SQLiteDatabase::Close()
377
377
m_db = nullptr ;
378
378
}
379
379
380
+ bool SQLiteDatabase::HasActiveTxn ()
381
+ {
382
+ // 'sqlite3_get_autocommit' returns true by default, and false if a transaction has begun and not been committed or rolled back.
383
+ return m_db && sqlite3_get_autocommit (m_db) == 0 ;
384
+ }
385
+
380
386
int SQliteExecHandler::Exec (SQLiteDatabase& database, const std::string& statement)
381
387
{
382
388
return sqlite3_exec (database.m_db , statement.data (), nullptr , nullptr , nullptr );
@@ -399,8 +405,8 @@ SQLiteBatch::SQLiteBatch(SQLiteDatabase& database)
399
405
400
406
void SQLiteBatch::Close ()
401
407
{
402
- // If m_db is in a transaction (i.e. not in autocommit mode), then abort the transaction in progress
403
- if (m_database.m_db && sqlite3_get_autocommit (m_database. m_db ) == 0 ) {
408
+ // If we began a transaction, and it wasn't committed, abort the transaction in progress
409
+ if (m_database.HasActiveTxn () ) {
404
410
if (TxnAbort ()) {
405
411
LogPrintf (" SQLiteBatch: Batch closed unexpectedly without the transaction being explicitly committed or aborted\n " );
406
412
} else {
@@ -611,7 +617,7 @@ std::unique_ptr<DatabaseCursor> SQLiteBatch::GetNewPrefixCursor(Span<const std::
611
617
612
618
bool SQLiteBatch::TxnBegin ()
613
619
{
614
- if (!m_database.m_db || sqlite3_get_autocommit ( m_database.m_db ) == 0 ) return false ;
620
+ if (!m_database.m_db || m_database.HasActiveTxn () ) return false ;
615
621
int res = Assert (m_exec_handler)->Exec (m_database, " BEGIN TRANSACTION" );
616
622
if (res != SQLITE_OK) {
617
623
LogPrintf (" SQLiteBatch: Failed to begin the transaction\n " );
@@ -621,7 +627,7 @@ bool SQLiteBatch::TxnBegin()
621
627
622
628
bool SQLiteBatch::TxnCommit ()
623
629
{
624
- if (!m_database.m_db || sqlite3_get_autocommit (m_database. m_db ) != 0 ) return false ;
630
+ if (!m_database.HasActiveTxn () ) return false ;
625
631
int res = Assert (m_exec_handler)->Exec (m_database, " COMMIT TRANSACTION" );
626
632
if (res != SQLITE_OK) {
627
633
LogPrintf (" SQLiteBatch: Failed to commit the transaction\n " );
@@ -631,7 +637,7 @@ bool SQLiteBatch::TxnCommit()
631
637
632
638
bool SQLiteBatch::TxnAbort ()
633
639
{
634
- if (!m_database.m_db || sqlite3_get_autocommit (m_database. m_db ) != 0 ) return false ;
640
+ if (!m_database.HasActiveTxn () ) return false ;
635
641
int res = Assert (m_exec_handler)->Exec (m_database, " ROLLBACK TRANSACTION" );
636
642
if (res != SQLITE_OK) {
637
643
LogPrintf (" SQLiteBatch: Failed to abort the transaction\n " );
0 commit comments