You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@phoenix.apache.org by sk...@apache.org on 2020/08/07 23:01:08 UTC
[phoenix] branch 4.x updated: PHOENIX-5946: Implement
SchemaExtractionTool utility to get effective DDL from the cluster
(Co-authored by Tanuj Khurana)
This is an automated email from the ASF dual-hosted git repository.
skadam pushed a commit to branch 4.x
in repository https://gitbox.apache.org/repos/asf/phoenix.git
The following commit(s) were added to refs/heads/4.x by this push:
new bba7d59 PHOENIX-5946: Implement SchemaExtractionTool utility to get effective DDL from the cluster (Co-authored by Tanuj Khurana)
bba7d59 is described below
commit bba7d59f81f2b91342fa5a7ee213170739573d6a
Author: Swaroopa Kadam <sw...@gmail.com>
AuthorDate: Mon Jul 27 15:58:55 2020 -0700
PHOENIX-5946: Implement SchemaExtractionTool utility to get effective DDL from the cluster (Co-authored by Tanuj Khurana)
Phoenix-5947 Add tests and extensions to Schema Extraction Tool utility (#848) (Co-authored by Rachel Li)
Co-authored-by: s.kadam <s....@apache.org>
---
.../phoenix/query/ConnectionQueryServicesImpl.java | 8 +-
.../apache/phoenix/query/QueryServicesOptions.java | 2 +
.../org/apache/phoenix/schema/DelegateTable.java | 9 +-
.../java/org/apache/phoenix/schema/PTable.java | 3 +
.../java/org/apache/phoenix/schema/PTableImpl.java | 71 ++++
.../java/org/apache/phoenix/util/MetaDataUtil.java | 2 +-
phoenix-tools/pom.xml | 154 +++++++
.../phoenix/schema/SchemaExtractionToolIT.java | 342 +++++++++++++++
.../phoenix/schema/SchemaExtractionProcessor.java | 473 +++++++++++++++++++++
.../phoenix/schema/SchemaExtractionTool.java | 109 +++++
pom.xml | 6 +
11 files changed, 1171 insertions(+), 8 deletions(-)
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/query/ConnectionQueryServicesImpl.java b/phoenix-core/src/main/java/org/apache/phoenix/query/ConnectionQueryServicesImpl.java
index e418163..7214e90 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/query/ConnectionQueryServicesImpl.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/query/ConnectionQueryServicesImpl.java
@@ -2762,7 +2762,7 @@ public class ConnectionQueryServicesImpl extends DelegateQueryServices implement
return existingColumnFamilies(table);
}
- private HashSet<String> existingColumnFamilies(PTable table) {
+ public HashSet<String> existingColumnFamilies(PTable table) {
List<PColumnFamily> cfs = table.getColumnFamilies();
HashSet<String> cfNames = new HashSet<>(cfs.size());
for (PColumnFamily cf : table.getColumnFamilies()) {
@@ -2771,14 +2771,14 @@ public class ConnectionQueryServicesImpl extends DelegateQueryServices implement
return cfNames;
}
- private static int getTTL(PTable table, HTableDescriptor tableDesc, Integer newTTL) throws SQLException {
+ public static int getTTL(PTable table, HTableDescriptor tableDesc, Integer newTTL) throws SQLException {
// If we're setting TTL now, then use that value. Otherwise, use empty column family value
int ttl = newTTL != null ? newTTL
: tableDesc.getFamily(SchemaUtil.getEmptyColumnFamily(table)).getTimeToLive();
return ttl;
}
- private static KeepDeletedCells getKeepDeletedCells(PTable table, HTableDescriptor tableDesc,
+ public static KeepDeletedCells getKeepDeletedCells(PTable table, HTableDescriptor tableDesc,
KeepDeletedCells newKeepDeletedCells) throws SQLException {
// If we're setting KEEP_DELETED_CELLS now, then use that value. Otherwise, use the empty column family value
return (newKeepDeletedCells != null) ?
@@ -2786,7 +2786,7 @@ public class ConnectionQueryServicesImpl extends DelegateQueryServices implement
tableDesc.getFamily(SchemaUtil.getEmptyColumnFamily(table)).getKeepDeletedCells();
}
- private static int getReplicationScope(PTable table, HTableDescriptor tableDesc,
+ public static int getReplicationScope(PTable table, HTableDescriptor tableDesc,
Integer newReplicationScope) throws SQLException {
// If we're setting replication scope now, then use that value. Otherwise, use the empty column family value
return (newReplicationScope != null) ?
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/query/QueryServicesOptions.java b/phoenix-core/src/main/java/org/apache/phoenix/query/QueryServicesOptions.java
index cc42ca7..3773174 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/query/QueryServicesOptions.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/query/QueryServicesOptions.java
@@ -281,6 +281,7 @@ public class QueryServicesOptions {
public static final String DEFAULT_CLIENT_METRICS_TAG = "FAT_CLIENT";
public static final boolean DEFAULT_TRANSACTIONAL = false;
+ public static final boolean DEFAULT_MULTI_TENANT = false;
public static final boolean DEFAULT_AUTO_FLUSH = false;
private static final String DEFAULT_CLIENT_RPC_CONTROLLER_FACTORY = ClientRpcControllerFactory.class.getName();
@@ -362,6 +363,7 @@ public class QueryServicesOptions {
public static final String DEFAULT_LOGGING_LEVEL = LogLevel.OFF.name();
public static final String DEFAULT_LOG_SAMPLE_RATE = "1.0";
public static final int DEFAULT_LOG_SALT_BUCKETS = 32;
+ public static final int DEFAULT_SALT_BUCKETS = 0;
public static final boolean DEFAULT_SYSTEM_CATALOG_SPLITTABLE = true;
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/schema/DelegateTable.java b/phoenix-core/src/main/java/org/apache/phoenix/schema/DelegateTable.java
index a2e9757..13e7bf1 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/schema/DelegateTable.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/schema/DelegateTable.java
@@ -18,6 +18,7 @@
package org.apache.phoenix.schema;
import java.util.List;
+import java.util.Map;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.hbase.index.util.KeyValueBuilder;
@@ -138,9 +139,7 @@ public class DelegateTable implements PTable {
}
@Override
- public List<PTable> getIndexes() {
- return delegate.getIndexes();
- }
+ public List<PTable> getIndexes() { return delegate.getIndexes(); }
@Override
public PIndexState getIndexState() {
@@ -350,4 +349,8 @@ public class DelegateTable implements PTable {
@Override public boolean hasViewModifiedPhoenixTTL() {
return delegate.hasViewModifiedPhoenixTTL();
}
+
+ @Override public Map<String, String> getPropertyValues() { return delegate.getPropertyValues(); }
+
+ @Override public Map<String, String> getDefaultPropertyValues() { return delegate.getDefaultPropertyValues(); }
}
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/schema/PTable.java b/phoenix-core/src/main/java/org/apache/phoenix/schema/PTable.java
index 941e422..d15fe2c 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/schema/PTable.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/schema/PTable.java
@@ -56,6 +56,7 @@ public interface PTable extends PMetaDataEntity {
public static final long INITIAL_SEQ_NUM = 0;
public static final String IS_IMMUTABLE_ROWS_PROP_NAME = "IMMUTABLE_ROWS";
public static final boolean DEFAULT_DISABLE_WAL = false;
+ public static final boolean DEFAULT_IMMUTABLE_ROWS = false;
public enum ViewType {
MAPPED((byte)1),
@@ -800,6 +801,8 @@ public interface PTable extends PMetaDataEntity {
Boolean useStatsForParallelization();
boolean hasViewModifiedUpdateCacheFrequency();
boolean hasViewModifiedUseStatsForParallelization();
+ Map<String, String> getPropertyValues();
+ Map<String, String> getDefaultPropertyValues();
/**
* @return The PHOENIX_TTL duration associated with the entity.
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/schema/PTableImpl.java b/phoenix-core/src/main/java/org/apache/phoenix/schema/PTableImpl.java
index fcd09d3..dd6dccc 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/schema/PTableImpl.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/schema/PTableImpl.java
@@ -20,7 +20,31 @@ package org.apache.phoenix.schema;
import static org.apache.phoenix.coprocessor.ScanRegionObserver.DYNAMIC_COLUMN_METADATA_STORED_FOR_MUTATION;
import static org.apache.phoenix.hbase.index.util.KeyValueBuilder.addQuietly;
import static org.apache.phoenix.hbase.index.util.KeyValueBuilder.deleteQuietly;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.APPEND_ONLY_SCHEMA;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.AUTO_PARTITION_SEQ;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_ENCODED_BYTES;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.DISABLE_WAL;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.ENCODING_SCHEME;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.GUIDE_POSTS_WIDTH;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.IMMUTABLE_ROWS;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.DEFAULT_COLUMN_FAMILY_NAME;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.IMMUTABLE_STORAGE_SCHEME;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.MULTI_TENANT;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SALT_BUCKETS;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TRANSACTIONAL;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TRANSACTION_PROVIDER;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.UPDATE_CACHE_FREQUENCY;
+import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.USE_STATS_FOR_PARALLELIZATION;
+import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_COLUMN_ENCODED_BYTES;
+import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_IMMUTABLE_STORAGE_SCHEME;
+import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_MULTI_TENANT;
+import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_SALT_BUCKETS;
+import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_TRANSACTIONAL;
+import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_TRANSACTION_PROVIDER;
+import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_UPDATE_CACHE_FREQUENCY;
+import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_USE_STATS_FOR_PARALLELIZATION;
import static org.apache.phoenix.schema.SaltingUtil.SALTING_COLUMN;
+import static org.apache.phoenix.schema.TableProperty.DEFAULT_COLUMN_FAMILY;
import static org.apache.phoenix.schema.types.PDataType.TRUE_BYTES;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.PHOENIX_TTL_NOT_DEFINED;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.MIN_PHOENIX_TTL_HWM;
@@ -34,6 +58,7 @@ import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -173,6 +198,7 @@ public class PTableImpl implements PTable {
private final long phoenixTTL;
private final long phoenixTTLHighWaterMark;
private final BitSet viewModifiedPropSet;
+ private Map<String, String> propertyValues;
public static class Builder {
private PTableKey key;
@@ -229,6 +255,7 @@ public class PTableImpl implements PTable {
private Boolean useStatsForParallelization;
private long phoenixTTL;
private long phoenixTTLHighWaterMark;
+ private Map<String, String> propertyValues = new HashMap<>();
// Used to denote which properties a view has explicitly modified
private BitSet viewModifiedPropSet = new BitSet(3);
@@ -342,6 +369,9 @@ public class PTableImpl implements PTable {
}
public Builder setBucketNum(Integer bucketNum) {
+ if(bucketNum!=null) {
+ propertyValues.put(SALT_BUCKETS, String.valueOf(bucketNum));
+ }
this.bucketNum = bucketNum;
return this;
}
@@ -377,6 +407,7 @@ public class PTableImpl implements PTable {
}
public Builder setImmutableRows(boolean immutableRows) {
+ propertyValues.put(IMMUTABLE_ROWS, String.valueOf(immutableRows));
isImmutableRows = immutableRows;
return this;
}
@@ -392,6 +423,9 @@ public class PTableImpl implements PTable {
}
public Builder setDefaultFamilyName(PName defaultFamilyName) {
+ if (defaultFamilyName != null){
+ propertyValues.put(DEFAULT_COLUMN_FAMILY_NAME, defaultFamilyName.getString());
+ }
this.defaultFamilyName = defaultFamilyName;
return this;
}
@@ -402,11 +436,13 @@ public class PTableImpl implements PTable {
}
public Builder setDisableWAL(boolean disableWAL) {
+ propertyValues.put(DISABLE_WAL, String.valueOf(disableWAL));
this.disableWAL = disableWAL;
return this;
}
public Builder setMultiTenant(boolean multiTenant) {
+ propertyValues.put(MULTI_TENANT, String.valueOf(multiTenant));
this.multiTenant = multiTenant;
return this;
}
@@ -417,6 +453,9 @@ public class PTableImpl implements PTable {
}
public Builder setTransactionProvider(TransactionFactory.Provider transactionProvider) {
+ if(transactionProvider != null) {
+ propertyValues.put(TRANSACTION_PROVIDER, String.valueOf(transactionProvider));
+ }
this.transactionProvider = transactionProvider;
return this;
}
@@ -467,6 +506,7 @@ public class PTableImpl implements PTable {
}
public Builder setUpdateCacheFrequency(long updateCacheFrequency) {
+ propertyValues.put(UPDATE_CACHE_FREQUENCY, String.valueOf(updateCacheFrequency));
this.updateCacheFrequency = updateCacheFrequency;
return this;
}
@@ -477,21 +517,25 @@ public class PTableImpl implements PTable {
}
public Builder setAutoPartitionSeqName(String autoPartitionSeqName) {
+ propertyValues.put(AUTO_PARTITION_SEQ, autoPartitionSeqName);
this.autoPartitionSeqName = autoPartitionSeqName;
return this;
}
public Builder setAppendOnlySchema(boolean appendOnlySchema) {
+ propertyValues.put(APPEND_ONLY_SCHEMA, String.valueOf(appendOnlySchema));
isAppendOnlySchema = appendOnlySchema;
return this;
}
public Builder setImmutableStorageScheme(ImmutableStorageScheme immutableStorageScheme) {
+ propertyValues.put(IMMUTABLE_STORAGE_SCHEME, immutableStorageScheme.toString());
this.immutableStorageScheme = immutableStorageScheme;
return this;
}
public Builder setQualifierEncodingScheme(QualifierEncodingScheme qualifierEncodingScheme) {
+ propertyValues.put(ENCODING_SCHEME, qualifierEncodingScheme.toString());
this.qualifierEncodingScheme = qualifierEncodingScheme;
return this;
}
@@ -502,6 +546,9 @@ public class PTableImpl implements PTable {
}
public Builder setUseStatsForParallelization(Boolean useStatsForParallelization) {
+ if(useStatsForParallelization!=null) {
+ propertyValues.put(USE_STATS_FOR_PARALLELIZATION, String.valueOf(useStatsForParallelization));
+ }
this.useStatsForParallelization = useStatsForParallelization;
return this;
}
@@ -807,6 +854,7 @@ public class PTableImpl implements PTable {
this.phoenixTTL = builder.phoenixTTL;
this.phoenixTTLHighWaterMark = builder.phoenixTTLHighWaterMark;
this.viewModifiedPropSet = builder.viewModifiedPropSet;
+ this.propertyValues = builder.propertyValues;
}
// When cloning table, ignore the salt column as it will be added back in the constructor
@@ -2025,4 +2073,27 @@ public class PTableImpl implements PTable {
}
}
+
+ @Override
+ public Map<String, String> getPropertyValues() {
+ return Collections.unmodifiableMap(propertyValues);
+ }
+
+ @Override
+ public Map<String, String> getDefaultPropertyValues() {
+ Map<String, String> map = new HashMap<>();
+ map.put(DISABLE_WAL, String.valueOf(DEFAULT_DISABLE_WAL));
+ map.put(IMMUTABLE_ROWS, String.valueOf(DEFAULT_IMMUTABLE_ROWS));
+ map.put(TRANSACTION_PROVIDER, DEFAULT_TRANSACTION_PROVIDER);
+ map.put(IMMUTABLE_STORAGE_SCHEME, DEFAULT_IMMUTABLE_STORAGE_SCHEME);
+ map.put(COLUMN_ENCODED_BYTES, String.valueOf(DEFAULT_COLUMN_ENCODED_BYTES));
+ map.put(UPDATE_CACHE_FREQUENCY, String.valueOf(DEFAULT_UPDATE_CACHE_FREQUENCY));
+ map.put(USE_STATS_FOR_PARALLELIZATION, String.valueOf(DEFAULT_USE_STATS_FOR_PARALLELIZATION));
+ map.put(TRANSACTIONAL, String.valueOf(DEFAULT_TRANSACTIONAL));
+ map.put(MULTI_TENANT, String.valueOf(DEFAULT_MULTI_TENANT));
+ map.put(SALT_BUCKETS, String.valueOf(DEFAULT_SALT_BUCKETS));
+ map.put(DEFAULT_COLUMN_FAMILY_NAME, String.valueOf(DEFAULT_COLUMN_FAMILY));
+ return Collections.unmodifiableMap(map);
+ }
+
}
diff --git a/phoenix-core/src/main/java/org/apache/phoenix/util/MetaDataUtil.java b/phoenix-core/src/main/java/org/apache/phoenix/util/MetaDataUtil.java
index a5288fc..268d72b 100644
--- a/phoenix-core/src/main/java/org/apache/phoenix/util/MetaDataUtil.java
+++ b/phoenix-core/src/main/java/org/apache/phoenix/util/MetaDataUtil.java
@@ -89,7 +89,7 @@ public class MetaDataUtil {
public static final String VIEW_INDEX_SEQUENCE_PREFIX = "_SEQ_";
public static final String VIEW_INDEX_SEQUENCE_NAME_PREFIX = "_ID_";
public static final byte[] VIEW_INDEX_SEQUENCE_PREFIX_BYTES = Bytes.toBytes(VIEW_INDEX_SEQUENCE_PREFIX);
- private static final String VIEW_INDEX_ID_COLUMN_NAME = "_INDEX_ID";
+ public static final String VIEW_INDEX_ID_COLUMN_NAME = "_INDEX_ID";
public static final String PARENT_TABLE_KEY = "PARENT_TABLE";
public static final String IS_VIEW_INDEX_TABLE_PROP_NAME = "IS_VIEW_INDEX_TABLE";
public static final byte[] IS_VIEW_INDEX_TABLE_PROP_BYTES = Bytes.toBytes(IS_VIEW_INDEX_TABLE_PROP_NAME);
diff --git a/phoenix-tools/pom.xml b/phoenix-tools/pom.xml
new file mode 100644
index 0000000..6c9b451
--- /dev/null
+++ b/phoenix-tools/pom.xml
@@ -0,0 +1,154 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>phoenix</artifactId>
+ <groupId>org.apache.phoenix</groupId>
+ <version>4.16.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>phoenix-tools</artifactId>
+
+ <dependencies>
+ <!-- Depend on all other internal projects -->
+ <dependency>
+ <groupId>org.apache.phoenix</groupId>
+ <artifactId>phoenix-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.phoenix</groupId>
+ <artifactId>phoenix-core</artifactId>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-auth</artifactId>
+ <version>2.7.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hbase</groupId>
+ <artifactId>hbase-testing-util</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.jcabi</groupId>
+ <artifactId>jcabi-jdbc</artifactId>
+ <version>0.15</version>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-junit</artifactId>
+ <version>1.0.0.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.github.stefanbirkner</groupId>
+ <artifactId>system-rules</artifactId>
+ <version>1.8.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hbase</groupId>
+ <artifactId>hbase-testing-util</artifactId>
+ <scope>test</scope>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hbase</groupId>
+ <artifactId>hbase-it</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tephra</groupId>
+ <artifactId>tephra-core</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-minicluster</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ </resource>
+ <resource>
+ <directory>config</directory>
+ <excludes>
+ <exclude>**/*.sql</exclude>
+ <exclude>**/*.xml</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ <testResources>
+ <testResource>
+ <directory>src/test/resources</directory>
+ </testResource>
+ <testResource>
+ <directory>${project.basedir}/config</directory>
+ </testResource>
+ </testResources>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-failsafe-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <artifactId>maven-dependency-plugin</artifactId>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.7</source>
+ <target>1.7</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <workingDirectory>${java.io.tmpdir}</workingDirectory>
+ <forkCount>1</forkCount>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-resources-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.rat</groupId>
+ <artifactId>apache-rat-plugin</artifactId>
+ <configuration>
+ <excludes>
+ <exclude>*/RESULTS/**</exclude>
+ <exclude>README.md</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
\ No newline at end of file
diff --git a/phoenix-tools/src/it/java/org/apache/phoenix/schema/SchemaExtractionToolIT.java b/phoenix-tools/src/it/java/org/apache/phoenix/schema/SchemaExtractionToolIT.java
new file mode 100644
index 0000000..ff672e4
--- /dev/null
+++ b/phoenix-tools/src/it/java/org/apache/phoenix/schema/SchemaExtractionToolIT.java
@@ -0,0 +1,342 @@
+package org.apache.phoenix.schema;
+
+import org.apache.phoenix.jdbc.PhoenixConnection;
+import org.apache.phoenix.query.BaseTest;
+import org.apache.phoenix.util.PhoenixRuntime;
+import org.apache.phoenix.util.PropertiesUtil;
+import org.apache.phoenix.util.ReadOnlyProps;
+import org.apache.phoenix.util.SchemaUtil;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Map;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Arrays;
+import java.util.Properties;
+
+import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
+
+public class SchemaExtractionToolIT extends BaseTest {
+
+ @BeforeClass
+ public static void setup() throws Exception {
+ Map<String, String> props = Collections.emptyMap();
+ setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
+ }
+
+ @Test
+ public void testCreateTableStatement() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String createTableStmt = "CREATE TABLE "+ pTableFullName + "(K VARCHAR NOT NULL PRIMARY KEY, "
+ + "V1 VARCHAR, V2 VARCHAR) TTL=2592000, IMMUTABLE_ROWS=TRUE, DISABLE_WAL=TRUE";
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(createTableStmt);
+ String result = runSchemaExtractionTool(schemaName, tableName, null, queries);
+ Assert.assertEquals(createTableStmt, result.toUpperCase());
+ }
+
+ @Test
+ public void testCreateIndexStatement() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String indexName = generateUniqueName();
+ String indexName1 = generateUniqueName();
+ String indexName2 = generateUniqueName();
+ String properties = "TTL=2592000,IMMUTABLE_ROWS=true,DISABLE_WAL=true";
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String createTableStatement = "CREATE TABLE "+pTableFullName + "(k VARCHAR NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR)"
+ + properties;
+ String createIndexStatement = "CREATE INDEX "+indexName + " ON "+pTableFullName+"(v1 DESC) INCLUDE (v2)";
+ String createIndexStatement1 = "CREATE INDEX "+indexName1 + " ON "+pTableFullName+"(v2 DESC) INCLUDE (v1)";
+ String createIndexStatement2 = "CREATE INDEX "+indexName2 + " ON "+pTableFullName+"(k)";
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(createTableStatement);
+ queries.add(createIndexStatement);
+ queries.add(createIndexStatement1);
+ queries.add(createIndexStatement2);
+
+ String result = runSchemaExtractionTool(schemaName, indexName2, null, queries);
+ Assert.assertEquals(createIndexStatement2.toUpperCase(), result.toUpperCase());
+ }
+
+ @Test
+ public void testCreateViewStatement() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String viewName = generateUniqueName();
+ String properties = "TTL=2592000,IMMUTABLE_ROWS=true,DISABLE_WAL=true";
+
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String createTableStmt = "CREATE TABLE "+pTableFullName + "(k BIGINT NOT NULL PRIMARY KEY, "
+ + "v1 VARCHAR, v2 VARCHAR)"
+ + properties;
+ String viewFullName = SchemaUtil.getQualifiedTableName(schemaName, viewName);
+ String viewFullName1 = SchemaUtil.getQualifiedTableName(schemaName, viewName+"1");
+ String createView = "CREATE VIEW "+viewFullName + "(id1 BIGINT, id2 BIGINT NOT NULL, "
+ + "id3 VARCHAR NOT NULL CONSTRAINT PKVIEW PRIMARY KEY (id2, id3 DESC)) "
+ + "AS SELECT * FROM "+pTableFullName;
+ String createView1 = "CREATE VIEW "+viewFullName1 + "(id1 BIGINT, id2 BIGINT NOT NULL, "
+ + "id3 VARCHAR NOT NULL CONSTRAINT PKVIEW PRIMARY KEY (id2, id3 DESC)) "
+ + "AS SELECT * FROM "+pTableFullName;
+
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(createTableStmt);
+ queries.add(createView);
+ queries.add(createView1);
+ String result = runSchemaExtractionTool(schemaName, viewName, null, queries);
+ Assert.assertEquals(createView.toUpperCase(), result.toUpperCase());
+
+ }
+
+ @Test
+ public void testCreateViewIndexStatement() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String viewName = generateUniqueName();
+ String childView = generateUniqueName();
+ String indexName = generateUniqueName();
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String createTableStmt = "CREATE TABLE "+pTableFullName + "(k BIGINT NOT NULL PRIMARY KEY, "
+ + "v1 VARCHAR, v2 VARCHAR)";
+ String viewFullName = SchemaUtil.getQualifiedTableName(schemaName, viewName);
+ String childviewName = SchemaUtil.getQualifiedTableName(schemaName, childView);
+ String createView = "CREATE VIEW "+viewFullName + "(id1 BIGINT, id2 BIGINT NOT NULL, "
+ + "id3 VARCHAR NOT NULL CONSTRAINT PKVIEW PRIMARY KEY (id2, id3 DESC)) "
+ + "AS SELECT * FROM "+pTableFullName;
+ String createView1 = "CREATE VIEW "+childviewName + " AS SELECT * FROM "+viewFullName;
+ String createIndexStatement = "CREATE INDEX "+indexName + " ON "+childviewName+"(id1) INCLUDE (v1)";
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(createTableStmt);
+ queries.add(createView);
+ queries.add(createView1);
+ queries.add(createIndexStatement);
+ String result = runSchemaExtractionTool(schemaName, indexName, null, queries);
+ Assert.assertEquals(createIndexStatement.toUpperCase(), result.toUpperCase());
+ }
+
+ @Test
+ public void testCreateTableStatement_tenant() throws Exception {
+ String tableName = generateUniqueName();
+ String viewName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String tenantId = "abc";
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String createTableStmt = "CREATE TABLE "+pTableFullName + "(k BIGINT NOT NULL PRIMARY KEY, "
+ + "v1 VARCHAR, v2 VARCHAR)";
+ String viewFullName = SchemaUtil.getQualifiedTableName(schemaName, viewName);
+ String createViewStmt = "CREATE VIEW "+viewFullName + "(id1 BIGINT, id2 BIGINT NOT NULL, "
+ + "id3 VARCHAR NOT NULL CONSTRAINT PKVIEW PRIMARY KEY (id2, id3 DESC)) "
+ + "AS SELECT * FROM "+pTableFullName;
+
+ List<String> queries1 = new ArrayList<String>(){};
+ queries1.add(createTableStmt);
+ runSchemaExtractionTool(schemaName, tableName, null, queries1);
+ List<String> queries2 = new ArrayList<String>();
+ queries2.add(createViewStmt);
+ String result2 = runSchemaExtractionTool(schemaName, viewName, tenantId, queries2);
+ Assert.assertEquals(createViewStmt.toUpperCase(), result2.toUpperCase());
+ }
+
+ @Test
+ public void testSaltedTableStatement() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String query = "create table " + pTableFullName +
+ "(a_integer integer not null CONSTRAINT pk PRIMARY KEY (a_integer)) SALT_BUCKETS=16";
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(query);
+ String result = runSchemaExtractionTool(schemaName, tableName, null, queries);
+ Assert.assertTrue(getProperties(result).contains("SALT_BUCKETS=16"));
+ }
+
+ @Test
+ public void testCreateTableWithPKConstraint() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String query = "create table " + pTableFullName +
+ "(a_char CHAR(15) NOT NULL, " +
+ "b_char CHAR(15) NOT NULL, " +
+ "c_bigint BIGINT NOT NULL CONSTRAINT PK PRIMARY KEY (a_char, b_char, c_bigint)) IMMUTABLE_ROWS=TRUE";
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(query);
+ String result = runSchemaExtractionTool(schemaName, tableName, null, queries);
+ Assert.assertEquals(query.toUpperCase(), result.toUpperCase());
+ }
+
+ @Test
+ public void testCreateTableWithArrayColumn() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String query = "create table " + pTableFullName +
+ "(a_char CHAR(15) NOT NULL, " +
+ "b_char CHAR(10) NOT NULL, " +
+ "c_var_array VARCHAR ARRAY, " +
+ "d_char_array CHAR(15) ARRAY[3] CONSTRAINT PK PRIMARY KEY (a_char, b_char)) " +
+ "TTL=2592000, IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, REPLICATION_SCOPE=1";
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(query);
+ String result = runSchemaExtractionTool(schemaName, tableName, null, queries);
+ Assert.assertEquals(query.toUpperCase(), result.toUpperCase());
+ }
+
+ @Test
+ public void testCreateTableWithDefaultCFProperties() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String properties = "KEEP_DELETED_CELLS=TRUE, TTL=1209600, IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, REPLICATION_SCOPE=1, DEFAULT_COLUMN_FAMILY=cv, SALT_BUCKETS=16, MULTI_TENANT=true";
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String query = "create table " + pTableFullName +
+ "(a_char CHAR(15) NOT NULL, " +
+ "b_char CHAR(10) NOT NULL, " +
+ "\"av\".\"_\" CHAR(1), " +
+ "\"bv\".\"_\" CHAR(1), " +
+ "\"cv\".\"_\" CHAR(1), " +
+ "\"dv\".\"_\" CHAR(1) CONSTRAINT PK PRIMARY KEY (a_char, b_char)) " + properties;
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(query);
+ String result = runSchemaExtractionTool(schemaName, tableName, null, queries);
+ Assert.assertTrue(compareProperties(properties, getProperties(result)));
+ }
+
+ @Test
+ public void testCreateTableWithCFProperties() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String properties = "\"av\".VERSIONS=2, \"bv\".VERSIONS=2, " +
+ "DATA_BLOCK_ENCODING=DIFF, " +
+ "IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, SALT_BUCKETS=16, MULTI_TENANT=true";
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String query = "create table " + pTableFullName +
+ "(a_char CHAR(15) NOT NULL, " +
+ "b_char CHAR(10) NOT NULL, " +
+ "\"av\".\"_\" CHAR(1), " +
+ "\"bv\".\"_\" CHAR(1), " +
+ "\"cv\".\"_\" CHAR(1) CONSTRAINT PK PRIMARY KEY (a_char, b_char)) " + properties;
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(query);
+ String result = runSchemaExtractionTool(schemaName, tableName, null, queries);
+ Assert.assertTrue(compareProperties(properties, getProperties(result)));
+ }
+
+ @Test
+ public void testCreateTableWithMultipleCF() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String properties = "\"av\".VERSIONS=2, \"bv\".VERSIONS=3, " +
+ "\"cv\".VERSIONS=4, DATA_BLOCK_ENCODING=DIFF, " +
+ "IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, SALT_BUCKETS=16, MULTI_TENANT=true";
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ final String query = "create table " + pTableFullName +
+ "(a_char CHAR(15) NOT NULL, " +
+ "b_char CHAR(10) NOT NULL, " +
+ "\"av\".\"_\" CHAR(1), " +
+ "\"bv\".\"_\" CHAR(1), " +
+ "\"cv\".\"_\" CHAR(1), " +
+ "\"dv\".\"_\" CHAR(1) CONSTRAINT PK PRIMARY KEY (a_char, b_char)) " + properties;
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(query);
+ String result = runSchemaExtractionTool(schemaName, tableName, null, queries);
+ Assert.assertTrue(compareProperties(properties, getProperties(result)));
+ }
+
+ @Test
+ public void testCreateTableWithMultipleCFProperties() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String properties = "\"av\".DATA_BLOCK_ENCODING=DIFF, \"bv\".DATA_BLOCK_ENCODING=DIFF, \"cv\".DATA_BLOCK_ENCODING=DIFF, " +
+ "IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, SALT_BUCKETS=16, MULTI_TENANT=true";
+ String simplifiedProperties = "DATA_BLOCK_ENCODING=DIFF, IMMUTABLE_STORAGE_SCHEME=ONE_CELL_PER_COLUMN, SALT_BUCKETS=16, MULTI_TENANT=true";
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String query = "create table " + pTableFullName +
+ "(a_char CHAR(15) NOT NULL, " +
+ "b_char CHAR(10) NOT NULL, " +
+ "\"av\".\"_\" CHAR(1), " +
+ "\"bv\".\"_\" CHAR(1), " +
+ "\"cv\".\"_\" CHAR(1) CONSTRAINT PK PRIMARY KEY (a_char, b_char)) " + properties;
+ List<String> queries = new ArrayList<String>(){};
+ queries.add(query);
+ String result = runSchemaExtractionTool(schemaName, tableName, null, queries);
+ Assert.assertTrue(compareProperties(simplifiedProperties, getProperties(result)));
+ }
+
+ @Test
+ public void testCreateIndexStatementWithColumnFamily() throws Exception {
+ String tableName = generateUniqueName();
+ String schemaName = generateUniqueName();
+ String indexName = generateUniqueName();
+ String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName);
+ String createTableStmt = "CREATE TABLE "+pTableFullName + "(k VARCHAR NOT NULL PRIMARY KEY, \"av\".\"_\" CHAR(1), v2 VARCHAR)";
+ String createIndexStmt = "CREATE INDEX "+ indexName + " ON "+pTableFullName+ "(\"av\".\"_\")";
+ List<String> queries = new ArrayList<String>() {};
+ queries.add(createTableStmt);
+ queries.add(createIndexStmt);
+ String result = runSchemaExtractionTool(schemaName, indexName, null, queries);
+ Assert.assertEquals(createIndexStmt.toUpperCase(), result.toUpperCase());
+ }
+
+ private Connection getTenantConnection(String url, String tenantId) throws SQLException {
+ Properties props = new Properties();
+ props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, tenantId);
+ return DriverManager.getConnection(url, props);
+ }
+
+ private String runSchemaExtractionTool(String schemaName, String tableName, String tenantId, List<String> queries) throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ String output;
+ if (tenantId == null){
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ executeCreateStatements(conn, queries);
+ String [] args = {"-tb", tableName, "-s", schemaName};
+ output = extractSchema(conn, args);
+ }
+ } else {
+ try (Connection conn = getTenantConnection(getUrl(), tenantId)) {
+ executeCreateStatements(conn, queries);
+ String [] args = {"-tb", tableName, "-s", schemaName, "-t", tenantId};
+ output = extractSchema(conn, args);
+ }
+ }
+ return output;
+ }
+
+ private void executeCreateStatements(Connection conn, List<String> queries) throws SQLException {
+ for (String query: queries){
+ conn.createStatement().execute(query);
+ }
+ conn.commit();
+ }
+
+ private String extractSchema(Connection conn, String [] args) throws Exception {
+ SchemaExtractionTool set = new SchemaExtractionTool();
+ set.setConf(conn.unwrap(PhoenixConnection.class).getQueryServices().getConfiguration());
+ set.run(args);
+ return set.getOutput();
+ }
+
+ private String getProperties(String query){
+ return query.substring(query.lastIndexOf(")")+1);
+ }
+
+ private boolean compareProperties(String prop1, String prop2){
+ String[] propArray1 = prop1.toUpperCase().replaceAll("\\s+","").split(",");
+ String[] propArray2 = prop2.toUpperCase().replaceAll("\\s+","").split(",");
+
+ Set<String> set1 = new HashSet<>(Arrays.asList(propArray1));
+ Set<String> set2 = new HashSet<>(Arrays.asList(propArray2));
+
+ return set1.equals(set2);
+ }
+}
diff --git a/phoenix-tools/src/main/java/org/apache/phoenix/schema/SchemaExtractionProcessor.java b/phoenix-tools/src/main/java/org/apache/phoenix/schema/SchemaExtractionProcessor.java
new file mode 100644
index 0000000..e3004e1
--- /dev/null
+++ b/phoenix-tools/src/main/java/org/apache/phoenix/schema/SchemaExtractionProcessor.java
@@ -0,0 +1,473 @@
+package org.apache.phoenix.schema;
+
+import com.google.common.collect.Sets;
+import org.apache.commons.lang.StringUtils;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HColumnDescriptor;
+import org.apache.hadoop.hbase.HTableDescriptor;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.phoenix.jdbc.PhoenixConnection;
+import org.apache.phoenix.mapreduce.util.ConnectionUtil;
+import org.apache.phoenix.query.ConnectionQueryServices;
+import org.apache.phoenix.query.QueryConstants;
+import org.apache.phoenix.util.MetaDataUtil;
+import org.apache.phoenix.util.PhoenixRuntime;
+import org.apache.phoenix.util.SchemaUtil;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.HashSet;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.List;
+import java.util.ArrayList;
+
+
+import static org.apache.phoenix.util.MetaDataUtil.SYNCED_DATA_TABLE_AND_INDEX_COL_FAM_PROPERTIES;
+
+public class SchemaExtractionProcessor {
+ Map<String, String> defaultProps = new HashMap<>();
+ Map<String, String> definedProps = new HashMap<>();
+
+ private static final String CREATE_TABLE = "CREATE TABLE %s";
+ private static final String CREATE_INDEX = "CREATE %sINDEX %s ON %s";
+ private static final String CREATE_VIEW = "CREATE VIEW %s%s AS SELECT * FROM %s%s";
+
+ private PTable table;
+ private Configuration conf;
+ private String ddl = null;
+ private String tenantId;
+
+ public SchemaExtractionProcessor(String tenantId, Configuration conf,
+ String pSchemaName, String pTableName)
+ throws SQLException {
+ this.tenantId = tenantId;
+ this.conf = conf;
+ this.table = getPTable(pSchemaName, pTableName);
+ }
+
+ public String process() throws Exception {
+ if (ddl != null) {
+ return ddl;
+ }
+ if(this.table.getType().equals(PTableType.TABLE)) {
+ ddl = extractCreateTableDDL(this.table);
+ } else if(this.table.getType().equals(PTableType.INDEX)) {
+ ddl = extractCreateIndexDDL(this.table);
+ } else if(this.table.getType().equals(PTableType.VIEW)) {
+ ddl = extractCreateViewDDL(this.table);
+ }
+ return ddl;
+ }
+
+ protected String extractCreateIndexDDL(PTable indexPTable)
+ throws SQLException {
+ String pTableName = indexPTable.getTableName().getString();
+
+ String baseTableName = indexPTable.getParentTableName().getString();
+ String baseTableFullName = SchemaUtil
+ .getQualifiedTableName(indexPTable.getSchemaName().getString(), baseTableName);
+ PTable dataPTable = getPTable(baseTableFullName);
+
+ String defaultCF = SchemaUtil.getEmptyColumnFamilyAsString(indexPTable);
+ String indexedColumnsString = getIndexedColumnsString(indexPTable, dataPTable, defaultCF);
+ String coveredColumnsString = getCoveredColumnsString(indexPTable, defaultCF);
+
+ return generateIndexDDLString(baseTableFullName, indexedColumnsString, coveredColumnsString,
+ indexPTable.getIndexType().equals(PTable.IndexType.LOCAL), pTableName);
+ }
+
+ //TODO: Indexed on an expression
+ //TODO: test with different CF
+ private String getIndexedColumnsString(PTable indexPTable, PTable dataPTable, String defaultCF) {
+
+ List<PColumn> indexPK = indexPTable.getPKColumns();
+ List<PColumn> dataPK = dataPTable.getPKColumns();
+ Set<String> indexPkSet = new HashSet<>();
+ Set<String> dataPkSet = new HashSet<>();
+ Map<String, SortOrder> sortOrderMap = new HashMap<>();
+ StringBuilder indexedColumnsBuilder = new StringBuilder();
+ for (PColumn indexedColumn : indexPK) {
+ String indexColumn = extractIndexColumn(indexedColumn.getName().getString(), defaultCF);
+ if(indexColumn.equalsIgnoreCase(MetaDataUtil.VIEW_INDEX_ID_COLUMN_NAME)) {
+ continue;
+ }
+ indexPkSet.add(indexColumn);
+ sortOrderMap.put(indexColumn, indexedColumn.getSortOrder());
+ }
+
+ for(PColumn pColumn : dataPK) {
+ dataPkSet.add(pColumn.getName().getString());
+ }
+
+ Set<String> effectivePK = Sets.symmetricDifference(indexPkSet, dataPkSet);
+ if (effectivePK.isEmpty()) {
+ effectivePK = indexPkSet;
+ }
+ for (String column : effectivePK) {
+ if(indexedColumnsBuilder.length()!=0) {
+ indexedColumnsBuilder.append(", ");
+ }
+ indexedColumnsBuilder.append(column);
+ if(sortOrderMap.containsKey(column) && sortOrderMap.get(column) != SortOrder.getDefault()) {
+ indexedColumnsBuilder.append(" ");
+ indexedColumnsBuilder.append(sortOrderMap.get(column));
+ }
+ }
+ return indexedColumnsBuilder.toString();
+ }
+
+ private String extractIndexColumn(String columnName, String defaultCF) {
+ String [] columnNameSplit = columnName.split(":");
+ if(columnNameSplit[0].equals("") || columnNameSplit[0].equalsIgnoreCase(defaultCF)) {
+ return columnNameSplit[1];
+ } else {
+ return columnNameSplit.length > 1 ?
+ String.format("\"%s\".\"%s\"", columnNameSplit[0], columnNameSplit[1]) : columnNameSplit[0];
+ }
+ }
+
+ private String getCoveredColumnsString(PTable indexPTable, String defaultCF) {
+ StringBuilder coveredColumnsBuilder = new StringBuilder();
+ List<PColumn> pkColumns = indexPTable.getColumns();
+ for (PColumn cc : pkColumns) {
+ if(coveredColumnsBuilder.length()!=0) {
+ coveredColumnsBuilder.append(", ");
+ }
+ if(cc.getFamilyName()!=null) {
+ String indexColumn = extractIndexColumn(cc.getName().getString(), defaultCF);
+ coveredColumnsBuilder.append(indexColumn);
+ }
+ }
+ return coveredColumnsBuilder.toString();
+ }
+
+ protected String generateIndexDDLString(String baseTableFullName, String indexedColumnString,
+ String coveredColumnString, boolean local, String pTableName) {
+ StringBuilder outputBuilder = new StringBuilder(String.format(CREATE_INDEX,
+ local ? "LOCAL " : "", pTableName, baseTableFullName));
+ outputBuilder.append("(");
+ outputBuilder.append(indexedColumnString);
+ outputBuilder.append(")");
+ if(!coveredColumnString.equals("")) {
+ outputBuilder.append(" INCLUDE (");
+ outputBuilder.append(coveredColumnString);
+ outputBuilder.append(")");
+ }
+ return outputBuilder.toString();
+ }
+
+ PTable getPTable(String pTableFullName) throws SQLException {
+ try (Connection conn = getConnection()) {
+ return PhoenixRuntime.getTable(conn, pTableFullName);
+ }
+ }
+
+ protected String extractCreateViewDDL(PTable table) throws SQLException {
+ String pSchemaName = table.getSchemaName().getString();
+ String pTableName = table.getTableName().getString();
+ String baseTableName = table.getParentTableName().getString();
+ String baseTableFullName = SchemaUtil.getQualifiedTableName(pSchemaName, baseTableName);
+ PTable baseTable = getPTable(baseTableFullName);
+ String columnInfoString = getColumnInfoStringForView(table, baseTable);
+
+ String whereClause = table.getViewStatement();
+ if(whereClause != null) {
+ whereClause = whereClause.substring(whereClause.indexOf("WHERE"));
+ }
+ return generateCreateViewDDL(columnInfoString, baseTableFullName,
+ whereClause == null ? "" : " "+whereClause, pSchemaName, pTableName);
+ }
+
+ private String generateCreateViewDDL(String columnInfoString, String baseTableFullName,
+ String whereClause, String pSchemaName, String pTableName) {
+ String viewFullName = SchemaUtil.getQualifiedTableName(pSchemaName, pTableName);
+ StringBuilder outputBuilder = new StringBuilder(String.format(CREATE_VIEW, viewFullName,
+ columnInfoString, baseTableFullName, whereClause));
+ return outputBuilder.toString();
+ }
+
+ public String extractCreateTableDDL(PTable table) throws IOException, SQLException {
+ String pSchemaName = table.getSchemaName().getString();
+ String pTableName = table.getTableName().getString();
+
+ ConnectionQueryServices cqsi = getCQSIObject();
+ HTableDescriptor htd = getTableDescriptor(cqsi, table);
+ HColumnDescriptor[] hcds = htd.getColumnFamilies();
+ populateDefaultProperties(table);
+ setPTableProperties(table);
+ setHTableProperties(htd);
+ setHColumnFamilyProperties(hcds);
+
+ String columnInfoString = getColumnInfoStringForTable(table);
+ String propertiesString = convertPropertiesToString();
+
+ return generateTableDDLString(columnInfoString, propertiesString, pSchemaName, pTableName);
+ }
+ private String generateTableDDLString(String columnInfoString, String propertiesString,
+ String pSchemaName, String pTableName) {
+ String pTableFullName = SchemaUtil.getQualifiedTableName(pSchemaName, pTableName);
+ StringBuilder outputBuilder = new StringBuilder(String.format(CREATE_TABLE, pTableFullName));
+ outputBuilder.append(columnInfoString).append(" ").append(propertiesString);
+ return outputBuilder.toString();
+ }
+
+ private void populateDefaultProperties(PTable table) {
+ Map<String, String> propsMap = HColumnDescriptor.getDefaultValues();
+ for (Map.Entry<String, String> entry : propsMap.entrySet()) {
+ String key = entry.getKey();
+ String value = entry.getValue();
+ defaultProps.put(key, value);
+ if(key.equalsIgnoreCase(HColumnDescriptor.BLOOMFILTER) || key.equalsIgnoreCase(
+ HColumnDescriptor.COMPRESSION)) {
+ defaultProps.put(key, "NONE");
+ }
+ if(key.equalsIgnoreCase(HColumnDescriptor.DATA_BLOCK_ENCODING)) {
+ defaultProps.put(key, String.valueOf(SchemaUtil.DEFAULT_DATA_BLOCK_ENCODING));
+ }
+ }
+ defaultProps.putAll(table.getDefaultPropertyValues());
+ }
+
+ private void setHTableProperties(HTableDescriptor htd) {
+ Map<ImmutableBytesWritable, ImmutableBytesWritable> propsMap = htd.getValues();
+ for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> entry : propsMap.entrySet()) {
+ ImmutableBytesWritable key = entry.getKey();
+ ImmutableBytesWritable value = entry.getValue();
+ if(Bytes.toString(key.get()).contains("coprocessor") || Bytes.toString(key.get()).contains(
+ HTableDescriptor.IS_META)) {
+ continue;
+ }
+ defaultProps.put(Bytes.toString(key.get()), "false");
+ definedProps.put(Bytes.toString(key.get()), Bytes.toString(value.get()));
+ }
+ }
+
+ private void setHColumnFamilyProperties(HColumnDescriptor[] columnDescriptors) {
+ Map<ImmutableBytesWritable, ImmutableBytesWritable> propsMap = columnDescriptors[0].getValues();
+ for(Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> entry : propsMap.entrySet()) {
+ ImmutableBytesWritable key = entry.getKey();
+ ImmutableBytesWritable globalValue = entry.getValue();
+ Map<String, String> cfToPropertyValueMap = new HashMap<String, String>();
+ Set<ImmutableBytesWritable> cfPropertyValueSet = new HashSet<ImmutableBytesWritable>();
+ for(HColumnDescriptor columnDescriptor: columnDescriptors) {
+ String columnFamilyName = Bytes.toString(columnDescriptor.getName());
+ ImmutableBytesWritable value = columnDescriptor.getValues().get(key);
+ // check if it is universal properties
+ if (SYNCED_DATA_TABLE_AND_INDEX_COL_FAM_PROPERTIES.contains(Bytes.toString(key.get()))) {
+ definedProps.put(Bytes.toString(key.get()), Bytes.toString(value.get()));
+ break;
+ }
+ cfToPropertyValueMap.put(columnFamilyName, Bytes.toString(value.get()));
+ cfPropertyValueSet.add(value);
+ }
+ if (cfPropertyValueSet.size() > 1) {
+ for(Map.Entry<String, String> mapEntry: cfToPropertyValueMap.entrySet()) {
+ definedProps.put(String.format("%s.%s", mapEntry.getKey(), Bytes.toString(key.get())), mapEntry.getValue());
+ }
+ } else {
+ definedProps.put(Bytes.toString(key.get()), Bytes.toString(globalValue.get()));
+ }
+ }
+ }
+
+ private void setPTableProperties(PTable table) {
+ Map <String, String> map = table.getPropertyValues();
+ for(Map.Entry<String, String> entry : map.entrySet()) {
+ String key = entry.getKey();
+ String value = entry.getValue();
+ if(value != null) {
+ definedProps.put(key, value);
+ }
+ }
+ }
+
+ private HTableDescriptor getTableDescriptor(ConnectionQueryServices cqsi, PTable table)
+ throws SQLException, IOException {
+ return cqsi.getAdmin().getTableDescriptor(
+ TableName.valueOf(table.getPhysicalName().getString()));
+ }
+
+ private String convertPropertiesToString() {
+ StringBuilder optionBuilder = new StringBuilder();
+ for(Map.Entry<String, String> entry : definedProps.entrySet()) {
+ String key = entry.getKey();
+ String value = entry.getValue();
+ String columnFamilyName = QueryConstants.DEFAULT_COLUMN_FAMILY;
+
+ String[] colPropKey = key.split("\\.");
+ if (colPropKey.length > 1) {
+ columnFamilyName = colPropKey[0];
+ key = colPropKey[1];
+ }
+
+ if(value!=null && defaultProps.get(key) != null && !value.equals(defaultProps.get(key))) {
+ if (optionBuilder.length() != 0) {
+ optionBuilder.append(", ");
+ }
+ key = columnFamilyName.equals(QueryConstants.DEFAULT_COLUMN_FAMILY)? key : String.format("\"%s\".%s", columnFamilyName, key);
+ optionBuilder.append(key+"="+value);
+ }
+ }
+ return optionBuilder.toString();
+ }
+
+ private PTable getPTable(String pSchemaName, String pTableName) throws SQLException {
+ String pTableFullName = SchemaUtil.getQualifiedTableName(pSchemaName, pTableName);
+ return getPTable(pTableFullName);
+ }
+
+ private ConnectionQueryServices getCQSIObject() throws SQLException {
+ try(Connection conn = getConnection()) {
+ return conn.unwrap(PhoenixConnection.class).getQueryServices();
+ }
+ }
+
+ public Connection getConnection() throws SQLException {
+ if(tenantId!=null) {
+ conf.set(PhoenixRuntime.TENANT_ID_ATTRIB, tenantId);
+ }
+ return ConnectionUtil.getInputConnection(conf);
+ }
+
+ private String getColumnInfoStringForTable(PTable table) {
+ StringBuilder colInfo = new StringBuilder();
+ List<PColumn> columns = table.getBucketNum() == null ? table.getColumns() : table.getColumns().subList(1, table.getColumns().size());
+ List<PColumn> pkColumns = table.getBucketNum() == null ? table.getPKColumns() : table.getColumns().subList(1, table.getPKColumns().size());
+
+ return getColumnInfoString(table, colInfo, columns, pkColumns);
+ }
+
+ private String getColumnInfoString(PTable table, StringBuilder colInfo, List<PColumn> columns,
+ List<PColumn> pkColumns) {
+ ArrayList<String> colDefs = new ArrayList<>(columns.size());
+ for (PColumn col : columns) {
+ String def = extractColumn(col);
+ if (pkColumns.size() == 1 && pkColumns.contains(col)) {
+ def += " PRIMARY KEY" + extractPKColumnAttributes(col);
+ }
+ colDefs.add(def);
+ }
+ if (colDefs.size() > 0) {
+ colInfo.append('(');
+ colInfo.append(StringUtils.join(colDefs, ", "));
+ }
+ if (pkColumns.size() > 1) {
+ // multi column primary key
+ String
+ pkConstraint =
+ String.format(" CONSTRAINT %s PRIMARY KEY (%s)", table.getPKName().getString(),
+ extractPKConstraint(pkColumns));
+ colInfo.append(pkConstraint);
+ }
+ if (colDefs.size() > 0) {
+ colInfo.append(')');
+ }
+ return colInfo.toString();
+ }
+
+ private String getColumnInfoStringForView(PTable table, PTable baseTable) {
+ StringBuilder colInfo = new StringBuilder();
+
+ List<PColumn> columns = table.getColumns();
+ List<PColumn> pkColumns = table.getPKColumns();
+
+ Set<PColumn> columnSet = new HashSet<>(columns);
+ Set<PColumn> pkSet = new HashSet<>(pkColumns);
+
+ List<PColumn> baseColumns = baseTable.getColumns();
+ List<PColumn> basePkColumns = baseTable.getPKColumns();
+
+ Set<PColumn> baseColumnSet = new HashSet<>(baseColumns);
+ Set<PColumn> basePkSet = new HashSet<>(basePkColumns);
+
+ Set<PColumn> columnsSet = Sets.symmetricDifference(baseColumnSet, columnSet);
+ Set<PColumn> pkColumnsSet = Sets.symmetricDifference(basePkSet, pkSet);
+
+ columns = new ArrayList<>(columnsSet);
+ pkColumns = new ArrayList<>(pkColumnsSet);
+
+
+ return getColumnInfoString(table, colInfo, columns, pkColumns);
+ }
+
+ private String extractColumn(PColumn column) {
+ String colName = column.getName().getString();
+ if (column.getFamilyName() != null){
+ String colFamilyName = column.getFamilyName().getString();
+ // check if it is default column family name
+ colName = colFamilyName.equals(QueryConstants.DEFAULT_COLUMN_FAMILY)? colName : String.format("\"%s\".\"%s\"", colFamilyName, colName);
+ }
+ boolean isArrayType = column.getDataType().isArrayType();
+ String type = column.getDataType().getSqlTypeName();
+ Integer maxLength = column.getMaxLength();
+ Integer arrSize = column.getArraySize();
+ Integer scale = column.getScale();
+ StringBuilder buf = new StringBuilder(colName);
+ buf.append(' ');
+
+ if (isArrayType) {
+ String arrayPrefix = type.split("\\s+")[0];
+ buf.append(arrayPrefix);
+ appendMaxLengthAndScale(buf, maxLength, scale);
+ buf.append(' ');
+ buf.append("ARRAY");
+ if (arrSize != null) {
+ buf.append('[');
+ buf.append(arrSize);
+ buf.append(']');
+ }
+ } else {
+ buf.append(type);
+ appendMaxLengthAndScale(buf, maxLength, scale);
+ }
+
+ if (!column.isNullable()) {
+ buf.append(' ');
+ buf.append("NOT NULL");
+ }
+
+ return buf.toString();
+ }
+
+ private void appendMaxLengthAndScale(StringBuilder buf, Integer maxLength, Integer scale){
+ if (maxLength != null) {
+ buf.append('(');
+ buf.append(maxLength);
+ if (scale != null) {
+ buf.append(',');
+ buf.append(scale); // has both max length and scale. For ex- decimal(10,2)
+ }
+ buf.append(')');
+ }
+ }
+
+ private String extractPKColumnAttributes(PColumn column) {
+ StringBuilder buf = new StringBuilder();
+
+ if (column.getSortOrder() != SortOrder.getDefault()) {
+ buf.append(' ');
+ buf.append(column.getSortOrder().toString());
+ }
+
+ if (column.isRowTimestamp()) {
+ buf.append(' ');
+ buf.append("ROW_TIMESTAMP");
+ }
+
+ return buf.toString();
+ }
+
+ private String extractPKConstraint(List<PColumn> pkColumns) {
+ ArrayList<String> colDefs = new ArrayList<>(pkColumns.size());
+ for (PColumn pkCol : pkColumns) {
+ colDefs.add(pkCol.getName().getString() + extractPKColumnAttributes(pkCol));
+ }
+ return StringUtils.join(colDefs, ", ");
+ }
+
+}
diff --git a/phoenix-tools/src/main/java/org/apache/phoenix/schema/SchemaExtractionTool.java b/phoenix-tools/src/main/java/org/apache/phoenix/schema/SchemaExtractionTool.java
new file mode 100644
index 0000000..11188a7
--- /dev/null
+++ b/phoenix-tools/src/main/java/org/apache/phoenix/schema/SchemaExtractionTool.java
@@ -0,0 +1,109 @@
+package org.apache.phoenix.schema;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.PosixParser;
+import org.apache.commons.lang.StringUtils;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import java.util.logging.Logger;
+
+public class SchemaExtractionTool extends Configured implements Tool {
+
+ private static final Logger LOGGER = Logger.getLogger(SchemaExtractionTool.class.getName());
+ private static final Option HELP_OPTION = new Option("h", "help",
+ false, "Help");
+ private static final Option TABLE_OPTION = new Option("tb", "table", true,
+ "[Required] Table name ex. table1");
+ private static final Option SCHEMA_OPTION = new Option("s", "schema", true,
+ "[Optional] Schema name ex. schema");
+ private static final Option TENANT_OPTION = new Option("t", "tenant", true,
+ "[Optional] Tenant Id ex. abc");
+
+ private String pTableName;
+ private String pSchemaName;
+ private String tenantId;
+
+ public static Configuration conf;
+ private String output;
+
+ @Override
+ public int run(String[] args) throws Exception {
+ populateToolAttributes(args);
+ conf = HBaseConfiguration.addHbaseResources(getConf());
+ SchemaExtractionProcessor processor = new SchemaExtractionProcessor(tenantId,
+ conf, pSchemaName, pTableName);
+ output = processor.process();
+ return 0;
+ }
+
+ public String getOutput() {
+ return output;
+ }
+
+ private void populateToolAttributes(String[] args) {
+ try {
+ CommandLine cmdLine = parseOptions(args);
+ pTableName = cmdLine.getOptionValue(TABLE_OPTION.getOpt());
+ pSchemaName = cmdLine.getOptionValue(SCHEMA_OPTION.getOpt());
+ tenantId = cmdLine.getOptionValue(TENANT_OPTION.getOpt());
+ LOGGER.info("Schema Extraction Tool initiated: " + StringUtils.join( args, ","));
+ } catch (IllegalStateException e) {
+ printHelpAndExit(e.getMessage(), getOptions());
+ }
+ }
+
+ private CommandLine parseOptions(String[] args) {
+ final Options options = getOptions();
+ CommandLineParser parser = new PosixParser();
+ CommandLine cmdLine = null;
+ try {
+ cmdLine = parser.parse(options, args);
+ } catch (ParseException e) {
+ printHelpAndExit("severe parsing command line options: " + e.getMessage(),
+ options);
+ }
+ if (cmdLine.hasOption(HELP_OPTION.getOpt())) {
+ printHelpAndExit(options, 0);
+ }
+ if (!(cmdLine.hasOption(TABLE_OPTION.getOpt()))) {
+ throw new IllegalStateException("Table name should be passed "
+ +TABLE_OPTION.getLongOpt());
+ }
+ return cmdLine;
+ }
+
+ private Options getOptions() {
+ final Options options = new Options();
+ options.addOption(TABLE_OPTION);
+ SCHEMA_OPTION.setOptionalArg(true);
+ options.addOption(SCHEMA_OPTION);
+ TENANT_OPTION.setOptionalArg(true);
+ options.addOption(TENANT_OPTION);
+ return options;
+ }
+
+ private void printHelpAndExit(String severeMessage, Options options) {
+ System.err.println(severeMessage);
+ printHelpAndExit(options, 1);
+ }
+
+ private void printHelpAndExit(Options options, int exitCode) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("help", options);
+ System.exit(exitCode);
+ }
+
+ public static void main (String[] args) throws Exception {
+ int result = ToolRunner.run(new SchemaExtractionTool(), args);
+ System.exit(result);
+ }
+}
diff --git a/pom.xml b/pom.xml
index 5041a2b..b19cd3e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -48,6 +48,7 @@
<module>phoenix-client</module>
<module>phoenix-server</module>
<module>phoenix-assembly</module>
+ <module>phoenix-tools</module>
<module>phoenix-tracing-webapp</module>
</modules>
@@ -575,6 +576,11 @@
</dependency>
<dependency>
<groupId>org.apache.phoenix</groupId>
+ <artifactId>phoenix-tools</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.phoenix</groupId>
<artifactId>phoenix-tracing-webapp</artifactId>
<version>${project.version}</version>
</dependency>