package de.ikoffice.db;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DBErrorsAndTheConnectionPoolTest {

    public static void main(String[] args) throws SQLException {
        DriverManager.registerDriver(new org.postgresql.Driver());
        Connection c = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5434/IKOffice_Framework?loglevel=2",
                "ik","******");
        DriverManager.setLogWriter(new PrintWriter(System.out,true));
        Statement stmt = c.createStatement();
        
        try {
            stmt.execute("SELECT fail"); // This will fail.
            throw new AssertionError();     
        } catch( SQLException e ) {
            System.out.println("***** We failed as expected.");    
        }    
        
        try {
            stmt.execute("SELECT 1"); // This will work again.
            System.out.println("***** We recovered as expected.");    
        } catch( SQLException e ) {
            throw new AssertionError();     
        }    
        
        try {
            // Make this fail, by executing the first 3 lines of 
            // the following query in another connection:
            //
            // BEGIN;
            // LOCK TABLE company IN SHARE MODE;
            // LOCK TABLE dbuser IN SHARE MODE;
            // COMMIT;
            //
            stmt.execute("BEGIN;"+
                         "SELECT FAIL;"+
                         "COMMIT;");
        } catch( SQLException e ) {
            System.out.println("***** We failed as expected.");    
        }    
        
        // Note: c.rollback will always raise an exception, even if the 
        //       backend is still in autocommit mode!
       
        try {
            stmt.execute("SELECT 1"); // This will hopefully work again.
            System.out.println("***** GREAT! We recovered as expected.");    
        } catch( SQLException e ) {
            System.out.println("***** BIG BUG HERE! We failed!");    
        }        
         
    }
    
}
