Created
November 4, 2023 13:06
-
-
Save beeb/ae63e77ff33447ead545da2e43a9eb42 to your computer and use it in GitHub Desktop.
Build script to initialize dev db in sqlx project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was added in the
Cargo.toml
: