{"record":{"id":"95b8acd5c1a28a2b","repo":"SeaQL/sea-orm","slug":"not-mock-connection-95b8ac","errorCode":null,"errorMessage":"Not mock connection","messagePattern":"Not mock connection","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"src/database/db_connection.rs","lineNumber":581,"sourceCode":"                    .map_err(TransactionError::Connection)?;\n                transaction.run(_callback).await\n            }\n            DatabaseConnectionType::Disconnected => Err(conn_err(\"Disconnected\").into()),\n        }\n    }\n}\n\n#[cfg(feature = \"mock\")]\nimpl DatabaseConnection {\n    /// Generate a database connection for testing the Mock database\n    ///\n    /// # Panics\n    ///\n    /// Panics if [DbConn] is not a mock connection.\n    pub fn as_mock_connection(&self) -> &crate::MockDatabaseConnection {\n        match &self.inner {\n            DatabaseConnectionType::MockDatabaseConnection(mock_conn) => mock_conn,\n            _ => panic!(\"Not mock connection\"),\n        }\n    }\n\n    /// Get the transaction log as a collection Vec<[crate::Transaction]>\n    ///\n    /// # Panics\n    ///\n    /// Panics if the mocker mutex is being held by another thread.\n    pub fn into_transaction_log(self) -> Vec<crate::Transaction> {\n        let mut mocker = self\n            .as_mock_connection()\n            .get_mocker_mutex()\n            .lock()\n            .expect(\"Fail to acquire mocker\");\n        mocker.drain_transaction_log()\n    }\n}\n","sourceCodeStart":563,"sourceCodeEnd":599,"githubUrl":"https://github.com/SeaQL/sea-orm/blob/e29bcd1b417c41a553b386fe94511d7c64a1c8ec/src/database/db_connection.rs#L563-L599","documentation":"`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\".","triggerScenarios":"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`.","commonSituations":"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.","solutions":["In tests, build the connection from a mock: `let db = MockDatabase::new(DatabaseBackend::Postgres).into_connection();` and pass that to the code under test.","Remove or feature-gate the `as_mock_connection()` call (and mock-only assertions) from code paths that run against real connections.","Guard the call with a runtime check, e.g. match on the backend / `db.supports_mock()` style check or `#[cfg(test)]`, before downcasting.","If mixing real and mock connections, hold two separate `DatabaseConnection` values and only invoke mock APIs on the mock one."],"exampleFix":"// before\nlet db = Database::connect(\"postgres://localhost/app\").await?;\nlet log = db.as_mock_connection().extract_sql(); // panics: not a mock\n\n// after\nlet db = MockDatabase::new(DatabaseBackend::Postgres).into_connection();\n// ... run queries ...\nlet log = db.as_mock_connection().extract_sql();","handlingStrategy":"type-guard","validationCode":"// Only exercise mock APIs on connections built from MockDatabase\nlet db = MockDatabase::new(DatabaseBackend::MySql).into_connection();\ndebug_assert!(matches!(db.get_database_backend(), DatabaseBackend::MySql));","typeGuard":"// Narrow by construction, not by inspection:\nstruct TestDb { conn: DatabaseConnection } // conn is ALWAYS MockDatabase::into_connection()\nimpl TestDb {\n    fn new(backend: DatabaseBackend) -> Self {\n        Self { conn: MockDatabase::new(backend).into_connection() }\n    }\n    fn mock(&self) -> &MockDatabaseConnection { self.conn.as_mock_connection() } // infallible by construction\n}","tryCatchPattern":"// panic! is not catchable in Rust; restrict with cfg(test) instead\n#[cfg(test)]\nfn extract_log(db: &DatabaseConnection) -> Vec<Transaction> {\n    db.as_mock_connection().extract_sql()\n}","preventionTips":["Wrap mock connections in a dedicated TestDb/test-fixture type so mock-only APIs are unreachable on real connections.","Never copy production `Database::connect` setup into tests that call as_mock_connection/transaction-log helpers.","Gate all mock-only calls behind #[cfg(test)] and keep them out of library/runtime code paths."],"tags":["panic","testing","mock-database","type-mismatch","seaorm"],"backgroundTag":"type-mismatch","analyzedSha":"e29bcd1b417c41a553b386fe94511d7c64a1c8ec","analyzedAt":"2026-09-10T11:31:52.468Z","contentChangedAt":"2026-09-10T11:31:52.468Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}