/** Drop table constraints */
  public void dropTableConstraints(Session session) {
    if (!SchemaManager.FAST_TABLE_CREATOR) {
      if (session.getLogin().getPlatform().isOracle()) {
        try {
          session.executeNonSelectingCall(new SQLCall("drop table BUS CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }

        try {
          session.executeNonSelectingCall(new SQLCall("drop table CAR CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }

        try {
          session.executeNonSelectingCall(new SQLCall("drop table COMPANY CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }

        try {
          session.executeNonSelectingCall(new SQLCall("drop table FUEL_VEH CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }

        try {
          session.executeNonSelectingCall(new SQLCall("drop table NH_COMP CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }

        try {
          session.executeNonSelectingCall(new SQLCall("drop table INH_MF CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }

        try {
          session.executeNonSelectingCall(
              new SQLCall("drop table KING_DEVELOPER CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }

        try {
          session.executeNonSelectingCall(
              new SQLCall("drop table KING_PERSONG CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }

        try {
          session.executeNonSelectingCall(new SQLCall("drop table PARTNUMS CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }

        try {
          session.executeNonSelectingCall(new SQLCall("drop table VEHICLE CASCADE CONSTRAINTS"));
        } catch (Exception e) {
        }
      }

      // Drop old constraints.
      try {
        if (session.getPlatform().supportsUniqueKeyConstraints()
            && !session.getPlatform().requiresUniqueConstraintCreationOnTableCreate()) {
          session.executeNonSelectingSQL(
              "Alter TABLE PROJECT_WORKER_BATCH DROP CONSTRAINT PROJECT_WORKER_BATCH_HD");
          session.executeNonSelectingSQL(
              "Alter TABLE PROJECT_BATCH DROP CONSTRAINT PROJECT_WORKER_BATCH_FK");
          session.executeNonSelectingSQL(
              "Alter TABLE ALLIGATOR DROP CONSTRAINT FK_ALLIGATOR_VICTIM_ID");
          session.executeNonSelectingSQL(
              "Alter TABLE PERSON2 DROP CONSTRAINT PERSON2_PERSON2_FRND");
          session.executeNonSelectingSQL("Alter TABLE PERSON2 DROP CONSTRAINT PERSON2_PERSON2_REP");
          session.executeNonSelectingSQL("Alter TABLE PERSON2 DROP CONSTRAINT PERSON2_PERSON2_BS");
        }
      } catch (Exception ignore) {
      }
    }
  }
  public void setup() {
    oldSession = getSession();
    DatabaseLogin login = (DatabaseLogin) oldSession.getLogin().clone();
    if (login.getConnector() instanceof JNDIConnector) {
      login.setConnector(new JNDIConnector("jdbc/OracleCoreAQ"));
    } else {
      login.setUserName("aquser");
      login.setPassword("aquser");
    }
    DatabaseSession session = new Project(login).createDatabaseSession();
    session.setSessionLog(getSession().getSessionLog());
    try {
      session.login();
    } catch (Exception exception) {
      throw new TestProblemException(
          "Database needs to be setup for AQ, with the aquser", exception);
    }

    /**
     * to setup aquser, need to execute, 1 - login as sys (default password is password) - login as
     * scott tiger connect sys/password@james as sysdba
     *
     * <p>2 - might need to install aq procesures? - in sqlplus
     * - @@<orahome>\ora92\rdbms\admin\catproc.sql
     *
     * <p>3 - create a aq user (i.e aquser) grant connect, resource , aq_administrator_role to
     * aquser identified by aquser grant execute on dbms_aq to aquser grant execute on dbms_aqadm to
     * aquser grant execute on dbms_lock to aquser connect aquser/aquser
     */
    try {
      session.executeNonSelectingCall(
          new SQLCall("begin DBMS_AQADM.STOP_QUEUE (queue_name => 'order_queue'); end;"));
    } catch (Exception notThere) {
    }
    try {
      session.executeNonSelectingCall(
          new SQLCall("begin DBMS_AQADM.DROP_QUEUE (queue_name => 'order_queue'); end;"));
    } catch (Exception notThere) {
    }
    try {
      session.executeNonSelectingCall(
          new SQLCall(
              "begin DBMS_AQADM.DROP_QUEUE_TABLE (queue_table => 'order_queue_table'); end;"));
    } catch (Exception notThere) {
    }
    try {
      session.executeNonSelectingCall(
          new SQLCall("begin DBMS_AQADM.STOP_QUEUE (queue_name => 'order_topic'); end;"));
    } catch (Exception notThere) {
    }
    try {
      session.executeNonSelectingCall(
          new SQLCall("begin DBMS_AQADM.DROP_QUEUE (queue_name => 'order_topic'); end;"));
    } catch (Exception notThere) {
    }
    try {
      session.executeNonSelectingCall(
          new SQLCall(
              "begin DBMS_AQADM.DROP_QUEUE_TABLE (queue_table => 'order_topic_table'); end;"));
    } catch (Exception notThere) {
    }
    try {
      session.executeNonSelectingCall(
          new SQLCall("begin DBMS_AQADM.STOP_QUEUE (queue_name => 'raw_order_queue'); end;"));
    } catch (Exception notThere) {
    }
    try {
      session.executeNonSelectingCall(
          new SQLCall("begin DBMS_AQADM.DROP_QUEUE (queue_name => 'raw_order_queue'); end;"));
    } catch (Exception notThere) {
    }
    try {
      session.executeNonSelectingCall(
          new SQLCall(
              "begin DBMS_AQADM.DROP_QUEUE_TABLE (queue_table => 'raw_order_queue_table'); end;"));
    } catch (Exception notThere) {
    }

    session.executeNonSelectingCall(
        new SQLCall(
            "begin DBMS_AQADM.CREATE_QUEUE_TABLE (queue_table => 'order_queue_table', multiple_consumers => FALSE, queue_payload_type => 'SYS.AQ$_JMS_TEXT_MESSAGE'); end;"));
    session.executeNonSelectingCall(
        new SQLCall(
            "begin DBMS_AQADM.CREATE_QUEUE (queue_name => 'order_queue', queue_table => 'order_queue_table'); end;"));
    session.executeNonSelectingCall(
        new SQLCall("begin DBMS_AQADM.START_QUEUE (queue_name => 'order_queue'); end;"));

    session.executeNonSelectingCall(
        new SQLCall(
            "begin DBMS_AQADM.CREATE_QUEUE_TABLE (queue_table => 'order_topic_table', multiple_consumers => TRUE, queue_payload_type => 'SYS.AQ$_JMS_TEXT_MESSAGE'); end;"));
    session.executeNonSelectingCall(
        new SQLCall(
            "begin DBMS_AQADM.CREATE_QUEUE (queue_name => 'order_topic', queue_table => 'order_topic_table'); end;"));
    session.executeNonSelectingCall(
        new SQLCall("begin DBMS_AQADM.START_QUEUE (queue_name => 'order_topic'); end;"));

    session.executeNonSelectingCall(
        new SQLCall(
            "begin DBMS_AQADM.CREATE_QUEUE_TABLE (queue_table => 'raw_order_queue_table', multiple_consumers => FALSE, queue_payload_type => 'RAW'); end;"));
    session.executeNonSelectingCall(
        new SQLCall(
            "begin DBMS_AQADM.CREATE_QUEUE (queue_name => 'raw_order_queue', queue_table => 'raw_order_queue_table'); end;"));
    session.executeNonSelectingCall(
        new SQLCall("begin DBMS_AQADM.START_QUEUE (queue_name => 'raw_order_queue'); end;"));

    session =
        XMLProjectReader.read(
                "org/eclipse/persistence/testing/models/order/eis/aq/order-project.xml",
                getClass().getClassLoader())
            .createDatabaseSession();
    session.setSessionLog(getSession().getSessionLog());

    // String url = oldSession.getLogin().getConnectionString();
    String url;
    try {
      url = ((AbstractSession) getSession()).getAccessor().getConnection().getMetaData().getURL();
    } catch (java.sql.SQLException se) {
      se.printStackTrace();
      throw new TestErrorException("There is SQLException");
    }
    EISLogin eisLogin = (EISLogin) session.getDatasourceLogin();
    eisLogin.setConnectionSpec(new AQEISConnectionSpec());
    eisLogin.setProperty(AQEISConnectionSpec.URL, url);
    eisLogin.setUserName("aquser");
    eisLogin.setPassword("aquser");
    session.login();

    getExecutor().setSession(session);
  }
  /**
   * Load the last test result from the test result database. Find only the results run on the same
   * machine and database. Compare the current test run result with the previous results do
   * determine if the test passes or fails.
   */
  public static void verify(PerformanceRegressionTest test) {
    // Ensures all tests pass to reset baseline,
    // Required when tests or environment change to be slower to avoid failures.
    if (reset) {
      throw new TestWarningException("Reseting baseline.");
    }
    Session session = LoadBuildSystem.getSystem().getSession();

    // Query all previous successful test results for this test on the same machine and database.
    // Find only the baseline version, or last version run different than current version.
    // If you need to compare results against the current version you must change the TopLink
    // version string.
    ReadAllQuery query = new ReadAllQuery(TestResult.class);
    ExpressionBuilder result = new ExpressionBuilder();
    query.setSelectionCriteria(
        result
            .get("name")
            .equal(test.getName())
            .and(
                result
                    .get("loadBuildSummary")
                    .get("machine")
                    .equal(LoadBuildSystem.getSummary().getMachine()))
            .and(
                result
                    .get("loadBuildSummary")
                    .get("loginChoice")
                    .equal(LoadBuildSystem.getSummary().getLoginChoice())));
    // Allow comparing to a set version through a system property.
    String currentVersion = LoadBuildSystem.getSummary().getToplinkVersion();
    String baselineVersion = null;
    if (System.getProperties().containsKey("toplink.loadbuild.baseline-version")) {
      baselineVersion = System.getProperties().getProperty("toplink.loadbuild.baseline-version");
      // System properties cannot store spaces so need to replace them from \b.
      baselineVersion = baselineVersion.replace('_', ' ');
      ((PerformanceComparisonTestResult) ((TestCase) test).getTestResult()).baselineVersion =
          baselineVersion;
    } else {
      // Compare against the last successful version.
      ReportQuery reportQuery = new ReportQuery(TestResult.class, query.getExpressionBuilder());
      reportQuery.useDistinct();
      reportQuery.returnSingleValue();
      reportQuery.addAttribute("version", result.get("loadBuildSummary").get("toplinkVersion"));
      reportQuery.setSelectionCriteria(
          query
              .getSelectionCriteria()
              .and(
                  (result.get("outcome").equal(TestResult.PASSED))
                      .or(result.get("outcome").equal(TestResult.WARNING)))
              .and(result.get("loadBuildSummary").get("toplinkVersion").notEqual(currentVersion)));
      reportQuery.addOrdering(result.get("loadBuildSummary").get("timestamp").descending());
      baselineVersion = (String) session.executeQuery(reportQuery);
    }
    query.setSelectionCriteria(
        query
            .getSelectionCriteria()
            .and(result.get("loadBuildSummary").get("toplinkVersion").equal(baselineVersion)));
    query.addOrdering(result.get("loadBuildSummary").get("timestamp").descending());
    query.setMaxRows(10);
    query.useCursoredStream(1, 1);
    CursoredStream stream = (CursoredStream) session.executeQuery(query);
    if (!stream.hasMoreElements()) {
      throw new TestWarningException("No previous test result to compare performance with.");
    }
    TestResult lastResult = (TestResult) stream.nextElement();
    double lastCount = lastResult.getTestTime();
    PerformanceComparisonTestResult testResult =
        (PerformanceComparisonTestResult) ((TestCase) test).getTestResult();
    testResult.getBaselineVersionResults().add(new Double(lastCount));
    // Average last 5 runs.
    int numberOfRuns = 0;
    while (stream.hasMoreElements() && (numberOfRuns < 4)) {
      TestResult nextResult = (TestResult) stream.nextElement();
      testResult.getBaselineVersionResults().add(new Double(nextResult.getTestTime()));
      numberOfRuns++;
    }
    stream.close();
    double baselineAverage =
        PerformanceComparisonTestResult.averageResults(testResult.getBaselineVersionResults());
    double currentCount = ((TestCase) test).getTestResult().getTestTime();
    testResult.baselineVersion = lastResult.getLoadBuildSummary().getToplinkVersion();
    testResult.percentageDifferenceLastRun =
        PerformanceComparisonTestResult.percentageDifference(currentCount, lastCount);

    // Query the current version last 5 runs for averaging.
    query = new ReadAllQuery(TestResult.class);
    result = new ExpressionBuilder();
    query.setSelectionCriteria(
        result
            .get("name")
            .equal(((TestCase) test).getName())
            .and(
                result
                    .get("loadBuildSummary")
                    .get("machine")
                    .equal(LoadBuildSystem.getSummary().getMachine()))
            .and(
                result
                    .get("loadBuildSummary")
                    .get("loginChoice")
                    .equal(LoadBuildSystem.getSummary().getLoginChoice()))
            .and(result.get("loadBuildSummary").get("toplinkVersion").equal(currentVersion)));
    query.addOrdering(result.get("loadBuildSummary").get("timestamp").descending());
    query.useCursoredStream(1, 1);
    stream = (CursoredStream) session.executeQuery(query);
    // Average last 5 runs.
    testResult.getCurrentVersionResults().add(new Double(currentCount));
    numberOfRuns = 0;
    while (stream.hasMoreElements() && (numberOfRuns < 4)) {
      TestResult nextResult = (TestResult) stream.nextElement();
      testResult.getCurrentVersionResults().add(new Double(nextResult.getTestTime()));
      numberOfRuns++;
    }
    stream.close();
    double currentAverage =
        PerformanceComparisonTestResult.averageResults(testResult.getCurrentVersionResults());
    testResult.percentageDifferenceAverage =
        PerformanceComparisonTestResult.percentageDifference(currentAverage, baselineAverage);

    testResult.baselineStandardDeviation =
        PerformanceComparisonTestResult.standardDeviationResults(
            testResult.getBaselineVersionResults());
    testResult.currentStandardDeviation =
        PerformanceComparisonTestResult.standardDeviationResults(
            testResult.getCurrentVersionResults());

    if (testResult.percentageDifferenceAverage < test.getAllowableDecrease()) {
      throw new TestErrorException(
          "Test is "
              + ((long) testResult.percentageDifferenceAverage)
              + "% slower than last successful execution.");
    }
  }