feat: set up basic database migration
commit
a410e4f9ec
|
@ -0,0 +1 @@
|
|||
/target
|
File diff suppressed because it is too large
Load Diff
|
@ -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"] }
|
|
@ -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(())
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
create table migration_version (
|
||||
version integer,
|
||||
updated_at integer
|
||||
);
|
Loading…
Reference in New Issue