Skip to content

Commit

Permalink
fixed issue where multiple entities in schema would cause creation an…
Browse files Browse the repository at this point in the history
…d truncation to fail; updated async-graphql example; bumped up to v0.1.4
  • Loading branch information
yasamoka committed Apr 8, 2024
1 parent 2827dcc commit e6efa14
Show file tree
Hide file tree
Showing 20 changed files with 173 additions and 124 deletions.
26 changes: 25 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "db-pool"
version = "0.1.3"
version = "0.1.4"
edition = "2021"
description = "A thread-safe database pool for running database-tied integration tests in parallel"
license = "MIT"
Expand Down Expand Up @@ -63,6 +63,7 @@ poem = "2.0.1"
serde = "1.0.197"
serde_json = "1.0.114"
tokio-postgres = "0.7.10"
diesel_async_migrations = "0.12.0"


[features]
Expand Down
2 changes: 1 addition & 1 deletion book/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 8 additions & 9 deletions examples/async-graphql/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ mod tests {
r#async::{DatabasePool, DatabasePoolBuilderTrait, DieselAsyncPostgresBackend, DieselBb8},
PrivilegedPostgresConfig,
};
use diesel::sql_query;
use diesel_async_migrations::{embed_migrations, EmbeddedMigrations};
use dotenvy::dotenv;
use futures::future::join_all;
use serde::{Deserialize, Serialize};
Expand All @@ -156,13 +156,14 @@ mod tests {
use crate::{build_schema, Book, PoolWrapper};

async fn get_connection_pool() -> PoolWrapper<DieselAsyncPostgresBackend<DieselBb8>> {
static MIGRATIONS: EmbeddedMigrations =
embed_migrations!("examples/async-graphql/migrations");

static DB_POOL: OnceCell<DatabasePool<DieselAsyncPostgresBackend<DieselBb8>>> =
OnceCell::const_new();

let db_pool = DB_POOL
.get_or_init(|| async {
use diesel_async::RunQueryDsl;

dotenv().ok();

let config = PrivilegedPostgresConfig::from_env().unwrap();
Expand All @@ -173,12 +174,10 @@ mod tests {
|| Pool::builder().max_size(1).test_on_check_out(true),
move |mut conn| {
Box::pin(async move {
sql_query(
"CREATE TABLE book(id SERIAL PRIMARY KEY, title TEXT NOT NULL)",
)
.execute(&mut conn)
.await
.unwrap();
MIGRATIONS
.run_pending_migrations(&mut conn)
.await
.expect("Database migrations must succeed");
conn
})
},
Expand Down
23 changes: 10 additions & 13 deletions src/async/backend/mysql/diesel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use async_trait::async_trait;
use diesel::{prelude::*, result::Error, sql_query, table};
use diesel_async::{
pooled_connection::AsyncDieselConnectionManager, AsyncConnection, AsyncMysqlConnection,
RunQueryDsl,
RunQueryDsl, SimpleAsyncConnection,
};
use futures::Future;
use uuid::Uuid;
Expand Down Expand Up @@ -122,22 +122,21 @@ impl<'pool, P: DieselPoolAssociation<AsyncMysqlConnection>> MySQLBackend<'pool>
P::get_connection(&self.default_pool).await
}

async fn execute_stmt(&self, query: &str, conn: &mut AsyncMysqlConnection) -> QueryResult<()> {
async fn execute_query(&self, query: &str, conn: &mut AsyncMysqlConnection) -> QueryResult<()> {
sql_query(query).execute(conn).await?;
Ok(())
}

async fn batch_execute_stmt<'a>(
async fn batch_execute_query<'a>(
&self,
query: impl IntoIterator<Item = Cow<'a, str>> + Send,
conn: &mut AsyncMysqlConnection,
) -> QueryResult<()> {
let chunks = query.into_iter().collect::<Vec<_>>();
if chunks.is_empty() {
let query = query.into_iter().collect::<Vec<_>>();
if query.is_empty() {
Ok(())
} else {
let query = chunks.join(";");
self.execute_stmt(query.as_str(), conn).await
conn.batch_execute(query.join(";").as_str()).await
}
}

Expand Down Expand Up @@ -250,13 +249,13 @@ mod tests {

use bb8::Pool;
use diesel::{insert_into, sql_query, table, Insertable, QueryDsl};
use diesel_async::RunQueryDsl;
use diesel_async::{RunQueryDsl, SimpleAsyncConnection};
use futures::future::join_all;
use tokio_shared_rt::test;

use crate::{
common::statement::mysql::tests::{
CREATE_ENTITIES_STATEMENT, DDL_STATEMENTS, DML_STATEMENTS,
CREATE_ENTITIES_STATEMENTS, DDL_STATEMENTS, DML_STATEMENTS,
},
r#async::{backend::common::pool::diesel::bb8::DieselBb8, db_pool::DatabasePoolBuilder},
tests::get_privileged_mysql_config,
Expand Down Expand Up @@ -291,10 +290,8 @@ mod tests {
move |mut conn| {
if with_table {
Box::pin(async move {
sql_query(CREATE_ENTITIES_STATEMENT)
.execute(&mut conn)
.await
.unwrap();
let query = CREATE_ENTITIES_STATEMENTS.join(";");
conn.batch_execute(query.as_str()).await.unwrap();
})
} else {
Box::pin(async {})
Expand Down
10 changes: 5 additions & 5 deletions src/async/backend/mysql/sea_orm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl<'pool> MySQLBackend<'pool> for SeaORMMySQLBackend {
Ok(self.default_pool.clone().into())
}

async fn execute_stmt(
async fn execute_query(
&self,
query: &str,
conn: &mut DatabaseConnection,
Expand All @@ -134,7 +134,7 @@ impl<'pool> MySQLBackend<'pool> for SeaORMMySQLBackend {
Ok(())
}

async fn batch_execute_stmt<'a>(
async fn batch_execute_query<'a>(
&self,
query: impl IntoIterator<Item = Cow<'a, str>> + Send,
conn: &mut DatabaseConnection,
Expand All @@ -144,7 +144,7 @@ impl<'pool> MySQLBackend<'pool> for SeaORMMySQLBackend {
Ok(())
} else {
let query = chunks.join(";");
self.execute_stmt(query.as_str(), conn).await
self.execute_query(query.as_str(), conn).await
}
}

Expand Down Expand Up @@ -299,7 +299,7 @@ mod tests {

use crate::{
common::statement::mysql::tests::{
CREATE_ENTITIES_STATEMENT, DDL_STATEMENTS, DML_STATEMENTS,
CREATE_ENTITIES_STATEMENTS, DDL_STATEMENTS, DML_STATEMENTS,
},
r#async::db_pool::DatabasePoolBuilder,
tests::get_privileged_mysql_config,
Expand Down Expand Up @@ -334,7 +334,7 @@ mod tests {
move |conn| {
if with_table {
Box::pin(async move {
conn.execute_unprepared(CREATE_ENTITIES_STATEMENT)
conn.execute_unprepared(CREATE_ENTITIES_STATEMENTS.join(";").as_str())
.await
.unwrap();
})
Expand Down
17 changes: 11 additions & 6 deletions src/async/backend/mysql/sqlx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ impl<'pool> MySQLBackend<'pool> for SqlxMySQLBackend {
self.default_pool.acquire().await.map_err(Into::into)
}

async fn execute_stmt(
async fn execute_query(
&self,
query: &str,
conn: &mut MySqlConnection,
Expand All @@ -118,7 +118,7 @@ impl<'pool> MySQLBackend<'pool> for SqlxMySQLBackend {
Ok(())
}

async fn batch_execute_stmt<'a>(
async fn batch_execute_query<'a>(
&self,
query: impl IntoIterator<Item = Cow<'a, str>> + Send,
conn: &mut MySqlConnection,
Expand All @@ -128,7 +128,7 @@ impl<'pool> MySQLBackend<'pool> for SqlxMySQLBackend {
Ok(())
} else {
let query = chunks.join(";");
self.execute_stmt(query.as_str(), conn).await
self.execute_query(query.as_str(), conn).await
}
}

Expand Down Expand Up @@ -218,7 +218,7 @@ impl Backend for SqlxMySQLBackend {
mod tests {
#![allow(clippy::unwrap_used, clippy::needless_return)]

use futures::future::join_all;
use futures::{future::join_all, StreamExt};
use sqlx::{
mysql::{MySqlConnectOptions, MySqlPoolOptions},
query, query_as, Executor, FromRow, Row,
Expand All @@ -227,7 +227,7 @@ mod tests {

use crate::{
common::statement::mysql::tests::{
CREATE_ENTITIES_STATEMENT, DDL_STATEMENTS, DML_STATEMENTS,
CREATE_ENTITIES_STATEMENTS, DDL_STATEMENTS, DML_STATEMENTS,
},
r#async::db_pool::DatabasePoolBuilder,
tests::get_privileged_mysql_config,
Expand Down Expand Up @@ -255,7 +255,12 @@ mod tests {
move |mut conn| {
if with_table {
Box::pin(async move {
conn.execute(CREATE_ENTITIES_STATEMENT).await.unwrap();
conn.execute_many(CREATE_ENTITIES_STATEMENTS.join(";").as_str())
.collect::<Vec<_>>()
.await
.drain(..)
.collect::<Result<Vec<_>, _>>()
.unwrap();
})
} else {
Box::pin(async {})
Expand Down
28 changes: 14 additions & 14 deletions src/async/backend/mysql/trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ pub(super) trait MySQLBackend<'pool>: Send + Sync + 'static {

async fn get_connection(&'pool self) -> Result<Self::PooledConnection, Self::PoolError>;

async fn execute_stmt(
async fn execute_query(
&self,
query: &str,
conn: &mut Self::Connection,
) -> Result<(), Self::QueryError>;
async fn batch_execute_stmt<'a>(
async fn batch_execute_query<'a>(
&self,
query: impl IntoIterator<Item = Cow<'a, str>> + Send,
conn: &mut Self::Connection,
Expand Down Expand Up @@ -119,7 +119,7 @@ where
let conn = &mut self.get_connection().await.map_err(Into::into)?;

// Get previous database names
self.execute_stmt(mysql::USE_DEFAULT_DATABASE, conn)
self.execute_query(mysql::USE_DEFAULT_DATABASE, conn)
.await
.map_err(Into::into)?;
let mut db_names = self
Expand All @@ -132,7 +132,7 @@ where
.drain(..)
.map(|db_name| async move {
let conn = &mut self.get_connection().await.map_err(Into::into)?;
self.execute_stmt(mysql::drop_database(db_name.as_str()).as_str(), conn)
self.execute_query(mysql::drop_database(db_name.as_str()).as_str(), conn)
.await
.map_err(Into::into)?;
Ok::<
Expand Down Expand Up @@ -167,26 +167,26 @@ where
let conn = &mut self.get_connection().await.map_err(Into::into)?;

// Create database
self.execute_stmt(mysql::create_database(db_name).as_str(), conn)
self.execute_query(mysql::create_database(db_name).as_str(), conn)
.await
.map_err(Into::into)?;

// Create CRUD user
self.execute_stmt(mysql::create_user(db_name, host).as_str(), conn)
self.execute_query(mysql::create_user(db_name, host).as_str(), conn)
.await
.map_err(Into::into)?;

// Create entities
self.execute_stmt(mysql::use_database(db_name).as_str(), conn)
self.execute_query(mysql::use_database(db_name).as_str(), conn)
.await
.map_err(Into::into)?;
self.create_entities(db_name).await.map_err(Into::into)?;
self.execute_stmt(mysql::USE_DEFAULT_DATABASE, conn)
self.execute_query(mysql::USE_DEFAULT_DATABASE, conn)
.await
.map_err(Into::into)?;

// Grant privileges to CRUD role
self.execute_stmt(mysql::grant_privileges(db_name, host).as_str(), conn)
self.execute_query(mysql::grant_privileges(db_name, host).as_str(), conn)
.await
.map_err(Into::into)?;

Expand Down Expand Up @@ -222,17 +222,17 @@ where
.map(|table_name| mysql::truncate_table(table_name.as_str(), db_name).into());

// Turn off foreign key checks
self.execute_stmt(mysql::TURN_OFF_FOREIGN_KEY_CHECKS, conn)
self.execute_query(mysql::TURN_OFF_FOREIGN_KEY_CHECKS, conn)
.await
.map_err(Into::into)?;

// Truncate tables
self.batch_execute_stmt(stmts, conn)
self.batch_execute_query(stmts, conn)
.await
.map_err(Into::into)?;

// Turn on foreign key checks
self.execute_stmt(mysql::TURN_ON_FOREIGN_KEY_CHECKS, conn)
self.execute_query(mysql::TURN_ON_FOREIGN_KEY_CHECKS, conn)
.await
.map_err(Into::into)?;

Expand All @@ -254,12 +254,12 @@ where
let conn = &mut self.get_connection().await.map_err(Into::into)?;

// Drop database
self.execute_stmt(mysql::drop_database(db_name).as_str(), conn)
self.execute_query(mysql::drop_database(db_name).as_str(), conn)
.await
.map_err(Into::into)?;

// Drop CRUD role
self.execute_stmt(mysql::drop_user(db_name, host).as_str(), conn)
self.execute_query(mysql::drop_user(db_name, host).as_str(), conn)
.await
.map_err(Into::into)?;

Expand Down
Loading

0 comments on commit e6efa14

Please sign in to comment.