Skip to content

Commit

Permalink
setup is no longer async
Browse files Browse the repository at this point in the history
  • Loading branch information
m1guelpf committed Dec 13, 2023
1 parent fbfcbe7 commit 35e783d
Show file tree
Hide file tree
Showing 8 changed files with 32 additions and 34 deletions.
22 changes: 11 additions & 11 deletions ensemble/src/connection.rs
Original file line number Diff line number Diff line change
@@ -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<dyn RbdcConnection>;

Expand All @@ -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")]
Expand All @@ -48,9 +49,8 @@ pub async fn setup(database_url: &str) -> Result<(), SetupError> {
#[cfg(feature = "postgres")]
rb.init_option::<PgDriver, PgConnectOptions, DefaultPool>(
PgDriver {},
PgConnectOptions::from_str(database_url),
)
.await?;
PgConnectOptions::from_str(database_url)?,
)?;

DB_POOL
.set(rb)
Expand Down Expand Up @@ -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)
}
}

Expand Down
18 changes: 11 additions & 7 deletions ensemble/src/migrations/migrator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn Migration>) {
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));
}
Expand Down Expand Up @@ -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()))?;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion ensemble/src/migrations/schema/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"));
}
}

Expand Down
11 changes: 4 additions & 7 deletions ensemble/src/migrations/schema/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -142,7 +139,7 @@ impl Table {

#[cfg(feature = "mysql")]
{
return column.unsigned(true);
column.unsigned(true)
}

#[cfg(not(feature = "mysql"))]
Expand Down
10 changes: 5 additions & 5 deletions ensemble/src/types/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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<DateTime> = serde_json::from_value(v).unwrap();
assert_eq!(new_dt, dt);
}
Expand All @@ -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,
Expand All @@ -239,15 +239,15 @@ mod test {
#[test]
fn test_default() {
let dt = DateTime::default();
println!("{}", dt);

assert_eq!(dt.to_string(), "DateTime(1970-01-01T00:00:00Z)");
}

#[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");
}
}
1 change: 0 additions & 1 deletion examples/migrations/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion examples/relationships/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
Expand Down
1 change: 0 additions & 1 deletion examples/user/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 35e783d

Please sign in to comment.