refactor: some lil things

This commit is contained in:
Jef Roosens 2025-01-05 12:48:07 +01:00
parent cc69935a88
commit 1bc9ae01d8
Signed by: Jef Roosens
GPG key ID: 21FD3D77D56BAF49
4 changed files with 43 additions and 43 deletions

View file

@ -45,3 +45,35 @@ impl From<rusqlite::Error> for DbError {
Self::Db(value)
}
}
pub fn run_migrations(pool: &DbPool, migrations: &[&str]) -> rusqlite::Result<()> {
let mut conn = pool.get().unwrap();
// If the migration version query fails, we assume it's because the table isn't there yet so we
// try to run the first migration
let mut next_version = conn
.query_row("select max(version) from migration_version", (), |row| {
row.get::<_, usize>(0).map(|n| n + 1)
})
.unwrap_or(0);
while next_version < migrations.len() {
let tx = conn.transaction()?;
tx.execute(migrations[next_version], ())?;
let cur_time = chrono::Local::now().timestamp();
tx.execute(
"insert into migration_version values ($1, $2)",
(next_version, cur_time),
)?;
tx.commit()?;
tracing::info!("Applied migration {next_version}");
next_version += 1;
}
Ok(())
}

View file

@ -11,6 +11,13 @@ pub struct Plant {
description: String,
}
#[derive(Deserialize)]
pub struct NewPlant {
name: String,
species: String,
description: String,
}
impl Plant {
pub fn from_row(row: &Row<'_>) -> Result<Self, rusqlite::Error> {
Ok(Self {
@ -30,7 +37,7 @@ impl Plant {
Ok(plants?)
}
pub fn with_id(pool: &DbPool, id: i32) -> Result<Option<Self>, DbError> {
pub fn by_id(pool: &DbPool, id: i32) -> Result<Option<Self>, DbError> {
let conn = pool.get()?;
let mut stmt = conn.prepare("select * from plants where id = $1")?;
@ -50,13 +57,6 @@ impl Plant {
}
}
#[derive(Deserialize)]
pub struct NewPlant {
name: String,
species: String,
description: String,
}
impl NewPlant {
pub fn insert(self, pool: &DbPool) -> Result<Plant, DbError> {
let conn = pool.get()?;