Java Code Examples for org.postgresql.util.PSQLException

The following examples show how to use org.postgresql.util.PSQLException. 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
Source Project: pxf   Source File: PluginTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(groups = "features")
public void emptyCredentialsGUCsTransferredAsNull() throws Exception {

    ReadableExternalTable exTable = new ReadableExternalTable("extens", new String[] {
            "num1 integer",
            "t1 text",
            "num2 integer" }, "regression_location", "CUSTOM");

    exTable.setFragmenter(testPackage + "DummyFragmenter");
    exTable.setAccessor(testPackage + "FaultyGUCAccessor");
    exTable.setResolver(testPackage + "DummyResolver");
    exTable.setFormatter("pxfwritable_import");

    exTable.setHost(pxfHost);
    exTable.setPort(pxfPort);

    gpdb.runQuery("SET pxf_remote_service_login = ''");
    gpdb.runQuery("SET pxf_remote_service_secret = ''");
    gpdb.createTableAndVerify(exTable);
    try {
        gpdb.queryResults(exTable, "SELECT num1, t1 FROM " + exTable.getName() + " ORDER BY num1, t1");
    } catch (Exception e) {
        ExceptionUtils.validate(null, e, new PSQLException("FaultyGUCAccessor: login null secret null", null), true);
    }
}
 
Example 2
Source Project: pxf   Source File: PluginTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(groups = "features")
public void defaultCredentialsGUCsTransferredAsNull() throws Exception {

    ReadableExternalTable exTable = new ReadableExternalTable("extens", new String[] {
            "num1 integer",
            "t1 text",
            "num2 integer" }, "regression_location", "CUSTOM");

    exTable.setFragmenter(testPackage + "DummyFragmenter");
    exTable.setAccessor(testPackage + "FaultyGUCAccessor");
    exTable.setResolver(testPackage + "DummyResolver");
    exTable.setFormatter("pxfwritable_import");

    exTable.setHost(pxfHost);
    exTable.setPort(pxfPort);

    gpdb.createTableAndVerify(exTable);
    try {
        gpdb.queryResults(exTable, "SELECT num1, t1 FROM " + exTable.getName() + " ORDER BY num1, t1");
    } catch (Exception e) {
        ExceptionUtils.validate(null, e, new PSQLException("FaultyGUCAccessor: login null secret null", null), true);
    }
}
 
Example 3
Source Project: pxf   Source File: HdfsWritableSequenceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test unsupported type in writable resolver -- negative
 *
 * @throws Exception if test fails to run
 */
@Test(groups = { "features", "gpdb", "hcfs", "security" })
public void negativeCharType() throws Exception {

    String[] fields = { "a1 INTEGER", "c1 CHAR" };
    String hdfsDir = hdfsWritePath + writableTableName + "char";

    writableExTable.setName("wr_char");
    writableExTable.setFields(fields);
    writableExTable.setPath(hdfsDir);
    writableExTable.setDataSchema(schemaPackage + customSchemaWithCharFileName);
    gpdb.createTableAndVerify(writableExTable);

    Table dataTable = new Table("data", null);
    dataTable.addRow(new String[] { "100", "a" });
    dataTable.addRow(new String[] { "1000", "b" });

    try {
        gpdb.insertData(dataTable, writableExTable);
        Assert.fail("Insert data should fail because of unsupported type");
    } catch (PSQLException e) {
        ExceptionUtils.validate(null, e, new PSQLException("ERROR.*Type char is not supported " +
                "by GPDBWritable.*?", null), true);
    }
}
 
Example 4
Source Project: pxf   Source File: ProfilesTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * work with same profile defined multiple times
 *
 * @throws Exception if test fails to run
 */
