diff --git a/wallet/db.c b/wallet/db.c index 15929e608..da691dd3e 100644 --- a/wallet/db.c +++ b/wallet/db.c @@ -554,8 +554,15 @@ sqlite3_stmt *db_select_prepare_(const char *location, struct db *db, const char return stmt; } +static void db_stmt_free(struct db_stmt *stmt) +{ + if (stmt->inner_stmt) + stmt->db->config->stmt_free_fn(stmt); + assert(stmt->inner_stmt == NULL); +} + struct db_stmt *db_prepare_v2_(const char *location, struct db *db, - const char *query_id) + const char *query_id) { struct db_stmt *stmt = tal(db, struct db_stmt); size_t num_slots; @@ -586,12 +593,11 @@ struct db_stmt *db_prepare_v2_(const char *location, struct db *db, stmt->location = location; stmt->error = NULL; stmt->db = db; - return stmt; -} + stmt->inner_stmt = NULL; -void db_stmt_free(struct db_stmt *stmt) -{ - stmt->db->config->stmt_free_fn(stmt); + tal_add_destructor(stmt, db_stmt_free); + + return stmt; } #define db_prepare_v2(db,query) \ @@ -882,7 +888,7 @@ static void db_migrate(struct lightningd *ld, struct db *db, struct log *log) struct db_stmt *stmt = db_prepare_v2(db, dbmigrations[current].sql); db_exec_prepared_v2(stmt); - db_stmt_free(stmt); + tal_free(stmt); } if (dbmigrations[current].func) dbmigrations[current].func(ld, db); @@ -1281,7 +1287,7 @@ void migrate_pr2342_feerate_per_channel(struct lightningd *ld, struct db *db) db_bind_int(stmt, 1, ld->config.fee_per_satoshi); db_exec_prepared_v2(stmt); - db_stmt_free(stmt); + tal_free(stmt); } void sqlite3_bind_timeabs(sqlite3_stmt *stmt, int col, struct timeabs t) diff --git a/wallet/db.h b/wallet/db.h index 8a996d71b..bcd29b248 100644 --- a/wallet/db.h +++ b/wallet/db.h @@ -249,7 +249,6 @@ void db_bind_blob(struct db_stmt *stmt, int pos, u8 *val, size_t len); void db_bind_text(struct db_stmt *stmt, int pos, const char *val); bool db_exec_prepared_v2(struct db_stmt *stmt TAKES); -void db_stmt_free(struct db_stmt *stmt); struct db_stmt *db_prepare_v2_(const char *location, struct db *db, const char *query_id); diff --git a/wallet/db_sqlite3.c b/wallet/db_sqlite3.c index 645c5e9ed..fe2d68452 100644 --- a/wallet/db_sqlite3.c +++ b/wallet/db_sqlite3.c @@ -128,7 +128,7 @@ static void db_sqlite3_stmt_free(struct db_stmt *stmt) { if (stmt->inner_stmt) sqlite3_finalize(stmt->inner_stmt); - tal_free(stmt); + stmt->inner_stmt = NULL; } struct db_config db_sqlite3_config = {