Skip to content
This repository has been archived by the owner on Sep 2, 2022. It is now read-only.

Commit

Permalink
database_inspector: Move free functions out of trait
Browse files Browse the repository at this point in the history
  • Loading branch information
aknuds1 committed Aug 21, 2019
1 parent 73a154a commit 8142569
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,69 +22,63 @@ use std::convert::TryFrom;
use std::sync::Arc;
use url::Url;

const PARSE_ERROR: &'static str = "Parsing of the provided connector url failed.";

pub trait DatabaseInspector: Send + Sync + 'static {
fn introspect(&self, schema: &String) -> DatabaseSchema;
}

impl dyn DatabaseInspector {
const PARSE_ERROR: &'static str = "Parsing of the provided connector url failed.";

pub fn empty() -> EmptyDatabaseInspectorImpl {
EmptyDatabaseInspectorImpl {}
}

pub fn sqlite(file_path: String) -> Sqlite {
let conn = Arc::new(SqliteDriver::new(&file_path).unwrap());
Self::sqlite_with_database(conn)
}
pub fn sqlite(file_path: String) -> Sqlite {
let conn = Arc::new(SqliteDriver::new(&file_path).unwrap());
sqlite_with_database(conn)
}

pub fn sqlite_with_database(database: Arc<dyn MigrationDatabase + Send + Sync + 'static>) -> Sqlite {
Sqlite::new(database)
}
pub fn sqlite_with_database(database: Arc<dyn MigrationDatabase + Send + Sync + 'static>) -> Sqlite {
Sqlite::new(database)
}

pub fn postgres(url: String) -> Postgres {
let url = Url::parse(&url).expect(Self::PARSE_ERROR);
let db_name = url.path().trim_start_matches("/");
pub fn postgres(url: String) -> Postgres {
let url = Url::parse(&url).expect(PARSE_ERROR);
let db_name = url.path().trim_start_matches("/");

let mut root_url = url.clone();
root_url.set_path("postgres");
let mut root_url = url.clone();
root_url.set_path("postgres");

let root_params = connector::PostgresParams::try_from(root_url).expect(Self::PARSE_ERROR);
let root_params = connector::PostgresParams::try_from(root_url).expect(PARSE_ERROR);

let schema_name = root_params.schema.clone();
let root_connection = Arc::new(PostgresDriver::new(root_params).unwrap());
let schema_name = root_params.schema.clone();
let root_connection = Arc::new(PostgresDriver::new(root_params).unwrap());

let db_sql = format!("CREATE DATABASE \"{}\";", &db_name);
debug!("{}", db_sql);
let db_sql = format!("CREATE DATABASE \"{}\";", &db_name);
debug!("{}", db_sql);

let _ = root_connection.query_raw(&schema_name, &db_sql, &[]); // ignoring errors as there's no CREATE DATABASE IF NOT EXISTS in Postgres
let _ = root_connection.query_raw(&schema_name, &db_sql, &[]); // ignoring errors as there's no CREATE DATABASE IF NOT EXISTS in Postgres

let params = connector::PostgresParams::try_from(url).expect(Self::PARSE_ERROR);
let schema_connection = Arc::new(PostgresDriver::new(params).unwrap());
let params = connector::PostgresParams::try_from(url).expect(PARSE_ERROR);
let schema_connection = Arc::new(PostgresDriver::new(params).unwrap());

let schema_sql = format!("CREATE SCHEMA IF NOT EXISTS \"{}\";", &schema_name);
debug!("{}", schema_sql);
let schema_sql = format!("CREATE SCHEMA IF NOT EXISTS \"{}\";", &schema_name);
debug!("{}", schema_sql);

schema_connection
.query_raw(&schema_name, &schema_sql, &[])
.expect("Creation of Postgres Schema failed");
schema_connection
.query_raw(&schema_name, &schema_sql, &[])
.expect("Creation of Postgres Schema failed");

Postgres::new(schema_connection)
}
Postgres::new(schema_connection)
}

pub fn postgres_with_database(database: Arc<dyn MigrationDatabase + Send + Sync + 'static>) -> Postgres {
Postgres::new(database)
}
pub fn postgres_with_database(database: Arc<dyn MigrationDatabase + Send + Sync + 'static>) -> Postgres {
Postgres::new(database)
}

pub fn mysql(url: String) -> MysqlInspector {
let url = Url::parse(&url).expect(Self::PARSE_ERROR);
let params = connector::MysqlParams::try_from(url).expect(Self::PARSE_ERROR);
let database = MysqlDriver::new(params).unwrap();
pub fn mysql(url: String) -> MysqlInspector {
let url = Url::parse(&url).expect(PARSE_ERROR);
let params = connector::MysqlParams::try_from(url).expect(PARSE_ERROR);
let database = MysqlDriver::new(params).unwrap();

Self::mysql_with_database(Arc::new(database))
}
mysql_with_database(Arc::new(database))
}

pub fn mysql_with_database(database: Arc<dyn MigrationDatabase + Send + Sync + 'static>) -> MysqlInspector {
MysqlInspector::new(database)
}
pub fn mysql_with_database(database: Arc<dyn MigrationDatabase + Send + Sync + 'static>) -> MysqlInspector {
MysqlInspector::new(database)
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ mod sql_migration_persistence;
pub use error::*;
pub use sql_migration::*;

use database_inspector::DatabaseInspector;
use database_inspector::{DatabaseInspector, sqlite_with_database, postgres_with_database, mysql_with_database};
use migration_connector::*;
use migration_database::*;
use prisma_query::connector::{MysqlParams, PostgresParams};
Expand Down Expand Up @@ -140,9 +140,9 @@ impl SqlMigrationConnector {
file_path: Option<String>,
) -> Self {
let inspector: Arc<dyn DatabaseInspector + Send + Sync + 'static> = match sql_family {
SqlFamily::Sqlite => Arc::new(DatabaseInspector::sqlite_with_database(Arc::clone(&conn))),
SqlFamily::Postgres => Arc::new(DatabaseInspector::postgres_with_database(Arc::clone(&conn))),
SqlFamily::Mysql => Arc::new(DatabaseInspector::mysql_with_database(Arc::clone(&conn))),
SqlFamily::Sqlite => Arc::new(sqlite_with_database(Arc::clone(&conn))),
SqlFamily::Postgres => Arc::new(postgres_with_database(Arc::clone(&conn))),
SqlFamily::Mysql => Arc::new(mysql_with_database(Arc::clone(&conn))),
};

let migration_persistence = Arc::new(SqlMigrationPersistence {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ where
{
let mut migration = Migration::new().schema(SCHEMA);
migrationFn("sqlite", &mut migration);
let (inspector, database) = sqlite();
let (inspector, database) = get_sqlite();
let full_sql = migration.make::<barrel::backend::Sqlite>();
run_full_sql(&database, &full_sql);
println!("Running the test function now");
Expand All @@ -179,7 +179,7 @@ where
{
let mut migration = Migration::new().schema(SCHEMA);
migrationFn("postgres", &mut migration);
let (inspector, database) = postgres();
let (inspector, database) = get_postgres();
let full_sql = migration.make::<barrel::backend::Pg>();
run_full_sql(&database, &full_sql);
println!("Running the test function now");
Expand All @@ -191,7 +191,7 @@ where
let mut migration = Migration::new().schema(SCHEMA);
migrationFn("mysql", &mut migration);

let (inspector, database) = mysql();
let (inspector, database) = get_mysql();
let full_sql = dbg!(migration.make::<barrel::backend::MySql>());

run_full_sql(&database, &full_sql);
Expand All @@ -209,47 +209,47 @@ fn run_full_sql(database: &Arc<dyn MigrationDatabase>, full_sql: &str) {
}
}

fn sqlite() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
fn get_sqlite() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
let server_root = std::env::var("SERVER_ROOT").expect("Env var SERVER_ROOT required but not found.");
let database_folder_path = format!("{}/db", server_root);
let database_file_path = dbg!(format!("{}/{}.db", database_folder_path, SCHEMA));
let _ = std::fs::remove_file(database_file_path.clone()); // ignore potential errors

let inspector = DatabaseInspector::sqlite(database_file_path);
let inspector = sqlite(database_file_path);
let database = Arc::clone(&inspector.database);

(Arc::new(inspector), database)
}

fn postgres() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
fn get_postgres() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
let url = format!(
"postgresql://postgres:prisma@{}:5432/db?schema={}",
db_host_postgres(),
SCHEMA
);

let drop_schema = dbg!(format!("DROP SCHEMA IF EXISTS \"{}\" CASCADE;", SCHEMA));
let setup_database = DatabaseInspector::postgres(url.to_string()).database;
let setup_database = postgres(url.to_string()).database;
let _ = setup_database.query_raw(SCHEMA, &drop_schema, &[]);

let inspector = DatabaseInspector::postgres(url.to_string());
let inspector = postgres(url.to_string());
let database = Arc::clone(&inspector.database);

(Arc::new(inspector), database)
}

fn mysql() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
fn get_mysql() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
let url_without_db = format!("mysql://root:prisma@{}:3306", db_host_mysql());
let drop_database = dbg!(format!("DROP DATABASE IF EXISTS `{}`;", SCHEMA));

let create_database = dbg!(format!("CREATE DATABASE `{}`;", SCHEMA));
let setup_database = DatabaseInspector::mysql(url_without_db.to_string()).database;
let setup_database = mysql(url_without_db.to_string()).database;

let _ = setup_database.query_raw(SCHEMA, &drop_database, &[]);
let _ = setup_database.query_raw(SCHEMA, &create_database, &[]);

let url = format!("mysql://root:prisma@{}:3306/{}", db_host_mysql(), SCHEMA);
let inspector = DatabaseInspector::mysql(url.to_string());
let inspector = mysql(url.to_string());
let database = Arc::clone(&inspector.database);

(Arc::new(inspector), database)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ where
// SQLite
if !ignores.contains(&SqlFamily::Sqlite) {
println!("Testing with SQLite now");
let (inspector, database) = sqlite();
let (inspector, database) = get_sqlite();

println!("Running the test function now");
let connector = SqlMigrationConnector::sqlite(&sqlite_test_file()).unwrap();
Expand All @@ -328,7 +328,7 @@ where
// POSTGRES
if !ignores.contains(&SqlFamily::Postgres) {
println!("Testing with Postgres now");
let (inspector, database) = postgres();
let (inspector, database) = get_postgres();

println!("Running the test function now");
let connector = SqlMigrationConnector::postgres(&postgres_url()).unwrap();
Expand All @@ -346,23 +346,23 @@ where
}
}

fn sqlite() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
fn get_sqlite() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
let database_file_path = sqlite_test_file();
let _ = std::fs::remove_file(database_file_path.clone()); // ignore potential errors

let inspector = DatabaseInspector::sqlite(database_file_path);
let inspector = sqlite(database_file_path);
let database = Arc::clone(&inspector.database);

(Arc::new(inspector), database)
}

fn postgres() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
fn get_postgres() -> (Arc<dyn DatabaseInspector>, Arc<dyn MigrationDatabase>) {
let url = postgres_url();
let drop_schema = dbg!(format!("DROP SCHEMA IF EXISTS \"{}\" CASCADE;", SCHEMA_NAME));
let setup_database = DatabaseInspector::postgres(url.to_string()).database;
let setup_database = postgres(url.to_string()).database;
let _ = setup_database.query_raw(SCHEMA_NAME, &drop_schema, &[]);

let inspector = DatabaseInspector::postgres(url.to_string());
let inspector = postgres(url.to_string());
let database = Arc::clone(&inspector.database);

(Arc::new(inspector), database)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ where

pub fn introspect_database(api: &dyn GenericApi) -> DatabaseSchema {
let inspector: Box<dyn DatabaseInspector> = match api.connector_type() {
"postgresql" => Box::new(DatabaseInspector::postgres(postgres_url())),
"sqlite" => Box::new(DatabaseInspector::sqlite(sqlite_test_file())),
"mysql" => Box::new(DatabaseInspector::mysql(mysql_url())),
"postgresql" => Box::new(postgres(postgres_url())),
"sqlite" => Box::new(sqlite(sqlite_test_file())),
"mysql" => Box::new(mysql(mysql_url())),
_ => unimplemented!(),
};

Expand Down

0 comments on commit 8142569

Please sign in to comment.