@Test(groups = { "profile" })
public void duplicateProfile() throws Exception {

    exTable.setProfile(null);
    exTable.setUserParameters(new String[] {
            "Profile=" + EnumPxfDefaultProfiles.HdfsTextSimple.toString().toUpperCase(),
            "Profile=" + EnumPxfDefaultProfiles.HdfsTextSimple
    });

    try {
        gpdb.createTableAndVerify(exTable);
        Assert.fail("Exception should have been thrown because of duplicate profile");
    } catch (PSQLException e) {
        ExceptionUtils.validate(null, e,
                new PSQLException("ERROR: .?nvalid URI pxf://" + exTable.getPath() +
                        "\\?Profile=HDFSTEXTSIMPLE&Profile=HdfsTextSimple: " +
                        "Duplicate option\\(s\\): PROFILE", null), true);
    }
}
 
Example 5
@Test
public void testExtractPSQLException() {
  PSQLException psqlException = new PSQLException("fake error", PSQLState.UNEXPECTED_ERROR);
  // passing in the exception itself works
  assertEquals(psqlException, Manager.extractPSQLException(psqlException));

  // wrapping the exception in a SQLException (as done by ORMLite) works
  SQLException wrap1 = new SQLException("wrapper", psqlException);
  assertEquals(psqlException, Manager.extractPSQLException(wrap1));

  // ORMLite can also double wrap the exception
  SQLException wrap2 = new SQLException("double", wrap1);
  assertEquals(psqlException, Manager.extractPSQLException(wrap2));

  // SQLException with some other kind of exception: null
  SQLException other = new SQLException("other", new RuntimeException("cause"));
  assertNull(Manager.extractPSQLException(other));
  
  Throwable t = new Throwable("hello", psqlException);
  assertEquals(psqlException, Manager.extractPSQLException(t));
}
 
Example 6
@Test
public void testJPATimeout() {
    doInJPA(entityManager -> {
        try {
            List<Post> posts = entityManager
            .createQuery(
                "select p " +
                "from Post p " +
                "where function('1 >= ALL ( SELECT 1 FROM pg_locks, pg_sleep(2) ) --',) is ''", Post.class)
            .getResultList();

            fail("Timeout failure expected");
        } catch (Exception e) {
            PSQLException rootCause = ExceptionUtil.rootCause(e);
            assertTrue(rootCause.getMessage().contains("canceling statement due to user request"));            }
    });
}
 
Example 7
Source Project: tajo   Source File: TestPgSQLJdbcTableSpace.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConnPropertiesNegative() throws Exception {
  Map<String, String> connProperties = new HashMap<>();
  connProperties.put("user", "postgresX");
  connProperties.put("password", "");

  String uri = PgSQLTestServer.getInstance().getJdbcUrl().split("\\?")[0];
  Tablespace space = new PgSQLTablespace("t1", URI.create(uri), getJsonTablespace(connProperties));
  try {
    space.init(new TajoConf());
    fail("Must be failed");
  } catch (IOException ioe) {
    assertTrue(ioe.getCause() instanceof PSQLException);
  } finally {
    space.close();
  }
}
 
Example 8
@Override
@Nullable
@CheckForNull
public DataAccessException doTranslate(TransactionException transactionException) {
  DataAccessException translatedException;

  Throwable cause = transactionException.getCause();
  if (cause instanceof PSQLException) {
    PSQLException psqlException = (PSQLException) cause;
    String task = "commit transaction";
    DataAccessException dataAccessException = super.doTranslate(task, null, psqlException);
    if (dataAccessException != null) {
      translatedException = doTranslate(transactionException, dataAccessException);
    } else {
      translatedException = doTranslate(transactionException, psqlException);
    }
  } else {
    translatedException = null;
  }

  return translatedException;
}
 
Example 9
private DataAccessException doTranslate(Throwable sourceThrowable, SQLException sqlException) {
  SQLException relevantSqlException;
  if (sqlException instanceof BatchUpdateException) {
    relevantSqlException = sqlException.getNextException();
  } else {
    relevantSqlException = sqlException;
  }

  DataAccessException translatedException;
  if (relevantSqlException instanceof PSQLException) {
    translatedException = doTranslate(sourceThrowable, (PSQLException) relevantSqlException);
  } else {
    translatedException = null;
  }
  return translatedException;
}
 
Example 10
private DataAccessException doTranslate(Throwable sourceThrowable, PSQLException pSqlException) {
  switch (pSqlException.getSQLState()) {
    case "22001":
      return translateValueTooLongViolation(sourceThrowable);
    case "22007": // invalid_datetime_format
    case "22P02": // not an integer exception
      return translateInvalidIntegerException(sourceThrowable, pSqlException);
    case "23502": // not_null_violation
      return translateNotNullViolation(sourceThrowable, pSqlException);
    case "23503": // foreign_key_violation
      return translateForeignKeyViolation(sourceThrowable, pSqlException);
    case "23505": // unique_violation
      return translateUniqueKeyViolation(sourceThrowable, pSqlException);
    case "23514": // check_violation
      return translateCheckConstraintViolation(sourceThrowable, pSqlException);
    case "2BP01":
      return translateDependentObjectsStillExist(sourceThrowable, pSqlException);
    case "42703":
      return translateUndefinedColumnException(pSqlException);
    case PostgreSqlQueryGenerator.ERR_CODE_READONLY_VIOLATION:
      return translateReadonlyViolation(sourceThrowable, pSqlException);
    default:
      return null;
  }
}
 
Example 11
/** Package private for testability */
ReadonlyValueException translateReadonlyViolation(
    Throwable sourceThrowable, PSQLException pSqlException) {
  Matcher matcher =
      Pattern.compile(
              "Updating read-only column \"?(.*?)\"? of table \"?(.*?)\"? with id \\[(.*?)] is not allowed")
          .matcher(pSqlException.getServerErrorMessage().getMessage());
  boolean matches = matcher.matches();
  if (!matches) {
    LOG.error(ERROR_TRANSLATING_POSTGRES_EXC_MSG, pSqlException);
    throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
  }
  String colName = matcher.group(1);
  String tableName = matcher.group(2);
  String id = matcher.group(3);

  String attributeName = tryGetAttributeName(tableName, colName).orElse(null);
  String entityTypeId = tryGetEntityTypeName(tableName).orElse(null);
  return new ReadonlyValueException(entityTypeId, attributeName, id, sourceThrowable);
}
 
Example 12
@Test
void translateForeignKeyViolationStillReferenced() {
  ServerErrorMessage serverErrorMessage = mock(ServerErrorMessage.class);
  when(serverErrorMessage.getSQLState()).thenReturn("23503");
  when(serverErrorMessage.getTable()).thenReturn("myTable");
  when(serverErrorMessage.getMessage())
      .thenReturn(
          "update or delete on table \"myDependentTable\" violates foreign key constraint \"myTable_myAttr_fkey\" on table \"myTable\"");
  when(serverErrorMessage.getDetail())
      .thenReturn("Key (myColumn)=(myValue) is still referenced from table \"myTable\"");
  //noinspection ThrowableResultOfMethodCallIgnored

  Exception e =
      postgreSqlExceptionTranslator.translateForeignKeyViolation(
          mock(Throwable.class), new PSQLException(serverErrorMessage));
  assertEquals("entityTypeId:myEntity attributeName:myAttr value:myValue", e.getMessage());
  assertTrue(e instanceof ValueReferencedException);
}
 
Example 13
@Test
void translateUniqueKeyViolationCompositeKey() {
  ServerErrorMessage serverErrorMessage = mock(ServerErrorMessage.class);
  when(serverErrorMessage.getSQLState()).thenReturn("23505");
  when(serverErrorMessage.getTable()).thenReturn("myTable");
  when(serverErrorMessage.getDetail())
      .thenReturn("Key (myIdColumn, myColumn)=(myIdValue, myValue) already exists.");
  //noinspection ThrowableResultOfMethodCallIgnored

  Exception e =
      postgreSqlExceptionTranslator.translateUniqueKeyViolation(
          mock(Throwable.class), new PSQLException(serverErrorMessage));
  assertEquals(
      "entityTypeId:myEntity attributeName:myAttr entityId:myIdValue value:myValue",
      e.getMessage());
  assertTrue(e instanceof ListValueAlreadyExistsException);
}
 
Example 14
Source Project: crate   Source File: PostgresITest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorRecoveryFromErrorsOutsideSqlOperations() throws Exception {
    try (Connection conn = DriverManager.getConnection(url(RW), properties)) {
        conn.setAutoCommit(true);
        PreparedStatement stmt = conn.prepareStatement("select cast([10.3, 20.2] as integer) " +
                                                       "from information_schema.tables");
        try {
            stmt.executeQuery();
            fail("Should've raised PSQLException");
        } catch (PSQLException e) {
            assertThat(e.getMessage(), Matchers.containsString("Cannot cast expressions from type `double precision_array` to type `integer`"));
        }

        assertSelectNameFromSysClusterWorks(conn);
    }
}
 
Example 15
Source Project: crate   Source File: PostgresITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSetMultipleSchemasOnSession() throws Exception {
    try (Connection conn = DriverManager.getConnection(url(RW), properties)) {
        conn.setAutoCommit(true);

        conn.createStatement().execute("set session search_path to bar ,custom");
        conn.createStatement().executeUpdate("create table foo (id int) with (number_of_replicas=0)");
        conn.createStatement().executeQuery("select * from bar.foo");

        expectedException.expect(PSQLException.class);
        expectedException.expectMessage("SchemaUnknownException: Schema 'custom' unknown");
        conn.createStatement().execute("select * from custom.foo");
    }
}
 
Example 16
Source Project: pxf   Source File: PluginTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(groups = "features")
public void credentialsGUCsTransferredToFragmenter() throws Exception {

    ReadableExternalTable exTable = new ReadableExternalTable("extens", new String[] {
            "num1 integer",
            "t1 text",
            "num2 integer" }, "regression_location", "CUSTOM");

    exTable.setFragmenter(testPackage + "FaultyGUCFragmenter");
    exTable.setAccessor(testPackage + "DummyAccessor");
    exTable.setResolver(testPackage + "DummyResolver");
    exTable.setFormatter("pxfwritable_import");

    exTable.setHost(pxfHost);
    exTable.setPort(pxfPort);

    gpdb.runQuery("SET pxf_remote_service_login = 'mommy'");
    gpdb.runQuery("SET pxf_remote_service_secret = 'daddy'");
    gpdb.createTableAndVerify(exTable);
    try {
        gpdb.queryResults(exTable, "SELECT num1, t1 FROM " + exTable.getName() + " ORDER BY num1, t1");
    } catch (Exception e) {
        ExceptionUtils.validate(null, e, new PSQLException("FaultyGUCFragmenter: login mommy secret daddy", null), true);
    } finally {
        gpdb.runQuery("SET pxf_remote_service_login = ''");
        gpdb.runQuery("SET pxf_remote_service_secret = ''");
    }
}
 
Example 17
Source Project: pxf   Source File: PluginTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(groups = "features")
public void credentialsGUCsTransferredToAccessor() throws Exception {

    ReadableExternalTable exTable = new ReadableExternalTable("extens", new String[] {
            "num1 integer",
            "t1 text",
            "num2 integer" }, "regression_location", "CUSTOM");

    exTable.setFragmenter(testPackage + "DummyFragmenter");
    exTable.setAccessor(testPackage + "FaultyGUCAccessor");
    exTable.setResolver(testPackage + "DummyResolver");
    exTable.setFormatter("pxfwritable_import");

    exTable.setHost(pxfHost);
    exTable.setPort(pxfPort);

    gpdb.runQuery("SET pxf_remote_service_login = 'mommy'");
    gpdb.runQuery("SET pxf_remote_service_secret = 'daddy'");
    gpdb.createTableAndVerify(exTable);
    try {
        gpdb.queryResults(exTable, "SELECT num1, t1 FROM " + exTable.getName() + " ORDER BY num1, t1");
    } catch (Exception e) {
        ExceptionUtils.validate(null, e, new PSQLException("FaultyGUCAccessor: login mommy secret daddy", null), true);
    } finally {
        gpdb.runQuery("SET pxf_remote_service_login = ''");
        gpdb.runQuery("SET pxf_remote_service_secret = ''");
    }
}
 
Example 18
Source Project: pxf   Source File: SyntaxTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check Syntax validation, try to create Readable Table without PXF
 * options, expect failure and Error message.
 *
 * @throws Exception
 */
@Test(groups = "features")
public void negativeNoPxfParameters() throws Exception {

    ReportUtils.reportBold(
            null,
            getClass(),
            "Fail to create external table with missing or no PXF parameters: Formatter, Fragmenter, Accessor, Resolver");

    exTable = new ReadableExternalTable("pxf_extable_validations",
            syntaxFields, hdfsWorkingFolder, "CUSTOM");

    exTable.setHost(pxfHost);
    exTable.setPort(pxfPort);

    try {
        gpdb.createTable(exTable);
        Assert.fail("Table creation should fail with invalid URL error");
    } catch (Exception e) {
        String urlPort = exTable.getPort() == null ? "" : ":"
                + exTable.getPort();
        String pxfUrl = exTable.getHost() + urlPort + "/"
                + exTable.getPath();
        ExceptionUtils.validate(null, e, new PSQLException(
                "ERROR: Invalid URI pxf://" + pxfUrl
                        + "?: invalid option after '?'", null), false);
    }
}
 
Example 19
Source Project: pxf   Source File: SyntaxTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create Table with no Fragmenter, Accessor and Resolver. Should fail and
 * throw the right message.
 *
 * @throws Exception
 */
@Test(groups = "features")
public void negativeNoFragmenterNoAccessorNoResolver() throws Exception {

    ReportUtils.reportBold(
            null,
            getClass(),
            "Fail to create external table with no PXF parameters: Fragmenter, Accessor, Resolver");

    exTable = new ReadableExternalTable("pxf_extable_validations",
            syntaxFields, (hdfsWorkingFolder + "/*"), "CUSTOM");

    exTable.setFormatter("pxfwritable_import");
    exTable.setHost(pxfHost);
    exTable.setPort(pxfPort);

    try {
        gpdb.createTableAndVerify(exTable);
        Assert.fail("Table creation should fail with invalid URI error");
    } catch (PSQLException e) {
        String urlPort = exTable.getPort() == null ? "" : ":"
                + exTable.getPort();
        String pxfUrl = exTable.getHost() + urlPort + "/"
                + exTable.getPath();
        ExceptionUtils.validate(null, e, new PSQLException(
                "ERROR: Invalid URI pxf://" + pxfUrl
                        + "?: invalid option after '?'", null), false);
    }
}
 
Example 20
Source Project: pxf   Source File: SyntaxTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create Table with no Fragmenter. Should fail and throw the right message.
 *
 * @throws Exception
 */
@Test(groups = "features")
public void negativeMissingFragmenter() throws Exception {

    ReportUtils.reportBold(null, getClass(),
            "Fail to create external table with no PXF parameters: Fragmenter");

    exTable = new ReadableExternalTable("pxf_extable_validations",
            syntaxFields, ("somepath/" + hdfsWorkingFolder), "CUSTOM");

    exTable.setAccessor("xacc");
    exTable.setResolver("xres");
    exTable.setUserParameters(new String[] { "someuseropt=someuserval" });
    exTable.setFormatter("pxfwritable_import");
    exTable.setHost(pxfHost);
    exTable.setPort(pxfPort);

    try {
        gpdb.createTableAndVerify(exTable);
        Assert.fail("Table creation should fail with invalid URI error");
    } catch (PSQLException e) {
        String urlPort = exTable.getPort() == null ? "" : ":"
                + exTable.getPort();
        String pxfUrl = exTable.getHost() + urlPort + "/"
                + exTable.getPath();
        ExceptionUtils.validate(
                null,
                e,
                new PSQLException(
                        "ERROR: Invalid URI pxf://"
                                + pxfUrl
                                + "?ACCESSOR=xacc&RESOLVER=xres&someuseropt=someuserval: PROFILE or FRAGMENTER option(s) missing",
                        null), false);
    }
}
 
