{"record":{"id":"096130180a090d17","repo":"t8y2/dbx","slug":"failed-to-restore-the-original-jdbc-schema-context","errorCode":null,"errorMessage":"Failed to restore the original JDBC schema context","messagePattern":"Failed to restore the original JDBC schema context","errorType":"exception","errorClass":"SQLException","httpStatus":null,"severity":"error","filePath":"agents/common/src/main/java/com/dbx/agent/JdbcSchemaSwitcher.java","lineNumber":31,"sourceCode":"    private static final Map<Connection, ResetState> RESET_STATE_BY_CONNECTION =\n        Collections.synchronizedMap(new WeakHashMap<>());\n\n    private JdbcSchemaSwitcher() {\n    }\n\n    static void apply(Connection conn, String schema, Function<String, String> setSchemaSql) throws Exception {\n        apply(conn, schema, setSchemaSql, () -> \"\");\n    }\n\n    static void apply(\n        Connection conn,\n        String schema,\n        Function<String, String> setSchemaSql,\n        Supplier<String> resetSchemaSql\n    ) throws Exception {\n        if (schema == null || schema.trim().isEmpty()) {\n            if (!restore(conn, true)) {\n                throw new SQLException(\"Failed to restore the original JDBC schema context\");\n            }\n            return;\n        }\n\n        ResetState resetState = resetState(conn);\n        SchemaSqlResult schemaSqlResult = applySchemaSql(conn, () -> setSchemaSql.apply(schema));\n        Exception schemaSqlError = schemaSqlResult.error;\n        if (schemaSqlError == null) {\n            resetState.mode = ResetMode.SQL;\n            rememberResetSql(resetState, resetSchemaSql);\n            return;\n        }\n\n        try {\n            conn.setSchema(schema);\n            resetState.mode = ResetMode.SCHEMA;\n            return;\n        } catch (SQLException | UnsupportedOperationException | AbstractMethodError ignored) {","sourceCodeStart":13,"sourceCodeEnd":49,"githubUrl":"https://github.com/t8y2/dbx/blob/c0390bff16418b651f4728520d99adf8ce48829a/agents/common/src/main/java/com/dbx/agent/JdbcSchemaSwitcher.java#L13-L49","documentation":"JdbcSchemaSwitcher.apply throws SQLException when asked to switch back to the original (null/blank schema) JDBC schema context and restore(conn, true) fails to reinstate the saved catalog/schema. It signals the connection's original schema context could not be re-established, leaving the connection on the wrong schema.","triggerScenarios":"Calling apply with a null/empty schema (meaning 'reset to original') while the connection has no recorded original state, or the reset statements fail (e.g. resetSchemaSql supplier returns SQL the driver rejects, connection already broken).","commonSituations":"Tooling that switches schemas per query then restores; connections where the original schema was never captured because switch happened before restore support; DB2/Postgres drivers rejecting the RESET SEARCH_PATH style statement; connection dropped mid-operation.","solutions":["Verify the connection is still open and valid before calling apply(null, ...) to restore","Ensure an original schema context was recorded by a prior successful switch (or capture conn.getSchema()/getCatalog() yourself before switching)","Check the resetSchemaSql supplier returns driver-correct SQL for your database","Catch the SQLException, close/reconnect, and re-run the intended schema switch"],"exampleFix":"// before\nswitcher.apply(conn, null, setSql, resetSql);\n// after\nif (conn.isValid(2)) {\n    switcher.apply(conn, null, setSql, resetSql);\n} else {\n    conn = reconnect(); // restore on a fresh connection\n}","handlingStrategy":"try-catch","validationCode":"if (conn == null || conn.isClosed()) throw new IllegalStateException(\"Cannot restore schema on a closed connection\");","typeGuard":"boolean restorable(Connection c) { try { return c != null && !c.isClosed(); } catch (SQLException e) { return false; } }","tryCatchPattern":"try {\n    switcher.apply(conn, null, setSql, resetSql);\n} catch (SQLException e) {\n    // restore failed: reconnect and re-apply intended schema\n    conn = reconnect();\n    switcher.apply(conn, targetSchema, setSql, resetSql);\n}","preventionTips":["Capture conn.getSchema()/getCatalog() before any schema switch","Validate the connection before restore attempts","Ensure resetSchemaSql matches the target database dialect","Restore schema context in a finally block and verify afterwards"],"tags":["jdbc","schema","sql-exception","state-restore"],"backgroundTag":"schema-restore-failed","analyzedSha":"c0390bff16418b651f4728520d99adf8ce48829a","analyzedAt":"2026-09-05T23:05:10.900Z","contentChangedAt":"2026-09-05T23:05:10.900Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}