Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup panic and unwrap #1231

Merged
merged 49 commits into from
Feb 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
985a1fe
Add clippy linter checks
billy1624 Nov 15, 2022
2cd1a56
Mock
billy1624 Nov 16, 2022
bd33f56
InnerConnection
billy1624 Nov 16, 2022
27dc588
panic -> Err
billy1624 Nov 16, 2022
1f4e28e
panic -> Err
billy1624 Nov 16, 2022
45c874b
More panic -> Err
billy1624 Nov 16, 2022
ac4fa59
Replace unwrap
billy1624 Nov 17, 2022
ee05afb
Fix clippy
billy1624 Nov 17, 2022
328354c
add clippy linters
billy1624 Nov 17, 2022
41017a7
Refactor
billy1624 Nov 17, 2022
9c82623
Dump DbErr::Mock
billy1624 Nov 17, 2022
db8115a
Revert if...else rewrite
billy1624 Nov 17, 2022
470e23d
Remove except
billy1624 Nov 17, 2022
a7cae67
DbErr helper functions
billy1624 Nov 17, 2022
5442d1f
Fix clippy
billy1624 Nov 17, 2022
050d6ce
Negative SQLite last_insert_rowid throw unreachable
billy1624 Nov 18, 2022
5e2a2c6
Update panics docs
billy1624 Nov 18, 2022
414c8c1
Merge branch 'master' into replace-panic
billy1624 Jan 31, 2023
7ee1deb
Fixup
billy1624 Jan 31, 2023
6065121
Fixup
billy1624 Jan 31, 2023
be455f9
Fixup
billy1624 Jan 31, 2023
7f09b10
Fixup
billy1624 Jan 31, 2023
6625b25
Revert adding `ExecResultHolder::Disconnected`
billy1624 Jan 31, 2023
e59b8b4
More fixup
billy1624 Jan 31, 2023
d5c3d2e
Fix
billy1624 Jan 31, 2023
44ecea6
Revert adding `QueryResultRow::Disconnected`
billy1624 Jan 31, 2023
af1127c
Fix
billy1624 Jan 31, 2023
22c0764
Merge remote-tracking branch 'origin/master' into replace-panic
billy1624 Jan 31, 2023
2887f86
Refactoring
billy1624 Jan 31, 2023
cc5a464
Fix
billy1624 Jan 31, 2023
1252142
Merge remote-tracking branch 'origin/master' into replace-panic
billy1624 Jan 31, 2023
5fcdc7b
Refactoring
billy1624 Jan 31, 2023
a0d516d
More refactoring
billy1624 Jan 31, 2023
697a1a5
More refactoring
billy1624 Jan 31, 2023
ba35235
Fix
billy1624 Jan 31, 2023
5dbc0f7
Merge remote-tracking branch 'origin/master' into replace-panic
billy1624 Jan 31, 2023
d240a78
Revert `InnerConnection::Disconnected`
billy1624 Jan 31, 2023
c4c95c6
Revert breaking changes
billy1624 Jan 31, 2023
c18f9d4
Fix
billy1624 Jan 31, 2023
fab856f
Fix
billy1624 Jan 31, 2023
c3ccf93
Fix
billy1624 Jan 31, 2023
0954fab
Refactor `.take().expect()`
billy1624 Feb 1, 2023
840cd54
Revert changing `if ... else` to `match` block
billy1624 Feb 1, 2023
14903a2
Revert changing return type of `MockDatabaseConnection` transaction m…
billy1624 Feb 1, 2023
cb9cd13
Borrow sqlcipher_key
billy1624 Feb 1, 2023
b665c42
Fetching unsupported type from query result will thrown `DbErr::Type(…
billy1624 Feb 1, 2023
3881f0a
Revert adding `DatabaseConnection::try_into_transaction_log()` method
billy1624 Feb 1, 2023
307a742
Refactoring
billy1624 Feb 1, 2023
fd03736
Refactoring
billy1624 Feb 1, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
89 changes: 52 additions & 37 deletions src/database/db_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ pub enum DatabaseConnection {
/// The same as a [DatabaseConnection]
pub type DbConn = DatabaseConnection;

impl Default for DatabaseConnection {
fn default() -> Self {
Self::Disconnected
}
}

/// The type of database backend for real world databases.
/// This is enabled by feature flags as specified in the crate documentation
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
Expand All @@ -50,6 +56,7 @@ pub enum DatabaseBackend {

/// The same as [DatabaseBackend] just shorter :)
pub type DbBackend = DatabaseBackend;

#[derive(Debug)]
pub(crate) enum InnerConnection {
#[cfg(feature = "sqlx-mysql")]
Expand All @@ -62,12 +69,6 @@ pub(crate) enum InnerConnection {
Mock(std::sync::Arc<crate::MockDatabaseConnection>),
}

impl Default for DatabaseConnection {
fn default() -> Self {
Self::Disconnected
}
}

impl std::fmt::Debug for DatabaseConnection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
Expand Down Expand Up @@ -116,9 +117,7 @@ impl ConnectionTrait for DatabaseConnection {
DatabaseConnection::SqlxSqlitePoolConnection(conn) => conn.execute(stmt).await,
#[cfg(feature = "mock")]
DatabaseConnection::MockDatabaseConnection(conn) => conn.execute(stmt),
DatabaseConnection::Disconnected => {
Err(DbErr::Conn(RuntimeErr::Internal("Disconnected".to_owned())))
}
DatabaseConnection::Disconnected => Err(conn_err("Disconnected")),
}
}

Expand All @@ -142,9 +141,7 @@ impl ConnectionTrait for DatabaseConnection {
let stmt = Statement::from_string(db_backend, sql.into());
conn.execute(stmt)
}
DatabaseConnection::Disconnected => {
Err(DbErr::Conn(RuntimeErr::Internal("Disconnected".to_owned())))
}
DatabaseConnection::Disconnected => Err(conn_err("Disconnected")),
}
}

Expand All @@ -160,9 +157,7 @@ impl ConnectionTrait for DatabaseConnection {
DatabaseConnection::SqlxSqlitePoolConnection(conn) => conn.query_one(stmt).await,
#[cfg(feature = "mock")]
DatabaseConnection::MockDatabaseConnection(conn) => conn.query_one(stmt),
DatabaseConnection::Disconnected => {
Err(DbErr::Conn(RuntimeErr::Internal("Disconnected".to_owned())))
}
DatabaseConnection::Disconnected => Err(conn_err("Disconnected")),
}
}

Expand All @@ -178,9 +173,7 @@ impl ConnectionTrait for DatabaseConnection {
DatabaseConnection::SqlxSqlitePoolConnection(conn) => conn.query_all(stmt).await,
#[cfg(feature = "mock")]
DatabaseConnection::MockDatabaseConnection(conn) => conn.query_all(stmt),
DatabaseConnection::Disconnected => {
Err(DbErr::Conn(RuntimeErr::Internal("Disconnected".to_owned())))
}
DatabaseConnection::Disconnected => Err(conn_err("Disconnected")),
}
}

Expand All @@ -195,25 +188,25 @@ impl StreamTrait for DatabaseConnection {
type Stream<'a> = crate::QueryStream;

#[instrument(level = "trace")]
#[allow(unused_variables, unreachable_code)]
#[allow(unused_variables)]
fn stream<'a>(
&'a self,
stmt: Statement,
) -> Pin<Box<dyn Future<Output = Result<Self::Stream<'a>, DbErr>> + 'a + Send>> {
Box::pin(async move {
Ok(match self {
match self {
#[cfg(feature = "sqlx-mysql")]
DatabaseConnection::SqlxMySqlPoolConnection(conn) => conn.stream(stmt).await?,
DatabaseConnection::SqlxMySqlPoolConnection(conn) => conn.stream(stmt).await,
#[cfg(feature = "sqlx-postgres")]
DatabaseConnection::SqlxPostgresPoolConnection(conn) => conn.stream(stmt).await?,
DatabaseConnection::SqlxPostgresPoolConnection(conn) => conn.stream(stmt).await,
#[cfg(feature = "sqlx-sqlite")]
DatabaseConnection::SqlxSqlitePoolConnection(conn) => conn.stream(stmt).await?,
DatabaseConnection::SqlxSqlitePoolConnection(conn) => conn.stream(stmt).await,
#[cfg(feature = "mock")]
DatabaseConnection::MockDatabaseConnection(conn) => {
crate::QueryStream::from((Arc::clone(conn), stmt, None))
Ok(crate::QueryStream::from((Arc::clone(conn), stmt, None)))
}
DatabaseConnection::Disconnected => panic!("Disconnected"),
})
DatabaseConnection::Disconnected => Err(conn_err("Disconnected")),
}
})
}
}
Expand All @@ -233,7 +226,7 @@ impl TransactionTrait for DatabaseConnection {
DatabaseConnection::MockDatabaseConnection(conn) => {
DatabaseTransaction::new_mock(Arc::clone(conn), None).await
}
DatabaseConnection::Disconnected => panic!("Disconnected"),
DatabaseConnection::Disconnected => Err(conn_err("Disconnected")),
}
}

Expand All @@ -260,7 +253,7 @@ impl TransactionTrait for DatabaseConnection {
DatabaseConnection::MockDatabaseConnection(conn) => {
DatabaseTransaction::new_mock(Arc::clone(conn), None).await
}
DatabaseConnection::Disconnected => panic!("Disconnected"),
DatabaseConnection::Disconnected => Err(conn_err("Disconnected")),
}
}

Expand Down Expand Up @@ -296,7 +289,7 @@ impl TransactionTrait for DatabaseConnection {
.map_err(TransactionError::Connection)?;
transaction.run(_callback).await
}
DatabaseConnection::Disconnected => panic!("Disconnected"),
DatabaseConnection::Disconnected => Err(conn_err("Disconnected").into()),
}
}

Expand Down Expand Up @@ -340,24 +333,36 @@ impl TransactionTrait for DatabaseConnection {
.map_err(TransactionError::Connection)?;
transaction.run(_callback).await
}
DatabaseConnection::Disconnected => panic!("Disconnected"),
DatabaseConnection::Disconnected => Err(conn_err("Disconnected").into()),
}
}
}

#[cfg(feature = "mock")]
impl DatabaseConnection {
/// Generate a database connection for testing the Mock database
///
/// # Panics
///
/// Panics if [DbConn] is not a mock connection.
pub fn as_mock_connection(&self) -> &crate::MockDatabaseConnection {
match self {
DatabaseConnection::MockDatabaseConnection(mock_conn) => mock_conn,
_ => panic!("not mock connection"),
_ => panic!("Not mock connection"),
}
}

/// Get the transaction log as a collection Vec<[crate::Transaction]>
/// Get the transaction log as a collection Vec<[crate::Transaction]>
///
/// # Panics
///
/// Panics if the mocker mutex is being held by another thread.
pub fn into_transaction_log(self) -> Vec<crate::Transaction> {
let mut mocker = self.as_mock_connection().get_mocker_mutex().lock().unwrap();
let mut mocker = self
.as_mock_connection()
.get_mocker_mutex()
.lock()
tyt2y3 marked this conversation as resolved.
Show resolved Hide resolved
.expect("Fail to acquire mocker");
mocker.drain_transaction_log()
}
}
Expand Down Expand Up @@ -399,16 +404,18 @@ impl DatabaseConnection {
// Nothing to cleanup, we just consume the `DatabaseConnection`
Ok(())
}
DatabaseConnection::Disconnected => {
Err(DbErr::Conn(RuntimeErr::Internal("Disconnected".to_owned())))
}
DatabaseConnection::Disconnected => Err(conn_err("Disconnected")),
}
}
}

#[cfg(feature = "sea-orm-internal")]
impl DatabaseConnection {
/// Get [sqlx::MySqlPool]
///
/// # Panics
///
/// Panics if [DbConn] is not a MySQL connection.
#[cfg(feature = "sqlx-mysql")]
pub fn get_mysql_connection_pool(&self) -> &sqlx::MySqlPool {
match self {
Expand All @@ -418,6 +425,10 @@ impl DatabaseConnection {
}

/// Get [sqlx::PgPool]
///
/// # Panics
///
/// Panics if [DbConn] is not a Postgres connection.
#[cfg(feature = "sqlx-postgres")]
pub fn get_postgres_connection_pool(&self) -> &sqlx::PgPool {
match self {
Expand All @@ -427,6 +438,10 @@ impl DatabaseConnection {
}

/// Get [sqlx::SqlitePool]
///
/// # Panics
///
/// Panics if [DbConn] is not a SQLite connection.
#[cfg(feature = "sqlx-sqlite")]
pub fn get_sqlite_connection_pool(&self) -> &sqlx::SqlitePool {
match self {
Expand All @@ -440,7 +455,7 @@ impl DbBackend {
/// Check if the URI is the same as the specified database backend.
/// Returns true if they match.
pub fn is_prefix_of(self, base_url: &str) -> bool {
let base_url_parsed = Url::parse(base_url).unwrap();
let base_url_parsed = Url::parse(base_url).expect("Fail to parse database URL");
match self {
Self::Postgres => {
base_url_parsed.scheme() == "postgres" || base_url_parsed.scheme() == "postgresql"
Expand Down