You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@phoenix.apache.org by sa...@apache.org on 2016/10/04 10:31:08 UTC

phoenix git commit: Use column name instead of column qualifier to determine if view has all index columns

Repository: phoenix
Updated Branches:
  refs/heads/encodecolumns 9aabdf211 -> 60ac733f5


Use column name instead of column qualifier to determine if view has all index columns


Project: http://git-wip-us.apache.org/repos/asf/phoenix/repo
Commit: http://git-wip-us.apache.org/repos/asf/phoenix/commit/60ac733f
Tree: http://git-wip-us.apache.org/repos/asf/phoenix/tree/60ac733f
Diff: http://git-wip-us.apache.org/repos/asf/phoenix/diff/60ac733f

Branch: refs/heads/encodecolumns
Commit: 60ac733f534d2217ab76e02aa73561b44169c79b
Parents: 9aabdf2
Author: Samarth <sa...@salesforce.com>
Authored: Tue Oct 4 03:30:54 2016 -0700
Committer: Samarth <sa...@salesforce.com>
Committed: Tue Oct 4 03:30:54 2016 -0700

----------------------------------------------------------------------
 .../end2end/index/IndexExpressionIT.java        | 20 +++---
 .../expression/ArrayColumnExpression.java       |  1 -
 .../apache/phoenix/index/IndexMaintainer.java   | 71 +++++++++++++++++++-
 .../apache/phoenix/schema/MetaDataClient.java   | 32 ++++-----
 .../java/org/apache/phoenix/util/IndexUtil.java | 31 ---------
 5 files changed, 96 insertions(+), 59 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/phoenix/blob/60ac733f/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexExpressionIT.java
----------------------------------------------------------------------
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexExpressionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexExpressionIT.java
index bdb5b93..fad5c70 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexExpressionIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/IndexExpressionIT.java
@@ -30,14 +30,9 @@ import java.sql.SQLException;
 import java.util.Properties;
 
 import org.apache.commons.lang.StringUtils;
-import org.apache.hadoop.hbase.client.HTable;
-import org.apache.hadoop.hbase.client.Result;
-import org.apache.hadoop.hbase.client.ResultScanner;
-import org.apache.hadoop.hbase.client.Scan;
 import org.apache.phoenix.end2end.BaseHBaseManagedTimeIT;
 import org.apache.phoenix.exception.SQLExceptionCode;
 import org.apache.phoenix.execute.CommitException;
-import org.apache.phoenix.jdbc.PhoenixConnection;
 import org.apache.phoenix.query.QueryConstants;
 import org.apache.phoenix.util.DateUtil;
 import org.apache.phoenix.util.IndexUtil;
@@ -843,7 +838,7 @@ public class IndexExpressionIT extends BaseHBaseManagedTimeIT {
 	
 	        // make sure that the tables are empty, but reachable
 	        conn.createStatement().execute(
-	          "CREATE TABLE t (k VARCHAR NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR)");
+	          "CREATE TABLE t (k VARCHAR NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR) " + (!mutable ? "IMMUTABLE_ROWS=true": ""));
 	        query = "SELECT * FROM t" ;
 	        rs = conn.createStatement().executeQuery(query);
 	        assertFalse(rs.next());
@@ -1207,12 +1202,21 @@ public class IndexExpressionIT extends BaseHBaseManagedTimeIT {
     }
     
     @Test
-    public void testViewUsesTableIndex() throws Exception {
+    public void testViewUsesMutableTableIndex() throws Exception {
+        helpTestViewUsesTableIndex(false);
+    }
+    
+    @Test
+    public void testViewUsesImmutableTableIndex() throws Exception {
+        helpTestViewUsesTableIndex(true);
+    }
+    
+    private void helpTestViewUsesTableIndex(boolean immutable) throws Exception {
         Connection conn = DriverManager.getConnection(getUrl());
         try 
         {
         	ResultSet rs;
-	        String ddl = "CREATE TABLE t (k1 INTEGER NOT NULL, k2 INTEGER NOT NULL, s1 VARCHAR, s2 VARCHAR, s3 VARCHAR, s4 VARCHAR CONSTRAINT pk PRIMARY KEY (k1, k2))";
+	        String ddl = "CREATE TABLE t (k1 INTEGER NOT NULL, k2 INTEGER NOT NULL, s1 VARCHAR, s2 VARCHAR, s3 VARCHAR, s4 VARCHAR CONSTRAINT pk PRIMARY KEY (k1, k2)) " + (immutable ? "IMMUTABLE_ROWS = true" : "");
 	        conn.createStatement().execute(ddl);
 	        conn.createStatement().execute("CREATE INDEX i1 ON t(k2, s2, s3, s1)");
 	        conn.createStatement().execute("CREATE INDEX i2 ON t(k2, s2||'_'||s3, s1, s4)");

http://git-wip-us.apache.org/repos/asf/phoenix/blob/60ac733f/phoenix-core/src/main/java/org/apache/phoenix/expression/ArrayColumnExpression.java
----------------------------------------------------------------------
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/expression/ArrayColumnExpression.java b/phoenix-core/src/main/java/org/apache/phoenix/expression/ArrayColumnExpression.java
index 9690809..03b6c61 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/expression/ArrayColumnExpression.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/expression/ArrayColumnExpression.java
@@ -61,7 +61,6 @@ public class ArrayColumnExpression extends ColumnExpression {
         // array indexes are 1-based TODO: samarth think about the case when the encodedcolumn qualifier is null. Probably best to add a check here for encodedcolumnname to be true
         this.index = column.getEncodedColumnQualifier() + 1;
         byte[] cf = column.getFamilyName().getBytes();
-        byte[] cq = EncodedColumnsUtil.getEncodedColumnQualifier(column);
         this.arrayExpression = new KeyValueColumnExpression(column, cf, cf);
         this.origKVExpression = new KeyValueColumnExpression(column, displayName, encodedColumnName);
         this.displayName = displayName;

http://git-wip-us.apache.org/repos/asf/phoenix/blob/60ac733f/phoenix-core/src/main/java/org/apache/phoenix/index/IndexMaintainer.java
----------------------------------------------------------------------
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/index/IndexMaintainer.java b/phoenix-core/src/main/java/org/apache/phoenix/index/IndexMaintainer.java
index a278c11..9c633b3 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/index/IndexMaintainer.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/index/IndexMaintainer.java
@@ -45,6 +45,7 @@ import org.apache.hadoop.hbase.client.Durability;
 import org.apache.hadoop.hbase.client.Put;
 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
 import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.Pair;
 import org.apache.hadoop.io.Writable;
 import org.apache.hadoop.io.WritableUtils;
 import org.apache.phoenix.compile.ColumnResolver;
@@ -71,6 +72,8 @@ import org.apache.phoenix.parse.SQLParser;
 import org.apache.phoenix.parse.StatelessTraverseAllParseNodeVisitor;
 import org.apache.phoenix.parse.UDFParseNode;
 import org.apache.phoenix.query.QueryConstants;
+import org.apache.phoenix.schema.AmbiguousColumnException;
+import org.apache.phoenix.schema.ColumnFamilyNotFoundException;
 import org.apache.phoenix.schema.ColumnNotFoundException;
 import org.apache.phoenix.schema.PColumn;
 import org.apache.phoenix.schema.PColumnFamily;
@@ -100,6 +103,7 @@ import org.apache.phoenix.util.SchemaUtil;
 import org.apache.phoenix.util.TrustedByteArrayOutputStream;
 import org.apache.tephra.TxConstants;
 
+import com.google.common.base.Preconditions;
 import com.google.common.base.Predicate;
 import com.google.common.collect.Iterators;
 import com.google.common.collect.Lists;
@@ -283,6 +287,8 @@ public class IndexMaintainer implements Writable, Iterable<ColumnReference> {
     // columns required to evaluate all expressions in indexedExpressions (this does not include columns in the data row key)
     private Set<ColumnReference> indexedColumns;
     private Set<ColumnReference> coveredColumns;
+    // Information for columns of data tables that are being indexed. The first part of the pair is column family and second part is the column name. 
+    private Set<Pair<String, String>> indexedColumnsInfo;
     // Map of covered columns where a key is column reference for a column in the data table
     // and value is column reference for corresponding column in the index table.
     // TODO: samarth confirm that we don't need a separate map for tracking column families of local indexes.
@@ -320,7 +326,7 @@ public class IndexMaintainer implements Writable, Iterable<ColumnReference> {
         this.isDataTableSalted = isDataTableSalted;
     }
 
-    private IndexMaintainer(PTable dataTable, PTable index, PhoenixConnection connection) {
+    private IndexMaintainer(final PTable dataTable, final PTable index, PhoenixConnection connection) {
         this(dataTable.getRowKeySchema(), dataTable.getBucketNum() != null);
         assert(dataTable.getType() == PTableType.SYSTEM || dataTable.getType() == PTableType.TABLE || dataTable.getType() == PTableType.VIEW);
         this.rowKeyOrderOptimizable = index.rowKeyOrderOptimizable();
@@ -414,6 +420,7 @@ public class IndexMaintainer implements Writable, Iterable<ColumnReference> {
             throw new RuntimeException(e); // Impossible
         }
         StatementContext context = new StatementContext(new PhoenixStatement(connection), resolver);
+        this.indexedColumnsInfo = Sets.newHashSetWithExpectedSize(nIndexColumns - nIndexPKColumns);
         IndexExpressionCompiler expressionIndexCompiler = new IndexExpressionCompiler(context);
         for (int i = indexPosOffset; i < index.getPKColumns().size(); i++) {
             PColumn indexColumn = index.getPKColumns().get(i);
@@ -432,14 +439,55 @@ public class IndexMaintainer implements Writable, Iterable<ColumnReference> {
 	            if (isPKColumn) {
 	                int dataPkPos = dataTable.getPKColumns().indexOf(column) - (dataTable.getBucketNum() == null ? 0 : 1) - (this.isMultiTenant ? 1 : 0);
 	                this.rowKeyMetaData.setIndexPkPosition(dataPkPos, indexPos);
+	                indexedColumnsInfo.add(new Pair<>((String)null, column.getName().getString()));
 	            } else {
 	                indexColByteSize += column.getDataType().isFixedWidth() ? SchemaUtil.getFixedByteSize(column) : ValueSchema.ESTIMATED_VARIABLE_LENGTH_SIZE;
 	                this.indexedExpressions.add(expression);
+	                indexedColumnsInfo.add(new Pair<>(column.getFamilyName().getString(), column.getName().getString()));
 	            }
             }
             else {
             	indexColByteSize += expression.getDataType().isFixedWidth() ? SchemaUtil.getFixedByteSize(expression) : ValueSchema.ESTIMATED_VARIABLE_LENGTH_SIZE;
                 this.indexedExpressions.add(expression);
+                KeyValueExpressionVisitor kvVisitor = new KeyValueExpressionVisitor() {
+                    @Override
+                    public Void visit(KeyValueColumnExpression colExpression) {
+                        return addDataColInfo(dataTable, colExpression);
+                    }
+
+                    @Override
+                    public Void visit(ArrayColumnExpression expression) {
+                        return addDataColInfo(dataTable, expression);
+                    }
+
+                    private Void addDataColInfo(final PTable dataTable, Expression expression) {
+                        Preconditions.checkArgument(expression instanceof ArrayColumnExpression
+                                || expression instanceof KeyValueColumnExpression);
+
+                        KeyValueColumnExpression colExpression = null;
+                        if (expression instanceof ArrayColumnExpression) {
+                            colExpression =
+                                    ((ArrayColumnExpression) expression).getKeyValueExpression();
+                        } else {
+                            colExpression = ((KeyValueColumnExpression) expression);
+                        }
+                        byte[] cf = colExpression.getColumnFamily();
+                        byte[] cq = colExpression.getColumnQualifier();
+                        try {
+                            PColumn dataColumn =
+                                    cf == null ? dataTable.getPColumnForColumnQualifier(null, cq)
+                                            : dataTable.getColumnFamily(cf)
+                                                    .getPColumnForColumnQualifier(cq);
+                            indexedColumnsInfo.add(new Pair<>(dataColumn.getFamilyName()
+                                    .getString(), dataColumn.getName().getString()));
+                        } catch (ColumnNotFoundException | ColumnFamilyNotFoundException
+                                | AmbiguousColumnException e) {
+                            throw new RuntimeException(e);
+                        }
+                        return null;
+                    }
+                };
+                expression.accept(kvVisitor);
             }
             // set the sort order of the expression correctly
             if (indexColumn.getSortOrder() == SortOrder.DESC) {
@@ -461,7 +509,7 @@ public class IndexMaintainer implements Writable, Iterable<ColumnReference> {
         this.estimatedIndexRowKeyBytes = estimateIndexRowKeyByteSize(indexColByteSize);
         initCachedState();
     }
-
+    
     public byte[] buildRowKey(ValueGetter valueGetter, ImmutableBytesWritable rowKeyPtr, byte[] regionStartKey, byte[] regionEndKey, boolean convertArrayColToKeyValueCol)  {
         ImmutableBytesWritable ptr = new ImmutableBytesWritable();
         boolean prependRegionStartKey = isLocalIndex && regionStartKey != null;
@@ -1211,6 +1259,14 @@ public class IndexMaintainer implements Writable, Iterable<ColumnReference> {
         int encodedEstimatedIndexRowKeyBytesAndImmutableRows = WritableUtils.readVInt(input);
         this.immutableRows = encodedEstimatedIndexRowKeyBytesAndImmutableRows < 0;
         this.estimatedIndexRowKeyBytes = Math.abs(encodedEstimatedIndexRowKeyBytesAndImmutableRows);
+        int numCols = WritableUtils.readVInt(input);
+        //TODO: samarth figure out a backward compatible way of reading/writing indexedColumnsInfo
+        indexedColumnsInfo = Sets.newHashSetWithExpectedSize(numCols);
+        for (int i = 1; i <= numCols; i++) {
+            byte[] dataTableCf = Bytes.readByteArray(input);
+            byte[] dataTableCq = Bytes.readByteArray(input);
+            indexedColumnsInfo.add(new Pair<>(Bytes.toString(dataTableCf), Bytes.toString(dataTableCq)));
+        }
         initCachedState();
     }
     
@@ -1264,6 +1320,11 @@ public class IndexMaintainer implements Writable, Iterable<ColumnReference> {
         WritableUtils.writeVInt(output, (nDataCFs + 1) * (indexWALDisabled ? -1 : 1));
         // Encode estimatedIndexRowKeyBytes and immutableRows together.
         WritableUtils.writeVInt(output, estimatedIndexRowKeyBytes * (immutableRows ? -1 : 1));
+        WritableUtils.writeVInt(output, indexedColumnsInfo.size());
+        for (Pair<String, String> colInfo : indexedColumnsInfo) {
+            Bytes.writeByteArray(output, colInfo.getFirst() == null ? null : colInfo.getFirst().getBytes());
+            Bytes.writeByteArray(output, colInfo.getSecond().getBytes());
+        }
     }
 
     public int getEstimatedByteSize() {
@@ -1331,7 +1392,7 @@ public class IndexMaintainer implements Writable, Iterable<ColumnReference> {
 					if (indexedColumns.add(new ColumnReference(colExpression.getColumnFamily(), colExpression.getColumnQualifier()))) {
                 		indexedColumnTypes.add(colExpression.getDataType());
                 	}
-                    return null;
+					return null;
                 }
             };
             expression.accept(visitor);
@@ -1597,4 +1658,8 @@ public class IndexMaintainer implements Writable, Iterable<ColumnReference> {
     public byte[] getEmptyKeyValueQualifier() {
         return emptyKeyValueQualifierPtr.copyBytes();
     }
+    
+    public Set<Pair<String, String>> getIndexedColumnInfo() {
+        return indexedColumnsInfo;
+    }
 }

http://git-wip-us.apache.org/repos/asf/phoenix/blob/60ac733f/phoenix-core/src/main/java/org/apache/phoenix/schema/MetaDataClient.java
----------------------------------------------------------------------
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/schema/MetaDataClient.java b/phoenix-core/src/main/java/org/apache/phoenix/schema/MetaDataClient.java
index 6cc5271..d9e555f 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/schema/MetaDataClient.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/schema/MetaDataClient.java
@@ -722,22 +722,24 @@ public class MetaDataClient {
             boolean containsAllReqdCols = true;
             // Ensure that all columns required to create index exist in the view too,
             // since view columns may be removed.
+            IndexMaintainer indexMaintainer = index.getIndexMaintainer(physicalTable, connection);
             // Check that the columns required for the index pk are present in the view
-            List<PColumn> indexPkColumns = index.getPKColumns();
-            int offset = (index.getBucketNum() != null ? 1 : 0) + (index.getViewIndexId() != null ? 1 : 0);
-            for (int i = offset; i < indexPkColumns.size(); i++) {
-                PColumn indexPkCol = indexPkColumns.get(i);
-                if (!IndexUtil.isDataPKColumn(indexPkCol)) {
-                    try {
-                        String colName = indexPkCol.getName().getString();
-                        String dataColumnCF = IndexUtil.getDataColumnFamilyName(colName);
-                        view.getColumnFamily(dataColumnCF).getPColumnForColumnName(IndexUtil.getDataColumnName(colName));
-                    } catch (ColumnNotFoundException e) { // Ignore this index and continue with others
-                        containsAllReqdCols = false;
-                        break;
+            Set<Pair<String, String>> indexedColInfos = indexMaintainer.getIndexedColumnInfo();
+            for (Pair<String, String> colInfo : indexedColInfos) {
+                try {
+                    String colFamily = colInfo.getFirst();
+                    String colName = colInfo.getSecond();
+                    if (colFamily == null) {
+                        view.getPColumnForColumnName(colName);
+                    } else {
+                        view.getColumnFamily(colFamily).getPColumnForColumnName(colName);
                     }
+                } catch (ColumnNotFoundException e) {
+                    containsAllReqdCols = false;
+                    break;
                 }
             }
+            
             // Ensure that constant columns (i.e. columns matched in the view WHERE clause)
             // all exist in the index on the physical table.
             for (PColumn col : view.getColumns()) {
@@ -3503,15 +3505,13 @@ public class MetaDataClient {
                 dropColumnMutations(table, tableColumnsToDrop, tableMetaData);
                 for (PTable index : table.getIndexes()) {
                     IndexMaintainer indexMaintainer = index.getIndexMaintainer(table, connection);
-                    int offset = (index.getBucketNum() != null ? 1 : 0) + (index.getViewIndexId() != null ? 1 : 0);
-                    // get the data table columns corresponding to the index pk columns
-                    Set<Pair<String, String>> dataColumnsForIndexPkColumns = IndexUtil.getDataColumnsForIndexColumns(index.getPKColumns().subList(offset, index.getPKColumns().size())); 
                     // get the covered columns 
                     Set<ColumnReference> coveredColumns = indexMaintainer.getCoveredColumns();
                     List<PColumn> indexColumnsToDrop = Lists.newArrayListWithExpectedSize(columnRefs.size());
                     for(PColumn columnToDrop : tableColumnsToDrop) {
                         ColumnReference columnToDropRef = new ColumnReference(columnToDrop.getFamilyName().getBytes(), EncodedColumnsUtil.getColumnQualifier(columnToDrop, index));
-                        if (dataColumnsForIndexPkColumns.contains(new Pair<>(columnToDrop.getFamilyName().getString(), columnToDrop.getName().getString()))) {
+                        boolean isColumnIndexed = indexMaintainer.getIndexedColumnInfo().contains(new Pair<>(columnToDrop.getFamilyName().getString(), columnToDrop.getName().getString()));
+                        if (isColumnIndexed) {
                             if (index.getViewIndexId()==null) 
                                 indexesToDrop.add(new TableRef(index));
                             connection.removeTable(tenantId, SchemaUtil.getTableName(schemaName, index.getName().getString()), index.getParentName() == null ? null : index.getParentName().getString(), index.getTimeStamp());

http://git-wip-us.apache.org/repos/asf/phoenix/blob/60ac733f/phoenix-core/src/main/java/org/apache/phoenix/util/IndexUtil.java
----------------------------------------------------------------------
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/util/IndexUtil.java b/phoenix-core/src/main/java/org/apache/phoenix/util/IndexUtil.java
index 80a7edf..2635c62 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/util/IndexUtil.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/util/IndexUtil.java
@@ -708,35 +708,4 @@ public class IndexUtil {
         return true;
     }
     
-    /**
-     * 
-     * @param indexColumns
-     * @return Set of pairs of data column info where the first element in the pair is the column family name
-     * and the second part is the column name. 
-     */
-    public static Set<Pair<String, String>> getDataColumnsForIndexColumns(List<PColumn> indexColumns) {
-        int numCols = indexColumns.size();
-        Set<Pair<String, String>> dataColumns = new HashSet<>(indexColumns.size());
-        for (int i = 0; i < numCols; i++) {
-            PColumn indexCol = indexColumns.get(i);
-            String indexColFullName = indexCol.getName().getString();
-            String dataColumnName = IndexUtil.getDataColumnName(indexColFullName);
-            String dataColFamilyName = null;
-            if (!IndexUtil.isDataPKColumn(indexCol)) {
-                dataColFamilyName = IndexUtil.getDataColumnFamilyName(indexColFullName);
-            }
-            dataColumns.add(new Pair<>(dataColFamilyName, dataColumnName));
-        }
-        return dataColumns;
-    }
-    
-    /**
-     * @param dataColumn
-     * @param dataColumns @see #getDataColumnsForIndexColumns(int, List) to how create this set.
-     * @return whether the column is in the set. 
-     */
-    public static boolean isColumnInSet(PColumn dataColumn, Set<Pair<String, String>> dataColumns) {
-        return dataColumns.contains(new Pair<>(dataColumn.getFamilyName().getString(), dataColumn
-                .getName().getString()));
-    }
 }