org.apache.phoenix.exception.SQLExceptionCode Java Examples

The following examples show how to use org.apache.phoenix.exception.SQLExceptionCode. 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 File: QueryCompilerTest.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testVarBinaryNotLastInMultipartPK() throws Exception {
    Connection conn = DriverManager.getConnection(getUrl());
    // When the VARBINARY key is the last column, it is allowed.
    String query = "CREATE TABLE foo (a_string varchar not null, b_string varchar not null, a_binary varbinary not null, " +
            "col1 decimal, col2 decimal CONSTRAINT pk PRIMARY KEY (a_string, b_string, a_binary))";
    PreparedStatement statement = conn.prepareStatement(query);
    statement.execute();
    try {
        // VARBINARY key is not allowed in the middle of the key.
        query = "CREATE TABLE foo (a_binary varbinary not null, a_string varchar not null, col1 decimal, col2 decimal CONSTRAINT pk PRIMARY KEY (a_binary, a_string))";
        statement = conn.prepareStatement(query);
        statement.execute();
        fail();
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.VARBINARY_IN_ROW_KEY.getErrorCode(), e.getErrorCode());
    } finally {
        conn.close();
    }
}
 
Example #2
Source File: QueryIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testToDateOnString() throws Exception { // TODO: test more conversion combinations
    String query = "SELECT a_string FROM " + tableName + " WHERE organization_id=? and a_integer = 5";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        rs.getDate(1);
        fail();
    } catch (SQLException e) { // Expected
        assertEquals(SQLExceptionCode.TYPE_MISMATCH.getErrorCode(),e.getErrorCode());
    } finally {
        conn.close();
    }
}
 
Example #3
Source File: SubqueryRewriter.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private ParseNode getJoinConditionNode(ParseNode lhs, List<AliasedNode> rhs, String rhsTableAlias) throws SQLException {
    List<ParseNode> lhsNodes;        
    if (lhs instanceof RowValueConstructorParseNode) {
        lhsNodes = ((RowValueConstructorParseNode) lhs).getChildren();
    } else {
        lhsNodes = Collections.singletonList(lhs);
    }
    if (lhsNodes.size() != (rhs.size() - 1))
        throw new SQLExceptionInfo.Builder(SQLExceptionCode.SUBQUERY_RETURNS_DIFFERENT_NUMBER_OF_FIELDS).build().buildException();
    
    int count = lhsNodes.size();
    TableName rhsTableName = NODE_FACTORY.table(null, rhsTableAlias);
    List<ParseNode> equalNodes = Lists.newArrayListWithExpectedSize(count);
    for (int i = 0; i < count; i++) {
        ParseNode rhsNode = NODE_FACTORY.column(rhsTableName, rhs.get(i + 1).getAlias(), null);
        equalNodes.add(NODE_FACTORY.equal(lhsNodes.get(i), rhsNode));
    }
    
    return count == 1 ? equalNodes.get(0) : NODE_FACTORY.and(equalNodes);
}
 
Example #4
Source File: UpsertCompiler.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Check that none of no columns in our updatable VIEW are changing values.
 * @param tableRef
 * @param overlapViewColumns
 * @param targetColumns
 * @param projector
 * @throws SQLException
 */
private static void throwIfNotUpdatable(TableRef tableRef, Set<PColumn> overlapViewColumns,
        List<PColumn> targetColumns, RowProjector projector, boolean sameTable) throws SQLException {
    PTable table = tableRef.getTable();
    if (table.getViewType() == ViewType.UPDATABLE && !overlapViewColumns.isEmpty()) {
        ImmutableBytesWritable ptr = new ImmutableBytesWritable();
        for (int i = 0; i < targetColumns.size(); i++) {
            PColumn targetColumn = targetColumns.get(i);
            if (overlapViewColumns.contains(targetColumn)) {
                Expression source = projector.getColumnProjector(i).getExpression();
                if (source.isStateless()) {
                    source.evaluate(null, ptr);
                    if (Bytes.compareTo(ptr.get(), ptr.getOffset(), ptr.getLength(), targetColumn.getViewConstant(), 0, targetColumn.getViewConstant().length-1) == 0) {
                        continue;
                    }
                }
                throw new SQLExceptionInfo.Builder(
                        SQLExceptionCode.CANNOT_UPDATE_VIEW_COLUMN)
                        .setColumnName(targetColumn.getName().getString())
                        .build().buildException();
            }
        }
    }
}
 
Example #5
Source File: DropMetadataIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testDropIndexTableHasSameNameWithDataTable() {
    String tableName = generateUniqueName();
    String indexName = "IDX_" + tableName;
    try (Connection conn = DriverManager.getConnection(getUrl())) {
        String createTable = "CREATE TABLE " + tableName + "  (id varchar not null primary key, col integer)";
        conn.createStatement().execute(createTable);
        String createIndex = "CREATE INDEX " + indexName + " on " + tableName + "(col)";
        conn.createStatement().execute(createIndex);
        String dropIndex = "DROP INDEX " + indexName + " on " + indexName;
        conn.createStatement().execute(dropIndex);
        fail("should not execute successfully");
    } catch (SQLException e) {
        assertTrue(SQLExceptionCode.PARENT_TABLE_NOT_FOUND.getErrorCode() == e.getErrorCode());
    }
}
 
Example #6
Source File: SequenceIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testSequenceIncreasingNoCycle() throws Exception {
    nextConnection();
    // client throws exception
    conn.createStatement().execute(
        "CREATE SEQUENCE foo.bar START WITH 2 INCREMENT BY 3 MINVALUE 1 MAXVALUE 10 CACHE 100");
    nextConnection();
    assertSequenceValuesForSingleRow(2, 5, 8);
    try {
        ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
        rs.next();
        fail();
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
            e.getErrorCode());
        assertTrue(e.getNextException() == null);
    }
}
 
Example #7
Source File: QueryIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testToDateOnString() throws Exception { // TODO: test more conversion combinations
    String query = "SELECT a_string FROM aTable WHERE organization_id=? and a_integer = 5";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 2
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        rs.getDate(1);
        fail();
    } catch (SQLException e) { // Expected
        assertEquals(SQLExceptionCode.TYPE_MISMATCH.getErrorCode(),e.getErrorCode());
    } finally {
        conn.close();
    }
}
 
Example #8
Source File: CorrelatePlanTest.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testCorrelatePlanWithSingleValueOnly() throws SQLException {
    Object[][] expected = new Object[][] {
            {1, "1", "1", 10},
            {2, "2", "2", 20},
            {2, "2", "2", 40},
    };
    try {
        testCorrelatePlan(LEFT_RELATION, RIGHT_RELATION, 1, 0, JoinType.Inner, expected);
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.SINGLE_ROW_SUBQUERY_RETURNS_MULTIPLE_ROWS.getErrorCode(), e.getErrorCode());
    }
    
    Object[][] rightRelation = new Object[][] {
            {"2", 20},
            {"6", 60},
            {"5", 100},
            {"1", 10},
    };        
    expected = new Object[][] {
            {1, "1", "1", 10},
            {2, "2", "2", 20},
            {5, "5", "5", 100},
    };
    testCorrelatePlan(LEFT_RELATION, rightRelation, 1, 0, JoinType.Inner, expected);
}
 
Example #9
Source File: UnionCompiler.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private static List<TargetDataExpression> checkProjectionNumAndExpressions(
    List<QueryPlan> selectPlans) throws SQLException {
    int columnCount = selectPlans.get(0).getProjector().getColumnCount();
    List<TargetDataExpression> targetTypes = new ArrayList<TargetDataExpression>(columnCount);

    for (int i = 0; i < columnCount; i++) {
        for (QueryPlan plan : selectPlans) {
            if (columnCount !=plan.getProjector().getColumnCount()) {
                throw new SQLExceptionInfo.Builder(SQLExceptionCode
                    .SELECT_COLUMN_NUM_IN_UNIONALL_DIFFS).setMessage("1st query has " + columnCount + " columns whereas 2nd " +
                        "query has " + plan.getProjector().getColumnCount())
                    .build().buildException();
            }
            ColumnProjector colproj = plan.getProjector().getColumnProjector(i);
            if(targetTypes.size() < i+1 ) {
                targetTypes.add(new TargetDataExpression(colproj.getExpression()));
            } else {
                compareExperssions(i, colproj.getExpression(), targetTypes);
            }
        }
    }
    return targetTypes;
}
 
Example #10
Source File: QueryCompilerTest.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testSelectDistinctAndAll() throws Exception {
    long ts = nextTimestamp();
    String query = "SELECT all distinct a_string,b_string from atable order by x_integer";
    String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(url, props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.executeQuery();
        fail();
    } catch (SQLException e) { // expected
        assertEquals(SQLExceptionCode.PARSER_ERROR.getErrorCode(), e.getErrorCode());
    } finally {
        conn.close();
    }
}
 
Example #11
Source File: TransactionIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testPreventLocalIndexCreation() throws Exception {
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
        for (TransactionFactory.Provider provider : TransactionFactory.Provider.values()) {
            if (provider.runTests() && provider.getTransactionProvider().isUnsupported(PhoenixTransactionProvider.Feature.ALLOW_LOCAL_INDEX)) {
                String tableName = generateUniqueName();
                conn.createStatement().execute(
                        "CREATE TABLE " + tableName + " (k VARCHAR NOT NULL PRIMARY KEY, v1 VARCHAR) TRANSACTIONAL=true,TRANSACTION_PROVIDER='" + provider + "'");
                String indexName = generateUniqueName();
                try {
                    conn.createStatement().execute("CREATE LOCAL INDEX " + indexName + "_IDX ON " + tableName + " (v1) INCLUDE(v2)");
                    fail();
                } catch (SQLException e) {
                    assertEquals(SQLExceptionCode.CANNOT_CREATE_LOCAL_INDEX_FOR_TXN_TABLE.getErrorCode(), e.getErrorCode());
                }
            }
        }
    }
}
 
Example #12
Source File: ConnectionQueryServicesImpl.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private void openConnection() throws SQLException {
    try {
        // check if we need to authenticate with kerberos
        String clientKeytab = this.getProps().get(HBASE_CLIENT_KEYTAB);
        String clientPrincipal = this.getProps().get(HBASE_CLIENT_PRINCIPAL);
        if (clientKeytab != null && clientPrincipal != null) {
            logger.info("Trying to connect to a secure cluster with keytab:" + clientKeytab);
            UserGroupInformation.setConfiguration(config);
            User.login(config, HBASE_CLIENT_KEYTAB, HBASE_CLIENT_PRINCIPAL, null);
            logger.info("Successfull login to secure cluster!!");
        }
        this.connection = HBaseFactoryProvider.getHConnectionFactory().createConnection(this.config);
    } catch (IOException e) {
        throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_ESTABLISH_CONNECTION)
            .setRootCause(e).build().buildException();
    }
    if (this.connection.isClosed()) { // TODO: why the heck doesn't this throw above?
        throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_ESTABLISH_CONNECTION).build().buildException();
    }
}
 
Example #13
Source File: ViewTTLIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testViewTTLWithViewIndexFails() throws Exception {

    // Define the test schema.
    // 1. Table with default columns => (ORG_ID, KP, COL1, COL2, COL3), PK => (ORG_ID, KP)
    // 2. Tenant with default columns => (ZID, COL7, COL8, COL9), PK => (ZID)
    final PhoenixTestBuilder.SchemaBuilder schemaBuilder = new PhoenixTestBuilder.SchemaBuilder(getUrl());

    TableOptions tableOptions = TableOptions.withDefaults();
    tableOptions.setTableProps("COLUMN_ENCODED_BYTES=0,MULTI_TENANT=true");

    TenantViewIndexOptions tenantViewIndexOptions = TenantViewIndexOptions.withDefaults();
    tenantViewIndexOptions.setIndexProps("VIEW_TTL=1000");
    try {
        schemaBuilder
                .withTableOptions(tableOptions)
                .withTenantViewDefaults()
                .withTenantViewIndexOptions(tenantViewIndexOptions)
                .buildNewView();
        fail();
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.VIEW_TTL_SUPPORTED_FOR_VIEWS_ONLY.getErrorCode(), e.getErrorCode());
    }
}
 
Example #14
Source File: UpsertCompiler.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Check that none of no columns in our updatable VIEW are changing values.
 * @param tableRef
 * @param overlapViewColumns
 * @param targetColumns
 * @param projector
 * @throws SQLException
 */
private static void throwIfNotUpdatable(TableRef tableRef, Set<PColumn> overlapViewColumns,
        List<PColumn> targetColumns, RowProjector projector, boolean sameTable) throws SQLException {
    PTable table = tableRef.getTable();
    if (table.getViewType() == ViewType.UPDATABLE && !overlapViewColumns.isEmpty()) {
        ImmutableBytesWritable ptr = new ImmutableBytesWritable();
        for (int i = 0; i < targetColumns.size(); i++) {
            PColumn targetColumn = targetColumns.get(i);
            if (overlapViewColumns.contains(targetColumn)) {
                Expression source = projector.getColumnProjector(i).getExpression();
                if (source.isStateless()) {
                    source.evaluate(null, ptr);
                    if (Bytes.compareTo(ptr.get(), ptr.getOffset(), ptr.getLength(), targetColumn.getViewConstant(), 0, targetColumn.getViewConstant().length-1) == 0) {
                        continue;
                    }
                }
                throw new SQLExceptionInfo.Builder(
                        SQLExceptionCode.CANNOT_UPDATE_VIEW_COLUMN)
                        .setColumnName(targetColumn.getName().getString())
                        .build().buildException();
            }
        }
    }
}
 
Example #15
Source File: Sequence.java    From phoenix with Apache License 2.0 6 votes vote down vote up
public boolean returnValue(Result result) throws SQLException {
    Cell statusKV = result.rawCells()[0];
    if (statusKV.getValueLength() == 0) { // No error, but unable to return sequence values
        return false;
    }
    long timestamp = statusKV.getTimestamp();
    int statusCode = PInteger.INSTANCE.getCodec().decodeInt(statusKV.getValueArray(), statusKV.getValueOffset(), SortOrder.getDefault());
    if (statusCode == SUCCESS) {  // Success - update nextValue down to currentValue
        SequenceValue value = findSequenceValue(timestamp);
        if (value == null) {
            throw new EmptySequenceCacheException(key.getSchemaName(),key.getSequenceName());
        }
        return true;
    }
    SQLExceptionCode code = SQLExceptionCode.fromErrorCode(statusCode);
    // TODO: We could have the server return the timestamps of the
    // delete markers and we could insert them here, but this seems
    // like overkill.
    // if (code == SQLExceptionCode.SEQUENCE_UNDEFINED) {
    // }
    throw new SQLExceptionInfo.Builder(code)
        .setSchemaName(key.getSchemaName())
        .setTableName(key.getSequenceName())
        .build().buildException();
}
 
Example #16
Source File: UpsertValuesIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpsertValuesWithMoreValuesThanNumColsInTable() throws Exception {
    String tableName = generateUniqueName();
    Properties props = new Properties();
    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DriverManager.getConnection(getUrl(), props);
        stmt = conn.createStatement();
        stmt.execute("create table " + tableName + " (k VARCHAR not null primary key desc)");
    } finally {
        closeStmtAndConn(stmt, conn);
    }

    try {
        conn = DriverManager.getConnection(getUrl(), props);
        stmt = conn.createStatement();
        stmt.execute("upsert into " + tableName + " values (to_char(100), to_char(100), to_char(100))");
        fail();
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.UPSERT_COLUMN_NUMBERS_MISMATCH.getErrorCode(),e.getErrorCode());
    } finally {
        closeStmtAndConn(stmt, conn);
    }
}
 