Example 21
Source Project: crate   Source File: PostgresJobsLogsITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFailingStatementIsRemovedFromSysJobs() throws Exception {
    try (Connection conn = DriverManager.getConnection(sqlExecutor.jdbcUrl())) {
        try {
            conn.createStatement().execute("set global 'foo.logger' = 'TRACE'");
        } catch (PSQLException e) {
            // this is expected
        }
        ResultSet result = conn.createStatement().executeQuery("select count(*) from sys.jobs");
        assertThat(result.next(), is(true));
        assertThat(result.getLong(1), is(1L));
    }
}
 
Example 22
Source Project: pxf   Source File: SyntaxTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create Table with no Resolver. Should fail and throw the right message.
 *
 * @throws Exception
 */
@Test(groups = "features")
public void negativeMissingResolver() throws Exception {

    exTable = new ReadableExternalTable("pxf_extable_validations",
            syntaxFields, ("somepath/" + hdfsWorkingFolder), "CUSTOM");

    exTable.setFragmenter("xfrag");
    exTable.setAccessor("xacc");
    exTable.setFormatter("pxfwritable_import");
    exTable.setHost(pxfHost);
    exTable.setPort(pxfPort);

    try {
        gpdb.createTableAndVerify(exTable);
        Assert.fail("Table creation should fail with invalid URI error");
    } catch (PSQLException e) {
        String urlPort = exTable.getPort() == null ? "" : ":"
                + exTable.getPort();
        String pxfUrl = exTable.getHost() + urlPort + "/"
                + exTable.getPath();
        ExceptionUtils.validate(
                null,
                e,
                new PSQLException(
                        "ERROR: Invalid URI pxf://"
                                + pxfUrl
                                + "?FRAGMENTER=xfrag&ACCESSOR=xacc: PROFILE or RESOLVER option(s) missing",
                        null), false);
    }
}
 
Example 23
Source Project: pxf   Source File: SyntaxTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create writable table with no accessor and resolver. Should fail and
 * throw the right message.
 *
 * @throws Exception
 */
@Test(groups = "features")
public void negativeMissingParameterWritable() throws Exception {

    weTable = new WritableExternalTable("pxf_writable", syntaxFields,
            hdfsWorkingFolder + "/writable", "CUSTOM");
    weTable.setFormatter("pxfwritable_export");
    weTable.setUserParameters(new String[] { "someuseropt=someuserval" });

    weTable.setHost(pxfHost);
    weTable.setPort(pxfPort);

    try {
        gpdb.createTableAndVerify(weTable);
        Assert.fail("Table creation should fail with invalid URI error");
    } catch (Exception e) {
        String urlPort = weTable.getPort() == null ? "" : ":"
                + weTable.getPort();
        String pxfUrl = weTable.getHost() + urlPort + "/"
                + weTable.getPath();
        ExceptionUtils.validate(
                null,
                e,
                new PSQLException(
                        "ERROR: Invalid URI pxf://"
                                + pxfUrl
                                + "?someuseropt=someuserval: PROFILE or ACCESSOR and RESOLVER option(s) missing",
                        null), false);
    }
}
 
Example 24
Source Project: pxf   Source File: SyntaxTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create writable table with no parameters. Should fail and throw the right
 * message.
 *
 * @throws Exception
 */
@Test(groups = "features")
public void negativeNoParametersWritable() throws Exception {

    weTable = new WritableExternalTable("pxf_writable", syntaxFields,
            hdfsWorkingFolder + "/writable/*", "CUSTOM");
    weTable.setFormatter("pxfwritable_export");

    weTable.setHost(pxfHost);
    weTable.setPort(pxfPort);

    String createQuery = weTable.constructCreateStmt();
    createQuery = createQuery.replace("?", "");

    try {
        gpdb.runQuery(createQuery);
        Assert.fail("Table creation should fail with invalid URI error");
    } catch (Exception e) {
        String urlPort = weTable.getPort() == null ? "" : ":"
                + weTable.getPort();
        String pxfUrl = weTable.getHost() + urlPort + "/"
                + weTable.getPath();
        ExceptionUtils.validate(null, e, new PSQLException(
                "ERROR: Invalid URI pxf://" + pxfUrl
                        + ": missing options section", null), false);
    }
}
 
Example 25
Source Project: crate   Source File: AuthenticationIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidUser() throws Exception {
    expectedException.expect(PSQLException.class);
    expectedException.expectMessage("FATAL: No valid auth.host_based entry found for host \"127.0.0.1\", user \"me\"");
    Properties properties = new Properties();
    properties.setProperty("user", "me");
    Connection conn = DriverManager.getConnection(sqlExecutor.jdbcUrl(), properties);
    conn.close();
}
 
Example 26
Source Project: pxf   Source File: SyntaxTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * insert into table with bad host name
 *
 * @throws Exception
 */
@Test(groups = "features")
public void negativeBadHostWritable() throws Exception {
    weTable = new WritableExternalTable("wr_host_err", new String[] {
            "t1 text",
            "a1 integer" }, hdfsWorkingFolder + "/writable/err", "TEXT");
    weTable.setDelimiter(",");
    weTable.setAccessor("TextFileWAccessor");
    weTable.setResolver("TextWResolver");

    weTable.setHost("badhostname");
    exTable.setPort("5888");

    Table dataTable = new Table("data", null);
    dataTable.addRow(new String[] { "first", "1" });
    dataTable.addRow(new String[] { "second", "2" });
    dataTable.addRow(new String[] { "third", "3" });

    gpdb.createTableAndVerify(weTable);

    try {
        gpdb.insertData(dataTable, weTable);
        Assert.fail("Insert data should fail because of wrong host name");
    } catch (PSQLException e) {
        String expectedWarningNormal = "remote component error \\(0\\): "
                + "Couldn't resolve host '" + weTable.getHost() + "'";
        String expectedWarningSecure = "fail to get filesystem credential for uri hdfs://badhostname";
        String expectedWarning = "(" + expectedWarningNormal + "|"
                + expectedWarningSecure + ")";
        ExceptionUtils.validate(null, e, new PSQLException(expectedWarning,
                null), true);
    }
}
 
Example 27
Source Project: pxf   Source File: SyntaxTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verify table creation fails when using the HEADER option
 *
 * @throws Exception
 */
@Test(groups = "features")
public void negativeHeaderOption() throws Exception {
    ReportUtils.reportBold(null, getClass(),
            "Fail to create external table with HEADER option");

    exTable = new ReadableExternalTable("pxf_extable_header", syntaxFields,
            ("somepath/" + hdfsWorkingFolder), "TEXT");

    exTable.setFragmenter("xfrag");
    exTable.setAccessor("xacc");
    exTable.setResolver("xres");
    exTable.setUserParameters(new String[] { "someuseropt=someuserval" });
    exTable.setHost(pxfHost);
    exTable.setPort(pxfPort);
    String sqlCmd = exTable.constructCreateStmt();
    sqlCmd += " (HEADER)"; // adding the HEADER option

    try {
        gpdb.runQuery(sqlCmd);
        Assert.fail("Table creation should fail with invalid option error");
    } catch (PSQLException e) {
        ExceptionUtils.validate(
                null,
                e,
                new PSQLException(
                        "ERROR: HEADER option is not allowed in a PXF external table",
                        null), false);
    }
}
 
Example 28
Source Project: pxf   Source File: HBaseTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * use long HBase table qualifier (over 64 chars) with no lookup table mapping. Verify the
 * column name in GPDB is being truncated and data for this column is missing
 *
 * @throws Exception if test fails to run
 */
