From 35e783dc848f8f65e9ed80a7a916e5ab680daf3f Mon Sep 17 00:00:00 2001 From: Miguel Piedrafita Date: Wed, 13 Dec 2023 02:54:08 +0100 Subject: [PATCH] `setup` is no longer async --- ensemble/src/connection.rs | 22 +++++++++++----------- ensemble/src/migrations/migrator.rs | 18 +++++++++++------- ensemble/src/migrations/schema/column.rs | 2 +- ensemble/src/migrations/schema/mod.rs | 11 ++++------- ensemble/src/types/datetime.rs | 10 +++++----- examples/migrations/src/main.rs | 1 - examples/relationships/src/main.rs | 1 - examples/user/src/main.rs | 1 - 8 files changed, 32 insertions(+), 34 deletions(-) diff --git a/ensemble/src/connection.rs b/ensemble/src/connection.rs index bc18149..f1fea0e 100644 --- a/ensemble/src/connection.rs +++ b/ensemble/src/connection.rs @@ -1,10 +1,11 @@ -use rbatis::{rbdc::db::Connection as RbdcConnection, DefaultPool, RBatis}; +use rbatis::{rbdc::db::Connection as RbdcConnection, RBatis}; #[cfg(feature = "mysql")] use rbdc_mysql::{driver::MysqlDriver, options::MySqlConnectOptions}; #[cfg(feature = "postgres")] -use rbdc_pg::driver::PgDriver; -use std::str::FromStr; +use rbdc_pg::{driver::PgDriver, options::PgConnectOptions}; use std::sync::OnceLock; +#[cfg(any(feature = "mysql", feature = "postgres"))] +use {rbatis::DefaultPool, std::str::FromStr}; pub type Connection = Box; @@ -26,7 +27,7 @@ pub enum SetupError { /// /// Returns an error if the database pool has already been initialized, or if the provided database URL is invalid. #[cfg(any(feature = "mysql", feature = "postgres"))] -pub async fn setup(database_url: &str) -> Result<(), SetupError> { +pub fn setup(database_url: &str) -> Result<(), SetupError> { let rb = RBatis::new(); #[cfg(feature = "mysql")] @@ -48,9 +49,8 @@ pub async fn setup(database_url: &str) -> Result<(), SetupError> { #[cfg(feature = "postgres")] rb.init_option::( PgDriver {}, - PgConnectOptions::from_str(database_url), - ) - .await?; + PgConnectOptions::from_str(database_url)?, + )?; DB_POOL .set(rb) @@ -88,12 +88,12 @@ pub enum Database { #[cfg(any(feature = "mysql", feature = "postgres"))] impl Database { - pub fn is_mysql(&self) -> bool { - matches!(self, Database::MySQL) + pub const fn is_mysql(&self) -> bool { + matches!(self, Self::MySQL) } - pub fn is_postgres(&self) -> bool { - matches!(self, Database::PostgreSQL) + pub const fn is_postgres(&self) -> bool { + matches!(self, Self::PostgreSQL) } } diff --git a/ensemble/src/migrations/migrator.rs b/ensemble/src/migrations/migrator.rs index d93b472..4d1ca3c 100644 --- a/ensemble/src/migrations/migrator.rs +++ b/ensemble/src/migrations/migrator.rs @@ -50,12 +50,17 @@ impl Migrator { } /// Registers a migration. + /// + /// # Panics + /// + /// Panics if a migration with the same name has already been registered. pub fn register(&mut self, name: String, migration: Box) { tracing::trace!("Registered migration [{name}]"); - if self.migrations.iter().any(|(n, _)| n == &name) { - panic!("A migration with the name [{name}] has already been registered."); - } + assert!( + !self.migrations.iter().any(|(n, _)| n == &name), + "A migration with the name [{name}] has already been registered." + ); self.migrations.push((name, migration)); } @@ -122,7 +127,7 @@ impl Migrator { self.connection .exec( "insert into migrations (migration, batch) values (?, ?)", - vec![value::for_db(&name)?, value::for_db(&self.batch)?], + vec![value::for_db(name)?, value::for_db(self.batch)?], ) .await .map_err(|e| Error::Database(e.to_string()))?; @@ -160,8 +165,7 @@ impl Migrator { let (name, migration) = self .migrations .iter() - .filter(|(name, _)| name == &record.migration) - .next() + .find(|(name, _)| name == &record.migration) .ok_or_else(|| Error::NotFound(record.migration.clone()))?; self.connection @@ -238,7 +242,7 @@ pub struct StoredMigration { pub migration: String, } -fn migrations_table_query() -> &'static str { +const fn migrations_table_query() -> &'static str { use crate::connection::Database; match connection::which_db() { diff --git a/ensemble/src/migrations/schema/column.rs b/ensemble/src/migrations/schema/column.rs index 4f7e802..ee60626 100644 --- a/ensemble/src/migrations/schema/column.rs +++ b/ensemble/src/migrations/schema/column.rs @@ -169,7 +169,7 @@ impl Column { if self.r#type == Type::Json { sql.push_str(&format!(" DEFAULT '{}'", default.as_str().unwrap())); } else { - sql.push_str(&format!(" DEFAULT {}", default)); + sql.push_str(&format!(" DEFAULT {default}")); } } diff --git a/ensemble/src/migrations/schema/mod.rs b/ensemble/src/migrations/schema/mod.rs index 849f1ec..461bca7 100644 --- a/ensemble/src/migrations/schema/mod.rs +++ b/ensemble/src/migrations/schema/mod.rs @@ -75,13 +75,10 @@ impl Schema { let mut conn_lock = MIGRATE_CONN.try_lock().map_err(|_| Error::Lock)?; let mut conn = conn_lock.take().ok_or(Error::Lock)?; - let (sql, bindings) = ( - format!("DROP TABLE ?"), - vec![Value::String(table_name.to_string())], - ); + let (sql, bindings) = ("DROP TABLE ?", vec![Value::String(table_name.to_string())]); - tracing::debug!(sql = sql.as_str(), bindings = ?bindings, "Running DROP TABLE SQL query"); - let query_result = conn.exec(&sql, bindings).await; + tracing::debug!(sql = sql, bindings = ?bindings, "Running DROP TABLE SQL query"); + let query_result = conn.exec(sql, bindings).await; conn_lock.replace(conn); drop(conn_lock); @@ -142,7 +139,7 @@ impl Table { #[cfg(feature = "mysql")] { - return column.unsigned(true); + column.unsigned(true) } #[cfg(not(feature = "mysql"))] diff --git a/ensemble/src/types/datetime.rs b/ensemble/src/types/datetime.rs index 7b1e7cf..d02ca26 100644 --- a/ensemble/src/types/datetime.rs +++ b/ensemble/src/types/datetime.rs @@ -191,7 +191,7 @@ mod test { #[test] fn test_de() { let dt = DateTime::from_str("2023-10-21T00:15:00.9233333+08:00").unwrap(); - println!("dt={}", dt); + let v = serde_json::to_value(&dt).unwrap(); let new_dt: DateTime = serde_json::from_value(v).unwrap(); assert_eq!(new_dt, dt); @@ -201,7 +201,7 @@ mod test { fn test_de2() { let dt = vec![DateTime::from_str("2023-10-21T00:15:00.9233333+08:00").unwrap()]; let v = serde_json::to_value(&dt).unwrap(); - println!("dt={:?}", dt); + let new_dt: Vec = serde_json::from_value(v).unwrap(); assert_eq!(new_dt, dt); } @@ -228,7 +228,7 @@ mod test { #[test] fn test_de5() { let dt = DateTime::from_str("2023-10-21T00:15:00.9233333+08:00").unwrap(); - let v = serde_json::to_value(&dt.unix_timestamp_millis()).unwrap(); + let v = serde_json::to_value(dt.unix_timestamp_millis()).unwrap(); let new_dt: DateTime = serde_json::from_value(v).unwrap(); assert_eq!( new_dt, @@ -239,7 +239,7 @@ mod test { #[test] fn test_default() { let dt = DateTime::default(); - println!("{}", dt); + assert_eq!(dt.to_string(), "DateTime(1970-01-01T00:00:00Z)"); } @@ -247,7 +247,7 @@ mod test { fn test_format() { let dt = DateTime::default(); let s = dt.format("YYYY-MM-DD/hh/mm/ss"); - println!("{}", s); + assert_eq!(s, "1970-1-1/0/0/0"); } } diff --git a/examples/migrations/src/main.rs b/examples/migrations/src/main.rs index de45aac..8c2edd3 100644 --- a/examples/migrations/src/main.rs +++ b/examples/migrations/src/main.rs @@ -4,7 +4,6 @@ mod migrations; #[tokio::main] async fn main() { ensemble::setup(&env::var("DATABASE_URL").expect("DATABASE_URL must be set")) - .await .expect("Failed to set up database pool."); ensemble::migrate!(migrations::CreateUsersTable, migrations::CreatePostsTable) diff --git a/examples/relationships/src/main.rs b/examples/relationships/src/main.rs index 3abcba4..d510bce 100644 --- a/examples/relationships/src/main.rs +++ b/examples/relationships/src/main.rs @@ -34,7 +34,6 @@ pub struct Post { #[tokio::main] async fn main() { ensemble::setup(&env::var("DATABASE_URL").expect("DATABASE_URL must be set")) - .await .expect("Failed to set up database pool."); let mut user = User::find(1).await.expect("Failed to find user."); diff --git a/examples/user/src/main.rs b/examples/user/src/main.rs index d69656f..62b5737 100644 --- a/examples/user/src/main.rs +++ b/examples/user/src/main.rs @@ -18,7 +18,6 @@ pub struct User { #[tokio::main] async fn main() { ensemble::setup(&env::var("DATABASE_URL").expect("DATABASE_URL must be set")) - .await .expect("Failed to set up database pool."); let users = User::all().await.unwrap();