Example #17
Source File: HavingCompiler.java    From phoenix with Apache License 2.0 6 votes vote down vote up
public static Expression compile(StatementContext context, SelectStatement statement, GroupBy groupBy) throws SQLException {
    ParseNode having = statement.getHaving();
    if (having == null) {
        return null;
    }
    ExpressionCompiler expressionBuilder = new ExpressionCompiler(context, groupBy);
    Expression expression = having.accept(expressionBuilder);
    if (expression.getDataType() != PBoolean.INSTANCE) {
        throw TypeMismatchException.newException(PBoolean.INSTANCE, expression.getDataType(), expression.toString());
    }
    if (LiteralExpression.isBooleanFalseOrNull(expression)) {
        context.setScanRanges(ScanRanges.NOTHING);
        return null;
    } else if (LiteralExpression.isTrue(expression)) {
        return null;
    }
    if (!expressionBuilder.isAggregate()) {
        throw new SQLExceptionInfo.Builder(SQLExceptionCode.ONLY_AGGREGATE_IN_HAVING_CLAUSE).build().buildException();
    }
    return expression;
}
 
Example #18
Source File: PhoenixIndexFailurePolicy.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private static void updateIndex(String indexFullName, PhoenixConnection conn,
        PIndexState indexState) throws SQLException, IOException {
    //Decrement the counter because we will be here when client give retry after getting failed or succeed
    decrementCounterForIndex(conn,indexFullName);
    Long indexDisableTimestamp = null;
    if (PIndexState.DISABLE.equals(indexState)) {
        LOGGER.info("Disabling index after hitting max number of index write retries: "
                + indexFullName);
        IndexUtil.updateIndexState(conn, indexFullName, indexState, indexDisableTimestamp);
    } else if (PIndexState.ACTIVE.equals(indexState)) {
        LOGGER.debug("Resetting index to active after subsequent success " + indexFullName);
        //At server disabled timestamp will be reset only if there is no other client is in PENDING_DISABLE state
        indexDisableTimestamp = 0L;
        try {
            IndexUtil.updateIndexState(conn, indexFullName, indexState, indexDisableTimestamp);
        } catch (SQLException e) {
            // It's possible that some other client had made the Index DISABLED already , so we can ignore unallowed
            // transition(DISABLED->ACTIVE)
            if (e.getErrorCode() != SQLExceptionCode.INVALID_INDEX_STATE_TRANSITION.getErrorCode()) { throw e; }
        }
    }
}
 
Example #19
Source File: SequenceIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testSequenceDecreasingNoCycle() throws Exception {
    nextConnection();
    // client will throw exception
    conn.createStatement()
            .execute(
                "CREATE SEQUENCE foo.bar START WITH 4 INCREMENT BY -2 MINVALUE 1 MAXVALUE 10 CACHE 100");
    nextConnection();
    assertSequenceValuesForSingleRow(4, 2);
    try {
        ResultSet rs = conn.createStatement().executeQuery(NEXT_VAL_SQL);
        rs.next();
        fail();
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MIN_VALUE.getErrorCode(),
            e.getErrorCode());
        assertTrue(e.getNextException() == null);
    }
}
 
Example #20
Source File: IndexUsageIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndexNotFoundForDropWongIndexName() throws Exception{
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(getUrl(), props);
    String dataTableName = generateUniqueName();
    String wrongIndexName = generateUniqueName();

    try {
        conn.createStatement().execute("CREATE TABLE " + dataTableName +
                " (k VARCHAR NOT NULL PRIMARY KEY, v VARCHAR)");
        conn.createStatement().execute("DROP INDEX " + wrongIndexName + " ON " +
                dataTableName);
    }catch (SQLException e) {
        assertEquals(e.getErrorCode(), SQLExceptionCode.INDEX_UNDEFINED.getErrorCode());
    } finally {
        conn.close();
    }
}
 
Example #21
Source File: DynamicUpsertIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Test an upsert of a full row with dynamic Columns and unbalanced number of values
 */
@Test
public void testFullUnbalancedUpsert() throws Exception {
    String upsertquery = "UPSERT INTO " + tableName
            + " (a.DynCol VARCHAR,b.DynCol varchar) VALUES('dynEntry','aValue','bValue','dyncola')";

    String url = getUrl() + ";";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(url, props);
    try {
        PreparedStatement statement = conn.prepareStatement(upsertquery);
        statement.execute();
        fail();
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.UPSERT_COLUMN_NUMBERS_MISMATCH.getErrorCode(),e.getErrorCode());
    } finally {
        conn.close();
    }
}
 
Example #22
Source File: CreateTableIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpecifyingColumnFamilyForTTLFails() throws Exception {
    String tableName = generateUniqueName();
    String ddl =
            "create table IF NOT EXISTS  " + tableName + "  (" + " id char(1) NOT NULL,"
                    + " col1 integer NOT NULL," + " CF.col2 integer,"
                    + " CONSTRAINT NAME_PK PRIMARY KEY (id, col1)"
                    + " ) DEFAULT_COLUMN_FAMILY='a', CF.TTL=10000, SALT_BUCKETS = 4";
    Properties props = new Properties();
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        conn.createStatement().execute(ddl);
    } catch (SQLException sqle) {
        assertEquals(SQLExceptionCode.COLUMN_FAMILY_NOT_ALLOWED_FOR_PROPERTY.getErrorCode(),
            sqle.getErrorCode());
    }
}
 
Example #23
Source File: PhoenixEmbeddedDriverTest.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testNegativeGetConnectionInfo() throws SQLException {
    String[] urls = new String[] {
        "jdbc:phoenix::",
        "jdbc:phoenix:;",
        "jdbc:phoenix:v1:1,v2:2,v3:3",
        "jdbc:phoenix:v1:1,v2:2,v3:3;test=true",
        "jdbc:phoenix:v1,v2,v3:-1:/hbase;test=true",
        "jdbc:phoenix:v1,v2,v3:-1",
        "jdbc:phoenix:v1,v2,v3:123::/hbase",
        "jdbc:phoenix:v1,v2,v3:123::/hbase;test=false",
    };
    for (String url : urls) {
        try {
            ConnectionInfo.create(url);
            throw new AssertionError("Expected exception for \"" + url + "\"");
        } catch (SQLException e) {
            try {
                assertEquals(SQLExceptionCode.MALFORMED_CONNECTION_URL.getSQLState(), e.getSQLState());
            } catch (AssertionError ae) {
                throw new AssertionError("For \"" + url + "\": " + ae.getMessage());
            }
        }
    }
}
 
Example #24
Source File: TephraTransactionContext.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Override
public void abort() throws SQLException {

    if (txContext == null || !isTransactionRunning()) {
        return;
    }

    try {
        txContext.abort();
    } catch (TransactionFailureException e) {
        throw new SQLExceptionInfo.Builder(
                SQLExceptionCode.TRANSACTION_FAILED)
                .setMessage(e.getMessage()).setRootCause(e).build()
                .buildException();
    }
}
 
Example #25
Source File: SequenceBulkAllocationIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Validates that if our current or start value is > 0 and we ask for Long.MAX
 * and overflow to the next value, the correct Exception is thrown when 
 * the expression is evaluated.
 */
public void testNextValuesForSequenceOverflowAllocation() throws Exception {
	String sequenceName = generateSequenceNameWithSchema();
    final SequenceProperties props =
            new SequenceProperties.Builder().name(sequenceName).incrementBy(1).startsWith(100).cacheSize(100)
                    .numAllocated(Long.MAX_VALUE).build();
    
    // Create Sequence
    createSequenceWithMinMax(props);

    // Bulk Allocate Sequence Slots
    try {
        conn.createStatement().executeQuery(
            "SELECT NEXT " + Long.MAX_VALUE
                    + " VALUES FOR  " + sequenceName + " ");
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
            e.getErrorCode());
        assertTrue(e.getNextException() == null);
    }
}
 
Example #26
Source File: PropertiesInSyncIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisallowSyncedPropsToBeSetColFamSpecificCreateTable() throws Exception {
    Connection conn = DriverManager.getConnection(getUrl(), new Properties());
    String tableName = generateUniqueName();
    for (String propName: SYNCED_DATA_TABLE_AND_INDEX_COL_FAM_PROPERTIES) {
        try {
            conn.createStatement().execute("create table " + tableName
                    + " (id INTEGER not null primary key, "
                    + COL_FAM1 + ".name varchar(10), " + COL_FAM2 + ".flag boolean) "
                    + COL_FAM1 + "." + propName + "=" + DUMMY_PROP_VALUE);
            fail("Should fail with SQLException when setting synced property for a specific column family");
        } catch (SQLException sqlE) {
            assertEquals("Should fail to set synced property for a specific column family",
                    SQLExceptionCode.COLUMN_FAMILY_NOT_ALLOWED_FOR_PROPERTY.getErrorCode(), sqlE.getErrorCode());
        }
    }
    conn.close();
}
 
Example #27
Source File: SchemaUtil.java    From phoenix with Apache License 2.0 6 votes vote down vote up
public static byte[][] processSplits(byte[][] splits, LinkedHashSet<PColumn> pkColumns, Integer saltBucketNum, boolean defaultRowKeyOrder) throws SQLException {
    // FIXME: shouldn't this return if splits.length == 0?
    if (splits == null) return null;
    // We do not accept user specified splits if the table is salted and we specify defaultRowKeyOrder. In this case,
    // throw an exception.
    if (splits.length > 0 && saltBucketNum != null && defaultRowKeyOrder) {
        throw new SQLExceptionInfo.Builder(SQLExceptionCode.NO_SPLITS_ON_SALTED_TABLE).build().buildException();
    }
    // If the splits are not specified and table is salted, pre-split the table. 
    if (splits.length == 0 && saltBucketNum != null) {
        splits = SaltingUtil.getSalteByteSplitPoints(saltBucketNum);
    }
    byte[][] newSplits = new byte[splits.length][];
    for (int i=0; i<splits.length; i++) {
        newSplits[i] = processSplit(splits[i], pkColumns); 
    }
    return newSplits;
}
 
Example #28
Source File: SequenceBulkAllocationIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testNextValuesForSequenceWithDefaultMax() throws Exception {
	String sequenceName = generateSequenceNameWithSchema();
    final SequenceProperties props =
            new SequenceProperties.Builder().name(sequenceName).incrementBy(1).startsWith(100).cacheSize(100)
                    .numAllocated(Long.MAX_VALUE - 100).build();
    
    // Create Sequence
    createSequenceWithMinMax(props);

    // Bulk Allocate Sequence Slots
    long currentValueAfterAllocation = 100;
    long startValueAfterAllocation = Long.MAX_VALUE;
    reserveSlotsInBulkAndAssertValue(sequenceName, currentValueAfterAllocation, props.numAllocated);
    assertExpectedStateInSystemSequence(props, startValueAfterAllocation);
    
    // Try and get next value
    try {
        conn.createStatement().executeQuery(String.format(SELECT_NEXT_VALUE_SQL, sequenceName));
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE.getErrorCode(),
            e.getErrorCode());
        assertTrue(e.getNextException() == null);
    }
}
 
Example #29
Source File: OmidTransactionContext.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Override
public void begin() throws SQLException {
    if (tm == null) {
        throw new SQLExceptionInfo.Builder(
                SQLExceptionCode.NULL_TRANSACTION_CONTEXT).build()
                .buildException();
    }


    try {
        tx = (HBaseTransaction) tm.begin();
    } catch (TransactionException e) {
        throw new SQLExceptionInfo.Builder(
                SQLExceptionCode.TRANSACTION_FAILED)
                .setMessage(e.getMessage()).setRootCause(e).build()
                .buildException();
    }
}
 
Example #30
Source File: QueryCompilerTest.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test 
public void testStatelessExpressionIndex() throws Exception {
    String ddl = "CREATE TABLE t (k1 INTEGER PRIMARY KEY)";
    Connection conn = DriverManager.getConnection(getUrl());
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        stmt.execute(ddl);
        stmt.execute("CREATE INDEX i ON t (2)");
        fail();
    } catch (SQLException e) {
        assertEquals(SQLExceptionCode.STATELESS_EXPRESSION_NOT_ALLOWED_IN_INDEX.getErrorCode(), e.getErrorCode());
    }
    finally {
        stmt.close();
    }
}