import java.util.*;
import java.sql.*;

/**
This test shows that when a postgres jdbc connection gets a referential integrity
exception, the connection no longer returns correct query results.
*/
public class JTest {

public static void main(String[] args) {

  // first load the driver
  try {
    Class.forName("org.postgresql.Driver");
    }
  catch (Exception ex) {
    System.out.println("Didn't expect this error: " + ex.getMessage());
    return;
    }

  Connection con = null;
  try {
    // substitute your own database name here
    String dbName = "jdbc:postgresql:everbasealmarode";
    con = DriverManager.getConnection(dbName, "postgres", "p0stgr3s");

    Statement query = null;
    // substitute any valid query string here
    String validSQLQuery = "SELECT * FROM ValidPaymentType";

    // 1. first execute a valid query
    System.out.println("About to execute a valid query (we expect results)");
    try {
      query = con.createStatement();
      ResultSet results = query.executeQuery(validSQLQuery);
      System.out.println("After executing a valid query (no exception thrown)");
      }
    catch (Exception ex) {
      System.out.println("After first valid query (unexpected exception): " + ex.getMessage());
      }

    // 2. now execute an sql statement that causes a referential integrity exception
    Statement statement = null;
    try {
      // there are no records with keys 99999 or 88888 (foreign key references)
      String sql = "INSERT INTO CustomerAddress VALUES (222, 99999, 88888, true)";
      statement = con.createStatement();
      int cnt = statement.executeUpdate(sql);
      }
    catch (Exception ex) {
      System.out.println("Expected this error: " + ex.getMessage());
      }
    finally {
      System.out.println("Closing error-producing statement");
      if (statement != null) {
        statement.close();
        }
      }

    // 3. now execute a query that we expect to be valid
    try {
      query = con.createStatement();
      System.out.println("About to execute another valid query");
      ResultSet results = query.executeQuery(validSQLQuery);
      System.out.println("After executing second valid query");
      }
    catch (Exception ex) {
      System.out.println("After second valid query (unexpected exception): " + ex.getMessage());
      }
    }
  catch (SQLException ex) {
    System.out.println("Didn't expect this error: " + ex.getMessage());
    }
  finally { // make sure we close the database connection
    if (con != null) {
      try {
        con.close();
        }
      catch (SQLException ex) {
        System.out.println("Didn't expect this error: " + ex.getMessage());
        }
      }
    }
  }
}

