Java Code Examples for org.h2.jdbc.JdbcSQLException

The following examples show how to use org.h2.jdbc.JdbcSQLException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
@DisplayName("Clean at start correctly")
public void testLiquibaseConfigInjection() throws Exception {
    try (Connection connection = defaultDataSource.getConnection(); Statement stat = connection.createStatement()) {
        try (ResultSet executeQuery = stat
                .executeQuery("select * from fake_existing_tbl")) {
            fail("fake_existing_tbl should not exist");
        } catch (JdbcSQLException e) {
            // expected fake_existing_tbl does not exist
        }
    }

    try (Liquibase liquibase = liquibaseFactory.createLiquibase()) {
        List<ChangeSetStatus> status = liquibase.getChangeSetStatuses(liquibaseFactory.createContexts(),
                liquibaseFactory.createLabels());
        assertNotNull(status, "Status is null");
        assertEquals(1, status.size(), "The set of changes is not null");
        assertTrue(status.get(0).getWillRun());

        List<ChangeSet> unrun = liquibase.listUnrunChangeSets(liquibaseFactory.createContexts(),
                liquibaseFactory.createLabels());
        assertNotNull(unrun, "Unrun is null");
        assertEquals(1, status.size(), "The set of unrun changes is not null");
    }
}
 
Example 2
@Test
@DisplayName("Clean and migrate at start correctly")
public void testLiquibaseConfigInjection() throws Exception {

    try (Connection connection = defaultDataSource.getConnection(); Statement stat = connection.createStatement()) {
        try (ResultSet executeQuery = stat
                .executeQuery("select * from fake_existing_tbl")) {
            fail("fake_existing_tbl should not exist");
        } catch (JdbcSQLException e) {
            // expected fake_existing_tbl does not exist
        }
    }
    try (Liquibase liquibase = liquibaseFactory.createLiquibase()) {
        List<ChangeSetStatus> status = liquibase.getChangeSetStatuses(liquibaseFactory.createContexts(),
                liquibaseFactory.createLabels());
        assertNotNull(status, "Status is null");
        assertEquals(1, status.size(), "The set of changes is not null");
        assertFalse(status.get(0).getWillRun());
    }
}
 
Example 3
/**
 *
 * @throws Exception if failed.
 */
@Test
public void testDropColumn() throws Exception {
    try {
        run("CREATE TABLE test (id INT PRIMARY KEY, a INT, b CHAR)");

        assertEquals(0, checkTableState(QueryUtils.DFLT_SCHEMA, "TEST",
            new QueryField("ID", Integer.class.getName(), true),
            new QueryField("A", Integer.class.getName(), true),
            new QueryField("B", String.class.getName(), true)));

        run("ALTER TABLE test DROP COLUMN a");

        assertEquals(0, checkTableState(QueryUtils.DFLT_SCHEMA, "TEST",
            new QueryField("ID", Integer.class.getName(), true),
            new QueryField("B", String.class.getName(), true)));

        run("ALTER TABLE test DROP COLUMN IF EXISTS a");

        assertThrowsAnyCause("ALTER TABLE test DROP COLUMN a", JdbcSQLException.class, "Column \"A\" not found");
    }
    finally {
        run("DROP TABLE IF EXISTS test");
    }
}
 
Example 4
Source Project: ignite   Source File: H2DynamicTableSelfTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check that given (non DDL) command throws an exception as expected.
 * @param checkedTblName Table name to expect in error message.
 * @param cmd Command to execute.
 */
private void assertCommandThrowsTableNotFound(String checkedTblName, final String cmd) {
    final Throwable e = GridTestUtils.assertThrowsWithCause(new Callable<Object>() {
        @Override public Object call() throws Exception {
            execute(cmd);

            return null;
        }
    }, JdbcSQLException.class);

    GridTestUtils.assertThrows(null, new Callable<Object>() {
        @SuppressWarnings("ConstantConditions")
        @Override public Object call() throws Exception {
            throw (Exception)e.getCause();
        }
    }, JdbcSQLException.class, "Table \"" + checkedTblName + "\" not found");
}
 
Example 5
Source Project: quarkus   Source File: FlywayExtensionCleanAtStartTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Clean at start correctly")
public void testFlywayConfigInjection() throws SQLException {

    try (Connection connection = defaultDataSource.getConnection(); Statement stat = connection.createStatement()) {
        try (ResultSet executeQuery = stat.executeQuery("select * from fake_existing_tbl")) {
            fail("fake_existing_tbl should not exist");
        } catch (JdbcSQLException e) {
            // expected fake_existing_tbl does not exist
        }
    }
    MigrationInfo current = flyway.info().current();
    assertNull(current, "Info is not null");
}
 
Example 6
Source Project: rxjava2-jdbc   Source File: DatabaseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDatabaseFrom() {
    Database.from(DatabaseCreator.nextUrl(), 3) //
            .select("select name from person") //
            .getAs(String.class) //
            .count() //
            .test() //
            .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
            .assertError(JdbcSQLException.class);
}
 
Example 7
/**
 *
 * @throws Exception if failed.
 */
