sqlite: separate DB migration from constructor

This is a slightly modified version of darosior's commit:
d826f9fa6336de6eb293a85af044c2c95550cfb5
This commit is contained in:
Antoine Poinsot 2024-07-29 18:07:53 +02:00 committed by jp1ac4
parent 50e7ffafa4
commit ba4c819918
No known key found for this signature in database
GPG Key ID: C61FA2110D7DC407
2 changed files with 14 additions and 5 deletions

View File

@ -140,6 +140,7 @@ pub struct SqliteDb {
impl SqliteDb {
/// Instanciate an SQLite database either from an existing database file or by creating a fresh
/// one.
/// NOTE: don't forget to apply any migration with `maybe_apply_migration` if necessary.
pub fn new(
db_path: path::PathBuf,
fresh_options: Option<FreshDbOptions>,
@ -155,11 +156,15 @@ impl SqliteDb {
}
log::info!("Checking if the database needs upgrading.");
maybe_apply_migration(&db_path)?;
Ok(SqliteDb { db_path })
}
/// If the database version is older than expected, migrate it to the current version.
pub fn maybe_apply_migrations(&self) -> Result<(), SqliteDbError> {
maybe_apply_migration(&self.db_path)
}
/// Get a new connection to the database.
pub fn connection(&self) -> Result<SqliteConn, SqliteDbError> {
let conn = rusqlite::Connection::open(&self.db_path)?;
@ -957,9 +962,13 @@ CREATE TABLE labels (
// TODO: version check
let db = SqliteDb::new(db_path.clone(), Some(options.clone()), &secp).unwrap();
db.sanity_check(bitcoin::Network::Bitcoin, &options.main_descriptor)
.unwrap();
let db = SqliteDb::new(db_path.clone(), None, &secp).unwrap();
db.sanity_check(bitcoin::Network::Bitcoin, &options.main_descriptor)
.unwrap();
let db = SqliteDb::new(db_path, None, &secp).unwrap();
db.maybe_apply_migrations().unwrap();
db.sanity_check(bitcoin::Network::Bitcoin, &options.main_descriptor)
.unwrap();
@ -2231,10 +2240,7 @@ CREATE TABLE labels (
create_fresh_db(&db_path, options, &secp).unwrap();
{
// Don't use SqliteDb::new() in order not to apply migration.
let db = SqliteDb {
db_path: db_path.clone(),
};
let db = SqliteDb::new(db_path.clone(), None, &secp).unwrap();
let mut conn = db.connection().unwrap();
assert!(conn.db_version() == 3);
@ -2423,6 +2429,7 @@ CREATE TABLE labels (
// SqliteDb new is doing the migration.
let db = SqliteDb::new(db_path, None, &secp).unwrap();
db.maybe_apply_migrations().unwrap();
{
let mut conn = db.connection().unwrap();

View File

@ -196,7 +196,9 @@ fn setup_sqlite(
} else {
None
};
let sqlite = SqliteDb::new(db_path, options, secp)?;
sqlite.maybe_apply_migrations()?;
sqlite.sanity_check(config.bitcoin_config.network, &config.main_descriptor)?;
log::info!("Database initialized and checked.");