feat: set up basic database migration

image-uploads
Jef Roosens 2024-12-28 10:36:13 +01:00
commit a410e4f9ec
No known key found for this signature in database
GPG Key ID: 21FD3D77D56BAF49
6 changed files with 1134 additions and 0 deletions

1
.gitignore vendored 100644
View File

@ -0,0 +1 @@
/target

1063
Cargo.lock generated 100644

File diff suppressed because it is too large Load Diff

11
Cargo.toml 100644
View File

@ -0,0 +1,11 @@
[package]
name = "calathea"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.7.9"
chrono = "0.4.39"
r2d2 = "0.8.10"
r2d2_sqlite = "0.25.0"
tokio = { version = "1.42.0", features = ["full"] }

BIN
db.sqlite 100644

Binary file not shown.

55
src/main.rs 100644
View File

@ -0,0 +1,55 @@
use r2d2_sqlite::{rusqlite, SqliteConnectionManager};
pub type DbPool = r2d2::Pool<SqliteConnectionManager>;
const MIGRATIONS: [&str; 1] = [include_str!("migrations/000_initial.sql")];
#[tokio::main]
async fn main() {
let manager = SqliteConnectionManager::file("db.sqlite");
let pool = r2d2::Pool::new(manager).unwrap();
run_migrations(&pool, true).unwrap();
}
fn run_migrations(pool: &DbPool, new: bool) -> rusqlite::Result<()> {
let mut conn = pool.get().unwrap();
// Run very first migration
if new {
let tx = conn.transaction()?;
tx.execute(MIGRATIONS[0], ())?;
let cur_time = chrono::Local::now().timestamp();
tx.execute(
"insert into migration_version values ($1, $2)",
[0, cur_time],
)?;
tx.commit()?;
}
let mut next_version = conn.query_row(
"select version from migration_version order by updated_at desc limit 1",
(),
|row| row.get::<_, usize>(0),
)? + 1;
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()?;
next_version += 1;
}
Ok(())
}

View File

@ -0,0 +1,4 @@
create table migration_version (
version integer,
updated_at integer
);