@Test(groups = { "hbase", "features", "gpdb" })
public void longHBaseQualifierNameNoLookupTable() throws Exception {

    HBaseTable longQualifiersNamesHBaseTable = new HBaseTable(
            "long_qualifiers_hbase_table", new String[] { "cf1" });
    String[] qualifiers = new String[] {
            "very_long_qualifier_name_that_gpdb_will_probaly_is_going_to_cut",
            "short_qualifier"
    };
    String[] gpdbFields = new String[] {
            "recordkey TEXT",
            "\"cf1:very_long_qualifier_name_that_gpdb_will_probaly_is_going_to_cut\" TEXT",
            "\"cf1:short_qualifier\" TEXT"
    };
    // create HBase table with data
    longQualifiersNamesHBaseTable.setQualifiers(qualifiers);
    hbase.createTableAndVerify(longQualifiersNamesHBaseTable);
    HBaseLongQualifierDataPreparer dataPreparer = new HBaseLongQualifierDataPreparer();
    dataPreparer.prepareData(10, longQualifiersNamesHBaseTable);
    hbase.put(longQualifiersNamesHBaseTable);
    // create external table pointing the the HBase table
    ReadableExternalTable externalTable = TableFactory.getPxfHBaseReadableTable(
            "long_qualifiers_hbase_table", gpdbFields, longQualifiersNamesHBaseTable);
    externalTable.setHost(pxfHost);
    externalTable.setPort(pxfPort);
    try {
        gpdb.createTableAndVerify(externalTable);
        // if no Exception thrown, fail test
        Assert.fail("Exception should have been thrown");
    } catch (Exception e) {
        // Verify message in caught exception
        ExceptionUtils.validate(null, e,
                new PSQLException("identifier \"cf1:very_long_qualifier_name_that_gpdb_will_probaly_is_going_to_cut\" "
                        + "will be truncated to \"cf1:very_long_qualifier_name_that_gpdb_will_probaly_is_going_to\"",
                        null), false, true);
    }
    // verify query results
    runTincTest("pxf.features.hbase.longQualifierNoLookup.runTest");
}
 
Example 29
Source Project: pxf   Source File: HdfsWritableSequenceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test COMPRESSION_TYPE = NONE -- negative
 *
 * @throws Exception if test fails to run
 */
@Test(groups = { "features", "gpdb", "hcfs", "security" })
public void negativeCompressionTypeNone() throws Exception {

    String[] fields = { "a1 INTEGER", "c1 CHAR" };
    String hdfsDir = hdfsWritePath + writableTableName + "none";

    writableExTable.setName("compress_type_none");
    writableExTable.setFields(fields);
    writableExTable.setPath(hdfsDir);
    writableExTable.setDataSchema(schemaPackage + customSchemaWithCharFileName);
    writableExTable.setUserParameters(new String[] { "COMPRESSION_TYPE=NONE" });
    gpdb.createTableAndVerify(writableExTable);

    Table dataTable = new Table("data", null);
    dataTable.addRow(new String[] { "100", "a" });
    dataTable.addRow(new String[] { "1000", "b" });

    try {
        gpdb.insertData(dataTable, writableExTable);
        Assert.fail("Insert data should fail because of illegal compression type");
    } catch (PSQLException e) {
        ExceptionUtils.validate(null, e,
                new PSQLException("ERROR.*Illegal compression type 'NONE'\\. For disabling compression " +
                        "remove COMPRESSION_CODEC parameter\\..*?", null), true);
    }
}
 
Example 30
Source Project: NLIDB   Source File: SQLExecutionService.java    License: Apache License 2.0 5 votes vote down vote up
public String executeSQL(DBConnectionConfig config, String query)
        throws SQLException {
    try {
        Connection conn = dbConnectionService.getConnection(config);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        ResultSetMetaData rsmd = rs.getMetaData();
        int numCols = rsmd.getColumnCount();
        StringBuilder sb = new StringBuilder();

        // SQL column index start from 1
        for (int col = 1; col <= numCols; col++) {
            sb.append(rsmd.getColumnName(col)).append("\t");
        }
        sb.append("\n");

        while (rs.next()) {
            for (int col = 1; col <= numCols; col++) {
                sb.append(rs.getString(col)).append("\t");
            }
            sb.append("\n");
        }

        rs.close();
        stmt.close();
        conn.close();

        return sb.toString();
    } catch (PSQLException e) {
        return e.getMessage();
    }
}