@Test
public void testDropNonExistingColumn() throws Exception {
    try {
        run("CREATE TABLE test (id INT PRIMARY KEY, a INT)");

        assertThrowsAnyCause("ALTER TABLE test DROP COLUMN b", JdbcSQLException.class, "Column \"B\" not found");
    }
    finally {
        run("DROP TABLE IF EXISTS test");
    }
}
 
Example 8
@Test
public void readOnlyAuditLog() throws Exception {
  // create an organization to test that path
  createOrganization(testIdentity, testIdentity.getName(), 
      Lists.newArrayList(testIdentity), Lists.newArrayList(testIdentity));

  // this must be a disk db for reopening as read-only to work (it seems)
  // Another alternative would be to create a read-only user, but I can't get that to work either
  final String PATH = tempFolder.newFile().getAbsolutePath();
  final String OTHER_DB_URL = "jdbc:h2:file:" + PATH + ";DATABASE_TO_UPPER=FALSE";
  // create a ManagerFactory just to create the tables (yuck)
  new ManagerFactory(OTHER_DB_URL, new Manager.Pool(), ManagerFactory.IDLE_TXN_POLL_SECONDS, TimeUnit.SECONDS, ManagerFactory.ConnectionMode.READ_WRITE);

  // create a read-only connection for the audit log
  JdbcConnectionSource readOnlyConnection = new JdbcConnectionSource(
      OTHER_DB_URL + ";ACCESS_MODE_DATA=r");
  try {
    readOnlyConnection.getReadWriteConnection().executeStatement(
        "UPDATE email_queue SET arg_string='';", DatabaseConnection.DEFAULT_RESULT_FLAGS);
    fail("expected exception");
  } catch (JdbcSQLException e) {
    assertThat(e.getMessage(), CoreMatchers.containsString("database is read only"));
  }
  Manager readOnlyAuditManager = new Manager(
      new Manager.Pool(),
      (JdbcConnectionSource) manager.identityDao.getConnectionSource(),
      readOnlyConnection,
      ManagerFactory.ConnectionMode.READ_WRITE);

  assertEquals(1, manager.auditDao.countOf());
  StatsGenerator.Snapshot output = StatsGenerator.generateStatistics(null, readOnlyAuditManager);
  assertEquals(1, manager.auditDao.countOf());
  assertEquals(2, output.userStateObjects.size());
  assertEquals(1, output.orgStateObjects.size());
}
 
Example 9
Source Project: attic-rave   Source File: H2OpenJpaDialect.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Translates an H2 database error into a Rave application Exception
 * 
 * @param re the RuntimeException to translate to a Rave application exception
 * @return a Rave application exception representing the database error
 */
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException re) {        
    DataAccessException e = null;
    // first make sure the root exception is actually an org.h2.jdbc.JdbcSQLException
    if (ExceptionUtils.getRootCause(re) instanceof JdbcSQLException) {
        JdbcSQLException rootException = (JdbcSQLException)ExceptionUtils.getRootCause(re);
                    
        // now translate the H2 specific error codes into Rave's common application Exceptions
        // add more error codes to the switch statement that should be specifically trapped                         
        switch(rootException.getErrorCode()) {
            case ErrorCode.DUPLICATE_KEY_1: {
                e = new DuplicateItemException("DUPLICATE_ITEM", rootException);
                break;
            }

            default: {
                e = new TranslatedH2Exception(rootException.getErrorCode(), "ERROR", "Unknown Database Error");
                break;
            }
        }
    } else {            
        // we got a RuntimeException that wasn't an org.h2.jdbc.JdbcSQLException
        e = new TranslatedH2Exception(TranslatedH2Exception.UNKNOWN_ERROR_CODE, "ERROR", "Unknown Runtime Exception");
    }
    
    return e;                
}
 
Example 10
Source Project: attic-rave   Source File: H2OpenJpaDialectTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of translateExceptionIfPossible method, of class H2OpenJpaDialect.
 */
@Test
public void testTranslateExceptionIfPossible_uniqueContstraintViolation() {                 
    JdbcSQLException jdbcEx = new JdbcSQLException("message", "sql statement", "state", ErrorCode.DUPLICATE_KEY_1, null, "stacktrace");
    RuntimeException re = new RuntimeException("dummy runtime exception", jdbcEx);

    assertTrue(dialect.translateExceptionIfPossible(re) instanceof DuplicateItemException);
}
 
Example 11
Source Project: attic-rave   Source File: H2OpenJpaDialectTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTranslateExceptionIfPossible_unknownJdbcSQLExceptionError() {                 
    JdbcSQLException jdbcEx = new JdbcSQLException("message", "sql statement", "state", ErrorCode.CANNOT_DROP_CURRENT_USER, null, "stacktrace");
    RuntimeException re = new RuntimeException("dummy runtime exception", jdbcEx);     
    
    TranslatedH2Exception translatedException = (TranslatedH2Exception) dialect.translateExceptionIfPossible(re);             
    assertThat(translatedException.getErrorCode(), is(ErrorCode.CANNOT_DROP_CURRENT_USER));        
}
 
Example 12
/**
 *
 * @throws Exception if failed.
 */
@Test
public void testDropColumnNonExistingTable() throws Exception {
    assertThrowsAnyCause("ALTER TABLE nosuchtable DROP COLUMN a", JdbcSQLException.class,
        "Table \"NOSUCHTABLE\" not found");
}