SeaQL/sea-orm · critical

Not mock connection

Error message

Not mock connection

What it means

`DatabaseConnection::as_mock_connection()` downcasts the connection to a `MockDatabaseConnection`. The connection's inner enum holds whichever backend was actually constructed (SqlxMySql, Postgres, Sqlite, or Mock); if the `DbConn` was not created via `MockDatabase::new(...).into_connection()`, the match falls through and panics with "Not mock connection".

Source

Thrown at src/database/db_connection.rs:581

                    .map_err(TransactionError::Connection)?;
                transaction.run(_callback).await
            }
            DatabaseConnectionType::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.inner {
            DatabaseConnectionType::MockDatabaseConnection(mock_conn) => mock_conn,
            _ => panic!("Not mock connection"),
        }
    }

    /// 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()
            .expect("Fail to acquire mocker");
        mocker.drain_transaction_log()
    }
}

View on GitHub (pinned to e29bcd1b41)

Solutions

  1. In tests, build the connection from a mock: `let db = MockDatabase::new(DatabaseBackend::Postgres).into_connection();` and pass that to the code under test.
  2. Remove or feature-gate the `as_mock_connection()` call (and mock-only assertions) from code paths that run against real connections.
  3. Guard the call with a runtime check, e.g. match on the backend / `db.supports_mock()` style check or `#[cfg(test)]`, before downcasting.
  4. If mixing real and mock connections, hold two separate `DatabaseConnection` values and only invoke mock APIs on the mock one.

Example fix

// before
let db = Database::connect("postgres://localhost/app").await?;
let log = db.as_mock_connection().extract_sql(); // panics: not a mock

// after
let db = MockDatabase::new(DatabaseBackend::Postgres).into_connection();
// ... run queries ...
let log = db.as_mock_connection().extract_sql();
Defensive patterns

Strategy: type-guard

Validate before calling

// Only exercise mock APIs on connections built from MockDatabase
let db = MockDatabase::new(DatabaseBackend::MySql).into_connection();
debug_assert!(matches!(db.get_database_backend(), DatabaseBackend::MySql));

Type guard

// Narrow by construction, not by inspection:
struct TestDb { conn: DatabaseConnection } // conn is ALWAYS MockDatabase::into_connection()
impl TestDb {
    fn new(backend: DatabaseBackend) -> Self {
        Self { conn: MockDatabase::new(backend).into_connection() }
    }
    fn mock(&self) -> &MockDatabaseConnection { self.conn.as_mock_connection() } // infallible by construction
}

Try / catch

// panic! is not catchable in Rust; restrict with cfg(test) instead
#[cfg(test)]
fn extract_log(db: &DatabaseConnection) -> Vec<Transaction> {
    db.as_mock_connection().extract_sql()
}

Prevention

When it happens

Trigger: Calling `db.as_mock_connection()` (directly or via the transaction-log helpers that require it) on a `DatabaseConnection` built with `Database::connect(...)` against a real database, instead of one produced from `MockDatabase`.

Common situations: Test scaffolding copies the connection setup from production code and connects to a real DB, then calls mock-only assertion helpers (e.g. `dump`ing the transaction log); feature-gated test code runs against a live connection; confusing `MockDatabaseConnector` with the real connector in fixture setup.

Understand the failure class

Background: Type mismatch errors: IllegalArgumentException, TypeError and type guards across 150 open-source libraries — this error's family across 150 libraries.

Related errors


AI-assisted analysis of SeaQL/sea-orm@e29bcd1b41 (2026-09-10). Data as JSON: /api/errors/95b8acd5c1a28a2b. Report an issue: GitHub.