Skip to content

Instantly share code, notes, and snippets.

@beeb
Created November 4, 2023 13:06
Show Gist options
  • Save beeb/ae63e77ff33447ead545da2e43a9eb42 to your computer and use it in GitHub Desktop.
Save beeb/ae63e77ff33447ead545da2e43a9eb42 to your computer and use it in GitHub Desktop.
Build script to initialize dev db in sqlx project
use std::str::FromStr;
use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode},
SqlitePool,
};
use tokio::runtime::Builder;
fn main() {
let database_url = std::env::var("DATABASE_URL").unwrap_or("sqlite://dev.db".to_string());
let options = SqliteConnectOptions::from_str(&database_url)
.expect("Error parsing database URL")
.create_if_missing(true)
.journal_mode(SqliteJournalMode::Wal);
let rt = Builder::new_current_thread()
.worker_threads(1)
.enable_time()
.build()
.unwrap();
rt.block_on(async move {
connect(options).await;
});
}
async fn connect(options: SqliteConnectOptions) {
let pool = SqlitePool::connect_with(options)
.await
.expect("Error connecting to database");
migrate(&pool).await;
}
async fn migrate(pool: &SqlitePool) {
sqlx::migrate!()
.run(pool)
.await
.expect("Error when applying database migrations");
}
@beeb
Copy link
Author

beeb commented Nov 4, 2023

This was added in the Cargo.toml:

[build-dependencies]
sqlx = { version = "0.7", features = [
  "sqlite",
] }
tokio = { version = "1", features = [
  "rt",
] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment