Search in sources :

Example 6 with KeyValueColumnExpression

use of org.apache.phoenix.expression.KeyValueColumnExpression in project phoenix by apache.

the class WhereCompilerTest method testAndPKAndNotPK.

@Test
public void testAndPKAndNotPK() throws SQLException {
    String query = "select * from bugTable where ID = 'i2' and company = 'c3'";
    PhoenixConnection pconn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES)).unwrap(PhoenixConnection.class);
    pconn.createStatement().execute("create table bugTable(ID varchar primary key,company varchar)");
    PhoenixPreparedStatement pstmt = newPreparedStatement(pconn, query);
    QueryPlan plan = pstmt.optimizeQuery();
    Scan scan = plan.getContext().getScan();
    Filter filter = scan.getFilter();
    PColumn column = plan.getTableRef().getTable().getColumnForColumnName("COMPANY");
    assertEquals(singleKVFilter(constantComparison(CompareOp.EQUAL, new KeyValueColumnExpression(column), "c3")), filter);
}
Also used : PColumn(org.apache.phoenix.schema.PColumn) PhoenixConnection(org.apache.phoenix.jdbc.PhoenixConnection) RowKeyComparisonFilter(org.apache.phoenix.filter.RowKeyComparisonFilter) TestUtil.multiEncodedKVFilter(org.apache.phoenix.util.TestUtil.multiEncodedKVFilter) SkipScanFilter(org.apache.phoenix.filter.SkipScanFilter) Filter(org.apache.hadoop.hbase.filter.Filter) TestUtil.singleKVFilter(org.apache.phoenix.util.TestUtil.singleKVFilter) Scan(org.apache.hadoop.hbase.client.Scan) KeyValueColumnExpression(org.apache.phoenix.expression.KeyValueColumnExpression) PhoenixPreparedStatement(org.apache.phoenix.jdbc.PhoenixPreparedStatement) Test(org.junit.Test) BaseConnectionlessQueryTest(org.apache.phoenix.query.BaseConnectionlessQueryTest)

Example 7 with KeyValueColumnExpression

use of org.apache.phoenix.expression.KeyValueColumnExpression in project phoenix by apache.

the class DropColumnIT method verifyColValue.

private void verifyColValue(String indexTableName, String dataTableName, Connection conn, PTable dataTable, PColumn dataColumn, byte[] dataCq, PTable globalIndexTable, PColumn glovalIndexCol, byte[] globalIndexCq, PTable localIndexTable, PColumn localIndexCol, byte[] localIndexCq) throws SQLException, IOException, ArrayComparisonFailure {
    // key value for v2 should exist in the data table
    Scan scan = new Scan();
    scan.setRaw(true);
    byte[] key = Bytes.toBytes("a");
    scan.setStartRow(key);
    scan.setStopRow(key);
    HTable table = (HTable) conn.unwrap(PhoenixConnection.class).getQueryServices().getTable(dataTableName.getBytes());
    ResultScanner results = table.getScanner(scan);
    Result result = results.next();
    assertNotNull(result);
    byte[] colValue;
    if (!mutable && columnEncoded) {
        KeyValueColumnExpression colExpression = new SingleCellColumnExpression(dataColumn, "V2", dataTable.getEncodingScheme());
        ImmutableBytesPtr ptr = new ImmutableBytesPtr();
        colExpression.evaluate(new ResultTuple(result), ptr);
        colValue = ptr.copyBytesIfNecessary();
    } else {
        colValue = result.getValue(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, dataCq);
    }
    assertArrayEquals("wrong column value for v2", Bytes.toBytes("1"), colValue);
    assertNull(results.next());
    // key value for v2 should exist in the global index table
    scan = new Scan();
    scan.setRaw(true);
    table = (HTable) conn.unwrap(PhoenixConnection.class).getQueryServices().getTable(indexTableName.getBytes());
    results = table.getScanner(scan);
    result = results.next();
    assertNotNull(result);
    if (!mutable && columnEncoded) {
        KeyValueColumnExpression colExpression = new SingleCellColumnExpression(glovalIndexCol, "0:V2", globalIndexTable.getEncodingScheme());
        ImmutableBytesPtr ptr = new ImmutableBytesPtr();
        colExpression.evaluate(new ResultTuple(result), ptr);
        colValue = ptr.copyBytesIfNecessary();
    } else {
        colValue = result.getValue(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, globalIndexCq);
    }
    assertArrayEquals("wrong column value for v2", Bytes.toBytes("1"), colValue);
    assertNull(results.next());
    // key value for v2 should exist in the local index table
    scan = new Scan();
    scan.setRaw(true);
    scan.addFamily(QueryConstants.DEFAULT_LOCAL_INDEX_COLUMN_FAMILY_BYTES);
    table = (HTable) conn.unwrap(PhoenixConnection.class).getQueryServices().getTable(dataTableName.getBytes());
    results = table.getScanner(scan);
    result = results.next();
    assertNotNull(result);
    if (!mutable && columnEncoded) {
        KeyValueColumnExpression colExpression = new SingleCellColumnExpression(localIndexCol, "0:V2", localIndexTable.getEncodingScheme());
        ImmutableBytesPtr ptr = new ImmutableBytesPtr();
        colExpression.evaluate(new ResultTuple(result), ptr);
        colValue = ptr.copyBytesIfNecessary();
    } else {
        colValue = result.getValue(QueryConstants.DEFAULT_LOCAL_INDEX_COLUMN_FAMILY_BYTES, localIndexCq);
    }
    assertArrayEquals("wrong column value for v2", Bytes.toBytes("1"), colValue);
    assertNull(results.next());
}
Also used : SingleCellColumnExpression(org.apache.phoenix.expression.SingleCellColumnExpression) PhoenixConnection(org.apache.phoenix.jdbc.PhoenixConnection) ResultScanner(org.apache.hadoop.hbase.client.ResultScanner) ImmutableBytesPtr(org.apache.phoenix.hbase.index.util.ImmutableBytesPtr) ResultTuple(org.apache.phoenix.schema.tuple.ResultTuple) Scan(org.apache.hadoop.hbase.client.Scan) KeyValueColumnExpression(org.apache.phoenix.expression.KeyValueColumnExpression) HTable(org.apache.hadoop.hbase.client.HTable) Result(org.apache.hadoop.hbase.client.Result)

Example 8 with KeyValueColumnExpression

use of org.apache.phoenix.expression.KeyValueColumnExpression in project phoenix by apache.

the class DropColumnIT method testDroppingIndexedColDropsIndex.

@Test
public void testDroppingIndexedColDropsIndex() throws Exception {
    String indexTableName = generateUniqueName();
    String dataTableFullName = SchemaUtil.getTableName(SCHEMA_NAME, generateUniqueName());
    String localIndexTableName1 = "LOCAL_" + indexTableName + "_1";
    String localIndexTableName2 = "LOCAL_" + indexTableName + "_2";
    try (Connection conn = getConnection()) {
        conn.setAutoCommit(false);
        conn.createStatement().execute("CREATE TABLE " + dataTableFullName + " (k VARCHAR NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR) " + tableDDLOptions);
        // create one regular and two local indexes
        conn.createStatement().execute("CREATE INDEX " + indexTableName + " ON " + dataTableFullName + " (v2) INCLUDE (v1)");
        conn.createStatement().execute("CREATE LOCAL INDEX " + localIndexTableName1 + " ON " + dataTableFullName + " (v2) INCLUDE (v1)");
        conn.createStatement().execute("CREATE LOCAL INDEX " + localIndexTableName2 + " ON " + dataTableFullName + " (k) INCLUDE (v1)");
        // upsert a single row
        PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + dataTableFullName + " VALUES(?,?,?)");
        stmt.setString(1, "a");
        stmt.setString(2, "x");
        stmt.setString(3, "1");
        stmt.execute();
        conn.commit();
        // verify the indexes were created
        PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
        PTable dataTable = pconn.getTable(new PTableKey(null, dataTableFullName));
        assertEquals("Unexpected number of indexes ", 3, dataTable.getIndexes().size());
        PTable indexTable = dataTable.getIndexes().get(0);
        byte[] indexTablePhysicalName = indexTable.getPhysicalName().getBytes();
        PName localIndexTablePhysicalName = dataTable.getIndexes().get(1).getPhysicalName();
        // drop v2 which causes the regular index and first local index to be dropped
        conn.createStatement().execute("ALTER TABLE " + dataTableFullName + " DROP COLUMN v2 ");
        // verify the both of the indexes' metadata were dropped
        conn.createStatement().execute("SELECT * FROM " + dataTableFullName);
        try {
            conn.createStatement().execute("SELECT * FROM " + indexTableName);
            fail("Index should have been dropped");
        } catch (TableNotFoundException e) {
        }
        pconn = conn.unwrap(PhoenixConnection.class);
        dataTable = pconn.getTable(new PTableKey(null, dataTableFullName));
        try {
            pconn.getTable(new PTableKey(null, indexTableName));
            fail("index should have been dropped");
        } catch (TableNotFoundException e) {
        }
        try {
            pconn.getTable(new PTableKey(null, localIndexTableName1));
            fail("index should have been dropped");
        } catch (TableNotFoundException e) {
        }
        assertEquals("Unexpected number of indexes ", 1, dataTable.getIndexes().size());
        // verify that the regular index physical table was dropped
        try {
            conn.unwrap(PhoenixConnection.class).getQueryServices().getTableDescriptor(indexTablePhysicalName);
            fail("Index table should have been dropped");
        } catch (TableNotFoundException e) {
        }
        // verify that the local index physical table was *not* dropped
        conn.unwrap(PhoenixConnection.class).getQueryServices().getTableDescriptor(localIndexTablePhysicalName.getBytes());
        PTable localIndex2 = conn.unwrap(PhoenixConnection.class).getTable(new PTableKey(null, localIndexTableName2));
        // there should be a single row belonging to localIndexTableName2 
        Scan scan = new Scan();
        scan.addFamily(QueryConstants.DEFAULT_LOCAL_INDEX_COLUMN_FAMILY_BYTES);
        HTable table = (HTable) conn.unwrap(PhoenixConnection.class).getQueryServices().getTable(localIndexTablePhysicalName.getBytes());
        ResultScanner results = table.getScanner(scan);
        Result result = results.next();
        assertNotNull(result);
        String indexColumnName = IndexUtil.getIndexColumnName(QueryConstants.DEFAULT_COLUMN_FAMILY, "V1");
        PColumn localIndexCol = localIndex2.getColumnForColumnName(indexColumnName);
        byte[] colValue;
        if (!mutable && columnEncoded) {
            KeyValueColumnExpression colExpression = new SingleCellColumnExpression(localIndexCol, indexColumnName, localIndex2.getEncodingScheme());
            ImmutableBytesPtr ptr = new ImmutableBytesPtr();
            colExpression.evaluate(new ResultTuple(result), ptr);
            colValue = ptr.copyBytesIfNecessary();
        } else {
            colValue = result.getValue(QueryConstants.DEFAULT_LOCAL_INDEX_COLUMN_FAMILY_BYTES, localIndexCol.getColumnQualifierBytes());
        }
        assertNotNull("localIndexTableName2 row is missing", colValue);
        assertNull(results.next());
    }
}
Also used : PhoenixConnection(org.apache.phoenix.jdbc.PhoenixConnection) ResultScanner(org.apache.hadoop.hbase.client.ResultScanner) ImmutableBytesPtr(org.apache.phoenix.hbase.index.util.ImmutableBytesPtr) ResultTuple(org.apache.phoenix.schema.tuple.ResultTuple) Connection(java.sql.Connection) PhoenixConnection(org.apache.phoenix.jdbc.PhoenixConnection) PreparedStatement(java.sql.PreparedStatement) HTable(org.apache.hadoop.hbase.client.HTable) PTable(org.apache.phoenix.schema.PTable) Result(org.apache.hadoop.hbase.client.Result) PColumn(org.apache.phoenix.schema.PColumn) TableNotFoundException(org.apache.phoenix.schema.TableNotFoundException) SingleCellColumnExpression(org.apache.phoenix.expression.SingleCellColumnExpression) PName(org.apache.phoenix.schema.PName) Scan(org.apache.hadoop.hbase.client.Scan) KeyValueColumnExpression(org.apache.phoenix.expression.KeyValueColumnExpression) PTableKey(org.apache.phoenix.schema.PTableKey) Test(org.junit.Test)

Example 9 with KeyValueColumnExpression

use of org.apache.phoenix.expression.KeyValueColumnExpression in project phoenix by apache.

the class StoreNullsIT method ensureNullsStoredCorrectly.

private void ensureNullsStoredCorrectly(Connection conn) throws Exception {
    ResultSet rs1 = conn.createStatement().executeQuery("SELECT NAME FROM " + dataTableName);
    rs1.next();
    assertEquals("v1", rs1.getString(1));
    rs1.next();
    assertNull(rs1.getString(1));
    rs1.next();
    HTable htable = new HTable(getUtility().getConfiguration(), dataTableName);
    Scan s = new Scan();
    s.setRaw(true);
    ResultScanner scanner = htable.getScanner(s);
    // first row has a value for name
    Result rs = scanner.next();
    PTable table = conn.unwrap(PhoenixConnection.class).getTable(new PTableKey(null, dataTableName));
    PColumn nameColumn = table.getColumnForColumnName("NAME");
    byte[] qualifier = table.getImmutableStorageScheme() == ImmutableStorageScheme.SINGLE_CELL_ARRAY_WITH_OFFSETS ? QueryConstants.SINGLE_KEYVALUE_COLUMN_QUALIFIER_BYTES : nameColumn.getColumnQualifierBytes();
    assertTrue(rs.containsColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, qualifier));
    // 2 because it also includes the empty key value column
    assertTrue(rs.size() == 2);
    KeyValueColumnExpression colExpression = table.getImmutableStorageScheme() == ImmutableStorageScheme.SINGLE_CELL_ARRAY_WITH_OFFSETS ? new SingleCellColumnExpression(nameColumn, "NAME", table.getEncodingScheme()) : new KeyValueColumnExpression(nameColumn);
    ImmutableBytesPtr ptr = new ImmutableBytesPtr();
    colExpression.evaluate(new ResultTuple(rs), ptr);
    assertEquals(new ImmutableBytesPtr(PVarchar.INSTANCE.toBytes("v1")), ptr);
    rs = scanner.next();
    if (// we don't issue a put with empty value for immutable tables with cols stored per key value
    !mutable && !columnEncoded || (mutable && !storeNulls)) {
        // for this case we use a delete to represent the null
        assertFalse(rs.containsColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, qualifier));
        assertEquals(1, rs.size());
    } else {
        assertTrue(rs.containsColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, qualifier));
        assertEquals(2, rs.size());
    }
    // assert null stored correctly 
    ptr = new ImmutableBytesPtr();
    if (colExpression.evaluate(new ResultTuple(rs), ptr)) {
        assertEquals(new ImmutableBytesPtr(ByteUtil.EMPTY_BYTE_ARRAY), ptr);
    }
    assertNull(scanner.next());
    scanner.close();
    htable.close();
}
Also used : ResultScanner(org.apache.hadoop.hbase.client.ResultScanner) PhoenixConnection(org.apache.phoenix.jdbc.PhoenixConnection) ImmutableBytesPtr(org.apache.phoenix.hbase.index.util.ImmutableBytesPtr) ResultTuple(org.apache.phoenix.schema.tuple.ResultTuple) HTable(org.apache.hadoop.hbase.client.HTable) PTable(org.apache.phoenix.schema.PTable) Result(org.apache.hadoop.hbase.client.Result) PColumn(org.apache.phoenix.schema.PColumn) SingleCellColumnExpression(org.apache.phoenix.expression.SingleCellColumnExpression) ResultSet(java.sql.ResultSet) Scan(org.apache.hadoop.hbase.client.Scan) KeyValueColumnExpression(org.apache.phoenix.expression.KeyValueColumnExpression) PTableKey(org.apache.phoenix.schema.PTableKey)

Example 10 with KeyValueColumnExpression

use of org.apache.phoenix.expression.KeyValueColumnExpression in project phoenix by apache.

the class WhereCompiler method setScanFilter.

/**
     * Sets the start/stop key range based on the whereClause expression.
     * @param context the shared context during query compilation
     * @param whereClause the final where clause expression.
     */
private static void setScanFilter(StatementContext context, FilterableStatement statement, Expression whereClause, boolean disambiguateWithFamily, boolean hashJoinOptimization) {
    Scan scan = context.getScan();
    if (LiteralExpression.isBooleanFalseOrNull(whereClause)) {
        context.setScanRanges(ScanRanges.NOTHING);
    } else if (whereClause != null && !ExpressionUtil.evaluatesToTrue(whereClause) && !hashJoinOptimization) {
        Filter filter = null;
        final Counter counter = new Counter();
        whereClause.accept(new KeyValueExpressionVisitor() {

            @Override
            public Iterator<Expression> defaultIterator(Expression node) {
                // Stop traversal once we've found multiple KeyValue columns
                if (counter.getCount() == Counter.Count.MULTIPLE) {
                    return Iterators.emptyIterator();
                }
                return super.defaultIterator(node);
            }

            @Override
            public Void visit(KeyValueColumnExpression expression) {
                counter.increment(expression);
                return null;
            }
        });
        PTable table = context.getCurrentTable().getTable();
        QualifierEncodingScheme encodingScheme = table.getEncodingScheme();
        ImmutableStorageScheme storageScheme = table.getImmutableStorageScheme();
        Counter.Count count = counter.getCount();
        boolean allCFs = false;
        byte[] essentialCF = null;
        if (counter.getCount() == Counter.Count.SINGLE && whereClause.requiresFinalEvaluation()) {
            if (table.getViewType() == ViewType.MAPPED) {
                allCFs = true;
            } else {
                byte[] emptyCF = SchemaUtil.getEmptyColumnFamily(table);
                if (Bytes.compareTo(emptyCF, counter.getColumn().getColumnFamily()) != 0) {
                    essentialCF = emptyCF;
                    count = Counter.Count.MULTIPLE;
                }
            }
        }
        switch(count) {
            case NONE:
                essentialCF = table.getType() == PTableType.VIEW ? ByteUtil.EMPTY_BYTE_ARRAY : SchemaUtil.getEmptyColumnFamily(table);
                filter = new RowKeyComparisonFilter(whereClause, essentialCF);
                break;
            case SINGLE:
                filter = disambiguateWithFamily ? new SingleCFCQKeyValueComparisonFilter(whereClause) : new SingleCQKeyValueComparisonFilter(whereClause);
                break;
            case MULTIPLE:
                filter = isPossibleToUseEncodedCQFilter(encodingScheme, storageScheme) ? new MultiEncodedCQKeyValueComparisonFilter(whereClause, encodingScheme, allCFs, essentialCF) : (disambiguateWithFamily ? new MultiCFCQKeyValueComparisonFilter(whereClause, allCFs, essentialCF) : new MultiCQKeyValueComparisonFilter(whereClause, allCFs, essentialCF));
                break;
        }
        scan.setFilter(filter);
    }
    ScanRanges scanRanges = context.getScanRanges();
    if (scanRanges.useSkipScanFilter()) {
        ScanUtil.andFilterAtBeginning(scan, scanRanges.getSkipScanFilter());
    }
}
Also used : MultiCQKeyValueComparisonFilter(org.apache.phoenix.filter.MultiCQKeyValueComparisonFilter) SingleCFCQKeyValueComparisonFilter(org.apache.phoenix.filter.SingleCFCQKeyValueComparisonFilter) MultiEncodedCQKeyValueComparisonFilter(org.apache.phoenix.filter.MultiEncodedCQKeyValueComparisonFilter) KeyValueExpressionVisitor(org.apache.phoenix.expression.visitor.KeyValueExpressionVisitor) PTable(org.apache.phoenix.schema.PTable) QualifierEncodingScheme(org.apache.phoenix.schema.PTable.QualifierEncodingScheme) MultiCFCQKeyValueComparisonFilter(org.apache.phoenix.filter.MultiCFCQKeyValueComparisonFilter) RowKeyComparisonFilter(org.apache.phoenix.filter.RowKeyComparisonFilter) SingleCFCQKeyValueComparisonFilter(org.apache.phoenix.filter.SingleCFCQKeyValueComparisonFilter) SingleCQKeyValueComparisonFilter(org.apache.phoenix.filter.SingleCQKeyValueComparisonFilter) Filter(org.apache.hadoop.hbase.filter.Filter) MultiCQKeyValueComparisonFilter(org.apache.phoenix.filter.MultiCQKeyValueComparisonFilter) EncodedColumnsUtil.isPossibleToUseEncodedCQFilter(org.apache.phoenix.util.EncodedColumnsUtil.isPossibleToUseEncodedCQFilter) MultiEncodedCQKeyValueComparisonFilter(org.apache.phoenix.filter.MultiEncodedCQKeyValueComparisonFilter) KeyValueColumnExpression(org.apache.phoenix.expression.KeyValueColumnExpression) Expression(org.apache.phoenix.expression.Expression) LiteralExpression(org.apache.phoenix.expression.LiteralExpression) AndExpression(org.apache.phoenix.expression.AndExpression) SingleCQKeyValueComparisonFilter(org.apache.phoenix.filter.SingleCQKeyValueComparisonFilter) Scan(org.apache.hadoop.hbase.client.Scan) ImmutableStorageScheme(org.apache.phoenix.schema.PTable.ImmutableStorageScheme) KeyValueColumnExpression(org.apache.phoenix.expression.KeyValueColumnExpression) MultiCFCQKeyValueComparisonFilter(org.apache.phoenix.filter.MultiCFCQKeyValueComparisonFilter) RowKeyComparisonFilter(org.apache.phoenix.filter.RowKeyComparisonFilter)

Aggregations

KeyValueColumnExpression (org.apache.phoenix.expression.KeyValueColumnExpression)18 Expression (org.apache.phoenix.expression.Expression)11 SingleCellColumnExpression (org.apache.phoenix.expression.SingleCellColumnExpression)11 Scan (org.apache.hadoop.hbase.client.Scan)8 PhoenixConnection (org.apache.phoenix.jdbc.PhoenixConnection)7 LiteralExpression (org.apache.phoenix.expression.LiteralExpression)6 PTable (org.apache.phoenix.schema.PTable)6 ImmutableBytesPtr (org.apache.phoenix.hbase.index.util.ImmutableBytesPtr)5 PColumn (org.apache.phoenix.schema.PColumn)5 Result (org.apache.hadoop.hbase.client.Result)4 CoerceExpression (org.apache.phoenix.expression.CoerceExpression)4 HTable (org.apache.hadoop.hbase.client.HTable)3 ResultScanner (org.apache.hadoop.hbase.client.ResultScanner)3 Filter (org.apache.hadoop.hbase.filter.Filter)3 ProjectedColumnExpression (org.apache.phoenix.expression.ProjectedColumnExpression)3 RowKeyColumnExpression (org.apache.phoenix.expression.RowKeyColumnExpression)3 RowKeyComparisonFilter (org.apache.phoenix.filter.RowKeyComparisonFilter)3 KeyValueSchema (org.apache.phoenix.schema.KeyValueSchema)3 ResultTuple (org.apache.phoenix.schema.tuple.ResultTuple)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2