added database_pool crate, for pool handling and migrations

This commit is contained in:
Philippe Loctaux 2023-02-27 14:36:48 +01:00
parent 27d02a0d5c
commit f60eb616d3
11 changed files with 197 additions and 0 deletions

View file

@ -0,0 +1,8 @@
[package]
name = "database_pool"
version = "0.0.0"
edition = "2021"
[dependencies.sqlx]
workspace = true
features = ["sqlite", "migrate", "runtime-tokio-rustls"]

View file

@ -0,0 +1,50 @@
//! # Initialize database pool connection
//!
//! ```
//! use database_pool::Pool;
//!
//! # async fn get_database() {
//! let database = Pool::init("/path/to/database.sqlite").await.expect("Failed to init pool");
//!
//! // Close pool
//! database.close().await;
//! # }
//! ```
//!
//! # Run migrations to pool
//!
//! ```
//! use database_pool::Pool;
//! use database_pool::run_migrations;
//!
//! # async fn migrations() {
//! # let database = Pool::init("/path/to/database.sqlite").await.unwrap();
//! run_migrations(&database.pool).await.expect("Failed to run migrations");
//! # }
//! ```
//!
//! # Run transaction on database
//!
//! ```
//! use database_pool::Pool;
//!
//! # async fn run_transaction() {
//! # let database = Pool::init("/path/to/database.sqlite").await.unwrap();
//! // Start transaction
//! let mut transaction = database.pool.begin().await.expect("Failed to start transaction");
//!
//! // Run functions requiring database
//!
//! // Commit transaction
//! transaction.commit().await.expect("Failed to commit transaction");
//!
//! // Do what you need :)
//!
//! # }
//! ```
mod migrations;
mod pool;
pub use migrations::run_migrations;
pub use pool::Pool;

View file

@ -0,0 +1,15 @@
use sqlx::migrate::MigrateError;
use sqlx::{Pool, Sqlite};
pub async fn run_migrations(pool: &Pool<Sqlite>) -> Result<(), MigrateError> {
match sqlx::migrate!("../database").run(pool).await {
Ok(ok) => {
println!("Migrations are OK");
Ok(ok)
}
Err(e) => {
eprintln!("Failed to run migrations!");
Err(e)
}
}
}

View file

@ -0,0 +1,29 @@
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::{Error, Pool as SqlxPool, Sqlite};
pub struct Pool {
url: String,
pub pool: SqlxPool<Sqlite>,
}
impl Pool {
/// Initializes a new connection pool to database
///
/// # Arguments
///
/// * `url` - Path to SQLite database, must be full path
pub async fn init(url: impl Into<String>) -> Result<Self, Error> {
let url = url.into();
let pool = SqlitePoolOptions::new().connect(&url).await?;
println!("SQLite pool established for `{url}`");
Ok(Self { url, pool })
}
/// Close connection pool to database
pub async fn close(&self) {
self.pool.close().await;
println!("SQLite pool closed for `{}`", self.url);
}
}