From 460299850fc14289af795b005ecb05ba58c207e4 Mon Sep 17 00:00:00 2001 From: Christian Decker Date: Tue, 20 Aug 2019 19:38:09 +0200 Subject: [PATCH] db: Add DB-specific db_last_insert_id This is likely the last part we need to completely encapsulate the part of the sqlite3 API that we were using. Like the `db_count_changes` call I decided to pass in the `struct db_stmt` since really they refer to the statement that was executed and not the db. Signed-off-by: Christian Decker --- wallet/db.c | 11 +++++++++++ wallet/db.h | 1 + wallet/db_common.h | 1 + wallet/db_sqlite3.c | 7 +++++++ 4 files changed, 20 insertions(+) diff --git a/wallet/db.c b/wallet/db.c index 399dc4bee..5e62f918c 100644 --- a/wallet/db.c +++ b/wallet/db.c @@ -645,6 +645,17 @@ size_t db_count_changes(struct db_stmt *stmt) return stmt->db->config->count_changes_fn(stmt); } +u64 db_last_insert_id_v2(struct db_stmt *stmt TAKES) +{ + u64 id; + id = stmt->db->config->last_insert_id_fn(stmt); + + if (taken(stmt)) + tal_free(stmt); + + return id; +} + bool db_select_step_(const char *location, struct db *db, struct sqlite3_stmt *stmt) { int ret; diff --git a/wallet/db.h b/wallet/db.h index 1dd746813..6e2f113dd 100644 --- a/wallet/db.h +++ b/wallet/db.h @@ -313,6 +313,7 @@ void db_close(struct db *db); bool db_exec_prepared_v2(struct db_stmt *stmt TAKES); bool db_query_prepared(struct db_stmt *stmt); size_t db_count_changes(struct db_stmt *stmt); +u64 db_last_insert_id_v2(struct db_stmt *stmt); struct db_stmt *db_prepare_v2_(const char *location, struct db *db, const char *query_id); #define db_prepare_v2(db,query) \ diff --git a/wallet/db_common.h b/wallet/db_common.h index 9fbae2790..bfc89a5b6 100644 --- a/wallet/db_common.h +++ b/wallet/db_common.h @@ -123,6 +123,7 @@ struct db_config { const unsigned char *(*column_text_fn)(struct db_stmt *stmt, int col); s64 (*column_int_fn)(struct db_stmt *stmt, int col); + u64 (*last_insert_id_fn)(struct db_stmt *stmt); size_t (*count_changes_fn)(struct db_stmt *stmt); bool (*setup_fn)(struct db *db); diff --git a/wallet/db_sqlite3.c b/wallet/db_sqlite3.c index 484dde743..94194843c 100644 --- a/wallet/db_sqlite3.c +++ b/wallet/db_sqlite3.c @@ -188,6 +188,12 @@ static void db_sqlite3_close(struct db *db) sqlite3_close(db->sql); } +static u64 db_sqlite3_last_insert_id(struct db_stmt *stmt) +{ + sqlite3 *s = stmt->db->conn; + return sqlite3_last_insert_rowid(s); +} + struct db_config db_sqlite3_config = { .name = "sqlite3", .queries = db_sqlite3_queries, @@ -207,6 +213,7 @@ struct db_config db_sqlite3_config = { .column_blob_fn = &db_sqlite3_column_blob, .column_text_fn = &db_sqlite3_column_text, + .last_insert_id_fn = &db_sqlite3_last_insert_id, .count_changes_fn = &db_sqlite3_count_changes, .setup_fn = &db_sqlite3_setup, .teardown_fn = &db_sqlite3_close,