Compare commits

..

1 Commits

2839 changed files with 61200 additions and 300825 deletions

3
.gitignore vendored
View File

@ -1,7 +1,6 @@
*.iml
*.ipr
*.iws
*.icloud
target/
/var
/*/var/
@ -28,4 +27,4 @@ node_modules
*/*.iml
*/.idea
*/.gitignore
*/dependency-reduced-pom.xml
*/dependency-reduced-pom.xml

1
OWNERS
View File

@ -7,4 +7,3 @@ approvers:
- farhan3
- fbird2020
- lizheng920625
- giteezhangjingfang

View File

@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Copyright (C) 2020-2021. Huawei Technologies Co., Ltd. All rights reserved.
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

View File

@ -0,0 +1,14 @@
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
connector.name=memory

View File

@ -22,7 +22,7 @@
<parent>
<groupId>io.hetu.core</groupId>
<artifactId>presto-root</artifactId>
<version>1.7.0-SNAPSHOT</version>
<version>1.2.0-SNAPSHOT</version>
</parent>
<artifactId>hetu-carbondata</artifactId>
@ -361,17 +361,13 @@
<artifactId>bootstrap</artifactId>
<groupId>io.airlift</groupId>
</exclusion>
<exclusion>
<artifactId>jetty-util</artifactId>
<groupId>org.eclipse.jetty</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
<version>1.19</version>
<scope>runtime</scope>
</dependency>
<dependency>

View File

@ -108,7 +108,8 @@ public class CarbondataAutoVacuumThread
AutoVacuumScanTask(SemiTransactionalHiveMetastore metastore)
{
this(metastore, null);
this.metastore = metastore;
this.schemaName = null;
}
AutoVacuumScanTask(SemiTransactionalHiveMetastore metastore, String schemaName)
@ -232,6 +233,7 @@ public class CarbondataAutoVacuumThread
private void submitTaskScanning(CarbondataAutoVacuumThread instanceAutoVacuum, SemiTransactionalHiveMetastore metastore)
{
//trigger task to do scanning of tables
//instanceAutoVacuum.executorService.submit(new AutoVacuumScanTask(metastore));
if (enableTracingCleanupTask) {
queuedTasks.add(instanceAutoVacuum.executorService.submit(new AutoVacuumScanTask(metastore)));
}

View File

@ -73,17 +73,16 @@ public class CarbondataColumnVectorWrapper
@Override
public void putShorts(int rowId, int count, short value)
{
int inputRowId = rowId;
if (filteredRowsExist) {
for (int i = 0; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putShort(counter++, value);
}
inputRowId++;
rowId++;
}
}
else {
columnVector.putShorts(inputRowId, count, value);
columnVector.putShorts(rowId, count, value);
}
}
@ -98,17 +97,16 @@ public class CarbondataColumnVectorWrapper
@Override
public void putInts(int rowId, int count, int value)
{
int inputRowId = rowId;
if (filteredRowsExist) {
for (int i = 0; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putInt(counter++, value);
}
inputRowId++;
rowId++;
}
}
else {
columnVector.putInts(inputRowId, count, value);
columnVector.putInts(rowId, count, value);
}
}
@ -123,17 +121,16 @@ public class CarbondataColumnVectorWrapper
@Override
public void putLongs(int rowId, int count, long value)
{
int inputRowId = rowId;
if (filteredRowsExist) {
for (int i = 0; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putLong(counter++, value);
}
inputRowId++;
rowId++;
}
}
else {
columnVector.putLongs(inputRowId, count, value);
columnVector.putLongs(rowId, count, value);
}
}
@ -148,12 +145,11 @@ public class CarbondataColumnVectorWrapper
@Override
public void putDecimals(int rowId, int count, BigDecimal value, int precision)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putDecimal(counter++, value, precision);
}
inputRowId++;
rowId++;
}
}
@ -168,17 +164,16 @@ public class CarbondataColumnVectorWrapper
@Override
public void putDoubles(int rowId, int count, double value)
{
int inputRowId = rowId;
if (filteredRowsExist) {
for (int i = 0; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putDouble(counter++, value);
}
inputRowId++;
rowId++;
}
}
else {
columnVector.putDoubles(inputRowId, count, value);
columnVector.putDoubles(rowId, count, value);
}
}
@ -201,12 +196,11 @@ public class CarbondataColumnVectorWrapper
@Override
public void putByteArray(int rowId, int count, byte[] value)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putByteArray(counter++, value);
}
inputRowId++;
rowId++;
}
}
@ -229,17 +223,16 @@ public class CarbondataColumnVectorWrapper
@Override
public void putNulls(int rowId, int count)
{
int inputRowId = rowId;
if (filteredRowsExist) {
for (int i = 0; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putNull(counter++);
}
inputRowId++;
rowId++;
}
}
else {
columnVector.putNulls(inputRowId, count);
columnVector.putNulls(rowId, count);
}
}
@ -326,72 +319,66 @@ public class CarbondataColumnVectorWrapper
@Override
public void putFloats(int rowId, int count, float[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = srcIndex; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putFloat(counter++, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putShorts(int rowId, int count, short[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = srcIndex; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putShort(counter++, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putInts(int rowId, int count, int[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = srcIndex; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putInt(counter++, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putLongs(int rowId, int count, long[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = srcIndex; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putLong(counter++, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putDoubles(int rowId, int count, double[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = srcIndex; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putDouble(counter++, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putBytes(int rowId, int count, byte[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = srcIndex; i < count; i++) {
if (!filteredRows[inputRowId]) {
if (!filteredRows[rowId]) {
columnVector.putByte(counter++, src[i]);
}
inputRowId++;
rowId++;
}
}

View File

@ -18,7 +18,7 @@ import com.google.gson.Gson;
import io.prestosql.plugin.hive.HiveACIDWriteType;
import io.prestosql.plugin.hive.HiveFileWriter;
import io.prestosql.plugin.hive.HiveType;
import io.prestosql.plugin.hive.util.FieldSetterFactory;
import io.prestosql.plugin.hive.HiveWriteUtils;
import io.prestosql.spi.Page;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.block.Block;
@ -64,7 +64,6 @@ import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TaskAttemptID;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.log4j.Logger;
import org.joda.time.DateTimeZone;
import java.io.IOException;
import java.io.UncheckedIOException;
@ -105,7 +104,7 @@ public class CarbondataFileWriter
private final Object row;
private final SettableStructObjectInspector tableInspector;
private final List<StructField> structFields;
private final FieldSetterFactory.FieldSetter[] setters;
private final HiveWriteUtils.FieldSetter[] setters;
private final Properties properties;
private final Optional<AcidOutputFormat.Options> acidOptions;
private final HiveACIDWriteType acidWriteType;
@ -127,16 +126,15 @@ public class CarbondataFileWriter
private boolean isInitDone;
private boolean isCommitDone;
public CarbondataFileWriter(Path paramOutPutPath, List<String> inputColumnNames, Properties properties,
public CarbondataFileWriter(Path outPutPath, List<String> inputColumnNames, Properties properties,
JobConf configuration, TypeManager typeManager, Optional<AcidOutputFormat.Options> acidOptions,
Optional<HiveACIDWriteType> acidWriteType, OptionalInt taskId) throws SerDeException
{
Path localOutPutPath = paramOutPutPath;
this.outPutPath = requireNonNull(localOutPutPath, "path is null");
this.outPutPath = requireNonNull(outPutPath, "path is null");
// in table creation this can be null
if (null != properties.getProperty("location")) {
this.outPutPath = new Path(properties.getProperty("location"));
localOutPutPath = new Path(properties.getProperty("location"));
outPutPath = new Path(properties.getProperty("location"));
}
this.configuration = requireNonNull(configuration, "conf is null");
this.properties = requireNonNull(properties, "Properties is null");
@ -185,12 +183,9 @@ public class CarbondataFileWriter
row = tableInspector.create();
setters = new FieldSetterFactory.FieldSetter[structFields.size()];
FieldSetterFactory fieldSetterFactory = new FieldSetterFactory(DateTimeZone.UTC);
setters = new HiveWriteUtils.FieldSetter[structFields.size()];
for (int i = 0; i < setters.length; i++) {
setters[i] = fieldSetterFactory.create(tableInspector, row, structFields.get(i),
setters[i] = HiveWriteUtils.createFieldSetter(tableInspector, row, structFields.get(i),
fileColumnTypes.get(structFields.get(i).getFieldID()));
}
@ -212,7 +207,7 @@ public class CarbondataFileWriter
Object writer =
Class.forName(MapredCarbonOutputFormat.class.getName()).getConstructor().newInstance();
recordWriter = ((MapredCarbonOutputFormat<?>) writer)
.getHiveRecordWriter(this.configuration, localOutPutPath, Text.class, compress,
.getHiveRecordWriter(this.configuration, outPutPath, Text.class, compress,
properties, Reporter.NULL);
}
@ -227,25 +222,25 @@ public class CarbondataFileWriter
private FileSinkOperator.RecordWriter getHiveWriter(String segmentId, long taskNo) throws Exception
{
Path finalOutPutPath = this.outPutPath;
Properties finalProperties = this.properties;
JobConf finalConfiguration = this.configuration;
boolean compress = HiveConf.getBoolVar(finalConfiguration, COMPRESSRESULT);
Path outPutPath = this.outPutPath;
Properties properties = this.properties;
JobConf configuration = this.configuration;
boolean compress = HiveConf.getBoolVar(configuration, COMPRESSRESULT);
CarbonLoadModel carbonLoadModel = HiveCarbonUtil.getCarbonLoadModel(finalProperties, finalConfiguration);
CarbonLoadModel carbonLoadModel = HiveCarbonUtil.getCarbonLoadModel(properties, configuration);
carbonLoadModel.setSegmentId(segmentId);
carbonLoadModel.setTaskNo(String.valueOf(taskNo));
carbonLoadModel.setFactTimeStamp(Long.parseLong(txnTimeStamp));
carbonLoadModel.setBadRecordsAction(TableOptionConstant.BAD_RECORDS_ACTION.getName() + ",force");
CarbonTableOutputFormat.setLoadModel(finalConfiguration, carbonLoadModel);
CarbonTableOutputFormat.setLoadModel(configuration, carbonLoadModel);
this.configuration.set(CarbondataConstants.TaskId, getTaskAttemptId(String.valueOf(taskNo)));
Object writer =
Class.forName(MapredCarbonOutputFormat.class.getName()).getConstructor().newInstance();
return ((MapredCarbonOutputFormat<?>) writer)
.getHiveRecordWriter(finalConfiguration, finalOutPutPath, Text.class, compress,
finalProperties, Reporter.NULL);
.getHiveRecordWriter(configuration, outPutPath, Text.class, compress,
properties, Reporter.NULL);
}
@Override
@ -286,7 +281,7 @@ public class CarbondataFileWriter
public void appendRow(Page dataPage, int position)
{
FileSinkOperator.RecordWriter finalRecordWriter = null;
FileSinkOperator.RecordWriter recordWriter = null;
if (HiveACIDWriteType.isUpdateOrDelete(acidWriteType)) {
try {
DeleteDeltaBlockDetails deleteDeltaBlockDetails = null;
@ -335,7 +330,7 @@ public class CarbondataFileWriter
return;
}
finalRecordWriter = segmentRecordWriterMap.computeIfAbsent(segmentId, v ->
recordWriter = segmentRecordWriterMap.computeIfAbsent(segmentId, v ->
{
try {
return getHiveWriter(segmentId, CarbonUpdateUtil.getLatestTaskIdForSegment(new Segment(segmentId), tablePath) + 1);
@ -352,7 +347,7 @@ public class CarbondataFileWriter
}
}
else {
finalRecordWriter = this.recordWriter;
recordWriter = this.recordWriter;
}
for (int field = 0; field < fieldCount; field++) {
@ -366,8 +361,8 @@ public class CarbondataFileWriter
}
try {
if (finalRecordWriter != null) {
finalRecordWriter.write(serDe.serialize(row, tableInspector));
if (recordWriter != null) {
recordWriter.write(serDe.serialize(row, tableInspector));
}
}
catch (SerDeException | IOException e) {

View File

@ -48,7 +48,6 @@ public class CarbondataHandleResolver
return CarbonDeleteAsInsertTableHandle.class;
}
@Override
public Class<? extends ConnectorOutputTableHandle> getOutputTableHandleClass()
{
return CarbondataOutputTableHandle.class;

View File

@ -317,11 +317,11 @@ public class CarbondataHetuFilterUtil
if (rawData instanceof Slice) {
String value = ((Slice) rawData).toStringUtf8();
if (type.getTypeInfo() instanceof CharTypeInfo) {
StringBuilder padding = new StringBuilder();
String padding = "";
int paddedLength = ((CharTypeInfo) type.getTypeInfo()).getLength();
int truncatedLength = value.length();
for (int i = 0; i < paddedLength - truncatedLength; i++) {
padding.append(" ");
padding += " ";
}
return value + padding;
}

View File

@ -103,6 +103,7 @@ public class CarbondataHetuOutputFormat<T>
OutputCommitter carbonOutputCommitter = super.getOutputCommitter(context);
JobContextImpl jobContext = new JobContextImpl(jc, new JobID());
carbonOutputCommitter.setupJob(jobContext);
CarbonLoadModel updatedCarbonLoadModel = CarbonTableOutputFormat.getLoadModel(jc);
org.apache.hadoop.mapreduce.RecordWriter re = super.getRecordWriter(context);
return new FileSinkOperator.RecordWriter()
{

View File

@ -80,6 +80,8 @@ public class CarbondataLocationService
{
// TODO: check and make it compatible for cloud scenario
HdfsEnvironment.HdfsContext context =
new HdfsEnvironment.HdfsContext(session, table.getDatabaseName(), table.getTableName());
Path targetPath = new Path(table.getStorage().getLocation());
return new LocationHandle(targetPath, targetPath, true,

View File

@ -92,28 +92,15 @@ import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
import org.apache.carbondata.core.datastore.impl.FileFactory;
import org.apache.carbondata.core.features.TableOperation;
import org.apache.carbondata.core.fileoperations.FileWriteOperation;
import org.apache.carbondata.core.index.Segment;
import org.apache.carbondata.core.locks.CarbonLockFactory;
import org.apache.carbondata.core.locks.CarbonLockUtil;
import org.apache.carbondata.core.locks.ICarbonLock;
import org.apache.carbondata.core.locks.LockUsage;
import org.apache.carbondata.core.metadata.AbsoluteTableIdentifier;
import org.apache.carbondata.core.metadata.CarbonMetadata;
import org.apache.carbondata.core.metadata.CarbonTableIdentifier;
import org.apache.carbondata.core.metadata.SegmentFileStore;
import org.apache.carbondata.core.metadata.converter.SchemaConverter;
import org.apache.carbondata.core.metadata.converter.ThriftWrapperSchemaConverterImpl;
import org.apache.carbondata.core.metadata.datatype.DataTypes;
import org.apache.carbondata.core.metadata.datatype.StructField;
import org.apache.carbondata.core.metadata.schema.PartitionInfo;
import org.apache.carbondata.core.metadata.schema.SchemaEvolutionEntry;
import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
import org.apache.carbondata.core.metadata.schema.table.TableInfo;
import org.apache.carbondata.core.metadata.schema.table.TableSchema;
import org.apache.carbondata.core.metadata.schema.table.TableSchemaBuilder;
import org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema;
import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
import org.apache.carbondata.core.mutate.SegmentUpdateDetails;
import org.apache.carbondata.core.mutate.data.BlockMappingVO;
@ -126,7 +113,6 @@ import org.apache.carbondata.core.util.CarbonUtil;
import org.apache.carbondata.core.util.ObjectSerializationUtil;
import org.apache.carbondata.core.util.ThreadLocalSessionInfo;
import org.apache.carbondata.core.util.path.CarbonTablePath;
import org.apache.carbondata.core.writer.ThriftWriter;
import org.apache.carbondata.hadoop.api.CarbonOutputCommitter;
import org.apache.carbondata.hadoop.api.CarbonTableInputFormat;
import org.apache.carbondata.hadoop.api.CarbonTableOutputFormat;
@ -156,21 +142,19 @@ import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.mapreduce.task.JobContextImpl;
import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl;
import org.apache.log4j.Logger;
import org.joda.time.DateTimeZone;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
@ -237,10 +221,6 @@ public class CarbondataMetadata
private List<SegmentUpdateDetails> blockUpdateDetailsList;
private State currentState = State.OTHER;
private CarbonLoadModel carbonLoadModel;
private AbsoluteTableIdentifier absoluteTableIdentifier;
private TableInfo tableInfo;
private SchemaTableName schemaTableName;
private String user;
private Optional<String> tableStorageLocation;
private String carbondataTableStore;
@ -265,14 +245,11 @@ public class CarbondataMetadata
CREATE_TABLE_AS,
DROP_TABLE,
OTHER,
ADD_COLUMN,
DROP_COLUMN,
RENAME_COLUMN
}
public CarbondataMetadata(SemiTransactionalHiveMetastore metastore,
HdfsEnvironment hdfsEnvironment, HivePartitionManager partitionManager,
boolean writesToNonManagedTablesEnabled,
HdfsEnvironment hdfsEnvironment, HivePartitionManager partitionManager, DateTimeZone timeZone,
boolean allowCorruptWritesForTesting, boolean writesToNonManagedTablesEnabled,
boolean createsOfNonManagedTablesEnabled, boolean tableCreatesWithLocationAllowed,
TypeManager typeManager, LocationService locationService,
JsonCodec<PartitionUpdate> partitionUpdateCodec,
@ -282,7 +259,7 @@ public class CarbondataMetadata
CarbondataTableReader carbondataTableReader, String carbondataTableStore, long carbondataMajorVacuumSegSize, long carbondataMinorVacuumSegCount,
ScheduledExecutorService executorService, ScheduledExecutorService hiveMetastoreClientService)
{
super(metastore, hdfsEnvironment, partitionManager,
super(metastore, hdfsEnvironment, partitionManager, timeZone, allowCorruptWritesForTesting,
writesToNonManagedTablesEnabled, createsOfNonManagedTablesEnabled, tableCreatesWithLocationAllowed,
typeManager, locationService, partitionUpdateCodec, typeTranslator, hetuVersion,
hiveStatisticsProvider, accessControlMetadata, false, 2, 0.0, executorService,
@ -306,13 +283,13 @@ public class CarbondataMetadata
private void setupCommitWriter(Properties hiveSchema, Path outputPath, Configuration initialConfiguration, boolean isOverwrite) throws PrestoException
{
CarbonLoadModel finalCarbonLoadModel;
CarbonLoadModel carbonLoadModel;
TaskAttemptID taskAttemptID = TaskAttemptID.forName(initialConfiguration.get("mapred.task.id"));
try {
ThreadLocalSessionInfo.setConfigurationToCurrentThread(initialConfiguration);
finalCarbonLoadModel = HiveCarbonUtil.getCarbonLoadModel(hiveSchema, initialConfiguration);
finalCarbonLoadModel.setBadRecordsAction(TableOptionConstant.BAD_RECORDS_ACTION.getName() + ",force");
CarbonTableOutputFormat.setLoadModel(initialConfiguration, finalCarbonLoadModel);
carbonLoadModel = HiveCarbonUtil.getCarbonLoadModel(hiveSchema, initialConfiguration);
carbonLoadModel.setBadRecordsAction(TableOptionConstant.BAD_RECORDS_ACTION.getName() + ",force");
CarbonTableOutputFormat.setLoadModel(initialConfiguration, carbonLoadModel);
}
catch (IOException ex) {
LOG.error("Error while creating carbon load model", ex);
@ -360,13 +337,13 @@ public class CarbondataMetadata
this.user = session.getUser();
return hdfsEnvironment.doAs(user, () -> {
SchemaTableName tableName = parent.getSchemaTableName();
Optional<Table> finalTable =
Optional<Table> table =
metastore.getTable(new HiveIdentity(session), tableName.getSchemaName(), tableName.getTableName());
if (finalTable.isPresent() && finalTable.get().getPartitionColumns().size() > 0) {
if (table.isPresent() && table.get().getPartitionColumns().size() > 0) {
throw new PrestoException(NOT_SUPPORTED, "Operations on Partitioned CarbonTables is not supported");
}
this.table = finalTable;
this.table = table;
Path outputPath =
new Path(parent.getLocationHandle().getJsonSerializableTargetPath());
initialConfiguration = ConfigurationUtils.toJobConf(this.hdfsEnvironment
@ -382,7 +359,7 @@ public class CarbondataMetadata
}
/* Create committer object */
setupCommitWriter(finalTable, outputPath, initialConfiguration, isOverwrite);
setupCommitWriter(table, outputPath, initialConfiguration, isOverwrite);
return new CarbondataInsertTableHandle(parent.getSchemaName(),
parent.getTableName(),
@ -411,18 +388,18 @@ public class CarbondataMetadata
}
@Override
public CarbondataUpdateTableHandle beginUpdateAsInsert(ConnectorSession session, ConnectorTableHandle tableHandle)
public CarbondataUpdateTableHandle beginUpdate(ConnectorSession session, ConnectorTableHandle tableHandle)
{
currentState = State.UPDATE;
HiveInsertTableHandle parent = super.beginInsert(session, tableHandle);
SchemaTableName tableName = parent.getSchemaTableName();
Optional<Table> finalTable =
Optional<Table> table =
this.metastore.getTable(new HiveIdentity(session), tableName.getSchemaName(), tableName.getTableName());
if (finalTable.isPresent() && finalTable.get().getPartitionColumns().size() > 0) {
if (table.isPresent() && table.get().getPartitionColumns().size() > 0) {
throw new PrestoException(NOT_SUPPORTED, "Operations on Partitioned CarbonTables is not supported");
}
this.table = finalTable;
this.table = table;
this.user = session.getUser();
hdfsEnvironment.doAs(user, () -> {
initialConfiguration = ConfigurationUtils.toJobConf(this.hdfsEnvironment
@ -430,8 +407,8 @@ public class CarbondataMetadata
new HdfsEnvironment.HdfsContext(session, parent.getSchemaName(),
parent.getTableName()),
new Path(parent.getLocationHandle().getJsonSerializableWritePath())));
Properties schema = MetastoreUtil.getHiveSchema(finalTable.get());
schema.setProperty("tablePath", finalTable.get().getStorage().getLocation());
Properties schema = MetastoreUtil.getHiveSchema(table.get());
schema.setProperty("tablePath", table.get().getStorage().getLocation());
carbonTable = getCarbonTable(parent.getSchemaName(),
parent.getTableName(),
schema,
@ -470,13 +447,13 @@ public class CarbondataMetadata
HiveInsertTableHandle parent = super.beginInsert(session, tableHandle);
List<HiveColumnHandle> inputColumns = parent.getInputColumns().stream().filter(HiveColumnHandle::isRequired).collect(toList());
SchemaTableName tableName = parent.getSchemaTableName();
Optional<Table> finalTable =
Optional<Table> table =
this.metastore.getTable(new HiveIdentity(session), tableName.getSchemaName(), tableName.getTableName());
if (finalTable.isPresent() && finalTable.get().getPartitionColumns().size() > 0) {
if (table.isPresent() && table.get().getPartitionColumns().size() > 0) {
throw new PrestoException(NOT_SUPPORTED, "Operations on Partitioned CarbonTables is not supported");
}
this.table = finalTable;
this.table = table;
this.user = session.getUser();
hdfsEnvironment.doAs(user, () -> {
initialConfiguration = ConfigurationUtils.toJobConf(this.hdfsEnvironment
@ -484,8 +461,8 @@ public class CarbondataMetadata
new HdfsEnvironment.HdfsContext(session, parent.getSchemaName(),
parent.getTableName()),
new Path(parent.getLocationHandle().getJsonSerializableWritePath())));
Properties schema = MetastoreUtil.getHiveSchema(finalTable.get());
schema.setProperty("tablePath", finalTable.get().getStorage().getLocation());
Properties schema = MetastoreUtil.getHiveSchema(table.get());
schema.setProperty("tablePath", table.get().getStorage().getLocation());
carbonTable = getCarbonTable(parent.getSchemaName(),
parent.getTableName(),
schema,
@ -539,10 +516,10 @@ public class CarbondataMetadata
}
@Override
public Optional<ConnectorOutputMetadata> finishUpdateAsInsert(ConnectorSession session,
ConnectorUpdateTableHandle updateHandle,
Collection<Slice> fragments,
Collection<ComputedStatistics> computedStatistics)
public Optional<ConnectorOutputMetadata> finishUpdate(ConnectorSession session,
ConnectorUpdateTableHandle updateHandle,
Collection<Slice> fragments,
Collection<ComputedStatistics> computedStatistics)
{
HiveUpdateTableHandle updateTableHandle = (HiveUpdateTableHandle) updateHandle;
HiveInsertTableHandle insertTableHandle = new HiveInsertTableHandle(
@ -643,7 +620,7 @@ public class CarbondataMetadata
return hdfsEnvironment.doAs(session.getUser(), () -> {
Properties hiveSchema = MetastoreUtil.getHiveSchema(this.table.get());
CarbonTable finalCarbonTable = getCarbonTable(carbondataVacuumTableHandle.getSchemaName(),
CarbonTable carbonTable = getCarbonTable(carbondataVacuumTableHandle.getSchemaName(),
carbondataVacuumTableHandle.getTableName(),
hiveSchema,
initialConfiguration);
@ -705,7 +682,7 @@ public class CarbondataMetadata
SegmentFileStore.mergeSegmentFiles(readPath, segmentFileName, CarbonTablePath.getSegmentFilesLocation(carbonLoadModel.getTablePath()));
String source;
for (String currPartitionName : partitionNames) {
source = finalCarbonTable.getTablePath() + "/" + currPartitionName;
source = carbonTable.getTablePath() + "/" + currPartitionName;
moveFromTempFolder(source + "/" + carbonLoadModel.getSegmentId() + "_" + timeStamp + ".tmp", source);
}
segmentFilesToBeUpdatedLatest.add(new Segment(carbonLoadModel.getSegmentId(), segmentFileName));
@ -719,7 +696,7 @@ public class CarbondataMetadata
for (CarbondataSegmentInfoUtil segmentInfo : newMergedSegmentInfoUtilList) {
String mergedLoadNumber = segmentInfo.getDestinationSegment();
try {
String segmentFileName = SegmentFileStore.writeSegmentFile(finalCarbonTable, mergedLoadNumber, String.valueOf(carbonLoadModel.getFactTimeStamp()));
String segmentFileName = SegmentFileStore.writeSegmentFile(carbonTable, mergedLoadNumber, String.valueOf(carbonLoadModel.getFactTimeStamp()));
}
catch (IOException e) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Failed while merging segment files", e);
@ -759,7 +736,7 @@ public class CarbondataMetadata
}
@Override
public ColumnHandle getDeleteRowIdColumnHandle(ConnectorSession session, ConnectorTableHandle tableHandle)
public ColumnHandle getUpdateRowIdColumnHandle(ConnectorSession session, ConnectorTableHandle tableHandle)
{
// Hive connector only supports metadata delete. It does not support generic row-by-row deletion.
// Metadata delete is implemented in Hetu by generating a plan for row-by-row delete first,
@ -771,14 +748,6 @@ public class CarbondataMetadata
Optional.empty());
}
@Override
public ColumnHandle getUpdateRowIdColumnHandle(ConnectorSession session, ConnectorTableHandle tableHandle, List<ColumnHandle> updatedColumns)
{
return new HiveColumnHandle(CarbonCommonConstants.CARBON_IMPLICIT_COLUMN_TUPLEID,
HIVE_STRING, HIVE_STRING.getTypeSignature(), -13, SYNTHESIZED,
Optional.empty());
}
@Override
protected Map<String, String> getEmptyTableProperties(ConnectorTableMetadata tableMetadata,
Optional<HiveBucketProperty> bucketProperty,
@ -875,14 +844,6 @@ public class CarbondataMetadata
case DROP_TABLE: {
break;
}
case ADD_COLUMN:
case DROP_COLUMN:
case RENAME_COLUMN: {
hdfsEnvironment.doAs(user, () -> {
revertAlterTableChanges();
});
break;
}
default: {
return;
}
@ -900,9 +861,9 @@ public class CarbondataMetadata
private LocationHandle getCarbonDataTableCreationPath(ConnectorSession session, ConnectorTableMetadata tableMetadata, HiveWriteUtils.OpertionType opertionType) throws PrestoException
{
Path targetPath = null;
SchemaTableName finalSchemaTableName = tableMetadata.getTable();
String finalSchemaName = finalSchemaTableName.getSchemaName();
String tableName = finalSchemaTableName.getTableName();
SchemaTableName schemaTableName = tableMetadata.getTable();
String schemaName = schemaTableName.getSchemaName();
String tableName = schemaTableName.getTableName();
Optional<String> location = getCarbondataLocation(tableMetadata.getProperties());
LocationHandle locationHandle;
FileSystem fileSystem;
@ -914,32 +875,32 @@ public class CarbondataMetadata
throw new PrestoException(NOT_SUPPORTED, format("Setting %s property is not allowed", LOCATION_PROPERTY));
}
/* if path not having prefix with filesystem type, than we will take fileSystem type from core-site.xml using below methods */
fileSystem = hdfsEnvironment.getFileSystem(new HdfsEnvironment.HdfsContext(session, finalSchemaName), new Path(location.get()));
fileSystem = hdfsEnvironment.getFileSystem(new HdfsEnvironment.HdfsContext(session, schemaName), new Path(location.get()));
targetLocation = fileSystem.getFileStatus(new Path(location.get())).getPath().toString();
targetPath = getPath(new HdfsEnvironment.HdfsContext(session, finalSchemaName, tableName), targetLocation, false);
targetPath = getPath(new HdfsEnvironment.HdfsContext(session, schemaName, tableName), targetLocation, false);
}
else {
updateEmptyCarbondataTableStorePath(session, finalSchemaName);
updateEmptyCarbondataTableStorePath(session, schemaName);
targetLocation = carbondataTableStore;
targetLocation = targetLocation + File.separator + finalSchemaName + File.separator + tableName;
targetLocation = targetLocation + File.separator + schemaName + File.separator + tableName;
targetPath = new Path(targetLocation);
}
}
catch (IllegalArgumentException | IOException e) {
throw new PrestoException(NOT_SUPPORTED, format("Error %s store path %s ", e.getMessage(), targetLocation));
}
locationHandle = locationService.forNewTable(metastore, session, finalSchemaName, tableName, Optional.empty(), Optional.of(targetPath), opertionType);
locationHandle = locationService.forNewTable(metastore, session, schemaName, tableName, Optional.empty(), Optional.of(targetPath), opertionType);
return locationHandle;
}
@Override
public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting)
{
SchemaTableName localSchemaTableName = tableMetadata.getTable();
String localSchemaName = localSchemaTableName.getSchemaName();
String tableName = localSchemaTableName.getTableName();
SchemaTableName schemaTableName = tableMetadata.getTable();
String schemaName = schemaTableName.getSchemaName();
String tableName = schemaTableName.getTableName();
this.user = session.getUser();
this.schemaName = localSchemaName;
this.schemaName = schemaName;
currentState = State.CREATE_TABLE;
List<String> partitionedBy = new ArrayList<String>();
List<SortingColumn> sortBy = new ArrayList<SortingColumn>();
@ -947,29 +908,29 @@ public class CarbondataMetadata
Map<String, String> tableProperties = new HashMap<String, String>();
getParametersForCreateTable(session, tableMetadata, partitionedBy, sortBy, columnHandles, tableProperties);
metastore.getDatabase(localSchemaName).orElseThrow(() -> new SchemaNotFoundException(localSchemaName));
metastore.getDatabase(schemaName).orElseThrow(() -> new SchemaNotFoundException(schemaName));
BaseStorageFormat hiveStorageFormat = CarbondataTableProperties.getCarbondataStorageFormat(tableMetadata.getProperties());
// it will get final path to create carbon table
LocationHandle locationHandle = getCarbonDataTableCreationPath(session, tableMetadata, HiveWriteUtils.OpertionType.CREATE_TABLE);
Path targetPath = locationService.getQueryWriteInfo(locationHandle).getTargetPath();
AbsoluteTableIdentifier finalAbsoluteTableIdentifier = AbsoluteTableIdentifier.from(targetPath.toString(),
new CarbonTableIdentifier(localSchemaName, tableName, UUID.randomUUID().toString()));
AbsoluteTableIdentifier absoluteTableIdentifier = AbsoluteTableIdentifier.from(targetPath.toString(),
new CarbonTableIdentifier(schemaName, tableName, UUID.randomUUID().toString()));
hdfsEnvironment.doAs(session.getUser(), () -> {
initialConfiguration = ConfigurationUtils.toJobConf(this.hdfsEnvironment.getConfiguration(
new HdfsEnvironment.HdfsContext(session, localSchemaName, tableName),
new HdfsEnvironment.HdfsContext(session, schemaName, tableName),
new Path(locationHandle.getJsonSerializableTargetPath())));
CarbondataMetadataUtils.createMetaDataFolderSchemaFile(hdfsEnvironment, session, columnHandles, finalAbsoluteTableIdentifier, partitionedBy,
CarbondataMetadataUtils.createMetaDataFolderSchemaFile(hdfsEnvironment, session, columnHandles, absoluteTableIdentifier, partitionedBy,
sortBy.stream().map(s -> s.getColumnName().toLowerCase(Locale.ENGLISH)).collect(toList()), targetPath.toString(), initialConfiguration);
this.tableStorageLocation = Optional.of(targetPath.toString());
try {
Map<String, String> serdeParameters = initSerDeProperties(tableName);
Table localTable = buildTableObject(
Table table = buildTableObject(
session.getQueryId(),
localSchemaName,
schemaName,
tableName,
session.getUser(),
columnHandles,
@ -981,11 +942,11 @@ public class CarbondataMetadata
true, // carbon table is set as external table
prestoVersion,
serdeParameters);
PrincipalPrivileges principalPrivileges = MetastoreUtil.buildInitialPrivilegeSet(localTable.getOwner());
HiveBasicStatistics basicStatistics = localTable.getPartitionColumns().isEmpty() ? HiveBasicStatistics.createZeroStatistics() : HiveBasicStatistics.createEmptyStatistics();
PrincipalPrivileges principalPrivileges = MetastoreUtil.buildInitialPrivilegeSet(table.getOwner());
HiveBasicStatistics basicStatistics = table.getPartitionColumns().isEmpty() ? HiveBasicStatistics.createZeroStatistics() : HiveBasicStatistics.createEmptyStatistics();
metastore.createTable(
session,
localTable,
table,
principalPrivileges,
Optional.empty(),
ignoreExisting,
@ -1051,15 +1012,6 @@ public class CarbondataMetadata
super.commit();
break;
}
case ADD_COLUMN:
case RENAME_COLUMN:
case DROP_COLUMN: {
hdfsEnvironment.doAs(user, () -> {
writeSchemaFile();
});
super.commit();
break;
}
default: {
super.commit();
}
@ -1092,8 +1044,8 @@ public class CarbondataMetadata
public CarbondataTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName)
{
requireNonNull(tableName, "tableName is null");
Optional<Table> finalTable = metastore.getTable(new HiveIdentity(session), tableName.getSchemaName(), tableName.getTableName());
if (!finalTable.isPresent()) {
Optional<Table> table = metastore.getTable(new HiveIdentity(session), tableName.getSchemaName(), tableName.getTableName());
if (!table.isPresent()) {
return null;
}
@ -1102,14 +1054,14 @@ public class CarbondataMetadata
throw new PrestoException(HiveErrorCode.HIVE_INVALID_METADATA, "Unexpected table present in Hive metastore: " + tableName);
}
MetastoreUtil.verifyOnline(tableName, Optional.empty(), MetastoreUtil.getProtectMode(finalTable.get()), finalTable.get().getParameters());
MetastoreUtil.verifyOnline(tableName, Optional.empty(), MetastoreUtil.getProtectMode(table.get()), table.get().getParameters());
return new CarbondataTableHandle(
tableName.getSchemaName(),
tableName.getTableName(),
finalTable.get().getParameters(),
getPartitionKeyColumnHandles(finalTable.get()),
HiveBucketing.getHiveBucketHandle(finalTable.get()));
table.get().getParameters(),
getPartitionKeyColumnHandles(table.get()),
HiveBucketing.getHiveBucketHandle(table.get()));
}
private Optional<ConnectorOutputMetadata> finishUpdateAndDelete(ConnectorSession session,
@ -1133,12 +1085,12 @@ public class CarbondataMetadata
hdfsEnvironment.doAs(user, () -> {
if (blockUpdateDetailsList.size() > 0) {
CarbonTable finalCarbonTable = getCarbonTable(tableHandle.getSchemaName(),
CarbonTable carbonTable = getCarbonTable(tableHandle.getSchemaName(),
tableHandle.getTableName(),
MetastoreUtil.getHiveSchema(table.get()),
initialConfiguration);
SegmentUpdateStatusManager statusManager = new SegmentUpdateStatusManager(finalCarbonTable);
SegmentUpdateStatusManager statusManager = new SegmentUpdateStatusManager(carbonTable);
SegmentUpdateDetails[] segementDetailsList = statusManager.getUpdateStatusDetails();
for (SegmentUpdateDetails segementDetails : segementDetailsList) {
segementDetails.getDeletedRowsInBlock();
@ -1179,26 +1131,28 @@ public class CarbondataMetadata
List<HiveColumnHandle> columnHandles,
Map<String, String> tableProperties)
{
SchemaTableName finalSchemaTableName = tableMetadata.getTable();
String finalSchemaName = finalSchemaTableName.getSchemaName();
String finalTableName = finalSchemaTableName.getTableName();
SchemaTableName schemaTableName = tableMetadata.getTable();
String schemaName = schemaTableName.getSchemaName();
String tableName = schemaTableName.getTableName();
partitionedBy.addAll(CarbondataTableProperties.getPartitionedBy(tableMetadata.getProperties()));
sortBy.addAll(CarbondataTableProperties.getSortedBy(tableMetadata.getProperties()));
Optional<HiveBucketProperty> bucketProperty = Optional.empty();
columnHandles.addAll(getColumnHandles(tableMetadata, ImmutableSet.copyOf(partitionedBy), typeTranslator));
tableProperties.putAll(getEmptyTableProperties(tableMetadata, bucketProperty, new HdfsEnvironment.HdfsContext(session, finalSchemaName, finalTableName)));
tableProperties.putAll(getEmptyTableProperties(tableMetadata, bucketProperty, new HdfsEnvironment.HdfsContext(session, schemaName, tableName)));
}
@Override
public CarbondataOutputTableHandle beginCreateTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, Optional<ConnectorNewTableLayout> layout)
{
verifyJvmTimeZone();
// get the root directory for the database
SchemaTableName finalSchemaTableName = tableMetadata.getTable();
String finalSchemaName = finalSchemaTableName.getSchemaName();
String finalTableName = finalSchemaTableName.getTableName();
SchemaTableName schemaTableName = tableMetadata.getTable();
String schemaName = schemaTableName.getSchemaName();
String tableName = schemaTableName.getTableName();
this.user = session.getUser();
this.schemaName = finalSchemaName;
this.schemaName = schemaName;
currentState = State.CREATE_TABLE_AS;
List<String> partitionedBy = new ArrayList<String>();
@ -1206,7 +1160,7 @@ public class CarbondataMetadata
List<HiveColumnHandle> columnHandles = new ArrayList<HiveColumnHandle>();
Map<String, String> tableProperties = new HashMap<String, String>();
getParametersForCreateTable(session, tableMetadata, partitionedBy, sortBy, columnHandles, tableProperties);
metastore.getDatabase(finalSchemaName).orElseThrow(() -> new SchemaNotFoundException(finalSchemaName));
metastore.getDatabase(schemaName).orElseThrow(() -> new SchemaNotFoundException(schemaName));
// to avoid type mismatch between HiveStorageFormat & Carbondata StorageFormat this hack no option
HiveStorageFormat tableStorageFormat = HiveStorageFormat.valueOf("CARBON");
@ -1222,29 +1176,29 @@ public class CarbondataMetadata
// it will get final path to create carbon table
LocationHandle locationHandle = getCarbonDataTableCreationPath(session, tableMetadata, HiveWriteUtils.OpertionType.CREATE_TABLE_AS);
Path targetPath = locationService.getTableWriteInfo(locationHandle, false).getTargetPath();
AbsoluteTableIdentifier finalAbsoluteTableIdentifier = AbsoluteTableIdentifier.from(targetPath.toString(),
new CarbonTableIdentifier(finalSchemaName, finalTableName, UUID.randomUUID().toString()));
AbsoluteTableIdentifier absoluteTableIdentifier = AbsoluteTableIdentifier.from(targetPath.toString(),
new CarbonTableIdentifier(schemaName, tableName, UUID.randomUUID().toString()));
hdfsEnvironment.doAs(session.getUser(), () -> {
initialConfiguration = ConfigurationUtils.toJobConf(this.hdfsEnvironment.getConfiguration(
new HdfsEnvironment.HdfsContext(session, finalSchemaName, finalTableName),
new HdfsEnvironment.HdfsContext(session, schemaName, tableName),
new Path(locationHandle.getJsonSerializableTargetPath())));
// Create Carbondata metadata folder and Schema file
CarbondataMetadataUtils.createMetaDataFolderSchemaFile(hdfsEnvironment, session, columnHandles, finalAbsoluteTableIdentifier, partitionedBy,
CarbondataMetadataUtils.createMetaDataFolderSchemaFile(hdfsEnvironment, session, columnHandles, absoluteTableIdentifier, partitionedBy,
sortBy.stream().map(s -> s.getColumnName().toLowerCase(Locale.ENGLISH)).collect(toList()), targetPath.toString(), initialConfiguration);
this.tableStorageLocation = Optional.of(targetPath.toString());
Path outputPath = new Path(locationHandle.getJsonSerializableTargetPath());
Properties schema = readSchemaForCarbon(finalSchemaName, finalTableName, targetPath, columnHandles, partitionColumns);
Properties schema = readSchemaForCarbon(schemaName, tableName, targetPath, columnHandles, partitionColumns);
// Create committer object
setupCommitWriter(schema, outputPath, initialConfiguration, false);
});
try {
CarbondataOutputTableHandle result = new CarbondataOutputTableHandle(
finalSchemaName,
finalTableName,
schemaName,
tableName,
columnHandles,
metastore.generatePageSinkMetadata(new HiveIdentity(session), finalSchemaTableName),
metastore.generatePageSinkMetadata(new HiveIdentity(session), schemaTableName),
locationHandle,
tableStorageFormat,
partitionStorageFormat,
@ -1255,7 +1209,7 @@ public class CarbondataMetadata
EncodedLoadModel, jobContext.getConfiguration().get(LOAD_MODEL)));
LocationService.WriteInfo writeInfo = locationService.getQueryWriteInfo(locationHandle);
metastore.declareIntentionToWrite(session, writeInfo.getWriteMode(), writeInfo.getWritePath(), finalSchemaTableName);
metastore.declareIntentionToWrite(session, writeInfo.getWriteMode(), writeInfo.getWritePath(), schemaTableName);
return result;
}
catch (RuntimeException ex) {
@ -1386,7 +1340,7 @@ public class CarbondataMetadata
List<Segment> segmentFilesToBeUpdated = blockUpdateDetailsList.stream()
.map(SegmentUpdateDetails::getSegmentName)
.map(Segment::new).collect(Collectors.toList());
List<Segment> finalSegmentFilesToBeUpdatedLatest = new ArrayList<>();
List<Segment> segmentFilesToBeUpdatedLatest = new ArrayList<>();
List<Segment> segmentFilesToBeDeleted = blockUpdateDetailsList.stream()
.filter(segmentUpdateDetails -> segmentUpdateDetails.getSegmentStatus() != null &&
segmentUpdateDetails.getSegmentStatus().equals(SegmentStatus.MARKED_FOR_DELETE))
@ -1396,12 +1350,12 @@ public class CarbondataMetadata
for (Segment segment : segmentFilesToBeUpdated) {
String file =
SegmentFileStore.writeSegmentFile(carbonTable, segment.getSegmentNo(), timeStamp.toString());
finalSegmentFilesToBeUpdatedLatest.add(new Segment(segment.getSegmentNo(), file));
segmentFilesToBeUpdatedLatest.add(new Segment(segment.getSegmentNo(), file));
}
if (!(updateSegmentStatusSuccess &&
CarbonUpdateUtil.updateTableMetadataStatus(new HashSet<>(segmentFilesToBeUpdated),
carbonTable, timeStamp.toString(), true, segmentFilesToBeDeleted,
finalSegmentFilesToBeUpdatedLatest, ""))) {
segmentFilesToBeUpdatedLatest, ""))) {
CarbonUpdateUtil.cleanStaleDeltaFiles(carbonTable, timeStamp.toString());
}
}
@ -1463,10 +1417,11 @@ public class CarbondataMetadata
Properties hiveschema = MetastoreUtil.getHiveSchema(table);
Configuration configuration = jobContext.getConfiguration();
configuration.set(SET_OVERWRITE, "false");
CarbonLoadModel loadModel = HiveCarbonUtil.getCarbonLoadModel(hiveschema, configuration);
LoadMetadataDetails loadMetadataDetails = loadModel.getCurrentLoadMetadataDetail();
loadModel.setSegmentId(loadMetadataDetails.getLoadName());
CarbonLoaderUtil.recordNewLoadMetadata(loadMetadataDetails, loadModel, false, true);
CarbonLoadModel carbonLoadModel =
HiveCarbonUtil.getCarbonLoadModel(hiveschema, configuration);
LoadMetadataDetails loadMetadataDetails = carbonLoadModel.getCurrentLoadMetadataDetail();
carbonLoadModel.setSegmentId(loadMetadataDetails.getLoadName());
CarbonLoaderUtil.recordNewLoadMetadata(loadMetadataDetails, carbonLoadModel, false, true);
}
catch (IOException e) {
LOG.error("Error occurred while committing the insert job.", e);
@ -1553,14 +1508,14 @@ public class CarbondataMetadata
try {
hdfsEnvironment.doAs(session.getUser(), () -> {
metastore.dropTable(session, handle.getSchemaName(), handle.getTableName());
Configuration finalInitialConfiguration = ConfigurationUtils.toJobConf(this.hdfsEnvironment
Configuration initialConfiguration = ConfigurationUtils.toJobConf(this.hdfsEnvironment
.getConfiguration(new HdfsEnvironment.HdfsContext(session, handle.getSchemaName(),
handle.getTableName()), new Path(this.tableStorageLocation.get())));
Properties schema = MetastoreUtil.getHiveSchema(target.get());
schema.setProperty("tablePath", this.tableStorageLocation.get());
this.carbonTable = getCarbonTable(handle.getSchemaName(), handle.getTableName(),
schema, finalInitialConfiguration);
schema, initialConfiguration);
takeLocks(State.DROP_TABLE);
AbsoluteTableIdentifier identifier = this.carbonTable.getAbsoluteTableIdentifier();
if (SegmentStatusManager.isLoadInProgressInTable(carbonTable)) {
@ -1569,7 +1524,7 @@ public class CarbondataMetadata
try {
//Simultaneous case after acquiring locks we should check table exist.
//if table is not there clean the lock folders
carbonTable = getCarbonTable(handle.getSchemaName(), handle.getTableName(), schema, finalInitialConfiguration);
carbonTable = getCarbonTable(handle.getSchemaName(), handle.getTableName(), schema, initialConfiguration);
}//CarbonFileException
catch (RuntimeException e) {
try {
@ -1620,350 +1575,6 @@ public class CarbondataMetadata
return serdeParameters;
}
@Override
public void addColumn(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnMetadata column)
{
currentState = State.ADD_COLUMN;
updateSchemaInfo(session, tableHandle, column, null, null);
super.addColumn(session, tableHandle, column);
}
@Override
public void renameColumn(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle source, String target)
{
currentState = State.RENAME_COLUMN;
updateSchemaInfo(session, tableHandle, null, source, target);
super.renameColumn(session, tableHandle, source, target);
}
@Override
public void dropColumn(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle column)
{
currentState = State.DROP_COLUMN;
updateSchemaInfo(session, tableHandle, null, column, null);
super.dropColumn(session, tableHandle, column);
}
private void updateSchemaInfo(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnMetadata column, ColumnHandle source, String target)
{
HiveTableHandle handle = (HiveTableHandle) tableHandle;
table = metastore.getTable(new HiveIdentity(session), handle.getSchemaName(), handle.getTableName());
String tablePath = table.get().getStorage().getLocation();
hdfsEnvironment.doAs(user, () -> {
initialConfiguration = ConfigurationUtils.toJobConf(this.hdfsEnvironment
.getConfiguration(
new HdfsEnvironment.HdfsContext(session, handle.getSchemaName(),
handle.getTableName()), new Path(tablePath)));
Properties schema = MetastoreUtil.getHiveSchema(table.get());
schema.setProperty("tablePath", tablePath);
carbonTable = getCarbonTable(handle.getSchemaName(),
handle.getTableName(),
schema,
initialConfiguration);
});
acquireLocksForAlter();
schemaTableName = handle.getSchemaTableName();
absoluteTableIdentifier = AbsoluteTableIdentifier.from(tablePath, handle.getTableName(), handle.getSchemaName());
tableInfo = carbonTable.getTableInfo();
SchemaEvolutionEntry schemaEvolutionEntry;
switch (currentState) {
case ADD_COLUMN: {
schemaEvolutionEntry = updateSchemaInfoAddColumn(column);
break;
}
case RENAME_COLUMN: {
schemaEvolutionEntry = updateSchemaInfoRenameColumn(source, target);
break;
}
case DROP_TABLE: {
schemaEvolutionEntry = updateSchemaInfoDropColumn(source);
break;
}
default: {
return;
}
}
if (schemaEvolutionEntry != null) {
tableInfo.getFactTable().getSchemaEvolution().getSchemaEvolutionEntryList()
.add(schemaEvolutionEntry);
}
}
private SchemaEvolutionEntry updateSchemaInfoAddColumn(ColumnMetadata column)
{
HiveColumnHandle columnHandle = new HiveColumnHandle(column.getName(), HiveType.toHiveType(typeTranslator, column.getType()),
column.getType().getTypeSignature(), tableInfo.getFactTable().getListOfColumns().size(), HiveColumnHandle.ColumnType.REGULAR, Optional.empty());
TableSchema tableSchema = tableInfo.getFactTable();
List<ColumnSchema> tableColumns = tableSchema.getListOfColumns();
int currentSchemaOrdinal = tableColumns.stream().max(Comparator.comparing(ColumnSchema::getSchemaOrdinal))
.orElseThrow(NoSuchElementException::new).getSchemaOrdinal() + 1;
List<ColumnSchema> longStringColumns = new ArrayList<>();
List<ColumnSchema> allColumns = tableColumns.stream().filter(cols -> cols.isDimensionColumn()
&& !cols.getDataType().isComplexType() && cols.getSchemaOrdinal() != -1 && (cols.getDataType() != DataTypes.VARCHAR)).collect(toList());
TableSchemaBuilder schemaBuilder = new TableSchemaBuilder();
List<ColumnSchema> columnSchemas = new ArrayList<ColumnSchema>();
ColumnSchema newColumn = schemaBuilder.addColumn(new StructField(columnHandle.getName(),
CarbondataHetuFilterUtil.spi2CarbondataTypeMapper(columnHandle)), null,
false, false);
newColumn.setSchemaOrdinal(currentSchemaOrdinal);
columnSchemas.add(newColumn);
if (newColumn.getDataType() == DataTypes.VARCHAR) {
longStringColumns.add(newColumn);
}
else if (newColumn.isDimensionColumn()) {
// add the column which is not long string
allColumns.add(newColumn);
}
// put the old long string columns
allColumns.addAll(tableColumns.stream().filter(cols -> cols.isDimensionColumn() && (cols.getDataType() == DataTypes.VARCHAR)).collect(toList()));
// and the new long string column after old long string columns
allColumns.addAll(longStringColumns);
// put complex type columns at the end of dimension columns
allColumns.addAll(tableColumns.stream().filter(cols -> cols.isDimensionColumn() &&
(cols.isComplexColumn() || cols.getSchemaOrdinal() == -1)).collect(toList()));
// original measure columns
allColumns.addAll(tableColumns.stream().filter(cols -> !cols.isDimensionColumn()).collect(toList()));
// add new measure column
if (!newColumn.isDimensionColumn()) {
allColumns.add(newColumn);
}
allColumns.stream().filter(cols -> !cols.isInvisible()).collect(Collectors.groupingBy(ColumnSchema::getColumnName))
.forEach((columnName, schemaList) -> {
if (schemaList.size() > 2) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Duplicate columns found"));
}
});
if (newColumn.isComplexColumn()) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Complex column cannot be added"));
}
List<ColumnSchema> finalAllColumns = allColumns;
allColumns.stream().forEach(columnSchema -> {
List<ColumnSchema> colWithSameId = finalAllColumns.stream().filter(x ->
x.getColumnUniqueId().equals(columnSchema.getColumnUniqueId())).collect(toList());
if (colWithSameId.size() > 1) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Two columns can not have same columnId"));
}
});
if (tableInfo.getFactTable().getPartitionInfo() != null) {
List<ColumnSchema> par = tableInfo.getFactTable().getPartitionInfo().getColumnSchemaList();
allColumns = allColumns.stream().filter(cols -> !par.contains(cols)).collect(toList());
allColumns.addAll(par);
}
tableSchema.setListOfColumns(allColumns);
tableInfo.setLastUpdatedTime(timeStamp);
tableInfo.setFactTable(tableSchema);
SchemaEvolutionEntry schemaEvolutionEntry = new SchemaEvolutionEntry();
schemaEvolutionEntry.setTimeStamp(timeStamp);
schemaEvolutionEntry.setAdded(columnSchemas);
return schemaEvolutionEntry;
}
private SchemaEvolutionEntry updateSchemaInfoRenameColumn(ColumnHandle source, String target)
{
HiveColumnHandle oldColumnHandle = (HiveColumnHandle) source;
String oldColumnName = oldColumnHandle.getColumnName();
String newColumnName = target;
if (!carbonTable.canAllow(carbonTable, TableOperation.ALTER_COLUMN_RENAME, oldColumnHandle.getName())) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Alter table rename column is not supported for index indexschema"));
}
TableSchema tableSchema = tableInfo.getFactTable();
List<ColumnSchema> tableColumns = tableSchema.getListOfColumns();
if (!tableColumns.stream().map(cols -> cols.getColumnName()).collect(toList()).contains(oldColumnHandle.getName())) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Column " + oldColumnHandle.getName() + "does not exist in " +
carbonTable.getDatabaseName() + "." + carbonTable.getTableName()));
}
List<ColumnSchema> carbonColumns = carbonTable.getCreateOrderColumn().stream().filter(cols -> !cols.isInvisible())
.map(cols -> cols.getColumnSchema()).collect(toList());
ColumnSchema oldCarbonColumn = carbonColumns.stream().filter(cols -> cols.getColumnName().equalsIgnoreCase(oldColumnName)).findFirst().get();
validateColumnsForRenaming(oldCarbonColumn);
TableSchemaBuilder schemaBuilder = new TableSchemaBuilder();
ColumnSchema deletedColumn = schemaBuilder.addColumn(new StructField(oldColumnHandle.getName(),
CarbondataHetuFilterUtil.spi2CarbondataTypeMapper(oldColumnHandle)), null, false, false);
SchemaEvolutionEntry schemaEvolutionEntry = new SchemaEvolutionEntry();
tableColumns.forEach(cols -> {
if (cols.getColumnName().equalsIgnoreCase(oldColumnName)) {
cols.setColumnName(newColumnName);
schemaEvolutionEntry.setTimeStamp(timeStamp);
schemaEvolutionEntry.setAdded(Arrays.asList(cols));
schemaEvolutionEntry.setRemoved(Arrays.asList(deletedColumn));
}
});
Map<String, String> tableProperties = tableInfo.getFactTable().getTableProperties();
tableProperties.forEach((tablePropertyKey, tablePropertyValue) -> {
if (tablePropertyKey.equalsIgnoreCase(oldColumnName)) {
tableProperties.put(tablePropertyKey, newColumnName);
}
});
tableInfo.setLastUpdatedTime(System.currentTimeMillis());
tableInfo.setFactTable(tableSchema);
return schemaEvolutionEntry;
}
private SchemaEvolutionEntry updateSchemaInfoDropColumn(ColumnHandle column)
{
HiveColumnHandle columnHandle = (HiveColumnHandle) column;
TableSchema tableSchema = tableInfo.getFactTable();
List<ColumnSchema> tableColumns = tableSchema.getListOfColumns();
int currentSchemaOrdinal = tableColumns.stream().max(Comparator.comparing(ColumnSchema::getSchemaOrdinal))
.orElseThrow(NoSuchElementException::new).getSchemaOrdinal() + 1;
TableSchemaBuilder schemaBuilder = new TableSchemaBuilder();
List<ColumnSchema> columnSchemas = new ArrayList<ColumnSchema>();
ColumnSchema newColumn = schemaBuilder.addColumn(new StructField(columnHandle.getColumnName(),
CarbondataHetuFilterUtil.spi2CarbondataTypeMapper(columnHandle)), null,
false, false);
newColumn.setSchemaOrdinal(currentSchemaOrdinal);
columnSchemas.add(newColumn);
PartitionInfo partitionInfo = tableInfo.getFactTable().getPartitionInfo();
if (partitionInfo != null) {
List<String> partitionColumnSchemaList = tableInfo.getFactTable().getPartitionInfo()
.getColumnSchemaList().stream().map(cols -> cols.getColumnName()).collect(toList());
if (partitionColumnSchemaList.stream().anyMatch(partitionColumn -> partitionColumn.equals(newColumn.getColumnName()))) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Partition columns cannot be dropped");
}
// when table has two columns, dropping unpartitioned column will be wrong
if (tableColumns.stream().filter(cols -> !cols.getColumnName().equals(newColumn.getColumnName()))
.map(cols -> cols.getColumnName()).equals(partitionColumnSchemaList)) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Cannot have table with all columns as partition columns");
}
}
if (!tableColumns.stream().filter(cols -> cols.getColumnName().equals(newColumn.getColumnName())).collect(toList()).isEmpty()) {
if (newColumn.isComplexColumn()) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Complex column cannot be dropped");
}
}
else {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Cannot have table with all columns as partition columns");
}
tableInfo.setLastUpdatedTime(System.currentTimeMillis());
tableInfo.setFactTable(tableSchema);
SchemaEvolutionEntry schemaEvolutionEntry = new SchemaEvolutionEntry();
schemaEvolutionEntry.setTimeStamp(timeStamp);
schemaEvolutionEntry.setRemoved(columnSchemas);
return schemaEvolutionEntry;
}
private void revertAlterTableChanges()
{
String tableName = absoluteTableIdentifier.getTableName();
String databaseName = absoluteTableIdentifier.getDatabaseName();
TableInfo finalTableInfo = carbonTable.getTableInfo();
List<SchemaEvolutionEntry> evolutionEntryList = finalTableInfo.getFactTable().getSchemaEvolution().getSchemaEvolutionEntryList();
Long updatedTime = evolutionEntryList.get(evolutionEntryList.size() - 1).getTimeStamp();
LOG.info("Reverting changes for " + databaseName + "." + tableName);
List<ColumnSchema> addedSchemas = evolutionEntryList.get(evolutionEntryList.size() - 1).getAdded();
List<ColumnSchema> removedSchemas = evolutionEntryList.get(evolutionEntryList.size() - 1).getRemoved();
if (updatedTime == timeStamp) {
switch (currentState) {
case ADD_COLUMN: {
carbonTable.getTableInfo().getFactTable().getListOfColumns().removeAll(addedSchemas);
break;
}
case DROP_COLUMN: {
finalTableInfo.getFactTable().getListOfColumns().forEach(cols -> removedSchemas.forEach(removedCols -> {
if (cols.isInvisible() && removedCols.getColumnUniqueId().equals(cols.getColumnUniqueId())) {
cols.setInvisible(false);
}
}));
break;
}
default:
break;
}
evolutionEntryList.remove(evolutionEntryList.size() - 1);
writeSchemaFile();
}
}
private void writeSchemaFile()
{
try {
String schemaFilePath = CarbonTablePath.getSchemaFilePath(table.get().getStorage().getLocation());
SchemaConverter schemaConverter = new ThriftWrapperSchemaConverterImpl();
ThriftWriter thriftWriter = new ThriftWriter(schemaFilePath, false);
thriftWriter.open(FileWriteOperation.OVERWRITE);
thriftWriter.write(schemaConverter.fromWrapperToExternalTableInfo(tableInfo, absoluteTableIdentifier.getTableName(),
absoluteTableIdentifier.getDatabaseName()));
thriftWriter.close();
FileFactory.getCarbonFile(schemaFilePath).setLastModifiedTime(timeStamp);
carbondataTableReader.deleteTableFromCarbonCache(new SchemaTableName(absoluteTableIdentifier.getDatabaseName(), absoluteTableIdentifier.getTableName()));
CarbonMetadata.getInstance().removeTable(absoluteTableIdentifier.getTablePath(), absoluteTableIdentifier.getDatabaseName());
CarbonMetadata.getInstance().loadTableMetadata(tableInfo);
LOG.info("Schema file written");
}
catch (IOException e) {
//TODO handle cases while exception thrown
releaseLocks();
throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Error while writing to schema file", e));
}
}
private void acquireLocksForAlter()
{
metadataLock = CarbonLockFactory.getCarbonLockObj(carbonTable
.getAbsoluteTableIdentifier(), LockUsage.METADATA_LOCK);
compactionLock = CarbonLockFactory.getCarbonLockObj(carbonTable
.getAbsoluteTableIdentifier(), LockUsage.COMPACTION_LOCK);
try {
boolean lockStatus = metadataLock.lockWithRetries();
if (lockStatus) {
LOG.info("Successfully able to get the table metadata file lock");
}
else {
throw new Exception("Table is already locked");
}
if (compactionLock.lockWithRetries()) {
LOG.info("Successfully able to get compaction lock");
}
else {
throw new RuntimeException("Unable to get compaction locks");
}
}
catch (Exception e) {
LOG.error("Exception in alter operation", e);
releaseLocks();
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Error while taking locks", e);
}
}
private void validateColumnsForRenaming(ColumnSchema oldColumn)
{
if (carbonTable != null) {
// if the column rename is for complex column, block the operation
if (oldColumn.isComplexColumn()) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Rename column is not supported for complex datatype"));
}
// if column rename operation is on partition column, then fail the rename operation
if (null != carbonTable.getPartitionInfo()) {
List<ColumnSchema> partitionColumns = carbonTable.getPartitionInfo().getColumnSchemaList();
if (!partitionColumns.stream().filter(cols -> cols.getColumnName()
.equalsIgnoreCase(oldColumn.getColumnName())).collect(toList()).isEmpty()) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Cannot rename a partition column"));
}
}
}
}
private void writeSegmentFileAndSetLoadModel()
{
hdfsEnvironment.doAs(user, () -> {
@ -2026,38 +1637,38 @@ public class CarbondataMetadata
@Override
protected ConnectorTableMetadata doGetTableMetadata(ConnectorSession session, SchemaTableName tableName)
{
Optional<Table> finalTable = metastore.getTable(new HiveIdentity(session), tableName.getSchemaName(), tableName.getTableName());
if (!finalTable.isPresent() || finalTable.get().getTableType().equals(TableType.VIRTUAL_VIEW.name())) {
Optional<Table> table = metastore.getTable(new HiveIdentity(session), tableName.getSchemaName(), tableName.getTableName());
if (!table.isPresent() || table.get().getTableType().equals(TableType.VIRTUAL_VIEW.name())) {
throw new TableNotFoundException(tableName);
}
Function<HiveColumnHandle, ColumnMetadata> metadataGetter = columnMetadataGetter(finalTable.get(), typeManager);
Function<HiveColumnHandle, ColumnMetadata> metadataGetter = columnMetadataGetter(table.get(), typeManager);
ImmutableList.Builder<ColumnMetadata> columns = ImmutableList.builder();
for (HiveColumnHandle columnHandle : hiveColumnHandles(finalTable.get())) {
for (HiveColumnHandle columnHandle : hiveColumnHandles(table.get())) {
columns.add(metadataGetter.apply(columnHandle));
}
// External location property
ImmutableMap.Builder<String, Object> properties = ImmutableMap.builder();
properties.put(LOCATION_PROPERTY, finalTable.get().getStorage().getLocation());
properties.put(LOCATION_PROPERTY, table.get().getStorage().getLocation());
// Storage format property
properties.put(HiveTableProperties.STORAGE_FORMAT_PROPERTY, CarbondataStorageFormat.CARBON);
// Partitioning property
List<String> partitionedBy = finalTable.get().getPartitionColumns().stream()
List<String> partitionedBy = table.get().getPartitionColumns().stream()
.map(Column::getName)
.collect(toList());
if (!partitionedBy.isEmpty()) {
properties.put(HiveTableProperties.PARTITIONED_BY_PROPERTY, partitionedBy);
}
Optional<String> comment = Optional.ofNullable(finalTable.get().getParameters().get(TABLE_COMMENT));
Optional<String> comment = Optional.ofNullable(table.get().getParameters().get(TABLE_COMMENT));
// add partitioned columns into immutableColumns
ImmutableList.Builder<ColumnMetadata> immutableColumns = ImmutableList.builder();
for (HiveColumnHandle columnHandle : hiveColumnHandles(finalTable.get())) {
for (HiveColumnHandle columnHandle : hiveColumnHandles(table.get())) {
if (columnHandle.getColumnType().equals(HiveColumnHandle.ColumnType.PARTITION_KEY)) {
immutableColumns.add(metadataGetter.apply(columnHandle));
}

View File

@ -37,6 +37,7 @@ import io.prestosql.plugin.hive.metastore.SemiTransactionalHiveMetastore;
import io.prestosql.plugin.hive.security.AccessControlMetadataFactory;
import io.prestosql.plugin.hive.statistics.MetastoreHiveStatisticsProvider;
import io.prestosql.spi.type.TypeManager;
import org.joda.time.DateTimeZone;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
@ -49,6 +50,7 @@ public class CarbondataMetadataFactory
extends HiveMetadataFactory
{
private static final Logger log = Logger.get(HiveMetadataFactory.class);
private final boolean allowCorruptWritesForTesting;
private final boolean skipDeletionForAlter;
private final boolean skipTargetCleanupOnRollback;
private final boolean writesToNonManagedTablesEnabled;
@ -58,6 +60,7 @@ public class CarbondataMetadataFactory
private final HiveMetastore metastore;
private final HdfsEnvironment hdfsEnvironment;
private final HivePartitionManager partitionManager;
private final DateTimeZone timeZone;
private final TypeManager typeManager;
private final LocationService locationService;
private final BoundedExecutor renameExecution;
@ -90,8 +93,9 @@ public class CarbondataMetadataFactory
AccessControlMetadataFactory accessControlMetadataFactory,
CarbondataTableReader carbondataTableReader)
{
this(metastore, hdfsEnvironment, partitionManager,
this(metastore, hdfsEnvironment, partitionManager, carbondataConfig.getDateTimeZone(),
carbondataConfig.getMaxConcurrentFileRenames(),
carbondataConfig.getAllowCorruptWritesForTesting(),
carbondataConfig.isSkipDeletionForAlter(),
carbondataConfig.isSkipTargetCleanupOnRollback(),
true,
@ -104,13 +108,13 @@ public class CarbondataMetadataFactory
vacuumExecutorService, heartbeatService, hiveMetastoreClientService, typeTranslator, nodeVersion.toString(),
accessControlMetadataFactory, carbondataTableReader, carbondataConfig.getStoreLocation(),
carbondataConfig.getMajorVacuumSegSize(), carbondataConfig.getMinorVacuumSegCount(),
carbondataConfig.getAutoVacuumEnable(), carbondataConfig.getMetastoreWriteBatchSize());
carbondataConfig.getAutoVacuumEnable());
}
public CarbondataMetadataFactory(HiveMetastore metastore, HdfsEnvironment hdfsEnvironment,
HivePartitionManager partitionManager,
HivePartitionManager partitionManager, DateTimeZone timeZone,
int maxConcurrentFileRenames,
boolean skipDeletionForAlter,
boolean allowCorruptWritesForTesting, boolean skipDeletionForAlter,
boolean skipTargetCleanupOnRollback, boolean writesToNonManagedTablesEnabled,
boolean createsOfNonManagedTablesEnabled, boolean tableCreatesWithLocationAllowed,
long perTransactionCacheMaximumSize,
@ -124,12 +128,14 @@ public class CarbondataMetadataFactory
TypeTranslator typeTranslator, String hetuVersion,
AccessControlMetadataFactory accessControlMetadataFactory,
CarbondataTableReader carbondataTableReader, String storeLocation, long majorVacuumSegSize, long minorVacuumSegCount,
boolean autoVacuumEnable, int hmsWriteBatchSize)
boolean autoVacuumEnable)
{
super(metastore,
hdfsEnvironment,
partitionManager,
timeZone,
maxConcurrentFileRenames,
allowCorruptWritesForTesting,
skipDeletionForAlter,
skipTargetCleanupOnRollback,
writesToNonManagedTablesEnabled,
@ -148,9 +154,8 @@ public class CarbondataMetadataFactory
typeTranslator,
hetuVersion,
accessControlMetadataFactory,
2, 0.0, false,
Optional.of(new Duration(5, TimeUnit.MINUTES)),
hmsWriteBatchSize);
2, 0.0, false, Optional.of(new Duration(5, TimeUnit.MINUTES)));
this.allowCorruptWritesForTesting = allowCorruptWritesForTesting;
this.skipDeletionForAlter = skipDeletionForAlter;
this.skipTargetCleanupOnRollback = skipTargetCleanupOnRollback;
this.writesToNonManagedTablesEnabled = writesToNonManagedTablesEnabled;
@ -160,6 +165,7 @@ public class CarbondataMetadataFactory
this.metastore = requireNonNull(metastore, "metastore is null");
this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null");
this.partitionManager = requireNonNull(partitionManager, "partitionManager is null");
this.timeZone = requireNonNull(timeZone, "timeZone is null");
this.typeManager = requireNonNull(typeManager, "typeManager is null");
this.locationService = requireNonNull(locationService, "locationService is null");
this.partitionUpdateCodec = requireNonNull(partitionUpdateCodec, "partitionUpdateCodec is null");
@ -168,6 +174,13 @@ public class CarbondataMetadataFactory
this.hetuVersion = requireNonNull(hetuVersion, "hetuVersion is null");
this.accessControlMetadataFactory = requireNonNull(accessControlMetadataFactory,
"accessControlMetadataFactory is null");
if (!allowCorruptWritesForTesting && !timeZone.equals(DateTimeZone.getDefault())) {
log.warn(
"Hive writes are disabled. To write data to Hive, your JVM timezone must match the " +
"Hive storage timezone. Add -Duser.timezone=%s to your JVM arguments",
timeZone.getID());
}
this.renameExecution = new BoundedExecutor(executorService, maxConcurrentFileRenames);
this.vacuumExecutorService = requireNonNull(vacuumExecutorService, "vacuumExecutorService is null");
this.hiveMetastoreClientService = requireNonNull(hiveMetastoreClientService, "hiveMetastoreClientService is null");
@ -191,18 +204,20 @@ public class CarbondataMetadataFactory
@Override
public HiveMetadata get()
{
SemiTransactionalHiveMetastore semiTransactionalHiveMetastore =
SemiTransactionalHiveMetastore metastore =
new SemiTransactionalHiveMetastore(this.hdfsEnvironment,
CachingHiveMetastore.memoizeMetastore(this.metastore, this.perTransactionCacheMaximumSize),
this.renameExecution,
vacuumExecutorService, this.vacuumCleanupInterval, this.skipDeletionForAlter,
this.skipTargetCleanupOnRollback,
this.hiveTransactionHeartbeatInterval,
this.heartbeatService, hiveMetastoreClientService, hmsWriteBatchSize);
this.heartbeatService, hiveMetastoreClientService);
return new CarbondataMetadata(semiTransactionalHiveMetastore,
return new CarbondataMetadata(metastore,
this.hdfsEnvironment,
this.partitionManager,
this.timeZone,
this.allowCorruptWritesForTesting,
this.writesToNonManagedTablesEnabled,
this.createsOfNonManagedTablesEnabled,
this.tableCreatesWithLocationAllowed,
@ -212,8 +227,8 @@ public class CarbondataMetadataFactory
this.segmentInfoCodec,
this.typeTranslator,
this.hetuVersion,
new MetastoreHiveStatisticsProvider(semiTransactionalHiveMetastore, statsCache, samplePartitionCache),
this.accessControlMetadataFactory.create(semiTransactionalHiveMetastore),
new MetastoreHiveStatisticsProvider(metastore),
this.accessControlMetadataFactory.create(metastore),
carbondataTableReader,
this.carbondataTableStore,
this.carbondataMajorVacuumSegmentSize,

View File

@ -167,9 +167,9 @@ public class CarbondataPageSink
{
//set flag here if called and change finish accordingly.
isCompactionCalled = true;
HdfsEnvironment finalHdfsEnvironment = connectorPageSource.getHdfsEnvironment();
HdfsEnvironment hdfsEnvironment = connectorPageSource.getHdfsEnvironment();
finalHdfsEnvironment.doAs(session.getUser(), () -> {
hdfsEnvironment.doAs(session.getUser(), () -> {
try {
// Worker part: each thread to run this code
boolean mergeStatus = false;

View File

@ -163,7 +163,6 @@ public class CarbondataPageSinkProvider
ImmutableMap.of(), handle.getAdditionalConf(), false);
}
@Override
public ConnectorPageSink createPageSink(ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorOutputTableHandle tableHandle)
{
CarbondataOutputTableHandle handle = (CarbondataOutputTableHandle) tableHandle;

View File

@ -232,15 +232,15 @@ public class CarbondataPageSource
nanoStart = System.nanoTime();
}
CarbondataVectorBatch columnarBatch = null;
int columnBatchSize = 0;
int batchSize = 0;
try {
batchId++;
if (vectorReader.nextKeyValue()) {
Object vectorBatch = vectorReader.getCurrentValue();
if (vectorBatch instanceof CarbondataVectorBatch) {
columnarBatch = (CarbondataVectorBatch) vectorBatch;
columnBatchSize = columnarBatch.numRows();
if (columnBatchSize == 0) {
batchSize = columnarBatch.numRows();
if (batchSize == 0) {
close();
return null;
}
@ -256,9 +256,9 @@ public class CarbondataPageSource
Block[] blocks = new Block[columnHandles.size()];
for (int column = 0; column < blocks.length; column++) {
blocks[column] = new LazyBlock(columnBatchSize, new CarbondataBlockLoader(column));
blocks[column] = new LazyBlock(batchSize, new CarbondataBlockLoader(column));
}
Page page = new Page(columnBatchSize, blocks);
Page page = new Page(batchSize, blocks);
return page;
}
catch (PrestoException e) {

View File

@ -14,7 +14,6 @@
package io.hetu.core.plugin.carbondata;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import io.hetu.core.plugin.carbondata.impl.CarbondataLocalInputSplit;
import io.hetu.core.plugin.carbondata.impl.CarbondataLocalMultiBlockSplit;
@ -140,7 +139,7 @@ public class CarbondataSplitManager
@Override
public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle,
ConnectorSession session, ConnectorTableHandle tableHandle,
SplitSchedulingStrategy splitSchedulingStrategy, Supplier<List<Set<DynamicFilter>>> dynamicFilterSupplier,
SplitSchedulingStrategy splitSchedulingStrategy, Supplier<Set<DynamicFilter>> dynamicFilterSupplier,
Optional<QueryType> queryType, Map<String, Object> queryProperties,
Set<TupleDomain<ColumnMetadata>> userDefinedCachePredicates,
boolean partOfReuse)
@ -201,7 +200,7 @@ public class CarbondataSplitManager
0, 0, 0, 0,
properties, new ArrayList(), getHostAddresses(split.getLocations()),
OptionalInt.empty(), false, new HashMap<>(),
Optional.empty(), false, Optional.empty(), Optional.empty(), false, ImmutableMap.of())));
Optional.empty(), false, Optional.empty(), Optional.empty(), false)));
/* Todo: Make this part aligned with rest of the HiveSlipt loading flow...
* and figure out how to pass valid transaction Ids to CarbonData? */
}
@ -310,7 +309,7 @@ public class CarbondataSplitManager
schemaTableName.getTableName(), tablePath, 0L, 0L, 0L, 0L,
properties, new ArrayList(), getHostAddresses(currSplit.getLocations()),
OptionalInt.empty(), false, new HashMap<>(),
Optional.empty(), false, Optional.empty(), Optional.empty(), false, ImmutableMap.of())));
Optional.empty(), false, Optional.empty(), Optional.empty(), false)));
}
}
LOGGER.info("Splits for compaction built and ready");

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -42,10 +42,4 @@ public class CarbondataTableHandle
{
return false;
}
@Override
public boolean isUpdateAsInsertSupported()
{
return true;
}
}

View File

@ -90,17 +90,16 @@ public class CarbondataTableProperties
private static SortingColumn sortingColumnFromString(String name)
{
String finalName = name;
SortingColumn.Order order = SortingColumn.Order.ASCENDING;
String lower = name.toUpperCase(ENGLISH);
if (lower.endsWith(" ASC")) {
finalName = name.substring(0, name.length() - 4).trim();
name = name.substring(0, name.length() - 4).trim();
}
else if (lower.endsWith(" DESC")) {
finalName = name.substring(0, name.length() - 5).trim();
name = name.substring(0, name.length() - 5).trim();
order = SortingColumn.Order.DESCENDING;
}
return new SortingColumn(finalName, order);
return new SortingColumn(name, order);
}
private static String sortingColumnToString(SortingColumn column)

View File

@ -47,7 +47,6 @@ import java.util.Set;
import static java.util.Objects.requireNonNull;
import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_LOCATION;
import static org.joda.time.DateTimeZone.UTC;
public class CarbondataWriterFactory
extends HiveWriterFactory
@ -88,7 +87,7 @@ public class CarbondataWriterFactory
additionalTableParameters, bucketCount, sortedBy, locationHandle,
locationService, queryId, pageSinkMetadataProvider,
typeManager, hdfsEnvironment, pageSorter, sortBufferSize,
maxOpenSortFiles, immutablePartitions, UTC, session, nodeManager,
maxOpenSortFiles, immutablePartitions, session, nodeManager,
eventClient, hiveSessionProperties, hiveWriterStats, orcFileWriterFactory);
this.additionalJobConf = requireNonNull(additionalJobConf, "Additional JobConf is null");
@ -133,7 +132,6 @@ public class CarbondataWriterFactory
{
}
@Override
protected void setAdditionalSchemaProperties(Properties schema)
{
schema.setProperty(META_TABLE_LOCATION, locationService.getTableWriteInfo(locationHandle, false).getTargetPath().toString());

View File

@ -143,15 +143,14 @@ class ColumnarVectorWrapperDirect
@Override
public void putDecimals(int rowId, int count, BigDecimal value, int precision)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
if (nullBitSet.get(inputRowId)) {
columnVector.putNull(inputRowId);
if (nullBitSet.get(rowId)) {
columnVector.putNull(rowId);
}
else {
columnVector.putDecimal(inputRowId, value, precision);
columnVector.putDecimal(rowId, value, precision);
}
inputRowId++;
rowId++;
}
}
@ -186,9 +185,8 @@ class ColumnarVectorWrapperDirect
@Override
public void putByteArray(int rowId, int count, byte[] value)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
columnVector.putByteArray(inputRowId++, value);
columnVector.putByteArray(rowId++, value);
}
}
@ -305,90 +303,84 @@ class ColumnarVectorWrapperDirect
@Override
public void putFloats(int rowId, int count, float[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
if (nullBitSet.get(inputRowId)) {
columnVector.putNull(inputRowId);
if (nullBitSet.get(rowId)) {
columnVector.putNull(rowId);
}
else {
columnVector.putFloat(inputRowId, src[i]);
columnVector.putFloat(rowId, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putShorts(int rowId, int count, short[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
if (nullBitSet.get(inputRowId)) {
columnVector.putNull(inputRowId);
if (nullBitSet.get(rowId)) {
columnVector.putNull(rowId);
}
else {
columnVector.putShort(inputRowId, src[i]);
columnVector.putShort(rowId, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putInts(int rowId, int count, int[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
if (nullBitSet.get(inputRowId)) {
columnVector.putNull(inputRowId);
if (nullBitSet.get(rowId)) {
columnVector.putNull(rowId);
}
else {
columnVector.putInt(inputRowId, src[i]);
columnVector.putInt(rowId, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putLongs(int rowId, int count, long[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
if (nullBitSet.get(inputRowId)) {
columnVector.putNull(inputRowId);
if (nullBitSet.get(rowId)) {
columnVector.putNull(rowId);
}
else {
columnVector.putLong(inputRowId, src[i]);
columnVector.putLong(rowId, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putDoubles(int rowId, int count, double[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
if (nullBitSet.get(inputRowId)) {
columnVector.putNull(inputRowId);
if (nullBitSet.get(rowId)) {
columnVector.putNull(rowId);
}
else {
columnVector.putDouble(inputRowId, src[i]);
columnVector.putDouble(rowId, src[i]);
}
inputRowId++;
rowId++;
}
}
@Override
public void putBytes(int rowId, int count, byte[] src, int srcIndex)
{
int inputRowId = rowId;
for (int i = 0; i < count; i++) {
if (nullBitSet.get(inputRowId)) {
columnVector.putNull(inputRowId);
if (nullBitSet.get(rowId)) {
columnVector.putNull(rowId);
}
else {
columnVector.putByte(inputRowId, src[i]);
columnVector.putByte(rowId, src[i]);
}
inputRowId++;
rowId++;
}
}

View File

@ -56,10 +56,7 @@ import org.apache.hadoop.mapreduce.Job;
import org.apache.log4j.Logger;
import org.apache.thrift.TBase;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
@ -142,19 +139,10 @@ public class CarbondataTableReader
carbonTableCacheModel.getCarbonTable().isTransactionalTable()) {
CarbonTable carbonTable = carbonTableCacheModel.getCarbonTable();
try {
String schemaFilePath = CarbonTablePath
.getSchemaFilePath(
carbonTable.getTablePath());
FileFactory.FileType fileType = FileFactory.getFileType(schemaFilePath);
CarbonFile carbonFile = FileFactory.getCarbonFile(schemaFilePath,
config);
long latestTime = carbonFile.getLastModifiedTime();
// Workaround for cache updation error due to round off of latestTime inside LocalCarbonFile
if (fileType == FileFactory.FileType.LOCAL) {
latestTime = Files.readAttributes(new File(schemaFilePath).toPath(), BasicFileAttributes.class).lastModifiedTime().toMillis();
}
long latestTime = FileFactory.getCarbonFile(CarbonTablePath
.getSchemaFilePath(
carbonTable.getTablePath()),
config).getLastModifiedTime();
carbonTableCacheModel.setCurrentSchemaTime(latestTime);
if (!carbonTableCacheModel.isValid()) {
// Invalidate datamaps
@ -162,7 +150,7 @@ public class CarbondataTableReader
.clearIndex(carbonTableCacheModel.getCarbonTable().getAbsoluteTableIdentifier());
}
}
catch (CarbonFileException | IOException e) {
catch (CarbonFileException e) {
carbonCache.get().remove(schemaTableName);
}
}
@ -223,11 +211,6 @@ public class CarbondataTableReader
tableInfo = (org.apache.carbondata.format.TableInfo) thriftReader.read();
thriftReader.close();
modifiedTime = schemaFile.getLastModifiedTime();
FileFactory.FileType fileType = FileFactory.getFileType(schemaFilePath);
// Workaround for cache updation error due to round off of latesttime inside LocalCarbonFile
if (fileType == FileFactory.FileType.LOCAL) {
modifiedTime = Files.readAttributes(new File(schemaFilePath).toPath(), BasicFileAttributes.class).lastModifiedTime().toMillis();
}
}
else {
tableInfo = CarbonUtil.inferSchema(tablePath, table.getTableName(), false, config);
@ -340,7 +323,7 @@ public class CarbondataTableReader
inputSplits.get(j).stream().flatMap(f -> Arrays.stream(getLocations(f))).distinct()
.toArray(String[]::new)));
}
LOGGER.error("Size of MultiblockList " + multiBlockSplitList.size());
LOGGER.error("Size fo MultiblockList " + multiBlockSplitList.size());
}
}
catch (IOException e) {

View File

@ -58,9 +58,8 @@ public class BooleanStreamReader
@Override
public void putBytes(int rowId, int count, byte[] src, int srcIndex)
{
int srcIdx = srcIndex;
for (int i = 0; i < count; i++) {
type.writeBoolean(builder, src[srcIdx++] == 1);
type.writeBoolean(builder, src[srcIndex++] == 1);
}
}

View File

@ -76,9 +76,8 @@ public class DecimalSliceStreamReader
@Override
public void putDecimals(int rowId, int count, BigDecimal value, int precision)
{
int id = rowId;
for (int i = 0; i < count; i++) {
putDecimal(id++, value, precision);
putDecimal(rowId++, value, precision);
}
}

View File

@ -58,9 +58,8 @@ public class IntegerStreamReader
@Override
public void putInts(int rowId, int count, int value)
{
int id = rowId;
for (int i = 0; i < count; i++) {
putInt(id++, value);
putInt(rowId++, value);
}
}

View File

@ -40,7 +40,6 @@ import java.util.List;
import java.util.Map;
import static org.testng.Assert.assertTrue;
import static org.testng.AssertJUnit.assertNotNull;
public class TestCarbonAutoVacuum
{
@ -100,6 +99,7 @@ public class TestCarbonAutoVacuum
@AfterClass
public void tearDown() throws SQLException, IOException, InterruptedException
{
//hetuServer.execute("drop table if exists hive.default.demotable");
logger.info("TearDown begin: " + this.getClass().getSimpleName());
hetuServer.stopServer();
CarbonUtil.deleteFoldersAndFiles(FileFactory.getCarbonFile(storePath));
@ -145,12 +145,11 @@ public class TestCarbonAutoVacuum
try {
CarbondataAutoVacuumThread.enableTracingVacuumTask(true);
assertNotNull(catalog);
connector = catalog.getConnector(catalog.getConnectorCatalogName());
connectorMetadata = connector.getConnectorMetadata();
connectorMetadata.getTablesForVacuum();
} catch (Exception e) {
logger.debug(e.getMessage());
}
CarbondataAutoVacuumThread.waitForSubmittedVacuumTasksFinish();
@ -216,7 +215,7 @@ public class TestCarbonAutoVacuum
connectorMetadata = connector.getConnectorMetadata();
connectorMetadata.getTablesForVacuum();
} catch (Exception e) {
logger.debug(e.getMessage());
}
CarbondataAutoVacuumThread.waitForSubmittedVacuumTasksFinish();

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -62,6 +62,7 @@ public class TestCarbondataAutoCleanup
public void setup() throws Exception
{
logger.info("Setup begin: " + this.getClass().getSimpleName());
String dataPath = rootPath + "/src/test/resources/alldatatype.csv";
CarbonProperties.getInstance().addProperty(CarbonCommonConstants.CARBON_WRITTEN_BY_APPNAME, "HetuTest");
CarbonProperties.getInstance().addProperty(CarbonCommonConstants.MAX_QUERY_EXECUTION_TIME, "0");
@ -89,7 +90,6 @@ public class TestCarbondataAutoCleanup
hetuServer.execute("drop table if exists testdb.testtableautocleanup6");
hetuServer.execute("drop table if exists testdb.testtableautocleanup7");
hetuServer.execute("drop table if exists testdb.testtableautocleanup8");
hetuServer.execute("drop table if exists testdb.testtableautocleanupwithpushdown");
hetuServer.execute("drop schema if exists testdb");
hetuServer.execute("drop schema if exists default");
hetuServer.execute("create schema testdb");
@ -130,7 +130,7 @@ public class TestCarbondataAutoCleanup
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup1/Fact/Part0/Segment_3", false), false);
}
catch (IOException exception) {
logger.debug(exception.getMessage());
}
CarbondataMetadata.enableTracingCleanupTask(false);
@ -159,7 +159,7 @@ public class TestCarbondataAutoCleanup
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup2/Fact/Part0/Segment_2", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup2/Fact/Part0/Segment_3", false), false);
} catch (IOException exception) {
logger.debug(exception.getMessage());
}
CarbondataMetadata.enableTracingCleanupTask(false);
@ -189,7 +189,7 @@ public class TestCarbondataAutoCleanup
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup3/Fact/Part0/Segment_2", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup3/Fact/Part0/Segment_3", false), false);
} catch (IOException exception) {
logger.debug(exception.getMessage());
}
CarbondataMetadata.enableTracingCleanupTask(false);
@ -201,32 +201,32 @@ public class TestCarbondataAutoCleanup
{
try {
hetuServer.execute("set session carbondata.orc_predicate_pushdown_enabled = true");
hetuServer.execute("drop table if exists testdb.testtableautocleanupwithpushdown");
hetuServer.execute("CREATE TABLE testdb.testtableautocleanupwithpushdown (a int, b int)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanupwithpushdown VALUES (10, 11)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanupwithpushdown VALUES (110, 211)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanupwithpushdown VALUES (120, 311)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanupwithpushdown VALUES (130, 411)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanupwithpushdown VALUES (130, 511)");
hetuServer.execute("vacuum table testdb.testtableautocleanupwithpushdown AND WAIT");
hetuServer.execute("drop table if exists testdb.testtableautocleanup3");
hetuServer.execute("CREATE TABLE testdb.testtableautocleanup3 (a int, b int)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanup3 VALUES (10, 11)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanup3 VALUES (110, 211)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanup3 VALUES (120, 311)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanup3 VALUES (130, 411)");
hetuServer.execute("INSERT INTO testdb.testtableautocleanup3 VALUES (130, 511)");
hetuServer.execute("vacuum table testdb.testtableautocleanup3 AND WAIT");
reduceModificationOrdeletionTimesStamp(storePath + "/carbon.store/testdb/testtableautocleanupwithpushdown/Metadata");
reduceModificationOrdeletionTimesStamp(storePath + "/carbon.store/testdb/testtableautocleanup3/Metadata");
CarbondataMetadata.enableTracingCleanupTask(true);
hetuServer.execute("DELETE FROM testdb.testtableautocleanupwithpushdown WHERE a=130");
hetuServer.execute("DELETE FROM testdb.testtableautocleanup3 WHERE a=130");
try {
CarbondataMetadata.waitForSubmittedTasksFinish();
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanupwithpushdown/Fact/Part0/Segment_0", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanupwithpushdown/Fact/Part0/Segment_1", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanupwithpushdown/Fact/Part0/Segment_2", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanupwithpushdown/Fact/Part0/Segment_3", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup3/Fact/Part0/Segment_0", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup3/Fact/Part0/Segment_1", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup3/Fact/Part0/Segment_2", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup3/Fact/Part0/Segment_3", false), false);
} catch (IOException exception) {
logger.debug(exception.getMessage());
}
}
finally {
CarbondataMetadata.enableTracingCleanupTask(false);
hetuServer.execute("drop table testdb.testtableautocleanupwithpushdown");
hetuServer.execute("drop table testdb.testtableautocleanup3");
hetuServer.execute("set session carbondata.orc_predicate_pushdown_enabled = false");
}
}
@ -254,7 +254,7 @@ public class TestCarbondataAutoCleanup
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup4/Fact/Part0/Segment_2", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup4/Fact/Part0/Segment_3", false), false);
} catch (IOException exception) {
logger.debug(exception.getMessage());
}
CarbondataMetadata.enableTracingCleanupTask(false);
@ -285,7 +285,7 @@ public class TestCarbondataAutoCleanup
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup5/Fact/Part0/Segment_3", false), false);
}
catch (IOException exception) {
logger.debug(exception.getMessage());
}
CarbondataMetadata.enableTracingCleanupTask(false);
@ -314,7 +314,7 @@ public class TestCarbondataAutoCleanup
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup6/Fact/Part0/Segment_2", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup6/Fact/Part0/Segment_3", false), false);
} catch (IOException exception) {
logger.debug(exception.getMessage());
}
CarbondataMetadata.enableTracingCleanupTask(false);
@ -344,7 +344,7 @@ public class TestCarbondataAutoCleanup
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup7/Fact/Part0/Segment_2", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup7/Fact/Part0/Segment_3", false), false);
} catch (IOException exception) {
logger.debug(exception.getMessage());
}
CarbondataMetadata.enableTracingCleanupTask(false);
@ -374,7 +374,7 @@ public class TestCarbondataAutoCleanup
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup8/Fact/Part0/Segment_2", false), false);
assertEquals(FileFactory.isFileExist(storePath + "/carbon.store/testdb/testtableautocleanup8/Fact/Part0/Segment_3", false), false);
} catch (IOException exception) {
logger.debug(exception.getMessage());
}
CarbondataMetadata.enableTracingCleanupTask(false);
@ -403,7 +403,7 @@ public class TestCarbondataAutoCleanup
content = content.replaceFirst(modificationOrdeletionTimesStamp, replace);
Files.write(path, content.getBytes(charset));
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
}

View File

@ -99,7 +99,7 @@ public class TestCarbondataMinorConfig
"/carbon.store/mytestdb/mytesttable/Fact/Part0/Segment_0.1", false), true);
} catch (IOException e) {
hetuServer.execute("DROP TABLE if exists mytestdb.mytesttable");
logger.error(e.getMessage());
e.printStackTrace();
}
hetuServer.execute("DROP TABLE if exists mytestdb.mytesttable");

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -15,7 +15,6 @@
package io.hetu.core.plugin.carbondata.integrationtest;
import io.airlift.log.Logger;
import io.hetu.core.plugin.carbondata.server.HetuTestServer;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.datastore.impl.FileFactory;
@ -37,7 +36,6 @@ import static org.testng.Assert.assertTrue;
public class TestsWithHiveConnector
{
private static final Logger log = Logger.get(TestsWithHiveConnector.class);
private String rootPath = new File(this.getClass().getResource("/").getPath() + "../..")
.getCanonicalPath();
@ -116,7 +114,7 @@ public class TestsWithHiveConnector
assertEquals(FileFactory.isFileExist(storePath +
"hive.store/default/parttable/year=2013", false), false);
} catch (IOException exception) {
log.error(exception.getMessage());
exception.printStackTrace();
}
hetuServer.execute("DROP TABLE hive.default.parttable");
}
@ -125,37 +123,37 @@ public class TestsWithHiveConnector
public void deleteTransactionTableDirUsing2tables()
throws SQLException
{
hetuServer.execute("drop table if exists hive.default.parttable2");
hetuServer.execute("drop table if exists hive.default.parttable");
hetuServer.execute("drop table if exists hive.default.parttable1");
hetuServer.execute("set session DELETE_TRANSACTIONAL_TABLE_DIRECT = true");
hetuServer.execute("create table hive.default.parttable2 (orderkey int, year int) WITH (transactional = true , format = 'ORC', partitioned_by = ARRAY[ 'year' ] )");
hetuServer.execute("insert into hive.default.parttable2 values (1,2011)");
hetuServer.execute("insert into hive.default.parttable2 values (2,2012)");
hetuServer.execute("insert into hive.default.parttable2 values (3,2013)");
hetuServer.execute("create table hive.default.parttable (orderkey int, year int) WITH (transactional = true , format = 'ORC', partitioned_by = ARRAY[ 'year' ] )");
hetuServer.execute("insert into hive.default.parttable values (1,2011)");
hetuServer.execute("insert into hive.default.parttable values (2,2012)");
hetuServer.execute("insert into hive.default.parttable values (3,2013)");
hetuServer.execute("create table hive.default.parttable1 (orderkey int, year int) WITH (transactional = true , format = 'ORC', partitioned_by = ARRAY[ 'year' ] )");
hetuServer.execute("insert into hive.default.parttable1 values (1,2011)");
hetuServer.execute("insert into hive.default.parttable1 values (2,2012)");
hetuServer.execute("insert into hive.default.parttable1 values (3,2013)");
hetuServer.execute("delete from hive.default.parttable2 where year >= (select max(year) from hive.default.parttable1) ");
hetuServer.execute("delete from hive.default.parttable where year >= (select max(year) from hive.default.parttable1) ");
try {
assertEquals(FileFactory.isFileExist(storePath +
"hive.store/default/parttable2/year=2013", false), false);
"hive.store/default/parttable/year=2013", false), false);
} catch (IOException exception) {
log.error(exception.getMessage());
exception.printStackTrace();
}
hetuServer.execute("insert into hive.default.parttable2 values (4,2014)");
hetuServer.execute("delete from hive.default.parttable2 where year >= (select year from hive.default.parttable1 where orderkey=4 ) ");
hetuServer.execute("insert into hive.default.parttable values (4,2014)");
hetuServer.execute("delete from hive.default.parttable where year >= (select year from hive.default.parttable1 where orderkey=4 ) ");
try {
assertEquals(FileFactory.isFileExist(storePath +
"hive.store/default/parttable2/year=2014", false), false);
"hive.store/default/parttable/year=2014", false), false);
} catch (IOException exception) {
log.error(exception.getMessage());
exception.printStackTrace();
}
hetuServer.execute("DROP TABLE hive.default.parttable2");
hetuServer.execute("DROP TABLE hive.default.parttable");
hetuServer.execute("DROP TABLE hive.default.parttable1");
}
@ -163,72 +161,46 @@ public class TestsWithHiveConnector
public void deleteTransactionTableDirDisable()
throws SQLException
{
hetuServer.execute("drop table if exists hive.default.parttable3");
hetuServer.execute("drop table if exists hive.default.parttable");
hetuServer.execute("set session DELETE_TRANSACTIONAL_TABLE_DIRECT = false");
hetuServer.execute("create table hive.default.parttable3 (orderkey int, year int) WITH (transactional = true , format = 'ORC', partitioned_by = ARRAY[ 'year' ] )");
hetuServer.execute("insert into hive.default.parttable3 values (1,2011)");
hetuServer.execute("insert into hive.default.parttable3 values (2,2012)");
hetuServer.execute("insert into hive.default.parttable3 values (3,2013)");
hetuServer.execute("create table hive.default.parttable (orderkey int, year int) WITH (transactional = true , format = 'ORC', partitioned_by = ARRAY[ 'year' ] )");
hetuServer.execute("insert into hive.default.parttable values (1,2011)");
hetuServer.execute("insert into hive.default.parttable values (2,2012)");
hetuServer.execute("insert into hive.default.parttable values (3,2013)");
hetuServer.execute("create table hive.default.parttable4 (orderkey int, year int) WITH (transactional = true , format = 'ORC', partitioned_by = ARRAY[ 'year' ] )");
hetuServer.execute("insert into hive.default.parttable4 values (1,2011)");
hetuServer.execute("insert into hive.default.parttable4 values (2,2012)");
hetuServer.execute("insert into hive.default.parttable4 values (3,2013)");
hetuServer.execute("create table hive.default.parttable1 (orderkey int, year int) WITH (transactional = true , format = 'ORC', partitioned_by = ARRAY[ 'year' ] )");
hetuServer.execute("insert into hive.default.parttable1 values (1,2011)");
hetuServer.execute("insert into hive.default.parttable1 values (2,2012)");
hetuServer.execute("insert into hive.default.parttable1 values (3,2013)");
hetuServer.execute("delete from hive.default.parttable3 where year >= (select max(year) from hive.default.parttable4) ");
hetuServer.execute("delete from hive.default.parttable where year >= (select max(year) from hive.default.parttable1) ");
try {
assertEquals(FileFactory.isFileExist(storePath +
"/hive.store/default/parttable3/year=2013", false), true);
"/hive.store/default/parttable/year=2013", false), true);
} catch (IOException exception) {
log.error(exception.getMessage());
exception.printStackTrace();
}
hetuServer.execute("DROP TABLE hive.default.parttable3");
hetuServer.execute("DROP TABLE hive.default.parttable");
}
@Test(dependsOnMethods = {"block_Hive_Table_from_Carbondata"})
public void block_Carbondata_Table_from_Hive()
throws SQLException
{
hetuServer.execute("CREATE TABLE carbondata.default.demotable1 (c1 int)");
hetuServer.execute("CREATE TABLE carbondata.default.demotable (c1 int)");
hetuServer.execute("use hive.default");
runQueryAndAssertErrorMessage("SELECT * FROM demotable1",
runQueryAndAssertErrorMessage("SELECT * FROM demotable",
"Hive connector can't read carbondata tables");
runQueryAndAssertErrorMessage("INSERT INTO demotable1 VALUES(1)",
runQueryAndAssertErrorMessage("INSERT INTO demotable VALUES(1)",
"Tables with MapredCarbonInputFormat are not supported by Hive connector");
runQueryAndAssertErrorMessage("UPDATE demotable1 SET c1=1",
runQueryAndAssertErrorMessage("UPDATE demotable SET c1=1",
"Tables with MapredCarbonInputFormat are not supported by Hive connector");
hetuServer.execute("use carbondata.default");
hetuServer.execute("DROP TABLE carbondata.default.demotable1");
}
@Test(dependsOnMethods = {"block_Hive_Table_from_Carbondata"})
public void block_Carbondata_Table_change_from_Hive()
throws SQLException
{
hetuServer.execute("CREATE TABLE carbondata.default.changetable (a int, b int, c int)");
hetuServer.execute("use hive.default");
//rename column
runQueryAndAssertErrorMessage("ALTER TABLE default.changetable RENAME COLUMN a TO aa",
"Tables with MapredCarbonInputFormat are not supported by Hive connector");
//add column
runQueryAndAssertErrorMessage("ALTER TABLE default.changetable ADD COLUMN e int COMMENT 'Hello World'",
"Tables with MapredCarbonInputFormat are not supported by Hive connector");
//drop column
runQueryAndAssertErrorMessage("ALTER TABLE hive.default.changetable DROP COLUMN c",
"Tables with MapredCarbonInputFormat are not supported by Hive connector");
//change table name
runQueryAndAssertErrorMessage("ALTER TABLE hive.default.changetable RENAME TO hive.default.changetable_N",
"Tables with MapredCarbonInputFormat are not supported by Hive connector");
//drop table
runQueryAndAssertErrorMessage("DROP TABLE default.changetable",
"Tables with MapredCarbonInputFormat are not supported by Hive connector");
hetuServer.execute("use carbondata.default");
hetuServer.execute("DROP TABLE carbondata.default.changetable");
hetuServer.execute("DROP TABLE hive.default.demotable");
}
private Map<String, String> createHiveProperties()
@ -237,11 +209,6 @@ public class TestsWithHiveConnector
hiveProperties.put("hive.metastore", "file");
hiveProperties.put("hive.allow-drop-table", "true");
hiveProperties.put("hive.non-managed-table-writes-enabled", "true");
hiveProperties.put("hive.allow-add-column", "true");
hiveProperties.put("hive.allow-drop-column", "true");
hiveProperties.put("hive.allow-rename-table", "true");
hiveProperties.put("hive.allow-comment-table", "true");
hiveProperties.put("hive.allow-rename-column", "true");
hiveProperties.put("hive.metastore.catalog.dir", "file://" + storePath + "/hive.store");
return hiveProperties;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -91,11 +91,11 @@ public class HetuTestServer
carbonProperties.putAll(properties);
logger.info("------------ Starting Presto Server -------------");
DistributedQueryRunner distributedQueryRunner = createQueryRunner(hetuProperties);
DistributedQueryRunner queryRunner = createQueryRunner(hetuProperties);
Connection connection = createJdbcConnection(dbName);
statement = (PrestoStatement) connection.createStatement();
logger.info("STARTED SERVER AT :" + distributedQueryRunner.getCoordinator().getBaseUrl());
logger.info("STARTED SERVER AT :" + queryRunner.getCoordinator().getBaseUrl());
}
public void stopServer() throws SQLException
@ -123,20 +123,14 @@ public class HetuTestServer
public List<Map<String, Object>> executeQuery(String query) throws SQLException
{
logger.info(">>>>> Executing Query: " + query);
ResultSet rs = null;
try {
rs = statement.executeQuery(query);
ResultSet rs = statement.executeQuery(query);
return convertResultSetToList(rs);
}
catch (SQLException e) {
logger.error("Exception Occured: " + e.getMessage() + "\n Failed Query: " + query);
throw e;
}
finally {
if (rs != null) {
rs.close();
}
}
}
private List<Map<String, Object>> convertResultSetToList(ResultSet rs) throws SQLException
@ -192,7 +186,7 @@ public class HetuTestServer
{
try {
queryRunner.installPlugin(new CarbondataPlugin());
Map<String, String> carbonPropertiesMap = ImmutableMap.<String, String>builder()
Map<String, String> carbonProperties = ImmutableMap.<String, String>builder()
.putAll(this.carbonProperties)
.put("carbon.unsafe.working.memory.in.mb", "512")
.build();
@ -203,7 +197,7 @@ public class HetuTestServer
.build();
// CreateCatalog will create a catalog for CarbonData in etc/catalog.
queryRunner.createCatalog(carbonDataCatalog, carbonDataConnector, carbonPropertiesMap);
queryRunner.createCatalog(carbonDataCatalog, carbonDataConnector, carbonProperties);
queryRunner.createCatalog(carbonDataCatalogLocationDisabled, carbonDataConnector, carbonPropertiesLocationDisabled);
}
catch (RuntimeException e) {

View File

@ -1,167 +0,0 @@
<?xml version="1.0"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.hetu.core</groupId>
<artifactId>presto-root</artifactId>
<version>1.7.0-SNAPSHOT</version>
</parent>
<artifactId>hetu-clickhouse</artifactId>
<description>hetu - ClickHouse Connector</description>
<packaging>hetu-plugin</packaging>
<properties>
<air.main.basedir>${project.parent.basedir}</air.main.basedir>
<resources.dir>src/main/resources</resources.dir>
<version.clickhouse-jdbc>0.2.4</version.clickhouse-jdbc>
<version.maven-surefire-plugin>3.0.0-M2</version.maven-surefire-plugin>
</properties>
<dependencies>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
</dependency>
<dependency>
<groupId>io.hetu.core</groupId>
<artifactId>presto-base-jdbc</artifactId>
</dependency>
<dependency>
<groupId>io.airlift</groupId>
<artifactId>configuration</artifactId>
</dependency>
<dependency>
<groupId>io.airlift</groupId>
<artifactId>log</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
</dependency>
<!-- Presto SPI -->
<dependency>
<groupId>io.hetu.core</groupId>
<artifactId>presto-spi</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.airlift</groupId>
<artifactId>slice</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.airlift</groupId>
<artifactId>units</artifactId>
<scope>provided</scope>
</dependency>
<!-- for testing -->
<dependency>
<groupId>io.hetu.core</groupId>
<artifactId>presto-main</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.airlift</groupId>
<artifactId>testing</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.hetu.core</groupId>
<artifactId>presto-tpch</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.airlift.tpch</groupId>
<artifactId>tpch</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.hetu.core</groupId>
<artifactId>presto-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.airlift</groupId>
<artifactId>testing-mysql-server</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.hetu.core</groupId>
<artifactId>presto-testing-docker</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/ru.yandex.clickhouse/clickhouse-jdbc -->
<dependency>
<groupId>ru.yandex.clickhouse</groupId>
<artifactId>clickhouse-jdbc</artifactId>
<version>${version.clickhouse-jdbc}</version>
<exclusions>
<exclusion>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<!-- <version>${version.maven-surefire-plugin}</version>-->
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
<forkCount>1</forkCount>
<parallel>classes</parallel>
<threadCount>1</threadCount>
<suiteXmlFiles>
<file>src/test/testng.xml</file>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,584 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.airlift.log.Logger;
import io.hetu.core.plugin.clickhouse.optimization.ClickHousePushDownParameter;
import io.hetu.core.plugin.clickhouse.optimization.ClickHouseQueryGenerator;
import io.prestosql.plugin.jdbc.BaseJdbcClient;
import io.prestosql.plugin.jdbc.BaseJdbcConfig;
import io.prestosql.plugin.jdbc.ColumnMapping;
import io.prestosql.plugin.jdbc.ConnectionFactory;
import io.prestosql.plugin.jdbc.JdbcColumnHandle;
import io.prestosql.plugin.jdbc.JdbcIdentity;
import io.prestosql.plugin.jdbc.JdbcOutputTableHandle;
import io.prestosql.plugin.jdbc.JdbcSplit;
import io.prestosql.plugin.jdbc.JdbcTableHandle;
import io.prestosql.plugin.jdbc.JdbcTypeHandle;
import io.prestosql.plugin.jdbc.StatsCollecting;
import io.prestosql.plugin.jdbc.WriteMapping;
import io.prestosql.plugin.jdbc.optimization.JdbcConverterContext;
import io.prestosql.plugin.jdbc.optimization.JdbcPushDownModule;
import io.prestosql.plugin.jdbc.optimization.JdbcQueryGeneratorResult;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.SuppressFBWarnings;
import io.prestosql.spi.connector.ColumnHandle;
import io.prestosql.spi.connector.ColumnMetadata;
import io.prestosql.spi.connector.ConnectorSession;
import io.prestosql.spi.connector.ConnectorTableMetadata;
import io.prestosql.spi.connector.SchemaTableName;
import io.prestosql.spi.function.ExternalFunctionHub;
import io.prestosql.spi.function.FunctionMetadataManager;
import io.prestosql.spi.function.StandardFunctionResolution;
import io.prestosql.spi.relation.DeterminismEvaluator;
import io.prestosql.spi.relation.RowExpressionService;
import io.prestosql.spi.sql.QueryGenerator;
import io.prestosql.spi.type.CharType;
import io.prestosql.spi.type.DecimalType;
import io.prestosql.spi.type.Type;
import javax.inject.Inject;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import static io.prestosql.plugin.jdbc.JdbcErrorCode.JDBC_ERROR;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.bigintColumnMapping;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.charWriteFunction;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.integerColumnMapping;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.longDecimalWriteFunction;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.shortDecimalWriteFunction;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.smallintColumnMapping;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.tinyintColumnMapping;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.varbinaryWriteFunction;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.varcharColumnMapping;
import static io.prestosql.plugin.jdbc.StandardColumnMappings.varcharWriteFunction;
import static io.prestosql.spi.StandardErrorCode.NOT_FOUND;
import static io.prestosql.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.prestosql.spi.type.BooleanType.BOOLEAN;
import static io.prestosql.spi.type.TimeWithTimeZoneType.TIME_WITH_TIME_ZONE;
import static io.prestosql.spi.type.TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE;
import static io.prestosql.spi.type.VarbinaryType.VARBINARY;
import static io.prestosql.spi.type.VarcharType.createUnboundedVarcharType;
import static io.prestosql.spi.type.Varchars.isVarcharType;
import static java.lang.String.format;
import static java.lang.String.join;
import static java.util.Collections.nCopies;
import static java.util.Locale.ENGLISH;
public class ClickHouseClient
extends BaseJdbcClient
{
private static final Logger logger = Logger.get(ClickHouseClient.class);
private String[] tableTypes;
private ClickHouseConfig clickHouseConfig;
private BaseJdbcConfig baseJdbcConfig;
/**
* If disabled, do not accept sub-query push down.
*/
private final JdbcPushDownModule pushDownModule;
/**
* constructor
*
* @param config Base config
* @param clickHouseConfig clickhouse config
* @param connectionFactory connectionFactory
*/
@Inject
public ClickHouseClient(BaseJdbcConfig config, ClickHouseConfig clickHouseConfig, @StatsCollecting ConnectionFactory connectionFactory, ExternalFunctionHub externalFunctionHub)
{
super(config, "", connectionFactory, externalFunctionHub);
tableTypes = clickHouseConfig.getTableTypes().split(",");
this.pushDownModule = config.getPushDownModule();
this.baseJdbcConfig = config;
this.clickHouseConfig = clickHouseConfig;
}
@Override
public Optional<ColumnMapping> toPrestoType(ConnectorSession session, Connection connection, JdbcTypeHandle typeHandle)
{
Optional<ColumnMapping> columnMapping;
String jdbcTypeName = "";
if (typeHandle.getJdbcTypeName().isPresent()) {
jdbcTypeName = typeHandle.getJdbcTypeName().get().toUpperCase(ENGLISH);
}
switch (typeHandle.getJdbcType()) {
case Types.TINYINT:
if (jdbcTypeName.equals("UINT8")) {
columnMapping = Optional.of(smallintColumnMapping());
}
else {
columnMapping = Optional.of(tinyintColumnMapping());
}
break;
case Types.INTEGER:
if (jdbcTypeName.equals("UINT32")) {
columnMapping = Optional.of(bigintColumnMapping());
}
else {
columnMapping = Optional.of(integerColumnMapping());
}
break;
case Types.SMALLINT:
if (jdbcTypeName.equals("UINT16")) {
columnMapping = Optional.of(integerColumnMapping());
}
else {
columnMapping = Optional.of(smallintColumnMapping());
}
break;
case Types.BIGINT:
if (jdbcTypeName.equals("UINT64")) {
logger.warn("openLooKeng doesn't support UInt64, it will convert to Int64");
}
columnMapping = Optional.of(bigintColumnMapping());
break;
case Types.VARCHAR:
columnMapping = Optional.of(varcharColumnMapping(createUnboundedVarcharType()));
break;
case Types.DATE:
case Types.TIMESTAMP:
case Types.OTHER:
default:
columnMapping = super.toPrestoType(session, connection, typeHandle);
}
if (!columnMapping.isPresent()) {
throw new UnsupportedOperationException(
"openLooKeng does not support the clickhouse type " + typeHandle.getJdbcTypeName().orElse("")
+ '(' + typeHandle.getColumnSize() + ", " + typeHandle.getDecimalDigits()
+ ')');
}
return columnMapping;
}
@Override
public WriteMapping toWriteMapping(ConnectorSession session, Type type)
{
if (isVarcharType(type)) {
return WriteMapping.sliceMapping("String", varcharWriteFunction());
}
else if (VARBINARY.equals(type)) {
return WriteMapping.sliceMapping("String", varbinaryWriteFunction());
}
else if (type instanceof CharType) {
return WriteMapping.sliceMapping("FixedString(" + ((CharType) type).getLength() + ')',
charWriteFunction());
}
else if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
String dataType = format("decimal(%s, %s)", decimalType.getPrecision(), decimalType.getScale());
if (decimalType.isShort()) {
return WriteMapping.longMapping(dataType, shortDecimalWriteFunction(decimalType));
}
return WriteMapping.sliceMapping(dataType, longDecimalWriteFunction(decimalType));
}
else if (BOOLEAN.equals(type)) {
throw new PrestoException(NOT_SUPPORTED, "There is no separate type for boolean values. Use UInt8 type, restricted to the values 0 or 1.");
}
else if (TIME_WITH_TIME_ZONE.equals(type) || TIMESTAMP_WITH_TIME_ZONE.equals(type)) {
throw new PrestoException(NOT_SUPPORTED, "Unsupported column type: " + type.getDisplayName());
}
return super.toWriteMapping(session, type);
}
@Override
protected Collection<String> listSchemas(Connection connection)
{
try (ResultSet resultSet = connection.getMetaData().getSchemas()) {
ImmutableSet.Builder<String> schemaNames = ImmutableSet.builder();
while (resultSet.next()) {
String schemaName = resultSet.getString(1);
schemaNames.add(schemaName);
}
return schemaNames.build();
}
catch (SQLException e) {
throw new PrestoException(JDBC_ERROR, "openLooKeng ClickHouse connector failed to list schemas");
}
}
@Override
protected ResultSet getTables(Connection connection, Optional<String> schemaName, Optional<String> tableName)
throws SQLException
{
DatabaseMetaData metadata = connection.getMetaData();
Optional<String> escape = Optional.ofNullable(metadata.getSearchStringEscape());
return metadata.getTables(connection.getCatalog(), escapeNamePattern(schemaName, escape).orElse(null), escapeNamePattern(tableName, escape).orElse(null), tableTypes);
}
/**
* create table function should be disabled.
*/
@Override
protected JdbcOutputTableHandle createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, String tableName)
{
throw new UnsupportedOperationException("ClickHouse Connector does not support create table.");
}
@Override
public void addColumn(ConnectorSession session, JdbcTableHandle handle, ColumnMetadata column)
{
try (Connection connection = connectionFactory.openConnection(JdbcIdentity.from(session))) {
String columnName = column.getName();
if (connection.getMetaData().storesUpperCaseIdentifiers()) {
columnName = columnName.toUpperCase(ENGLISH);
}
String schema = checkCatalog(handle.getCatalogName(), handle.getSchemaName());
String sql = format("ALTER TABLE %s ADD column %s", quoted(null, schema, handle.getTableName()), getColumnSql(session, column, columnName));
execute(connection, sql);
}
catch (SQLException e) {
throw new PrestoException(JDBC_ERROR, "openLooKeng ClickHouse connector failed to add column, check table engine and sql");
}
}
private String getColumnSql(ConnectorSession session, ColumnMetadata column, String columnName)
{
StringBuilder sb = new StringBuilder(ClickHouseConstants.DEAFULT_STRINGBUFFER_CAPACITY)
.append(quoted(columnName))
.append(" ")
.append(toWriteMapping(session, column.getType()).getDataType());
return sb.toString();
}
@Override
public void dropColumn(JdbcIdentity identity, JdbcTableHandle handle, JdbcColumnHandle column)
{
try (Connection connection = connectionFactory.openConnection(identity)) {
String schema = checkCatalog(handle.getCatalogName(), handle.getSchemaName());
String sql = format("ALTER TABLE %s DROP column %s", quoted(null, schema, handle.getTableName()), column.getColumnName());
execute(connection, sql);
}
catch (SQLException e) {
throw new PrestoException(JDBC_ERROR, "openLooKeng ClickHouse connector failed to drop column");
}
}
@Override
public long getTableModificationTime(ConnectorSession session, JdbcTableHandle handle)
{
String sql = format(
"SELECT max(modification_time) as modified_time FROM system.parts WHERE database='%s' and table='%s'",
handle.getSchemaTableName().getSchemaName(),
handle.getSchemaTableName().getTableName());
try (Connection connection = connectionFactory.openConnection(JdbcIdentity.from(session));
PreparedStatement preparedStatement = getPreparedStatement(connection, sql)) {
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
String updateTime = resultSet.getString("modified_time");
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return parser.parse(updateTime).getTime();
}
else {
// In the case where for some reason the table doesn't exist anymore in system.parts
return -1L;
}
}
catch (Exception e) {
// We want to make sure the query doesn't fail because of star-tree not being able to get last modified time
logger.error("Exception thrown while trying to get modified time", e);
return -1L;
}
}
@Override
public boolean isPreAggregationSupported(ConnectorSession session)
{
return true;
}
@Override
protected void renameTable(JdbcIdentity identity, String catalogName, String schemaName, String tableName, SchemaTableName newTable)
{
try (Connection connection = connectionFactory.openConnection(identity)) {
String newSchemaName = newTable.getSchemaName();
String newTableName = newTable.getTableName();
if (connection.getMetaData().storesUpperCaseIdentifiers()) {
newSchemaName = newSchemaName.toUpperCase(ENGLISH);
newTableName = newTableName.toUpperCase(ENGLISH);
}
String schema = checkCatalog(catalogName, schemaName);
String newSchema = checkCatalog(catalogName, newSchemaName);
String sql = format("RENAME TABLE %s TO %s", quoted(null, schema, tableName), quoted(null, newSchema, newTableName));
execute(connection, sql);
}
catch (SQLException e) {
throw new PrestoException(JDBC_ERROR, "openLooKeng ClickHouse connector failed to rename table");
}
}
@Override
public void renameColumn(JdbcIdentity identity, JdbcTableHandle handle, JdbcColumnHandle jdbcColumn, String inputNewColumnName)
{
String newColumnName = inputNewColumnName;
try (Connection connection = connectionFactory.openConnection(identity)) {
if (connection.getMetaData().storesUpperCaseIdentifiers()) {
newColumnName = newColumnName.toUpperCase(ENGLISH);
}
String schema = checkCatalog(handle.getCatalogName(), handle.getSchemaName());
String sql = format(
"ALTER TABLE %s RENAME COLUMN %s TO %s",
quoted(null, schema, handle.getTableName()),
jdbcColumn.getColumnName(),
newColumnName);
execute(connection, sql);
}
catch (SQLException e) {
throw new PrestoException(JDBC_ERROR, e);
}
}
@Override
public JdbcOutputTableHandle beginInsertTable(ConnectorSession session, ConnectorTableMetadata tableMetadata)
{
SchemaTableName schemaTableName = tableMetadata.getTable();
JdbcIdentity identity = JdbcIdentity.from(session);
if (!getSchemaNames(identity).contains(schemaTableName.getSchemaName())) {
throw new PrestoException(NOT_FOUND, "Schema not found: " + schemaTableName.getSchemaName());
}
try (Connection connection = connectionFactory.openConnection(identity)) {
boolean uppercase = connection.getMetaData().storesUpperCaseIdentifiers();
String remoteSchema = toRemoteSchemaName(identity, connection, schemaTableName.getSchemaName());
String remoteTable = toRemoteTableName(identity, connection, remoteSchema, schemaTableName.getTableName());
String temporaryTableName = generateTemporaryTableName();
String catalog = connection.getCatalog();
ImmutableList.Builder<String> columnNames = ImmutableList.builder();
ImmutableList.Builder<Type> columnTypes = ImmutableList.builder();
ImmutableList.Builder<String> columnList = ImmutableList.builder();
for (ColumnMetadata column : tableMetadata.getColumns()) {
String columnName = column.getName();
if (uppercase) {
columnName = columnName.toUpperCase(ENGLISH);
}
columnNames.add(columnName);
columnTypes.add(column.getType());
columnList.add(getColumnSql(session, column, columnName));
}
String schema = checkCatalog(catalog, remoteSchema);
String sql = format(
"CREATE TABLE %s engine=Log AS SELECT * FROM %s WHERE 0 = 1",
quoted(null, schema, temporaryTableName),
quoted(null, schema, remoteTable));
execute(connection, sql);
return new JdbcOutputTableHandle(
catalog,
remoteSchema,
remoteTable,
columnNames.build(),
columnTypes.build(),
temporaryTableName);
}
catch (SQLException e) {
throw new PrestoException(JDBC_ERROR, e);
}
}
@Override
public String buildInsertSql(JdbcOutputTableHandle handle)
{
String schema = checkCatalog(handle.getCatalogName(), handle.getSchemaName());
String sql = format(
"INSERT INTO %s VALUES (%s)",
quoted(null, schema, handle.getTemporaryTableName()),
join(",", nCopies(handle.getColumnNames().size(), "?")));
return sql;
}
@Override
public PreparedStatement buildSql(ConnectorSession session, Connection connection, JdbcSplit split, JdbcTableHandle table, List<JdbcColumnHandle> columns)
throws SQLException
{
if (table.getGeneratedSql().isPresent()) {
// openLooKeng: If the sub-query is pushed down, use it as the table
return new ClickHouseQueryBuilder(identifierQuote, true).buildSql(
this,
session,
connection,
null,
null,
table.getGeneratedSql().get().getSql(),
columns,
table.getConstraint(),
split.getAdditionalPredicate(),
tryApplyLimit(table.getLimit()));
}
return new ClickHouseQueryBuilder(identifierQuote).buildSql(
this,
session,
connection,
table.getCatalogName(),
table.getSchemaName(),
table.getTableName(),
columns,
table.getConstraint(),
split.getAdditionalPredicate(),
tryApplyLimit(table.getLimit()));
}
@Override
public void finishInsertTable(JdbcIdentity identity, JdbcOutputTableHandle handle)
{
String schema = checkCatalog(handle.getCatalogName(), handle.getSchemaName());
String temporaryTable = quoted(null, schema, handle.getTemporaryTableName());
String targetTable = quoted(null, schema, handle.getTableName());
String insertSql = format("INSERT INTO %s SELECT * FROM %s", targetTable, temporaryTable);
String cleanupSql = "DROP TABLE " + temporaryTable;
try (Connection connection = getConnection(identity, handle)) {
execute(connection, insertSql);
}
catch (SQLException e) {
throw new PrestoException(JDBC_ERROR, e);
}
try (Connection connection = getConnection(identity, handle)) {
execute(connection, cleanupSql);
}
catch (SQLException e) {
logger.warn(e, "Failed to cleanup temporary table: %s", temporaryTable);
}
}
@Override
public void dropTable(JdbcIdentity identity, JdbcTableHandle handle)
{
String schema = checkCatalog(handle.getCatalogName(), handle.getSchemaName());
String sql = "DROP TABLE " + quoted(null, schema, handle.getTableName());
try (Connection connection = connectionFactory.openConnection(identity)) {
execute(connection, sql);
}
catch (SQLException e) {
throw new PrestoException(JDBC_ERROR, e);
}
}
@Override
protected Optional<BiFunction<String, Long, String>> limitFunction()
{
return Optional.of((sql, limit) -> sql + " LIMIT " + limit);
}
@Override
public boolean isLimitGuaranteed()
{
return true;
}
@Override
public Optional<QueryGenerator<JdbcQueryGeneratorResult, JdbcConverterContext>> getQueryGenerator(DeterminismEvaluator determinismEvaluator, RowExpressionService rowExpressionService, FunctionMetadataManager functionManager, StandardFunctionResolution functionResolution)
{
ClickHousePushDownParameter pushDownParameter = new ClickHousePushDownParameter(getIdentifierQuote(), this.caseInsensitiveNameMatching, pushDownModule, clickHouseConfig, functionResolution);
return Optional.of(new ClickHouseQueryGenerator(determinismEvaluator, rowExpressionService, functionManager, functionResolution, pushDownParameter, baseJdbcConfig));
}
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
@Override
public Map<String, ColumnHandle> getColumns(ConnectorSession session, String sql, Map<String, Type> types)
{
try (Connection connection = connectionFactory.openConnection(JdbcIdentity.from(session));
PreparedStatement statement = connection.prepareStatement(sql)) {
ResultSetMetaData metadata = statement.getMetaData();
ImmutableMap.Builder<String, ColumnHandle> builder = new ImmutableMap.Builder<>();
for (int i = 1; i <= metadata.getColumnCount(); i++) {
String columnName = metadata.getColumnLabel(i);
String typeName = metadata.getColumnTypeName(i);
int precision = metadata.getPrecision(i);
int dataType = metadata.getColumnType(i);
int scale = metadata.getScale(i);
boolean isNullAble = metadata.isNullable(i) != ResultSetMetaData.columnNoNulls;
if (dataType == Types.DECIMAL) {
String loweredColumnName = columnName.toLowerCase(ENGLISH);
Type type = types.get(loweredColumnName);
if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
precision = decimalType.getPrecision();
scale = decimalType.getScale();
}
}
JdbcTypeHandle typeHandle = new JdbcTypeHandle(dataType, Optional.ofNullable(typeName), precision, scale, Optional.empty());
Optional<ColumnMapping> columnMapping;
try {
columnMapping = toPrestoType(session, connection, typeHandle);
}
catch (UnsupportedOperationException ex) {
// User configured to fail the query if the data type is not supported
return Collections.emptyMap();
}
// skip unsupported column types
if (columnMapping.isPresent()) {
Type type = columnMapping.get().getType();
JdbcColumnHandle handle = new JdbcColumnHandle(columnName, typeHandle, type, isNullAble);
builder.put(columnName.toLowerCase(ENGLISH), handle);
}
else {
return Collections.emptyMap();
}
}
return builder.build();
}
catch (SQLException | PrestoException e) {
logger.error("in clickhouse push down, clickhouse data source error msg[%s] rewrite sql[%s]", e.getMessage(), sql);
return Collections.emptyMap();
}
}
/**
* Clickhouse does not support operations on catalog.schema.table
*/
private String checkCatalog(String catalog, String remoteSchema)
{
String schema;
if (catalog != null && remoteSchema != null) {
schema = remoteSchema;
}
else {
schema = catalog == null ? remoteSchema : catalog;
}
return schema;
}
}

View File

@ -1,61 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import com.google.inject.Binder;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.Singleton;
import io.airlift.configuration.AbstractConfigurationAwareModule;
import io.hetu.core.plugin.clickhouse.optimization.externalfunc.ClickHouseExternalFunctionHub;
import io.prestosql.plugin.jdbc.BaseJdbcConfig;
import io.prestosql.plugin.jdbc.ConnectionFactory;
import io.prestosql.plugin.jdbc.DriverConnectionFactory;
import io.prestosql.plugin.jdbc.JdbcClient;
import io.prestosql.spi.function.ExternalFunctionHub;
import ru.yandex.clickhouse.ClickHouseDriver;
import ru.yandex.clickhouse.settings.ClickHouseConnectionSettings;
import java.util.Optional;
import java.util.Properties;
import static io.airlift.configuration.ConfigBinder.configBinder;
import static io.prestosql.plugin.jdbc.DriverConnectionFactory.basicConnectionProperties;
public class ClickHouseClientModule
extends AbstractConfigurationAwareModule
{
@Override
protected void setup(Binder binder)
{
binder.bind(JdbcClient.class).to(ClickHouseClient.class).in(Scopes.SINGLETON);
configBinder(binder).bindConfig(BaseJdbcConfig.class);
binder.bind(ExternalFunctionHub.class).to(ClickHouseExternalFunctionHub.class).in(Scopes.SINGLETON);
configBinder(binder).bindConfig(ClickHouseConfig.class);
}
@Provides
@Singleton
public static ConnectionFactory createConnectionFactory(BaseJdbcConfig config, ClickHouseConfig clickHouseConfig)
{
Properties connectionProperties = basicConnectionProperties(config);
connectionProperties.setProperty(ClickHouseConnectionSettings.SOCKET_TIMEOUT.getKey(),
String.valueOf(clickHouseConfig.getSocketTimeout()));
return new DriverConnectionFactory(new ClickHouseDriver(), config.getConnectionUrl(),
Optional.ofNullable(config.getUserCredentialName()),
Optional.ofNullable(config.getPasswordCredentialName()),
connectionProperties);
}
}

View File

@ -1,100 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import io.airlift.configuration.Config;
import io.airlift.configuration.ConfigDescription;
import java.util.Locale;
/**
* To get the custom properties to connect to the database.
*/
public class ClickHouseConfig
{
private static final int DEFAULT_SOCKET_TIMEOUT = 120000;
private int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
private String tableTypes = ClickHouseConstants.DEFAULT_TABLE_TYPES;
private String schemaPattern;
private boolean isQueryPushDownEnabled = true;
private String clickHouseSqlVersion = "DEFAULT";
public int getSocketTimeout()
{
return socketTimeout;
}
@Config("clickhouse.socket_timeout")
@ConfigDescription("Connection ClickHouse socket timeout ")
public ClickHouseConfig setSocketTimeout(int socketTimeout)
{
this.socketTimeout = socketTimeout;
return this;
}
@Config("clickhouse.query.pushdown.enabled")
@ConfigDescription("Enable sub-query push down to clickhouse. It's set by default")
public ClickHouseConfig setQueryPushDownEnabled(boolean isQueryPushDownEnabledParameter)
{
this.isQueryPushDownEnabled = isQueryPushDownEnabledParameter;
return this;
}
public boolean isQueryPushDownEnabled()
{
return this.isQueryPushDownEnabled;
}
public String getTableTypes()
{
return this.tableTypes;
}
public String getSchemaPattern()
{
return schemaPattern;
}
/**
* setTableTypes
*
* @param tableTypes the table types to set
* @return ClickHouseConfig
*/
@Config("clickhouse.table-types")
public ClickHouseConfig setTableTypes(String tableTypes)
{
this.tableTypes = tableTypes.toUpperCase(Locale.ENGLISH);
return this;
}
public String getClickHouseSqlVersion()
{
return this.clickHouseSqlVersion;
}
/**
* setSchemaPattern
*
* @param schemaPattern the schema pattern to set
* @return ClickHouseConfig
*/
@Config("clickhouse.schema-pattern")
public ClickHouseConfig setSchemaPattern(String schemaPattern)
{
this.schemaPattern = schemaPattern;
return this;
}
}

View File

@ -1,33 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
public class ClickHouseConstants
{
public static final String CLICKHOUSE_JDBC_DRIVER_CLASS_NAME = "ru.yandex.clickhouse.ClickHouseDriver";
public static final int DEAFULT_STRINGBUFFER_CAPACITY = 30;
/**
* default table type list for clickhouse
*/
public static final String DEFAULT_TABLE_TYPES = "TABLE,VIEW";
public static final String CONNECTOR_NAME = "ClickHouse";
private ClickHouseConstants()
{
}
}

View File

@ -1,51 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import io.prestosql.plugin.jdbc.BaseJdbcConfig;
import io.prestosql.plugin.jdbc.JdbcPlugin;
import io.prestosql.spi.function.ConnectorConfig;
import io.prestosql.spi.queryeditorui.ConnectorUtil;
import io.prestosql.spi.queryeditorui.ConnectorWithProperties;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;
@ConnectorConfig(connectorLabel = "Clickhouse: Query data in Clickhouse system",
propertiesEnabled = true,
catalogConfigFilesEnabled = true,
globalConfigFilesEnabled = true,
docLink = "https://openlookeng.io/docs/docs/connector/clickhouse.html",
configLink = "https://openlookeng.io/docs/docs/connector/clickhouse.html#configuration")
public class ClickHousePlugin
extends JdbcPlugin
{
public ClickHousePlugin()
{
super("clickhouse", new ClickHouseClientModule());
}
@Override
public Optional<ConnectorWithProperties> getConnectorWithProperties()
{
ConnectorConfig connectorConfig = ClickHousePlugin.class.getAnnotation(ConnectorConfig.class);
ArrayList<Method> methods = new ArrayList<>();
methods.addAll(Arrays.asList(BaseJdbcConfig.class.getDeclaredMethods()));
methods.addAll(Arrays.asList(ClickHouseConfig.class.getDeclaredMethods()));
return ConnectorUtil.assembleConnectorProperties(connectorConfig, methods);
}
}

View File

@ -1,346 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import com.google.common.base.Joiner;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import io.prestosql.plugin.jdbc.BlockWriteFunction;
import io.prestosql.plugin.jdbc.BooleanWriteFunction;
import io.prestosql.plugin.jdbc.DoubleWriteFunction;
import io.prestosql.plugin.jdbc.JdbcClient;
import io.prestosql.plugin.jdbc.JdbcColumnHandle;
import io.prestosql.plugin.jdbc.JdbcTypeHandle;
import io.prestosql.plugin.jdbc.LongWriteFunction;
import io.prestosql.plugin.jdbc.QueryBuilder;
import io.prestosql.plugin.jdbc.SliceWriteFunction;
import io.prestosql.plugin.jdbc.WriteFunction;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.connector.ColumnHandle;
import io.prestosql.spi.connector.ConnectorSession;
import io.prestosql.spi.predicate.Domain;
import io.prestosql.spi.predicate.Range;
import io.prestosql.spi.predicate.TupleDomain;
import io.prestosql.spi.type.ArrayType;
import io.prestosql.spi.type.BigintType;
import io.prestosql.spi.type.BooleanType;
import io.prestosql.spi.type.CharType;
import io.prestosql.spi.type.DateType;
import io.prestosql.spi.type.DoubleType;
import io.prestosql.spi.type.IntegerType;
import io.prestosql.spi.type.RealType;
import io.prestosql.spi.type.SmallintType;
import io.prestosql.spi.type.TimeType;
import io.prestosql.spi.type.TimeWithTimeZoneType;
import io.prestosql.spi.type.TimestampType;
import io.prestosql.spi.type.TimestampWithTimeZoneType;
import io.prestosql.spi.type.TinyintType;
import io.prestosql.spi.type.Type;
import io.prestosql.spi.type.VarcharType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.lang.String.format;
import static java.util.Collections.nCopies;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;
public class ClickHouseQueryBuilder
extends QueryBuilder
{
private static final String ALWAYS_TRUE = "1=1";
private static final String ALWAYS_FALSE = "1=0";
private boolean isPushSubQueryDown;
private final String identifierQuote;
public ClickHouseQueryBuilder(String identifierQuote)
{
super(identifierQuote);
this.identifierQuote = requireNonNull(identifierQuote, "quote is null");
}
public ClickHouseQueryBuilder(String identifierQuote, boolean isPushSubQueryDown)
{
this(identifierQuote);
this.isPushSubQueryDown = isPushSubQueryDown;
}
private static class TypeAndValue
{
private final Type type;
private final JdbcTypeHandle typeHandle;
private final Object value;
public TypeAndValue(Type type, JdbcTypeHandle typeHandle, Object value)
{
this.type = requireNonNull(type, "type is null");
this.typeHandle = requireNonNull(typeHandle, "typeHandle is null");
this.value = requireNonNull(value, "value is null");
}
public Type getType()
{
return type;
}
public JdbcTypeHandle getTypeHandle()
{
return typeHandle;
}
public Object getValue()
{
return value;
}
}
private String quote(String name)
{
return identifierQuote + name.replace(identifierQuote, identifierQuote + identifierQuote) + identifierQuote;
}
private static Domain pushDownDomain(JdbcClient client, ConnectorSession session, Connection connection, JdbcColumnHandle column, Domain domain)
{
return client.toPrestoType(session, connection, column.getJdbcTypeHandle())
.orElseThrow(() -> new IllegalStateException(format("Unsupported type %s with handle %s", column.getColumnType(), column.getJdbcTypeHandle())))
.getPushdownConverter().apply(domain);
}
private List<String> toConjuncts(
JdbcClient client,
ConnectorSession session,
Connection connection,
List<JdbcColumnHandle> columns,
TupleDomain<ColumnHandle> tupleDomain,
List<ClickHouseQueryBuilder.TypeAndValue> accumulator)
{
if (tupleDomain.isNone()) {
return ImmutableList.of(ALWAYS_FALSE);
}
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (JdbcColumnHandle column : columns) {
Domain domain = tupleDomain.getDomains().get().get(column);
if (domain != null) {
domain = pushDownDomain(client, session, connection, column, domain);
builder.add(toPredicate(column.getColumnName(), domain, column, accumulator));
}
}
return builder.build();
}
private String toPredicate(String columnName, Domain domain, JdbcColumnHandle column, List<ClickHouseQueryBuilder.TypeAndValue> accumulator)
{
if (domain.getValues().isNone()) {
return domain.isNullAllowed() ? quote(columnName) + " IS NULL" : ALWAYS_FALSE;
}
if (domain.getValues().isAll()) {
return domain.isNullAllowed() ? ALWAYS_TRUE : quote(columnName) + " IS NOT NULL";
}
List<String> disjuncts = new ArrayList<>();
List<Object> singleValues = new ArrayList<>();
for (Range range : domain.getValues().getRanges().getOrderedRanges()) {
checkState(!range.isAll()); // Already checked
if (range.isSingleValue()) {
singleValues.add(range.getLow().getValue());
}
else {
List<String> rangeConjuncts = new ArrayList<>();
if (!range.getLow().isLowerUnbounded()) {
switch (range.getLow().getBound()) {
case ABOVE:
rangeConjuncts.add(toPredicate(columnName, ">", range.getLow().getValue(), column, accumulator));
break;
case EXACTLY:
rangeConjuncts.add(toPredicate(columnName, ">=", range.getLow().getValue(), column, accumulator));
break;
case BELOW:
throw new IllegalArgumentException("Low marker should never use BELOW bound");
default:
throw new AssertionError("Unhandled bound: " + range.getLow().getBound());
}
}
if (!range.getHigh().isUpperUnbounded()) {
switch (range.getHigh().getBound()) {
case ABOVE:
throw new IllegalArgumentException("High marker should never use ABOVE bound");
case EXACTLY:
rangeConjuncts.add(toPredicate(columnName, "<=", range.getHigh().getValue(), column, accumulator));
break;
case BELOW:
rangeConjuncts.add(toPredicate(columnName, "<", range.getHigh().getValue(), column, accumulator));
break;
default:
throw new AssertionError("Unhandled bound: " + range.getHigh().getBound());
}
}
// If rangeConjuncts is null, then the range was ALL, which should already have been checked for
checkState(!rangeConjuncts.isEmpty());
disjuncts.add("(" + Joiner.on(" AND ").join(rangeConjuncts) + ")");
}
}
// Add back all of the possible single values either as an equality or an IN predicate
if (singleValues.size() == 1) {
disjuncts.add(toPredicate(columnName, "=", getOnlyElement(singleValues), column, accumulator));
}
else if (singleValues.size() > 1) {
for (Object value : singleValues) {
bindValue(value, column, accumulator);
}
String values = Joiner.on(",").join(nCopies(singleValues.size(), "?"));
disjuncts.add(quote(columnName) + " IN (" + values + ")");
}
// Add nullability disjuncts
checkState(!disjuncts.isEmpty());
if (domain.isNullAllowed()) {
disjuncts.add(quote(columnName) + " IS NULL");
}
return "(" + Joiner.on(" OR ").join(disjuncts) + ")";
}
private String toPredicate(String columnName, String operator, Object value, JdbcColumnHandle column, List<ClickHouseQueryBuilder.TypeAndValue> accumulator)
{
bindValue(value, column, accumulator);
return quote(columnName) + " " + operator + " ?";
}
private static void bindValue(Object value, JdbcColumnHandle column, List<ClickHouseQueryBuilder.TypeAndValue> accumulator)
{
Type type = column.getColumnType();
checkArgument(isAcceptedType(type), "Can't handle type: %s", type);
accumulator.add(new TypeAndValue(type, column.getJdbcTypeHandle(), value));
}
private static boolean isAcceptedType(Type type)
{
Type validType = requireNonNull(type, "type is null");
return validType.equals(BigintType.BIGINT) ||
validType.equals(TinyintType.TINYINT) ||
validType.equals(SmallintType.SMALLINT) ||
validType.equals(IntegerType.INTEGER) ||
validType.equals(DoubleType.DOUBLE) ||
validType.equals(RealType.REAL) ||
validType.equals(BooleanType.BOOLEAN) ||
validType.equals(DateType.DATE) ||
validType.equals(TimeType.TIME) ||
validType.equals(TimeWithTimeZoneType.TIME_WITH_TIME_ZONE) ||
validType.equals(TimestampType.TIMESTAMP) ||
validType.equals(TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE) ||
validType instanceof VarcharType ||
validType instanceof CharType ||
validType instanceof ArrayType;
}
@Override
public PreparedStatement buildSql(JdbcClient client,
ConnectorSession session,
Connection connection,
String catalog,
String schema,
String table,
List<JdbcColumnHandle> columns,
TupleDomain<ColumnHandle> tupleDomain,
Optional<String> additionalPredicate,
Function<String, String> sqlFunction)
throws SQLException
{
StringBuilder sql = new StringBuilder();
String columnNames = columns.stream()
.map(JdbcColumnHandle::getColumnName)
.map(this::quote)
.collect(joining(", "));
sql.append("SELECT ");
sql.append(columnNames);
if (columns.isEmpty()) {
sql.append("null");
}
sql.append(" FROM ");
if (!isNullOrEmpty(schema)) {
sql.append(quote(schema)).append('.');
}
if (isPushSubQueryDown) {
sql.append("(").append(table).append(") pushdown");
}
else {
sql.append(quote(table));
}
List<TypeAndValue> accumulator = new ArrayList<>();
List<String> clauses = toConjuncts(client, session, connection, columns, tupleDomain, accumulator);
if (additionalPredicate.isPresent()) {
clauses = ImmutableList.<String>builder()
.addAll(clauses)
.add(additionalPredicate.get())
.build();
}
if (!clauses.isEmpty()) {
sql.append(" WHERE ")
.append(Joiner.on(" AND ").join(clauses));
}
String query = sqlFunction.apply(sql.toString());
PreparedStatement statement = client.getPreparedStatement(connection, query);
for (int i = 0; i < accumulator.size(); i++) {
TypeAndValue typeAndValue = accumulator.get(i);
int parameterIndex = i + 1;
Type type = typeAndValue.getType();
WriteFunction writeFunction = client.toPrestoType(session, connection, typeAndValue.getTypeHandle())
.orElseThrow(() -> new VerifyException(format("Unsupported type %s with handle %s", type, typeAndValue.getTypeHandle())))
.getWriteFunction();
Class<?> javaType = type.getJavaType();
Object value = typeAndValue.getValue();
if (javaType == boolean.class) {
((BooleanWriteFunction) writeFunction).set(statement, parameterIndex, (boolean) value);
}
else if (javaType == long.class) {
((LongWriteFunction) writeFunction).set(statement, parameterIndex, (long) value);
}
else if (javaType == double.class) {
((DoubleWriteFunction) writeFunction).set(statement, parameterIndex, (double) value);
}
else if (javaType == Slice.class) {
((SliceWriteFunction) writeFunction).set(statement, parameterIndex, (Slice) value);
}
else if (javaType == Block.class) {
((BlockWriteFunction) writeFunction).set(statement, parameterIndex, (Block) value);
}
else {
throw new VerifyException(format("Unexpected type %s with java type %s", type, javaType.getName()));
}
}
return statement;
}
}

View File

@ -1,63 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.optimization;
import com.google.common.base.Joiner;
import io.hetu.core.plugin.clickhouse.optimization.externalfunc.ClickHouseExternalFunctionHub;
import io.prestosql.plugin.jdbc.BaseJdbcConfig;
import io.prestosql.plugin.jdbc.optimization.BaseJdbcRowExpressionConverter;
import io.prestosql.plugin.jdbc.optimization.JdbcConverterContext;
import io.prestosql.spi.function.SqlFunctionHandle;
import io.prestosql.spi.relation.CallExpression;
import io.prestosql.sql.builder.functioncall.ApplyRemoteFunctionPushDown;
import java.util.Map;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
public class ClickHouseApplyRemoteFunctionPushDown
extends ApplyRemoteFunctionPushDown
{
private static Map<String, String> clickHousePrimalFunctionNameMap = ClickHouseExternalFunctionHub.getPrimalFunctionNameMap();
public ClickHouseApplyRemoteFunctionPushDown(BaseJdbcConfig baseJdbcConfig, String connectorName)
{
super(baseJdbcConfig, connectorName);
}
/**
* rewrite the remote function to a executable function in the data source.
*/
@Override
public Optional<String> rewriteRemoteFunction(CallExpression callExpression, BaseJdbcRowExpressionConverter rowExpressionConverter, JdbcConverterContext jdbcConverterContext)
{
if (!isConnectorSupportedRemoteFunction(callExpression)) {
return Optional.empty();
}
jdbcConverterContext.setRemoteUdfVisited(true);
String displayName = ((SqlFunctionHandle) callExpression.getFunctionHandle()).getFunctionId().getFunctionName().getObjectName();
String args = Joiner.on(",").join(callExpression.getArguments().stream().map(expression -> expression.accept(rowExpressionConverter, jdbcConverterContext)).collect(toList()));
// The click house is case sensitive and presto only support the lower case function name,
// we need to handle this function into lower and store its primal name.
// The click house do not contain two different functions have the equal function name ignore case.
// If a data base contain two different functions have the equal function name ignore case,
// then we should register them into different function name space
if (!clickHousePrimalFunctionNameMap.containsKey(displayName)) {
return Optional.empty();
}
return Optional.of(String.format("%s(%s)", clickHousePrimalFunctionNameMap.get(displayName), args));
}
}

View File

@ -1,40 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.optimization;
import io.hetu.core.plugin.clickhouse.ClickHouseConfig;
import io.prestosql.plugin.jdbc.optimization.JdbcPushDownModule;
import io.prestosql.plugin.jdbc.optimization.JdbcPushDownParameter;
import io.prestosql.spi.function.StandardFunctionResolution;
/**
* Push Down parameter module
*/
public class ClickHousePushDownParameter
extends JdbcPushDownParameter
{
private final ClickHouseConfig clickHouseConfig;
public ClickHousePushDownParameter(String identifierQuote, boolean nameCaseInsensitive, JdbcPushDownModule pushDownModule, ClickHouseConfig clickHouseConfig, StandardFunctionResolution functionResolution)
{
super(identifierQuote, nameCaseInsensitive, pushDownModule, functionResolution);
this.clickHouseConfig = clickHouseConfig;
}
public ClickHouseConfig getClickHouseConfig()
{
return clickHouseConfig;
}
}

View File

@ -1,37 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.optimization;
import io.prestosql.plugin.jdbc.BaseJdbcConfig;
import io.prestosql.plugin.jdbc.optimization.BaseJdbcQueryGenerator;
import io.prestosql.spi.function.FunctionMetadataManager;
import io.prestosql.spi.function.StandardFunctionResolution;
import io.prestosql.spi.relation.DeterminismEvaluator;
import io.prestosql.spi.relation.RowExpressionService;
public class ClickHouseQueryGenerator
extends BaseJdbcQueryGenerator
{
public ClickHouseQueryGenerator(
DeterminismEvaluator determinismEvaluator,
RowExpressionService rowExpressionService,
FunctionMetadataManager functionManager,
StandardFunctionResolution functionResolution,
ClickHousePushDownParameter pushDownParameter,
BaseJdbcConfig baseJdbcConfig)
{
super(pushDownParameter, new ClickHouseRowExpressionConverter(determinismEvaluator, rowExpressionService, functionManager, functionResolution, pushDownParameter, baseJdbcConfig), new ClickHouseSqlStatementWriter(pushDownParameter));
}
}

View File

@ -1,257 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.optimization;
import com.google.common.base.Joiner;
import io.hetu.core.plugin.clickhouse.ClickHouseConfig;
import io.hetu.core.plugin.clickhouse.ClickHouseConstants;
import io.hetu.core.plugin.clickhouse.rewrite.BuildInDirectMapFunctionCallRewriter;
import io.hetu.core.plugin.clickhouse.rewrite.ClickHouseUnsupportedFunctionCallRewriter;
import io.hetu.core.plugin.clickhouse.rewrite.UdfFunctionRewriteConstants;
import io.hetu.core.plugin.clickhouse.rewrite.functioncall.DateParseFunctionCallRewriter;
import io.prestosql.configmanager.ConfigSupplier;
import io.prestosql.configmanager.DefaultUdfRewriteConfigSupplier;
import io.prestosql.plugin.jdbc.BaseJdbcConfig;
import io.prestosql.plugin.jdbc.optimization.BaseJdbcRowExpressionConverter;
import io.prestosql.plugin.jdbc.optimization.JdbcConverterContext;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.function.FunctionHandle;
import io.prestosql.spi.function.FunctionMetadata;
import io.prestosql.spi.function.FunctionMetadataManager;
import io.prestosql.spi.function.OperatorType;
import io.prestosql.spi.function.StandardFunctionResolution;
import io.prestosql.spi.relation.CallExpression;
import io.prestosql.spi.relation.ConstantExpression;
import io.prestosql.spi.relation.DeterminismEvaluator;
import io.prestosql.spi.relation.RowExpression;
import io.prestosql.spi.relation.RowExpressionService;
import io.prestosql.spi.relation.SpecialForm;
import io.prestosql.spi.sql.expression.QualifiedName;
import io.prestosql.spi.type.Type;
import io.prestosql.spi.type.VarcharType;
import io.prestosql.sql.builder.functioncall.FunctionWriterManager;
import io.prestosql.sql.builder.functioncall.FunctionWriterManagerGroup;
import io.prestosql.sql.builder.functioncall.functions.FunctionCallRewriter;
import io.prestosql.sql.builder.functioncall.functions.base.FromBase64CallRewriter;
import io.prestosql.sql.builder.functioncall.functions.config.DefaultConnectorConfigFunctionRewriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static io.prestosql.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.prestosql.sql.builder.functioncall.BaseFunctionUtil.isDefaultFunction;
import static java.lang.String.format;
import static java.util.Locale.ENGLISH;
public class ClickHouseRowExpressionConverter
extends BaseJdbcRowExpressionConverter
{
private static final Set<String> clickHouseNotSupportFunctions =
Stream.of("try", "try_cast", "at_timezone", "current_user", "current_path", "current_time").collect(toImmutableSet());
private static FunctionWriterManager clickHouseFunctionManager;
private final ClickHouseApplyRemoteFunctionPushDown clickHouseApplyRemoteFunctionPushDown;
/**
* ClickHouse sql query writer
*
* @param clickHouseConfig config
*/
public ClickHouseRowExpressionConverter(
DeterminismEvaluator determinismEvaluator,
RowExpressionService rowExpressionService,
FunctionMetadataManager functionManager,
StandardFunctionResolution functionResolution,
ClickHousePushDownParameter clickHouseConfig,
BaseJdbcConfig baseJdbcConfig)
{
super(functionManager, functionResolution, rowExpressionService, determinismEvaluator);
clickHouseFunctionManager = initFunctionManager(clickHouseConfig.getClickHouseConfig());
clickHouseApplyRemoteFunctionPushDown = new ClickHouseApplyRemoteFunctionPushDown(baseJdbcConfig, ClickHouseConstants.CONNECTOR_NAME);
}
private FunctionWriterManager initFunctionManager(ClickHouseConfig clickHouseConfig)
{
ConfigSupplier configSupplier = new DefaultUdfRewriteConfigSupplier(UdfFunctionRewriteConstants.DEFAULT_VERSION_UDF_REWRITE_PATTERNS);
DefaultConnectorConfigFunctionRewriter connectorConfigFunctionRewriter =
new DefaultConnectorConfigFunctionRewriter(ClickHouseConstants.CONNECTOR_NAME, configSupplier);
return FunctionWriterManagerGroup.newFunctionWriterManagerInstance(ClickHouseConstants.CONNECTOR_NAME,
clickHouseConfig.getClickHouseSqlVersion(), getInjectFunctionCallRewritersDefault(clickHouseConfig), connectorConfigFunctionRewriter);
}
private Map<String, FunctionCallRewriter> getInjectFunctionCallRewritersDefault(ClickHouseConfig clickHouseConfig)
{
// add the user define function re-writer
Map<String, FunctionCallRewriter> functionCallRewriters = new HashMap<>(Collections.emptyMap());
// 1. the base function re-writers all connector can use
FromBase64CallRewriter fromBase64CallRewriter = new FromBase64CallRewriter();
functionCallRewriters.put(FromBase64CallRewriter.INNER_FUNC_FROM_BASE64, fromBase64CallRewriter);
// 2. the specific user define function re-writers
FunctionCallRewriter unSupportedFunctionCallRewriter = new ClickHouseUnsupportedFunctionCallRewriter(ClickHouseConstants.CONNECTOR_NAME);
functionCallRewriters.put(ClickHouseUnsupportedFunctionCallRewriter.INNER_FUNC_INTERVAL_LITERAL_DAY2SEC, unSupportedFunctionCallRewriter);
functionCallRewriters.put(ClickHouseUnsupportedFunctionCallRewriter.INNER_FUNC_INTERVAL_LITERAL_YEAR2MONTH, unSupportedFunctionCallRewriter);
functionCallRewriters.put(ClickHouseUnsupportedFunctionCallRewriter.INNER_FUNC_TIME_WITH_TZ_LITERAL, unSupportedFunctionCallRewriter);
FunctionCallRewriter buildInDirectMapFunctionCallRewriter = new BuildInDirectMapFunctionCallRewriter();
functionCallRewriters.put(BuildInDirectMapFunctionCallRewriter.BUIDLIN_AGGR_FUNC_SUM, buildInDirectMapFunctionCallRewriter);
functionCallRewriters.put(BuildInDirectMapFunctionCallRewriter.BUILDIN_AGGR_FUNC_AVG, buildInDirectMapFunctionCallRewriter);
functionCallRewriters.put(BuildInDirectMapFunctionCallRewriter.BUILDIN_AGGR_FUNC_COUNT, buildInDirectMapFunctionCallRewriter);
functionCallRewriters.put(BuildInDirectMapFunctionCallRewriter.BUILDIN_AGGR_FUNC_MAX, buildInDirectMapFunctionCallRewriter);
functionCallRewriters.put(BuildInDirectMapFunctionCallRewriter.BUILDIN_AGGR_FUNC_MIN, buildInDirectMapFunctionCallRewriter);
FunctionCallRewriter dateParseFunctionCallRewriter = new DateParseFunctionCallRewriter();
functionCallRewriters.put(DateParseFunctionCallRewriter.BUILD_IN_FUNC_DATE_PARSE, dateParseFunctionCallRewriter);
return functionCallRewriters;
}
protected static String functionCall(QualifiedName name, boolean isDistinct, List<String> argumentsList, Optional<String> orderBy, Optional<String> filter, Optional<String> window)
{
if (clickHouseFunctionManager == null) {
throw new PrestoException(NOT_SUPPORTED, "Function manager is uninitialized");
}
try {
return clickHouseFunctionManager.getFunctionRewriteResult(name, isDistinct, argumentsList, orderBy, filter, window);
}
catch (UnsupportedOperationException e) {
throw new PrestoException(NOT_SUPPORTED, e.getMessage());
}
}
@Override
public String visitCall(CallExpression call, JdbcConverterContext context)
{
FunctionHandle functionHandle = call.getFunctionHandle();
// remote udf verify
if (!isDefaultFunction(call)) {
Optional<String> result = clickHouseApplyRemoteFunctionPushDown.rewriteRemoteFunction(call, this, context);
if (result.isPresent()) {
return result.get();
}
throw new PrestoException(NOT_SUPPORTED, String.format("ClickHouse connector does not support remote function: %s.%s", call.getDisplayName(), call.getFunctionHandle().getFunctionNamespace()));
}
FunctionMetadata functionMetadata = functionMetadataManager.getFunctionMetadata(functionHandle);
String functionName = functionMetadata.getName().getObjectName();
if (clickHouseNotSupportFunctions.contains(functionName)) {
throw new PrestoException(NOT_SUPPORTED, "ClickHouse connector does not support " + functionName);
}
if (standardFunctionResolution.isOperator(functionHandle)) {
return handleOperatorFunction(call, functionMetadata, context);
}
List<String> argumentList = call.getArguments().stream().map(expr -> expr.accept(this, context)).collect(Collectors.toList());
if (standardFunctionResolution.isNotFunction(functionHandle)) {
return format("(NOT %s)", argumentList.get(0));
}
if (standardFunctionResolution.isLikeFunction(functionHandle)) {
return format("(%s LIKE %s)", argumentList.get(0), argumentList.get(1));
}
/*
* Array needs to be tested
*/
if (standardFunctionResolution.isArrayConstructor(functionHandle)) {
return format("ARRAY(%s)", Joiner.on(", ").join(argumentList));
}
return functionCall(new QualifiedName(Collections.singletonList(functionName)), false, argumentList, Optional.empty(), Optional.empty(), Optional.empty());
}
private String handleOperatorFunction(CallExpression call, FunctionMetadata functionMetadata, JdbcConverterContext context)
{
Optional<OperatorType> operatorTypeOptional = functionMetadata.getOperatorType();
OperatorType type = operatorTypeOptional.get();
if (type.equals(OperatorType.CAST)) {
return handleCastOperator(call.getArguments().get(0), call.getType(), context);
}
List<String> argumentList = call.getArguments().stream().map(expr -> expr.accept(this, context)).collect(Collectors.toList());
if (type.isArithmeticOperator()) {
return format("(%s %s %s)", argumentList.get(0), type.getOperator(), argumentList.get(1));
}
if (type.isComparisonOperator()) {
final String[] clickHouseCompareOperators = new String[] {"=", ">", "<", ">=", "<=", "!=", "<>"};
if (Arrays.asList(clickHouseCompareOperators).contains(type.getOperator())) {
return format("(%s %s %s)", argumentList.get(0), type.getOperator(), argumentList.get(1));
}
else {
String exceptionInfo = "ClickHouse Connector does not support comparison operator " + type.getOperator();
throw new PrestoException(NOT_SUPPORTED, exceptionInfo);
}
}
if (type.equals(OperatorType.SUBSCRIPT)) {
throw new PrestoException(NOT_SUPPORTED, "ClickHouse Connector does not support subscript now");
}
/*
* "Negative" needs to be tested
*/
if (call.getArguments().size() == 1 && type.equals(OperatorType.NEGATION)) {
String value = argumentList.get(0);
String separator = value.startsWith("-") ? " " : "";
return format("-%s%s", separator, value);
}
throw new PrestoException(NOT_SUPPORTED, String.format("Unknown operator %s in push down", type.getOperator()));
}
private String handleCastOperator(RowExpression expression, Type dstType, JdbcConverterContext context)
{
/*
* In SqlToRowExpressionTranslator, it will translate GenericLiteral expression to a 'CONSTANT' rowExpression,
* so the 'CAST' operator is not needed.
* */
String value = expression.accept(this, context);
if (expression instanceof ConstantExpression && expression.getType() instanceof VarcharType) {
//dstType needs to be tested here.
//especially DateTime.
return value;
}
if (dstType.getDisplayName().equals(LIKE_PATTERN_NAME)) {
return value;
}
return format("CAST(%s AS %s)", value, dstType.getDisplayName().toLowerCase(ENGLISH));
}
@Override
public String visitSpecialForm(SpecialForm specialForm, JdbcConverterContext context)
{
if (specialForm.getForm().equals(SpecialForm.Form.DEREFERENCE)
|| specialForm.getForm().equals(SpecialForm.Form.ROW_CONSTRUCTOR)
|| specialForm.getForm().equals(SpecialForm.Form.BIND)) {
throw new PrestoException(NOT_SUPPORTED, "ClickHouse connector does not support" + specialForm.getForm().toString());
}
return super.visitSpecialForm(specialForm, context);
}
}

View File

@ -1,79 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.optimization;
import io.airlift.log.Logger;
import io.prestosql.plugin.jdbc.optimization.BaseJdbcSqlStatementWriter;
import io.prestosql.plugin.jdbc.optimization.JdbcPushDownParameter;
import io.prestosql.spi.sql.expression.Types;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
/**
* It is not clear what is the difference between aggregation and the previous version.
*/
public class ClickHouseSqlStatementWriter
extends BaseJdbcSqlStatementWriter
{
protected static final Logger log = Logger.get(ClickHouseSqlStatementWriter.class);
public ClickHouseSqlStatementWriter(JdbcPushDownParameter pushDownParameter)
{
super(pushDownParameter);
}
@Override
public String aggregation(String inputFunctionName, List<String> arguments, boolean isDistinct)
{
String functionName = inputFunctionName;
if (functionName.toUpperCase(Locale.ENGLISH).equals("VARIANCE")) {
functionName = "varPop";
}
return super.aggregation(functionName, arguments, isDistinct);
}
@Override
public String windowFrame(Types.WindowFrameType type, String start, Optional<String> end)
{
throw new UnsupportedOperationException("ClickHouse Connector does not support windows function");
}
@Override
public String window(String functionName, List<String> functionArgs, List<String> partitionBy, Optional<String> orderBy, Optional<String> frame)
{
throw new UnsupportedOperationException("ClickHouse Connector does not support windows function");
}
@Override
public String from(String selections, String from)
{
String[] froms = from.split("\\.");
if (froms.length == 2) {
return selections + " FROM " + from;
}
else if (froms.length == 3) {
StringBuilder sb = new StringBuilder(froms[1]);
sb.append(".");
sb.append(froms[2]);
return selections + " FROM " + sb.toString();
}
else {
log.error("params more than 3 " + from);
return selections + " FROM " + from;
}
}
}

View File

@ -1,74 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.optimization.externalfunc;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.prestosql.spi.function.ExternalFunctionInfo;
import io.prestosql.spi.type.StandardTypes;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
public class ClickHouseExternalDateTimeFunctions
{
public static Set<ExternalFunctionInfo> getFunctionsInfo()
{
return ImmutableSet.<ExternalFunctionInfo>builder()
.add(ClickHouse_toUnixTimeStamp_FUNCTION_INFO)
.add(ClickHouse_toDateTime_FUNCTION_INFO)
.build();
}
public static Map<String, String> getDateTimeHubFunctionStringMap()
{
// the click house is case sensitive and presto only support the lower case function name,
// we need to handle this function into lower and store its primal name.
// now the click house do not contain two different functions have the equal function name ignore case.
return ImmutableMap.<String, String>builder()
.put(TO_UNIX_TIME_STAMP_PRIMAL.toLowerCase(Locale.ENGLISH), TO_UNIX_TIME_STAMP_PRIMAL)
.put(TO_DATE_TIME_PRIMAL.toLowerCase(Locale.ENGLISH), TO_DATE_TIME_PRIMAL)
.build();
}
private static final String TO_UNIX_TIME_STAMP_PRIMAL = "toUnixTimestamp";
private static final String TO_DATE_TIME_PRIMAL = "toDateTime";
private static final ExternalFunctionInfo ClickHouse_toUnixTimeStamp_FUNCTION_INFO =
ExternalFunctionInfo.builder()
.functionName(TO_UNIX_TIME_STAMP_PRIMAL.toLowerCase(Locale.ENGLISH))
.inputArgs(StandardTypes.VARCHAR)
.returnType(StandardTypes.BIGINT)
.deterministic(true)
.calledOnNullInput(false)
.description("converts value to the number with type UInt32 -- Unix Timestamp")
.build();
private static final ExternalFunctionInfo ClickHouse_toDateTime_FUNCTION_INFO =
ExternalFunctionInfo.builder()
.functionName(TO_DATE_TIME_PRIMAL.toLowerCase(Locale.ENGLISH))
.inputArgs(StandardTypes.VARCHAR)
.returnType(StandardTypes.TIMESTAMP)
.deterministic(true)
.calledOnNullInput(false)
.description("converts value to the number with type UInt32 -- Unix Timestamp")
.build();
private ClickHouseExternalDateTimeFunctions()
{
}
}

View File

@ -1,68 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.optimization.externalfunc;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.prestosql.plugin.jdbc.BaseJdbcConfig;
import io.prestosql.spi.connector.CatalogSchemaName;
import io.prestosql.spi.function.ExternalFunctionInfo;
import io.prestosql.sql.builder.functioncall.JdbcExternalFunctionHub;
import javax.inject.Inject;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static java.util.Objects.requireNonNull;
public class ClickHouseExternalFunctionHub
extends JdbcExternalFunctionHub
{
private final BaseJdbcConfig jdbcConfig;
@Inject
public ClickHouseExternalFunctionHub(BaseJdbcConfig jdbcConfig)
{
this.jdbcConfig = requireNonNull(jdbcConfig, "jdbcConfig is null");
}
@Override
public Optional<CatalogSchemaName> getExternalFunctionCatalogSchemaName()
{
return jdbcConfig.getConnectorRegistryFunctionNamespace();
}
@Override
public Set<ExternalFunctionInfo> getExternalFunctions()
{
return ImmutableSet.<ExternalFunctionInfo>builder()
.addAll(ClickHouseExternalDateTimeFunctions.getFunctionsInfo())
.build();
}
public static Map<String, String> getPrimalFunctionNameMap()
{
// The click house is case sensitive and presto only support the lower case function name,
// we need to handle this function into lower and store its primal name.
// The click house do not contain two different functions have the equal function name ignore case.
// If a data base contain two different functions have the equal function name ignore case,
// then we should register them into different function name space
return ImmutableMap.<String, String>builder()
.putAll(ClickHouseExternalDateTimeFunctions.getDateTimeHubFunctionStringMap())
.build();
}
}

View File

@ -1,72 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.rewrite;
import io.hetu.core.plugin.clickhouse.ClickHouseConstants;
import io.prestosql.sql.builder.functioncall.FunctionCallArgsPackage;
import io.prestosql.sql.builder.functioncall.functions.FunctionCallRewriter;
public class BuildInDirectMapFunctionCallRewriter
implements FunctionCallRewriter
{
// ========= for Aggregate Functions =========
/**
* functioncall name of build-in direct map aggregate function max
*/
public static final String BUILDIN_AGGR_FUNC_MAX = "max";
/**
* functioncall name of build-in direct min aggregate function min
*/
public static final String BUILDIN_AGGR_FUNC_MIN = "min";
/**
* functioncall name of build-in direct map aggregate function count
*/
public static final String BUILDIN_AGGR_FUNC_COUNT = "count";
/**
* functioncall name of build-in direct map aggregate function avg
*/
public static final String BUILDIN_AGGR_FUNC_AVG = "avg";
/**
* functioncall name of build-in direct map aggregate function sum
*/
public static final String BUIDLIN_AGGR_FUNC_SUM = "sum";
@Override
public String rewriteFunctionCall(FunctionCallArgsPackage functionCallArgsPackage)
{
StringBuilder builder = new StringBuilder(ClickHouseConstants.DEAFULT_STRINGBUFFER_CAPACITY);
String arguments = RewriteUtil.joinExpressions(functionCallArgsPackage.getArgumentsList());
if (functionCallArgsPackage.getArgumentsList().isEmpty() && "count".equalsIgnoreCase(functionCallArgsPackage.getName().getSuffix())) {
arguments = "*";
}
if (functionCallArgsPackage.getIsDistinct()) {
arguments = "DISTINCT " + arguments;
}
builder.append(RewriteUtil.formatQualifiedName(functionCallArgsPackage.getName())).append('(').append(arguments);
functionCallArgsPackage.getOrderBy().ifPresent(exp -> builder.append(' ').append(exp));
builder.append(')');
functionCallArgsPackage.getFilter().ifPresent(exp -> builder.append(" FILTER ").append(exp));
functionCallArgsPackage.getWindow().ifPresent(exp -> builder.append(" OVER ").append(exp));
return builder.toString();
}
}

View File

@ -1,52 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.rewrite;
import io.prestosql.spi.type.StandardTypes;
import io.prestosql.sql.builder.functioncall.functions.base.UnsupportedFunctionCallRewriter;
import static io.hetu.core.plugin.clickhouse.rewrite.RewriteUtil.LITERAL_FUNCNAME_PREFIX;
public class ClickHouseUnsupportedFunctionCallRewriter
extends UnsupportedFunctionCallRewriter
{
/**
* functioncall name of INTERVAL_DAY_TO_SECOND literal in HeTu inner
*/
public static final String INNER_FUNC_INTERVAL_LITERAL_DAY2SEC =
LITERAL_FUNCNAME_PREFIX + StandardTypes.INTERVAL_DAY_TO_SECOND;
/**
* functioncall name of INTERVAL_YEAR_TO_MONTH literal in HeTu inner
*/
public static final String INNER_FUNC_INTERVAL_LITERAL_YEAR2MONTH =
LITERAL_FUNCNAME_PREFIX + StandardTypes.INTERVAL_YEAR_TO_MONTH;
/**
* functioncall name of TIME_WITH_TIME_ZONE literal in HeTu inner
*/
public static final String INNER_FUNC_TIME_WITH_TZ_LITERAL =
LITERAL_FUNCNAME_PREFIX + StandardTypes.TIME_WITH_TIME_ZONE;
/**
* the constructor of Unsupported Function Call Re-writer
*
* @param connectorName connector's name
*/
public ClickHouseUnsupportedFunctionCallRewriter(String connectorName)
{
super(connectorName);
}
}

View File

@ -1,77 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.rewrite;
import com.google.common.base.Joiner;
import io.prestosql.spi.sql.expression.QualifiedName;
import io.prestosql.spi.sql.expression.Selection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static java.util.stream.Collectors.joining;
/**
* util helper class for rewrite handle.
*/
public class RewriteUtil
{
private RewriteUtil()
{
}
/**
* interal function prefix name
*/
public static final String LITERAL_FUNCNAME_PREFIX = "$literal$";
/**
* expression list
*
* @param expressions expression lists
* @return sql statement
*/
public static final String joinExpressions(List<String> expressions)
{
return Joiner.on(", ").join(expressions);
}
/**
* formate identifier
*
* @param qualifiedNames qualified names
* @param identifier identifier
* @return sql statement
*/
public static final String formatIdentifier(Optional<Map<String, Selection>> qualifiedNames, String identifier)
{
if (qualifiedNames.isPresent()) {
return qualifiedNames.get().get(identifier).getExpression();
}
return identifier;
}
/**
* formate qualified name
*
* @param name qualified name
* @return sql statement
*/
public static final String formatQualifiedName(QualifiedName name)
{
return name.getParts().stream().map(identifier -> formatIdentifier(Optional.empty(), identifier)).collect(joining("."));
}
}

View File

@ -1,98 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.rewrite;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
public class UdfFunctionRewriteConstants
{
private UdfFunctionRewriteConstants()
{
}
/**
* udf rewrite pattern map
*/
public static final Map<String, String> DEFAULT_VERSION_UDF_REWRITE_PATTERNS =
new ImmutableMap.Builder<String, String>()
// Statistical aggregate functions
.put("CORR($1,$2)", "CORR($1, $2)")
.put("STDDEV($1)", "stddevSamp($1)")
.put("stddev_pop($1)", "stddev_pop($1)")
.put("stddev_samp($1)", "stddevSamp($1)")
.put("skewness($1)", "skewPop($1)")
.put("kurtosis($1)", "kurtPop($1)")
.put("VARIANCE($1)", "varSamp($1)")
.put("var_samp($1)", "varSamp($1)")
.put("APPROX_DISTINCT($1)", "uniq($1)")
.put("APPROX_DISTINCT($1,$2)", "uniq($1)")
// math functions
.put("ABS($1)", "ABS($1)")
.put("ACOS($1)", "ACOS($1)")
.put("ASIN($1)", "ASIN($1)")
.put("ATAN($1)", "ATAN($1)")
.put("ATAN2($1,$2)", "ATAN2($1, $2)")
.put("CEIL($1)", "CEIL($1)")
.put("CEILING($1)", "CEIL($1)")
.put("COS($1)", "COS($1)")
.put("e()", "e()")
.put("EXP($1)", "EXP($1)")
.put("FLOOR($1)", "FLOOR($1)")
.put("LN($1)", "LN($1)")
.put("LOG10($1)", "log10($1)")
.put("LOG2($1)", "log2($1)")
.put("MOD($1,$2)", "MOD($1, $2)")
.put("pi()", "pi()")
.put("POW($1,$2)", "POW($1, $2)")
.put("POWER($1,$2)", "POWER($1, $2)")
.put("RAND()", "RAND()")
.put("RANDOM()", "RAND()")
.put("ROUND($1)", "ROUND($1)")
.put("ROUND($1,$2)", "ROUND($1, $2)")
.put("SIGN($1)", "SIGN($1)")
.put("SIN($1)", "SIN($1)")
.put("SQRT($1)", "SQRT($1)")
.put("TAN($1)", "TAN($1)")
//character functions
.put("CONCAT($1,$2)", "CONCAT($1, $2)")
.put("LENGTH($1)", "LENGTH($1)")
.put("LOWER($1)", "LOWER($1)")
.put("LTRIM($1)", "trimLeft($1)")
.put("REPLACE($1,$2)", "replaceAll($1, $2, '')")
.put("REPLACE($1,$2,$3)", "replaceAll($1, $2, $3)")
.put("RTRIM($1)", "trimRight($1)")
.put("STRPOS($1,$2)", "position($1, $2)")
.put("SUBSTR($1,$2,$3)", "SUBSTR($1, $2, $3)")
.put("POSITION($1,$2)", "position($2, $1)")
.put("TRIM($1)", "trimBoth($1)")
.put("UPPER($1)", "UPPER($1)")
//date functions
.put("YEAR($1)", "toYear($1)")
.put("QUARTER($1)", "toQuarter($1)")
.put("MONTH($1)", "toMonth($1)")
.put("WEEK($1)", "toWeek($1)")
.put("YEAR_OF_WEEK($1)", "toISOYear($1)")
.put("DAY($1)", "toDayOfMonth($1)")
.put("HOUR($1)", "toHour($1)")
.put("MINUTE($1)", "toMinute($1)")
.put("SECOND($1)", "toSecond($1)")
.put("DAY_OF_WEEK($1)", "toDayOfWeek($1)")
.put("DAY_OF_MONTH($1)", "toDayOfMonth($1)")
.put("DAY_OF_YEAR($1)", "toDayOfYear($1)")
.put("TO_UNIXTIME($1)", "toUnixTimestamp($1)")
.build();
}

View File

@ -1,51 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse.rewrite.functioncall;
import io.hetu.core.plugin.clickhouse.rewrite.RewriteUtil;
import io.prestosql.sql.builder.functioncall.FunctionCallArgsPackage;
import io.prestosql.sql.builder.functioncall.functions.FunctionCallRewriter;
import java.util.List;
import java.util.Locale;
/**
* Clickhouse date time type conversion functions.
* The rewrite of this function limits date_parse.
*/
public class DateParseFunctionCallRewriter
implements FunctionCallRewriter
{
public static final String BUILD_IN_FUNC_DATE_PARSE = "date_parse";
@Override
public String rewriteFunctionCall(FunctionCallArgsPackage functionCallArgsPackage)
{
String functionName = RewriteUtil.formatQualifiedName(functionCallArgsPackage.getName());
if (!functionName.toLowerCase(Locale.ENGLISH).equals("date_parse") || functionCallArgsPackage.getArgumentsList().size() != 2) {
throw new UnsupportedOperationException("ClickHouse Connector does not support function call of " + RewriteUtil.formatQualifiedName(functionCallArgsPackage.getName()));
}
List<String> argsList = functionCallArgsPackage.getArgumentsList();
String args0 = argsList.get(0);
String args1 = argsList.get(1);
if (args1.equals("'%Y-%m-%d %H:%i:%s'")) {
return "toDateTime(" + args0 + ")";
}
else if (args1.equals("'%Y-%m-%d'")) {
return "toDate(" + args0 + ")";
}
return String.format("parseDateTimeBestEffort(%s)", args0);
}
}

View File

@ -1,355 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import com.google.common.collect.ImmutableSet;
import io.airlift.log.Logger;
import io.prestosql.plugin.jdbc.JdbcColumnHandle;
import io.prestosql.plugin.jdbc.JdbcIdentity;
import io.prestosql.plugin.jdbc.JdbcTableHandle;
import io.prestosql.spi.connector.ColumnMetadata;
import io.prestosql.spi.connector.ConnectorSession;
import io.prestosql.spi.connector.ConnectorTableMetadata;
import io.prestosql.spi.connector.SchemaTableName;
import io.prestosql.spi.type.IntegerType;
import io.prestosql.spi.type.Type;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static io.prestosql.testing.TestingSession.testSessionBuilder;
import static org.testng.Assert.assertEquals;
/**
* ClickHouseTest
*/
public class ClickHouseClientTest
{
private static final ConnectorSession SESSION = testSessionBuilder().build().toConnectorSession();
private static final Logger LOGGER = Logger.get(ClickHouseClientTest.class);
private DataBaseTest database;
private String catalogName;
private ClickHouseClient clickHouseClient;
private Connection connection;
private ClickHouseServerTest clickHouseServer;
private ClickHouseClientTest()
{
}
/**
* setUp
*
* @throws SQLException SQLException
*/
@BeforeClass
public void setUp()
throws SQLException
{
this.clickHouseServer = ClickHouseServerTest.getInstance();
if (!clickHouseServer.isClickHouseServerAvailable()) {
LOGGER.info("please set correct clickhouse data base info!");
throw new SkipException("skip the test");
}
LOGGER.info("running TestClickHouseClient...");
database = new DataBaseTest(clickHouseServer);
connection = database.getConnection();
catalogName = connection.getCatalog();
clickHouseClient = database.getClickHouseClient();
}
/**
* tearDown
*
* @throws SQLException SQLException
*/
@AfterClass(alwaysRun = true)
public void tearDown()
throws SQLException
{
if (this.clickHouseServer.isClickHouseServerAvailable()) {
database.close();
}
}
/**
* testCreateTable
*/
@Test(enabled = false)
public void testCreateTable()
throws SQLException
{
String tableName = "testCreateTable";
String schemaName = getNameByUpperCaseIdentifiers(database.getSchema());
JdbcIdentity identity = JdbcIdentity.from(SESSION);
SchemaTableName schemaTableName = new SchemaTableName(schemaName, tableName);
Type intType = IntegerType.INTEGER;
ColumnMetadata columnMetadata = new ColumnMetadata("col1", intType);
List<ColumnMetadata> columns = new ArrayList<>();
columns.add(columnMetadata);
ConnectorTableMetadata connectorTableMetadata = new ConnectorTableMetadata(schemaTableName, columns);
clickHouseClient.createTable(SESSION, connectorTableMetadata, tableName);
JdbcTableHandle tableHandle = clickHouseClient.getTableHandle(identity, schemaTableName).get();
clickHouseClient.dropTable(identity, tableHandle);
}
/**
* testListSchemas
*/
@Test
public void testListSchemas()
{
assertEquals(ImmutableSet.copyOf(clickHouseClient.listSchemas(connection)).contains("test"), true);
}
/**
* testGetTables
*/
@Test
public void testGetTables()
{
List<String> expectedTables = database.getTables();
List<String> allTables = getAllTables(getNameByUpperCaseIdentifiers(database.getSchema()));
List<String> actualTables = getActualTables(allTables, expectedTables);
assertEquals(actualTables, expectedTables);
}
@Test
public void testRenameTable()
{
String schemaName = getNameByUpperCaseIdentifiers(database.getSchema());
List<String> expectedTables = database.getTables();
List<String> allTables = getAllTables(schemaName);
List<String> actualTables = getActualTables(allTables, expectedTables);
assertEquals(actualTables, expectedTables);
String actualTable = database.getActualTable("number"); // get actual table number_*
String tableNumber = getNameByUpperCaseIdentifiers(actualTable);
String tableNewNumber = getNameByUpperCaseIdentifiers(actualTable.replace("number", "new_number"));
/* rename table number_* to new_number_* */
JdbcIdentity identity = JdbcIdentity.from(SESSION);
SchemaTableName newTableName = new SchemaTableName(schemaName, tableNewNumber);
clickHouseClient.renameTable(identity, null, schemaName, tableNumber, newTableName);
expectedTables.remove(3); //remove table "number_*"
expectedTables.add(actualTable.replace("number", "new_number")); //add table "new_number_*"
allTables = getAllTables(schemaName);
actualTables = getActualTables(allTables, expectedTables);
assertEquals(actualTables, expectedTables);
/* rename table new_number_* to number_* */
newTableName = new SchemaTableName(schemaName, tableNumber);
clickHouseClient.renameTable(identity, null, schemaName, tableNewNumber, newTableName);
expectedTables.remove(3); //remove table "new_number"
expectedTables.add(actualTable); //add table "number"
allTables = getAllTables(schemaName);
actualTables = getActualTables(allTables, expectedTables);
assertEquals(actualTables, expectedTables);
}
/**
* testRenameColumn
*/
@Test
public void testRenameColumn()
throws NoSuchFieldException, IllegalAccessException
{
String schemaName = getNameByUpperCaseIdentifiers(database.getSchema());
// get actual table table_with_float_col_*
String tableName = getNameByUpperCaseIdentifiers(database.getActualTable("table_with_float_col"));
List<String> expectedColumns = Arrays.asList("col1", "col2", "col3", "col4");
List<String> actualColumns = getActualColumns(schemaName, tableName);
assertEquals(actualColumns, expectedColumns);
JdbcIdentity identity = JdbcIdentity.from(SESSION);
SchemaTableName schemaTableName = new SchemaTableName(schemaName, tableName);
JdbcTableHandle tableHandle = clickHouseClient.getTableHandle(identity, schemaTableName).get();
List<JdbcColumnHandle> columns = clickHouseClient.getColumns(SESSION, tableHandle);
JdbcColumnHandle columnHandle = null;
for (JdbcColumnHandle column : columns) {
if ("col4".equalsIgnoreCase(column.getColumnName())) {
columnHandle = column;
break;
}
}
Field field = JdbcTableHandle.class.getDeclaredField("catalogName");
field.setAccessible(true);
field.set(tableHandle, null);
clickHouseClient.renameColumn(identity, tableHandle, columnHandle, "newcol4");
expectedColumns = Arrays.asList("col1", "col2", "col3", "newcol4");
actualColumns = getActualColumns(schemaName, tableName);
assertEquals(actualColumns, expectedColumns);
}
/**
* testAddColumn
*/
@Test
public void testAddColumn()
throws NoSuchFieldException, IllegalAccessException
{
String schemaName = getNameByUpperCaseIdentifiers(database.getSchema());
// get actual table student_*
String tableName = getNameByUpperCaseIdentifiers(database.getActualTable("student"));
List<String> expectedColumns = Arrays.asList("id");
List<String> actualColumns = getActualColumns(schemaName, tableName);
assertEquals(actualColumns, expectedColumns);
JdbcIdentity identity = JdbcIdentity.from(SESSION);
SchemaTableName schemaTableName = new SchemaTableName(schemaName, tableName);
JdbcTableHandle tableHandle = clickHouseClient.getTableHandle(identity, schemaTableName).get();
ColumnMetadata columnMetadata = new ColumnMetadata("name", VARCHAR);
Field field = JdbcTableHandle.class.getDeclaredField("catalogName");
field.setAccessible(true);
field.set(tableHandle, null);
clickHouseClient.addColumn(SESSION, tableHandle, columnMetadata);
expectedColumns = Arrays.asList("id", "name");
actualColumns = getActualColumns(schemaName, tableName);
assertEquals(actualColumns, expectedColumns);
}
/**
* testDropColumn
*/
@Test
public void testDropColumn()
throws NoSuchFieldException, IllegalAccessException
{
String schemaName = getNameByUpperCaseIdentifiers(database.getSchema());
String tableName = getNameByUpperCaseIdentifiers(database.getActualTable("example")); // get actual table example_*
List<String> expectedColumns = Arrays.asList("text", "text_short", "value");
List<String> actualColumns = getActualColumns(schemaName, tableName);
assertEquals(actualColumns, expectedColumns);
JdbcIdentity identity = JdbcIdentity.from(SESSION);
SchemaTableName schemaTableName = new SchemaTableName(schemaName, tableName);
JdbcTableHandle tableHandle = clickHouseClient.getTableHandle(identity, schemaTableName).get();
List<JdbcColumnHandle> columns = clickHouseClient.getColumns(SESSION, tableHandle);
JdbcColumnHandle columnHandle = null;
for (JdbcColumnHandle column : columns) {
if ("value".equalsIgnoreCase(column.getColumnName())) {
columnHandle = column;
break;
}
}
Field field = JdbcTableHandle.class.getDeclaredField("catalogName");
field.setAccessible(true);
field.set(tableHandle, null);
clickHouseClient.dropColumn(identity, tableHandle, columnHandle);
expectedColumns = Arrays.asList("text", "text_short");
actualColumns = getActualColumns(schemaName, tableName);
assertEquals(actualColumns, expectedColumns);
}
@Test(enabled = false)
public void testGetColumns()
{
}
private String getNameByUpperCaseIdentifiers(String name)
{
try {
if (connection.getMetaData().storesUpperCaseIdentifiers()) {
return name.toUpperCase(Locale.ENGLISH);
}
else {
return name;
}
}
catch (SQLException e) {
throw new RuntimeException("Failed to get metadata or storesUpperCaseIdentifiers", e);
}
}
private List<String> getAllTables(String schemaName)
{
List<String> allTables = new ArrayList<>();
try (ResultSet resultSet = clickHouseClient.getTables(connection, Optional.of(schemaName), Optional.empty())) {
while (resultSet.next()) {
String tableName = resultSet.getString("TABLE_NAME");
allTables.add(tableName.toLowerCase(Locale.ENGLISH));
}
return allTables;
}
catch (SQLException e) {
throw new RuntimeException("Failed to get tables", e);
}
}
private List<String> getActualTables(List<String> allTables, List<String> expectedTables)
{
List<String> actualTables = new ArrayList<>();
for (String table : expectedTables) {
if (allTables.contains(table)) {
actualTables.add(table);
}
}
return actualTables;
}
private List<String> getActualColumns(String schemaName, String tableName)
{
try (ResultSet resultSet = connection.getMetaData().getColumns(null, schemaName, tableName, null)) {
List<String> actualColumns = new ArrayList<>();
while (resultSet.next()) {
String columnName = resultSet.getString("COLUMN_NAME");
actualColumns.add(columnName.toLowerCase(Locale.ENGLISH));
}
return actualColumns;
}
catch (SQLException e) {
throw new RuntimeException("Failed to get metadata or columns", e);
}
}
}

View File

@ -1,75 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.Test;
import java.util.Map;
import static io.airlift.configuration.testing.ConfigAssertions.assertFullMapping;
import static org.testng.Assert.assertEquals;
/**
* This is testing ClickHouseConfig functions
*/
public class ClickHouseConfigTest
{
private static final int COMMUNICATION_TIMEOUT = 10;
private static final int PACKET_SIZE = 150000;
/**
* This is testing ClickHousePropertyMappings
*/
@Test
public void testClickHousePropertyMappings()
{
final String tableTypes = "TABLE,VIEW,USER DEFINED,SYNONYM,OLAP VIEW,JOIN VIEW,HIERARCHY VIEW" + ",CALC VIEW,SYSTEM TABLE,NO LOGGING TEMPORARY,GLOBAL TEMPORARY";
final String schemaPattern = "default";
Map<String, String> properties = new ImmutableMap.Builder<String, String>()
.put("clickhouse.table-types", tableTypes)
.put("clickhouse.schema-pattern", schemaPattern)
.put("clickhouse.query.pushdown.enabled", "false")
.put("clickhouse.socket_timeout", "100")
.build();
ClickHouseConfig expected = new ClickHouseConfig()
.setTableTypes(tableTypes)
.setSchemaPattern(schemaPattern)
.setQueryPushDownEnabled(false)
.setSocketTimeout(100);
assertFullMapping(properties, expected);
}
/**
* This is testing ClickHouseConfig class inner functions
*/
@Test
public void testGetFuncions()
{
ClickHouseConfig config = new ClickHouseConfig();
String tableTypes = config.getTableTypes();
assertEquals(tableTypes, ClickHouseConstants.DEFAULT_TABLE_TYPES);
String schemaPattern = config.getSchemaPattern();
assertEquals(schemaPattern, null);
boolean isQueryPushDown = config.isQueryPushDownEnabled();
assertEquals(isQueryPushDown, true);
}
}

View File

@ -1,27 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
public class ClickHouseConstantsTest
{
private ClickHouseConstantsTest()
{
}
/**
* "src/test/java/io/hetu/core/plugin/clickhouse/test-clickhouse-dev.properties"
*/
public static final String TEST_PROPERTY_FILE_PATH = "src/test/java/io/hetu/plugin/clickhouse/test-clickhouse-dev.properties";
}

View File

@ -1,34 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import com.google.common.collect.ImmutableMap;
import io.prestosql.spi.Plugin;
import io.prestosql.spi.connector.ConnectorFactory;
import io.prestosql.testing.TestingConnectorContext;
import org.testng.annotations.Test;
import static com.google.common.collect.Iterables.getOnlyElement;
public class ClickHousePluginTest
{
@Test
public void testCreateConnector()
{
Plugin plugin = new ClickHousePlugin();
ConnectorFactory factory = getOnlyElement(plugin.getConnectorFactories());
factory.create("test", ImmutableMap.of("connection-url", "jdbc:clickhouse://test"), new TestingConnectorContext());
}
}

View File

@ -1,221 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import io.airlift.log.Logger;
import io.airlift.tpch.TpchTable;
import javax.annotation.concurrent.GuardedBy;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static io.airlift.configuration.ConfigurationLoader.loadPropertiesFrom;
public final class ClickHouseServerTest
{
private static final Logger LOG = Logger.get(ClickHouseConstantsTest.class);
@GuardedBy("this")
private static int referenceCount;
@GuardedBy("this")
private static ClickHouseServerTest instance;
private final AtomicBoolean tpchLoaded = new AtomicBoolean(false);
private final CountDownLatch tpchLoadComplete = new CountDownLatch(1);
private static List<String> actualTables = new ArrayList<>();
private final AtomicBoolean isServerUsable = new AtomicBoolean(false);
private final AtomicInteger atomicIntegerTimes = new AtomicInteger(0);
private String jdbcUrl;
private String user;
private String password;
private String schema;
public static synchronized ClickHouseServerTest getInstance()
{
if (referenceCount == 0) {
instance = new ClickHouseServerTest();
instance.startup();
}
referenceCount++;
return instance;
}
public static synchronized void shutDown()
throws SQLException
{
referenceCount--;
if (referenceCount == 0) {
instance.shutdown();
instance = null;
}
}
private void startup()
{
for (TpchTable<?> table : TpchTable.getTables()) {
String newTable = generateNewTableName(table.getTableName());
actualTables.add(newTable);
}
}
private void shutdown()
throws SQLException
{
if (isClickHouseServerAvailable() && tpchLoaded.get()) {
for (String table : actualTables) {
String sql = "DROP TABLE " + schema + "." + table;
executeInClickHouse(sql);
}
}
}
private void executeInClickHouse(String sql)
throws SQLException
{
try (Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
Statement statement = connection.createStatement()) {
statement.execute(sql);
}
}
private ClickHouseServerTest()
{
File file = new File(ClickHouseConstantsTest.TEST_PROPERTY_FILE_PATH);
try {
Map<String, String> properties = new HashMap<>(loadPropertiesFrom(file.getPath()));
LOG.info("test-clickhouse properties: %s", properties);
String connectionUrl = properties.get("connection.url");
String connectionUser = properties.get("connection.user");
String connectionPass = properties.get("connection.password");
String connectionSchema = properties.get("connection.schema");
if (connectionUrl != null) {
this.jdbcUrl = connectionUrl;
}
if (connectionUser != null) {
this.user = connectionUser;
}
if (connectionPass != null) {
this.password = connectionPass;
}
if (connectionSchema != null) {
this.schema = connectionSchema;
}
}
catch (IOException e) {
LOG.warn("Failed to load properties for file %s", file);
}
}
public boolean isClickHouseServerAvailable()
{
if (atomicIntegerTimes.getAndIncrement() > 0) {
return isServerUsable.get();
}
try {
Connection connection = DriverManager.getConnection(this.jdbcUrl, this.user, this.password);
isServerUsable.set(true);
return isServerUsable.get();
}
catch (SQLException e) {
isServerUsable.set(false);
return isServerUsable.get();
}
}
public String getJdbcUrl()
{
return jdbcUrl;
}
public String getUser()
{
return user;
}
public String getPassword()
{
return password;
}
public String getSchema()
{
return schema;
}
public boolean isTpchLoaded()
{
return tpchLoaded.getAndSet(true);
}
public void setTpchLoaded()
{
tpchLoadComplete.countDown();
}
public void waitTpchLoaded()
throws InterruptedException
{
tpchLoadComplete.await(2, TimeUnit.MINUTES);
}
public static String generateNewTableName(String tableName)
{
return tableName + "_" + UUID.randomUUID().toString().replace("-", "");
}
public static String getActualTable(String tablePattern)
{
return getActualTable(actualTables, tablePattern);
}
public static String getActualTable(List<String> tables, String tablePattern)
{
String actualTable = tablePattern;
for (String table : tables) {
int lastIndex = table.lastIndexOf("_");
if (lastIndex == -1) {
continue;
}
if (table.substring(0, lastIndex).equalsIgnoreCase(tablePattern)) {
actualTable = tablePattern + table.substring(lastIndex);
break;
}
}
return actualTable;
}
}

View File

@ -1,145 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.clickhouse;
import io.prestosql.plugin.jdbc.BaseJdbcConfig;
import io.prestosql.plugin.jdbc.ConnectionFactory;
import io.prestosql.plugin.jdbc.DriverConnectionFactory;
import io.prestosql.spi.PrestoException;
import io.prestosql.sql.builder.functioncall.JdbcExternalFunctionHub;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static io.prestosql.plugin.jdbc.DriverConnectionFactory.basicConnectionProperties;
import static io.prestosql.plugin.jdbc.JdbcErrorCode.JDBC_ERROR;
public class DataBaseTest
implements AutoCloseable
{
private final Connection connection;
private final ClickHouseClient clickHouseClient;
private ClickHouseServerTest clickHouseServerTest;
private List<String> tables = new ArrayList<>();
/**
* constructor
*/
public DataBaseTest(ClickHouseServerTest clickHouseServer)
throws SQLException
{
this.clickHouseServerTest = clickHouseServer;
BaseJdbcConfig jdbcConfig = new BaseJdbcConfig();
ClickHouseConfig clickHouseConfig = new ClickHouseConfig();
jdbcConfig.setConnectionUrl(clickHouseServer.getJdbcUrl());
jdbcConfig.setConnectionUser(clickHouseServer.getUser());
jdbcConfig.setConnectionPassword(clickHouseServer.getPassword());
clickHouseConfig.setTableTypes("TABLE,VIEW");
clickHouseConfig.setSchemaPattern(clickHouseServer.getSchema());
clickHouseConfig.setQueryPushDownEnabled(false);
Driver driver = null;
try {
driver = (Driver) Class.forName(ClickHouseConstants.CLICKHOUSE_JDBC_DRIVER_CLASS_NAME).getConstructor(((Class<?>[]) null)).newInstance();
}
catch (InstantiationException e) {
throw new PrestoException(JDBC_ERROR, e);
}
catch (IllegalAccessException e) {
throw new PrestoException(JDBC_ERROR, e);
}
catch (ClassNotFoundException e) {
throw new PrestoException(JDBC_ERROR, e);
}
catch (InvocationTargetException e) {
throw new PrestoException(JDBC_ERROR, e);
}
catch (NoSuchMethodException e) {
throw new PrestoException(JDBC_ERROR, e);
}
ConnectionFactory connectionFactory = new DriverConnectionFactory(driver, jdbcConfig.getConnectionUrl(), Optional.ofNullable(jdbcConfig.getUserCredentialName()), Optional.ofNullable(jdbcConfig.getPasswordCredentialName()), basicConnectionProperties(jdbcConfig));
clickHouseClient = new ClickHouseClient(jdbcConfig, clickHouseConfig, connectionFactory, new JdbcExternalFunctionHub());
connection =
DriverManager.getConnection(clickHouseServer.getJdbcUrl(), clickHouseServer.getUser(), clickHouseServer.getPassword());
connection.createStatement()
.execute(buildCreateTableSql("example", "(text varchar,text_short varchar(32), value bigint)"));
connection.createStatement().execute(buildCreateTableSql("student", "(id varchar)"));
connection.createStatement()
.execute(buildCreateTableSql("table_with_float_col", "(col1 bigint, col2 double, col3 float, col4 real)"));
connection.createStatement()
.execute(buildCreateTableSql("number", "(text varchar, text_short varchar(32), value bigint)"));
}
@Override
public void close()
throws SQLException
{
for (String table : tables) {
String sql = "DROP TABLE " + clickHouseServerTest.getSchema() + "." + table;
connection.createStatement().execute(sql);
}
ClickHouseServerTest.shutDown();
}
public Connection getConnection()
{
return connection;
}
public ClickHouseClient getClickHouseClient()
{
return clickHouseClient;
}
public List<String> getTables()
{
return tables;
}
public String getSchema()
{
return clickHouseServerTest.getSchema();
}
public String getActualTable(String tablePattern)
{
return ClickHouseServerTest.getActualTable(tables, tablePattern);
}
private String buildCreateTableSql(String tableName, String columnInfo)
{
String newTableName = ClickHouseServerTest.generateNewTableName(tableName);
tables.add(newTableName);
String sql = "CREATE TABLE " + clickHouseServerTest.getSchema() + "." + newTableName + columnInfo + "engine=MergeTree() order by tuple()";
System.out.println(sql);
return sql;
}
}

View File

@ -1,10 +0,0 @@
#
# WARNING
# ^^^^^^^
# This configuration file is for development only and should NOT be used
# in production. For example configuration, see the Hetu documentation.
# please set your data source info here
connection.url=jdbc:clickhouse://localhost:8123
connection.user=default
connection.password=yourpassword
connection.schema=test

View File

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="TestGroupSuite">
<test name="GroupTest">
<classes>
<class name="io.hetu.core.plugin.clickhouse.ClickHouseConfigTest"/>
<class name="io.hetu.core.plugin.clickhouse.ClickHouseClientTest"/>
<class name="io.hetu.core.plugin.clickhouse.ClickHousePluginTest"/>
</classes>
</test>
</suite>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>io.hetu.core</groupId>
<artifactId>presto-root</artifactId>
<version>1.7.0-SNAPSHOT</version>
<version>1.2.0-SNAPSHOT</version>
</parent>
<artifactId>hetu-common</artifactId>

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -16,7 +16,6 @@ package io.hetu.core.common.util;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@ -37,7 +36,6 @@ public class SecurePathWhiteList
/**
* Due to security concerns, all data must be read from one of the whitelisted paths
*
* @return
* @throws IOException
*/
@ -55,11 +53,6 @@ public class SecurePathWhiteList
return securePathwhiteList;
}
public static boolean isSecurePath(Path absolutePath) throws IOException
{
return isSecurePath(absolutePath.toString());
}
public static boolean isSecurePath(String absolutePath) throws IOException
{
// absolutePath

View File

@ -47,6 +47,16 @@ public class SslSocketUtil
if (!tlsEnabled) {
return Optional.empty();
}
// https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#CustomizingStores
// as per link above, the default SSLContext will be constructed using the default KeyManager and
// default TrustManager. Those can be configured using the following system properties:
// javax.net.ssl.keyStore
// javax.net.ssl.keyStorePassword
// javax.net.ssl.keyStoreType
// javax.net.ssl.trustStore
// javax.net.ssl.trustStorePassword
// see link above for more details
return Optional.of(SSLContext.getDefault());
}

View File

@ -13,7 +13,6 @@
*/
package io.hetu.core.common.util;
import io.airlift.log.Logger;
import io.airlift.security.pem.PemReader;
import javax.security.auth.x500.X500Principal;
@ -30,8 +29,6 @@ import java.util.Optional;
public class TrustStore
{
private static final Logger LOGGER = Logger.get(TrustStore.class);
private TrustStore() {}
public static KeyStore loadTrustStore(File trustStorePath, Optional<String> trustStorePassword)
@ -51,7 +48,6 @@ public class TrustStore
}
}
catch (IOException | GeneralSecurityException ignored) {
LOGGER.error("loadTrustStore error : %s", ignored.getMessage());
}
try (InputStream in = new FileInputStream(trustStorePath)) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -34,9 +34,9 @@ public class TestTempFolder
root = folder.getRoot();
assertTrue(root.exists());
File newFile = folder.newFile("aNewFile");
assertEquals(newFile.getCanonicalPath(), folder.getRoot().getCanonicalPath() + "/aNewFile");
assertEquals(newFile.getAbsolutePath(), folder.getRoot().getAbsolutePath() + "/aNewFile");
File newFolder = folder.newFile("aNewFolder");
assertEquals(newFolder.getCanonicalPath(), folder.getRoot().getCanonicalPath() + "/aNewFolder");
assertEquals(newFolder.getAbsolutePath(), folder.getRoot().getAbsolutePath() + "/aNewFolder");
}
assertFalse(root.exists());
}

View File

@ -1,11 +1,11 @@
<?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">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.hetu.core</groupId>
<artifactId>presto-root</artifactId>
<version>1.7.0-SNAPSHOT</version>
<version>1.2.0-SNAPSHOT</version>
</parent>
<artifactId>hetu-cube</artifactId>

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,80 +0,0 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.spi.cube;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
public class CubeFilter
{
private final String sourceTablePredicate;
private final String cubePredicate;
@JsonCreator
public CubeFilter(
@JsonProperty("sourceTablePredicate") String sourceTablePredicate,
@JsonProperty("cubePredicate") String cubePredicate)
{
this.sourceTablePredicate = sourceTablePredicate;
this.cubePredicate = cubePredicate;
}
public CubeFilter(String sourceTablePredicate)
{
this(sourceTablePredicate, null);
}
public String getSourceTablePredicate()
{
return sourceTablePredicate;
}
public String getCubePredicate()
{
return cubePredicate;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CubeFilter that = (CubeFilter) o;
return Objects.equals(sourceTablePredicate, that.sourceTablePredicate)
&& Objects.equals(cubePredicate, that.cubePredicate);
}
@Override
public int hashCode()
{
return Objects.hash(sourceTablePredicate, cubePredicate);
}
@Override
public String toString()
{
return "CubeFilter{" +
"sourceTablePredicate='" + sourceTablePredicate + '\'' +
", cubePredicate='" + cubePredicate + '\'' +
'}';
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -56,11 +56,6 @@ public interface CubeMetadata
*/
List<String> getAggregations();
/**
* Cube selection filter
*/
CubeFilter getCubeFilter();
/**
* Return the group by columns
*/
@ -110,6 +105,11 @@ public interface CubeMetadata
*/
List<AggregationSignature> getAggregationSignatures();
/**
* Return cube predicate string
*/
String getPredicateString();
/**
* Return the status of the cube
*/

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -25,7 +25,7 @@ public interface CubeMetadataBuilder
void addGroup(Set<String> group);
void withCubeFilter(CubeFilter cubeFilter);
void withPredicate(String predicateString);
void setCubeStatus(CubeStatus cubeStatus);

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -23,6 +23,7 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
@ -30,12 +31,13 @@ import static java.util.Objects.requireNonNull;
public class CubeStatement
{
private final String from;
private final Set<String> groupBy;
private final Set<String> selection;
private final String from;
private final List<AggregationSignature> aggregations;
private final String where;
private CubeStatement(
public CubeStatement(
Set<String> selection,
String from,
Set<String> groupBy,
@ -43,6 +45,21 @@ public class CubeStatement
{
this.selection = requireNonNull(selection, "selection is null");
this.from = requireNonNull(from, "from is null");
this.where = null;
this.groupBy = requireNonNull(groupBy, "groupBy is null");
this.aggregations = requireNonNull(aggregations, "aggregations is null");
}
public CubeStatement(
Set<String> selection,
String from,
String where,
Set<String> groupBy,
List<AggregationSignature> aggregations)
{
this.selection = requireNonNull(selection, "selection is null");
this.from = requireNonNull(from, "from is null");
this.where = where;
this.groupBy = requireNonNull(groupBy, "groupBy is null");
this.aggregations = requireNonNull(aggregations, "aggregations is null");
}
@ -72,6 +89,11 @@ public class CubeStatement
return groupBy;
}
public Optional<String> getWhere()
{
return Optional.ofNullable(where);
}
@Override
public boolean equals(Object o)
{
@ -84,6 +106,7 @@ public class CubeStatement
CubeStatement that = (CubeStatement) o;
return Objects.equals(selection, that.selection) &&
Objects.equals(from, that.from) &&
Objects.equals(where, that.where) &&
Objects.equals(groupBy, that.groupBy) &&
Objects.equals(aggregations, that.aggregations);
}
@ -91,7 +114,7 @@ public class CubeStatement
@Override
public int hashCode()
{
return Objects.hash(selection, from, groupBy, aggregations);
return Objects.hash(selection, from, where, groupBy, aggregations);
}
@Override
@ -104,14 +127,21 @@ public class CubeStatement
StringJoiner groupingColumns = new StringJoiner(", ");
groupBy.forEach(groupingColumns::add);
StringBuilder whereBuilder = new StringBuilder();
if (where != null) {
whereBuilder.append(where.toString());
}
return "SELECT " + columns +
" FROM " + from +
whereBuilder.toString() +
(groupBy.isEmpty() ? "" : " GROUP BY " + groupingColumns);
}
public static class Builder
{
private String from;
private String where;
private final Set<String> groupBy = new HashSet<>();
private final Set<String> selection = new HashSet<>();
private final List<AggregationSignature> aggregations = new ArrayList<>();
@ -140,15 +170,21 @@ public class CubeStatement
return this;
}
public Builder groupByAddString(String column)
public Builder where(String where)
{
this.groupBy.add(column);
this.where = where;
return this;
}
public Builder groupByAddStringList(String... columns)
public Builder groupBy(String constraint)
{
this.groupBy.addAll(Arrays.asList(columns));
this.groupBy.add(constraint);
return this;
}
public Builder groupBy(String... constraints)
{
this.groupBy.addAll(Arrays.asList(constraints));
return this;
}
@ -157,7 +193,7 @@ public class CubeStatement
if (this.aggregations.isEmpty() && this.selection.isEmpty()) {
throw new UnsupportedOperationException("Cannot construct a cube statement without selection and aggregation");
}
return new CubeStatement(Collections.unmodifiableSet(selection), from, Collections.unmodifiableSet(groupBy), Collections.unmodifiableList(aggregations));
return new CubeStatement(Collections.unmodifiableSet(selection), from, where, Collections.unmodifiableSet(groupBy), Collections.unmodifiableList(aggregations));
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -34,8 +34,8 @@ public class TestCubeStatement
.select("name", "address", "nationkey")
.aggregate(AggregationSignature.count())
.from("tpch.tiny.customer")
.groupByAddString("address")
.groupByAddStringList("name", "nationkey")
.groupBy("address")
.groupBy("name", "nationkey")
.build();
assertEquals(statement.getFrom(), "tpch.tiny.customer", "incorrect from table");
@ -51,18 +51,21 @@ public class TestCubeStatement
.select("name", "address", "nationkey")
.aggregate(AggregationSignature.count())
.from("tpch.tiny.customer")
.where("nationkey = 123")
.build();
CubeStatement statement2 = CubeStatement.newBuilder()
.select("name", "address", "nationkey")
.aggregate(AggregationSignature.count())
.from("tpch.tiny.customer")
.where("nationkey = 123")
.build();
CubeStatement statement3 = CubeStatement.newBuilder()
.select("name", "address")
.aggregate(AggregationSignature.count())
.from("tpch.tiny.customer")
.where("nationkey = 123")
.build();
assertEquals(statement1, statement2, "statements are not equal");

View File

@ -4,7 +4,7 @@
<parent>
<groupId>io.hetu.core</groupId>
<artifactId>presto-root</artifactId>
<version>1.7.0-SNAPSHOT</version>
<version>1.2.0-SNAPSHOT</version>
</parent>
<artifactId>hetu-datacenter</artifactId>

View File

@ -55,7 +55,6 @@ public final class DataCenterColumnHandle
}
@JsonProperty
@Override
public String getColumnName()
{
return columnName;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -242,7 +242,7 @@ public class DataCenterMetadata
}
@Override
public TableStatistics getTableStatistics(ConnectorSession session, ConnectorTableHandle tableHandle, Constraint constraint, boolean includeColumnStatistics)
public TableStatistics getTableStatistics(ConnectorSession session, ConnectorTableHandle tableHandle, Constraint constraint)
{
Map<String, ColumnHandle> columnHandles = getColumnHandles(session, tableHandle);
String tableFullName = tableHandle.getSchemaPrefixedTableName();

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -56,11 +56,11 @@ public final class DataCenterTableHandle
*/
public DataCenterTableHandle(String catalogName, String schemaName, String tableName, OptionalLong limit)
{
this(catalogName,
requireNonNull(schemaName, "schemaName is null"),
requireNonNull(tableName, "tableName is null"),
requireNonNull(limit, "limit is null"),
"");
this.catalogName = catalogName;
this.schemaName = requireNonNull(schemaName, "schemaName is null");
this.tableName = requireNonNull(tableName, "tableName is null");
this.limit = requireNonNull(limit, "limit is null");
this.pushDownSql = "";
}
/**
@ -125,7 +125,6 @@ public final class DataCenterTableHandle
return new SchemaTableName(schemaName, tableName);
}
@Override
public String getSchemaPrefixedTableName()
{
return catalogName + SPLIT_DOT + schemaName + SPLIT_DOT + tableName;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -179,7 +179,7 @@ public class DataCenterPlanOptimizer
List<RowExpression> pushable = new ArrayList<>();
List<RowExpression> nonPushable = new ArrayList<>();
for (RowExpression conjunct : LogicalRowExpressions.extractConjuncts(node.getPredicate())) {
for (RowExpression conjunct : logicalRowExpressions.extractConjuncts(node.getPredicate())) {
try {
conjunct.accept(queryGenerator.getConverter(), new JdbcConverterContext());
pushable.add(conjunct);

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -116,20 +116,6 @@ public class DataCenterQueryGenerator
.setSchemaTableName(Optional.of(new SchemaTableName(dcTableHandle.getSchemaName(), dcTableHandle.getTableName())))
.setSelections(selections)
.setFrom(Optional.of(table.toString()));
String catalogName = dcTableHandle.getCatalogName();
if (catalogName != null) {
contextBuilder.setRemoteCatalogName(catalogName);
}
String schemaName = dcTableHandle.getSchemaName();
if (schemaName != null) {
contextBuilder.setRemoteSchemaName(schemaName);
}
String tableName = dcTableHandle.getTableName();
if (tableName != null) {
contextBuilder.setRemoteTablename(tableName);
}
// If LIMIT has been push down, add it to context
if (dcTableHandle.getLimit().isPresent()) {
contextBuilder.setLimit(dcTableHandle.getLimit());

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -102,10 +102,8 @@ public class DataCenterPageSource
@Override
public Page getNextPage()
{
if (dynamicFilterSupplier.isPresent() && !dynamicFilterSupplier.get().getDynamicFilters().isEmpty()) {
/* applying only for the first map in the dynamic filter since we do not have
more than one element as we do not expect disjuncts in this connector */
applyDynamicFilters(dynamicFilterSupplier.get().getDynamicFilters().get(0));
if (dynamicFilterSupplier.isPresent()) {
applyDynamicFilters(dynamicFilterSupplier.get().getDynamicFilters());
}
if (!this.pages.isEmpty()) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -1392,24 +1392,24 @@ public class TestCrossRegionDynamicFilter
hetuServer.installPlugin(new StateStoreManagerPlugin());
hetuServer.loadStateSotre();
DistributedQueryRunner distributedQueryRunner = null;
DistributedQueryRunner queryRunner = null;
try {
distributedQueryRunner = DistributedQueryRunner.builder(testSessionBuilder().build())
queryRunner = DistributedQueryRunner.builder(testSessionBuilder().build())
.setNodeCount(1)
.build();
Map<String, String> connectorProperties = new HashMap<>(properties);
connectorProperties.putIfAbsent("connection-url", hetuServer.getBaseUrl().toString());
connectorProperties.putIfAbsent("connection-user", "root");
distributedQueryRunner.installPlugin(new DataCenterPlugin());
distributedQueryRunner.createDCCatalog("dc", "dc", connectorProperties);
distributedQueryRunner.installPlugin(new TpchPlugin());
distributedQueryRunner.createCatalog("tpch", "tpch", properties);
queryRunner.installPlugin(new DataCenterPlugin());
queryRunner.createDCCatalog("dc", "dc", connectorProperties);
queryRunner.installPlugin(new TpchPlugin());
queryRunner.createCatalog("tpch", "tpch", properties);
return distributedQueryRunner;
return queryRunner;
}
catch (Throwable e) {
closeAllSuppress(e, distributedQueryRunner);
closeAllSuppress(e, queryRunner);
throw e;
}
}

View File

@ -212,31 +212,31 @@ public class TestDataCenterClient
@Test(expectedExceptions = RuntimeException.class)
public void testPasswordWithoutSSL()
{
DataCenterConfig dataCenterConfig = new DataCenterConfig().setConnectionUrl(this.baseUri)
DataCenterConfig config = new DataCenterConfig().setConnectionUrl(this.baseUri)
.setConnectionUser("root")
.setConnectionPassword("root")
.setSsl(false);
DataCenterStatementClientFactory.newHttpClient(dataCenterConfig);
DataCenterStatementClientFactory.newHttpClient(config);
}
@Test(expectedExceptions = RuntimeException.class)
public void testKerberosWithoutSSL()
{
DataCenterConfig dataCenterConfig = new DataCenterConfig().setConnectionUrl(this.baseUri)
DataCenterConfig config = new DataCenterConfig().setConnectionUrl(this.baseUri)
.setConnectionUser("root")
.setKerberosRemoteServiceName("kerberos")
.setSsl(false);
DataCenterStatementClientFactory.newHttpClient(dataCenterConfig);
DataCenterStatementClientFactory.newHttpClient(config);
}
@Test(expectedExceptions = RuntimeException.class)
public void testAccessTokenWithoutSSL()
{
DataCenterConfig dataCenterConfig = new DataCenterConfig().setConnectionUrl(this.baseUri)
DataCenterConfig config = new DataCenterConfig().setConnectionUrl(this.baseUri)
.setConnectionUser("root")
.setAccessToken("token")
.setSsl(false);
DataCenterStatementClientFactory.newHttpClient(dataCenterConfig);
DataCenterStatementClientFactory.newHttpClient(config);
}
@Test(expectedExceptions = RuntimeException.class)

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -104,6 +104,12 @@ public class TestDataCenterMetadata
return 0;
}
@Override
public boolean isLegacyTimestamp()
{
return false;
}
@Override
public <T> T getProperty(String name, Class<T> type)
{

View File

@ -1,6 +1,6 @@
# Audit Log
openLooKeng audit logging functionality is a custom event listener, which monitors the start and stop of openLooKeng cluster and the dynamic addition and deletion of nodes in the cluster; Listen to WebUi user login and exit events; Listen for query events and call when the query is created and completed (success or failure).
openLooKeng audit logging functionality is a custom event listener that is invoked for query creation and query completion (success or failure)
An audit log contains the following information:
1. time when an event occurs
@ -24,17 +24,15 @@ To enable audit logging feature, the following configs must be present in `etc/e
hetu.event.listener.type=AUDIT
hetu.event.listener.listen.query.creation=true
hetu.event.listener.listen.query.completion=true
hetu.auditlog.logoutput=/var/log/
hetu.auditlog.logconversionpattern=yyyy-MM-dd.HH
```
The following is a detailed description of audit logging properties:
Other audit logging properties include:
`hetu.event.listener.type`: property to define logging type for audit files. Allowed values are AUDIT and LOGGER.
`hetu.event.listener.audit.file`: Optional property to define absolute file path for the audit file. Ensure the process running the openLooKeng server has write access to this directory.
`hetu.auditlog.logoutput`: property to define absolute file directory for audit files. Ensure the process running the openLooKeng server has write access to this directory.
`hetu.event.listener.audit.filecount`: Optional property to define the number of files to use
`hetu.auditlog.logconversionpattern`: property to define the conversion pattern of audit files. Allowed values are yyyy-MM-dd.HH and yyyy-MM-dd.
`hetu.event.listener.audit.limit`: Optional property to define the maximum number of bytes to write to any one file
Example configuration file:
@ -43,6 +41,7 @@ event-listener.name=hetu-listener
hetu.event.listener.type=AUDIT
hetu.event.listener.listen.query.creation=true
hetu.event.listener.listen.query.completion=true
hetu.auditlog.logoutput=/var/log/
hetu.auditlog.logconversionpattern=yyyy-MM-dd.HH
hetu.event.listener.audit.file=/var/log/hetu/hetu-audit.log
hetu.event.listener.audit.filecount=1
hetu.event.listener.audit.limit=100000
```

View File

@ -1,25 +0,0 @@
#Extension Physical Execution Planner
This section describes how to add an extension physical execution planner in openLooKeng. With the extension physical execution planner, openLooKeng can utilize other operator acceleration libraries to speed up the execution of SQL statements.
##Configuration
To enable extension physical execution feature, the following configs must be added in
`config.properties`
``` properties
extension_execution_planner_enabled=true
extension_execution_planner_jar_path=file:///xxPath/omni-openLooKeng-adapter-1.6.1-SNAPSHOT.jar
extension_execution_planner_class_path=nova.hetu.olk.OmniLocalExecutionPlanner
```
The above attributes are described below:
- `extension_execution_planner_enabled`: Enable extension physical execution feature.
- `extension_execution_planner_jar_path`: Set the file path of the extension physical execution jar package.
- `extension_execution_planner_class_path`: Set the package path of extension physical execution generated class in jar。
##Usage
The below command can control the enablement of extension physical execution feature in WebUI or Cli while running openLooKeng:
```
set session extension_execution_planner_enabled=true/false
```

View File

@ -7,30 +7,30 @@ Function Namespace Managers
Introduction
------------
Function Namespace Managers support storing `external function`, and the `external functions` which register from connectors will be stored in it.
A function namespace is in the format of `catalog.schema`(For example:`mysqlfun.default`). It is only a schema for storing function, but not for storing table and view.
A function namespace is in the format of, `catalog.schema`(For example:`example.test`). It is only a schema for storing function, but not for storing table and view.
Every function in openLooKeng, no matter `built in function` or `external function`, belongs to a function namespace `catalog.schema`.
The `built in function` belong to `presto.default`. The `external function` belong to a function namespace which is supplied by the user, for example:`mysqlfun.default`.
The `built in function` belong to `presto.default`. The `external function` belong to a function namespace which is supplied by the uer, for example:`example.test`.
All of the `built in function` must be used with the function namespace omitted, for example:`select count(*) from ...`.
The `external function` must be used with a full qualified name, for example: `select mysqlfun.default.format(...) from ...`.
The `external function` must be used with a full qualified name, for example: `select example.default.format(...) from ...`.
Every instance of Function Namespace Manager related to a `catalog`, and manage all the function qualified by it.
We suggest that do not use a same name as the Connector `catalog`.
We suggest that do not use a same name as the `Connector catalog`.
Mount Function Namespace Manager Instance
------------------
If we want to mount a Function Namespace Manager Instance named `mysqlfun`, we can add a property file named `etc/function-namespace/mysqlfun.properties` which following contents:
For example ,we want to mount a Function Namespace Manager Instance named `example`, we can add a property file named `etc/function-namespace/example.properties` which following contents:
``` properties
function-namespace-manager.name=memory
supported-function-languages=JDBC
```
Now we only support Function Namespace Manager named `memory`. The function information stored in the manager will lose after we restart the openLooKeng.
The configuration property`supported-function-languages` declare function kind the function manager support. Now we only support `JDBC`.
The configuration property`supported-function-languages` declare function kind that the function manager support. Now we only support `JDBC`.
Mount Multiple Function Namespace Manager Instances
---------------------
We need to add different property files to mount multiple function namespace managers to manage different `catalog`.
We can add different property file to mount multiple function namespace managers to manage different `catalog`.
Register External Functions to Function Namespace Manager
--------------------------

View File

@ -16,7 +16,6 @@ hetu.metastore.type=jdbc
hetu.metastore.db.url=jdbc:mysql://....
hetu.metastore.db.user=root
hetu.metastore.db.password=123456
hetu.metastore.cache.type=local
```
The above properties are described below:
@ -25,7 +24,6 @@ The above properties are described below:
- `hetu.metastore.db.url`URL of RDBMS to connect to.
- `hetu.metastore.db.user` :User name of RDBMS to connect to.
- `hetu.metastore.db.password` :Password of RDBMS to connect to.
- `hetu.metastore.cache.type` : Select the cache model, where local is the local cache and global is the distributed cache.
### HDFS Storage

View File

@ -1,44 +0,0 @@
# JDBC Data Source Multi-Split Management
## Overview
This function applies to JDBC data sources. Data tables to be read are divided into multiple splits, and multiple worker nodes in the cluster simultaneously read the splits to accelerate data reading.
## Properties
Multi-split management is based on connectors. For a data table with this function enabled, add the following attributes to the configuration file of the connector to which the data table belong. For example, the configuration file corresponding to the **mysql** connector is **etc/mysql.properties**.
Property list:
Configure the properties as follows:
```properties
jdbc.table-split-enabled=true
jdbc.table-split-stepCalc-refresh-interval=10s
jdbc.table-split-stepCalc-threads=2
jdbc.table-split-fields=[{"catalogName":"test_catalog", "schemaName":null, "tableName":"test_table", "splitField":"id","dataReadOnly":"true", "calcStepEnable":"false", "splitCount":"5","fieldMinValue":"1","fieldMaxValue":"10000"},{"catalogName":"test_catalog1", "schemaName":"test_schema1", "tableName":"test_tabl1", "splitField":"id", "dataReadOnly":"false", "calcStepEnable":"true", "splitCount":"5", "fieldMinValue":"","fieldMaxValue":""}]
```
Descriptions of the properties:
- `jdbc.table-split-enabled`: whether to enable the multi-split data read function. The default value is **false**.
- `jdbc.table-split-stepCalc-refresh-interval`: interval for dynamically updating splits. The default value is 5 minutes.
- `jdbc.table-split-stepCalc-threads`: number of threads for dynamically updating splits. The default value is **4**.
- `jdbc.table-split-fields`: split configuration of each data table. For details, see section "Split Configuration".
### Split Configuration
The configuration of each data table consists of multiple sub-properties, which are set in the JSON format. The description is as follows:
> | Sub-property| Description| Suggestion|
> |----------|----------|----------|
> | `catalogName`| Name of the catalog to which the data table belongs in the data source, which corresponds to the value of the **TABLE\_CAT** field returned by the standard JDBC API **DatabaseMetaData.getTables**.| Set this sub-property to the actual value. If the value is empty, set it to **null**. |
> | `schemaName`| Name of the schema to which the data table belongs in the data source, which corresponds to the value of the **TABLE\_SCHEM** field returned by the standard JDBC API **DatabaseMetaData.getTables**.| Set this sub-property to the actual value. If the value is empty, set it to **null**. |
> | `tableName`| Name of the data table in the data source, which corresponds to the value of the **TABLE\_NAME** field returned by the standard JDBC API **DatabaseMetaData.getTables**.| Set this sub-property based on the actual value. |
> | `splitField`| Column name of the split | Select a column whose value is an integer. You are advised to select a column with fewer duplicate values to divide the column into even splits.|
> | `calcStepEnable`| Whether to dynamically adjust the split range| Set this sub-property to **true** for data tables with data changes. |
> | `dataReadOnly`| Whether the data table is read-only| Set this sub-property to **true** for read-only data tables. |
> | `splitCount`| Number of concurrent reads of data splits| Set this sub-property based on the optimal value. |
> | `fieldMinValue`| Minimum value of the **splitField** field| Set this sub-property for read-only data tables based on the query result. Otherwise, leave this sub-property empty or set it to **null**. |
> | `fieldMaxValue`| Maximum value of the **splitField** field| Set this sub-property for read-only data tables based on the query result. Otherwise, leave this sub-property empty or set it to **null**. |

View File

@ -29,12 +29,6 @@ This section describes the most important config properties that may be used to
>
> This property make exception stack trace which happen in openLooKeng visible or invisible. While it is set to be `true`, the stack trace is visible for all users. While it is set as default or `false`, the stack trace is invisible for all users.
### `openlookeng.admins`
> - **Type** `string`
> - **Default value** `No set`
>
> This property is used to set the admin user. The admin user has the authority to obtain all users query history and download all users WEB UI query results. The admin user is not set by default. When multiple admin users need to be set, use a comma to separate the multiple users.
## http security headers properties
@ -118,20 +112,6 @@ This section describes the most important config properties that may be used to
>
> This is the amount of memory set aside as headroom/buffer in the JVM heap for allocations that are not tracked by openLooKeng.
### `query.suspend-query-enabled`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Enables running query temporary suspension when system is in low resource situation.
### `query.max-suspended-queries`
> - **Type:** `integer`
> - **Default value:** `10`
>
> Maximum number of queries to attempt suspension before starting of killing the queries. This property comes in effect only if `query.suspend-query-enabled` is configured `true`
## Spilling Properties
### `experimental.spill-enabled`
@ -175,30 +155,6 @@ This section describes the most important config properties that may be used to
>
> This config property can be overridden by the `spill_window_operator` session property.
### `experimental.spill-build-for-outer-join-enabled`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Enables spill feature for right-outer and full-outer join operations.
>
>
>
> This config property can be overridden by the `spill_build_for_outer_join_enabled` session property.
### `experimental.inner-join-spill-filter-enabled`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Enables bloom filter based build-side spill matching for probe side spill decision.
>
>
>
> This config property can be overridden by the `inner_join_spill_filter_enabled` session property.
### `experimental.spill-reuse-tablescan`
> - **Type:** `boolean`
@ -217,7 +173,7 @@ This section describes the most important config properties that may be used to
>
> Directory where spilled content will be written. It can be a comma separated list to spill simultaneously to multiple directories, which helps to utilize multiple drives installed in the system.
>
> When `experimental.spiller-spill-to-hdfs` is to `true`, `experimental.spiller-spill-path` must contain only a single directory.
>
>
> It is not recommended to spill to system drives. Most importantly, do not spill to the drive on which the JVM logs are written, as disk overutilization might cause JVM to pause for lengthy periods, causing queries to fail.
@ -278,71 +234,6 @@ This section describes the most important config properties that may be used to
>
> Enables using a randomly generated secret key (per spill file) to encrypt and decrypt data spilled to disk
### `experimental.spill-direct-serde-enabled`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Enables to serialize/read the page directly to/from the stream.
### `experimental.spill-prefetch-read-pages`
> - **Type:** `integer`
> - **Default value:** `1`
>
> Sets number of pages prefetched while reading from spilled files.
### `experimental.spill-use-kryo-serialization`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Enables Kryo based serialization for spill to disk, instead of default java serializer.
### `experimental.revocable-memory-selection-threshold`
> - **Type:** `data size`
> - **Default value:** `512 MB`
>
> Sets memory selection threshold for revocable memory of operator to directly allocate revocable memory for remaining bytes ready to revoke.
### `experimental.prioritize-larger-spilts-memory-revoke`
> - **Type:** `boolean`
> - **Default value:** `true`
>
> Enables to prioritize splits with larger revocable memory.
### `experimental.spill-non-blocking-orderby`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Enables order by operator to use asynchronous mechanism to spill, i.e it can accumulate input even when a spill is in progress and initiate a secondary spill when the secondary data accumulate exceeds a threshold or when the primary spill is completed, the default value of the threshold is the minimum between 20MB and 5% of available free memory. This property must be used in conjunction with the `experimental.spill-enabled` property.
>
>
>
> This config property can be overridden by the `spill_non_blocking_orderby` session property.
### `experimental.spiller-spill-to-hdfs`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Enables spilling into HDFS. When this property is set to `true` the property `experimental.spiller-spill-profile` must be set and also `experimental.spiller-spill-path` must contain only a single path.
### `experimental.spiller-spill-profile`
> - **Type:** `string`
> - **No default value.** Must be set when spilling to hdfs is enabled
>
>
> This property defines the [filesystem](../develop/filesystem.md) profile used to spill. The corresponding profile must exist in `etc/filesystem`. For example, if this property is set as `experimental.spiller-spill-profile=spill-hdfs`, a profile describing this filesystem `spill-hdfs.properties` must be created in `etc/filesystem` with necessary information including authentication type, config, and keytabs (if applicable, refer [filesystem](../develop/filesystem.md) for details).
>
> This property is required when `experimental.spiller-spill-to-hdfs` is set to `true`. It must be included in configuration files for all coordinators and all workers. The specified file system must be accessible by all workers, and they must be able to read from and write to the path declared in `experimental.spiller-spill-path` folder in the specified file system.
## Exchange Properties
Exchanges transfer data between openLooKeng nodes for different stages of a query. Adjusting these properties may help to resolve inter-node communication issues or improve network utilization.
@ -378,6 +269,8 @@ Exchanges transfer data between openLooKeng nodes for different stages of a quer
>
> Maximum size of a response returned from an exchange request. The response will be placed in the exchange client buffer which is shared across all concurrent requests for the exchange.
>
>
>
> Increasing the value may improve network throughput if there is high latency. Decreasing the value may improve query performance for large clusters as it reduces skew due to the exchange client buffer holding responses for more tasks (rather than hold more data from fewer tasks).
### `sink.max-buffer-size`
@ -387,113 +280,6 @@ Exchanges transfer data between openLooKeng nodes for different stages of a quer
>
> Output buffer size for task data that is waiting to be pulled by upstream tasks. If the task output is hash partitioned, then the buffer will be shared across all of the partitioned consumers. Increasing this value may improve network throughput for data transferred between stages if the network has high latency or if there are many nodes in the cluster.
## Failure Recovery handling Properties
### Failure Retry Policies
### `failure.recovery.retry.profile`
> - **Type:** `String`
> - **Default value:** `default`
>
> This property defines the failure detection profile used to determine if failure has happened for a http client. The value `<profile-name>` set for this property has to correspond to `<profile-name>.properties` file in `etc/failure-retry-policy/`. In case no such profile is available, and this property is not set, "default" profile is used.
> For example, `failure.recovery.retry.profile="test"` requires `test.properties` file to be present in `etc/failure-retry-policy`.
> The file `test.properties` must contain `failure.recovery.retry.type` specified.
### `failure.recovery.retry.type`
> - **Type:** `String`
> - **Default value:** `timeout`
>
> The failure detection mechanism in use. Default is timeout based failure detection.
>
#### `timeout` based failure detection.
> Using this mechanism, HTTP client failures are retried for a specific duration before considering it as a permanent failure.
> Additional properties `max.error.duration` can be defined for this type of failure detection.
>
#### `max-retry` based failure detection.
> Using this mechanism, HTTP client failures are retried for a specific number of times before considering it as a permanent failure.
> Additional properties `max.retry.count` and `max.error.duration` can be defined for this type of failure detection.
> Using this type of failure detection is configured to be used, `max.retry.count` times retry is performed before consulting the failure detector module. When the remote node is failed as per the failure detector module, HTTP client considers it a permanent failure. Otherwise, i.e. When remote worker node is alive but not sending response, retry happens for `max.error.duration` before considering it as permanent failure.
### `max.error.duration`
> - **Type:** `duration`
> - **Default value:** `300s`
>
> The maximum amount of time coordinator waits for inter-task related errors to be resolved before it's considered a permanent failure.
### `max.retry.count`
> - **Type:** `integer`
> - **Default value:** `100`
>
> The maximum number of retry for failed task performed by the coordinator before consulting the failure detector module about the remote node status.
> This parameter is the minimum count before consulting the failure detection module. Hence, the actual number of failures may vary slightly based on the cluster size, and load on the cluster.
> This property is used only for `max-retry` based failure detection profiles.
> The minimum value for this parameter is 100.
### Gossip Protocol Configurations for Failure Detection
### `failure-detection-protocol`
>- **Type:** String
>- **Default value:** `heartbeat`
>
> This property defines the type of failure detector in use. Default configuration is `heartbeat` failure detector.
> Gossip protocol can be enabled by specifying this parameter in `config.properties` file, with the value `gossip`.
> All nodes (i.e. coordinator as well as workers) in a cluster should have this property specified in their respective `etc/config.properties` file.
### `failure-detector.heartbeat-interval`
>- **Type:** Duration
>- **Default value:** `500ms` (500 miliseconds)
>
> This is the interval of gossip between two nodes in the cluster.
> In gossip protocol, two workers are expected to gossip with higher frequency than the coordinator and a worker.
> In `config.properties` for the coordinator, this property can be set with a reasonably higher value, such as `5s` (5 seconds).
> In workers, this property can be left to use the default value.
>
### `failure-detector.worker-gossip-probe-interval`
>
> - **Type:** Duration
>- **Default value:** `5s` (5 seconds)
>
> Gossip protocol uses monitoring tasks (same as the heartbeat failure detector) to keep tab on the other nodes.
> This property specifies the interval of refreshing the monitoring tasks to trigger worker to worker gossip.
> This property, if needed to be configured with any other value than the default, should be specified only for the worker nodes.
> This parameter should have higher value than `failure-detector.heartbeat-interval`.
>
### `failure-detector.coordinator-gossip-probe-interval`
>
> - **Type:** Duration
>- **Default value:** `5s` (5 seconds)
>
> Gossip protocol uses monitoring tasks (same as the heartbeat failure detector) to keep tab on the other nodes.
> This property specifies the interval of refreshing the monitoring tasks to trigger coordinator to worker gossip.
> This property, if needed to be configured with any other value than the default, should be specified only for the coordinator.
> This parameter should have higher value than `failure-detector.heartbeat-interval` and `failure-detector.worker-gossip-probe-interval`.
>
### `failure-detector.coordinator-gossip-collate-interval`
>
> - **Type:** Duration
>- **Default value:** `2s` (2 seconds)
>
> This property specifies the interval in which the coordinator collates all the gossips it obtained from all the workers.
> This property has to be specified only for the coordinator.
> This parameter should have higher value than `failure-detector.heartbeat-interval`.
>
### `failure-detector.gossip-group-size`
>
> - **Type:** Integer
>- **Default value:** `Integer.MAX_VALUE`
>
> A worker should gossip with how many other workers in the cluster, is defined by this parameter.
> Any value higher than the cluster-size (i.e. the number of workers) implies all-to-all gossip.
> To keep the network overhead low, this value should be reasonably low for a big cluster (e.g. 10 for a cluster size of 100).
> On each refresh of the worker-monitoring tasks at the coordinator, the coordinator defines the list of worker URIs of size `failure-detector.gossip-group-size` to trigger worker-to-worker gossip.
## Task Properties
### `task.concurrency`
@ -695,8 +481,6 @@ Exchanges transfer data between openLooKeng nodes for different stages of a quer
>
> Use Reuse Exchange to cache data in memory if the query contains tables or Common Table Expressions(CTE) which are present more than one time with the same projections and filters on them. Enabling this feature will reduce the time taken to execute the query by caching data in memory and avoiding reading from disk multiple times.
> This can also be specified on a per-query basis using the `reuse_table_scan` session property.
>
> Note: when `cte_reuse_enabled` or `optimizer.cte-reuse-enabled` is enabled reuse exchange will be disabled.
### `optimizer.cte-reuse-enabled`
@ -707,25 +491,6 @@ Exchanges transfer data between openLooKeng nodes for different stages of a quer
> This will help to improve query execution performance when same CTE is used more than once.
> This can also be specified on a per-query basis using the `cte_reuse_enabled` session property.
### `optimizer.sort-based-aggregation-enabled`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Sort based aggregation is used when underlying source is in pre-sorted order, this is used instead of Hash aggregation which take more footprint to build hash tables.
> Sort based aggregation used less memory foot print when compared to hash aggregation.
> Conditions when Sort based aggregation in case of Hive
> - 1) Grouping columns should be same or less than sorted columns and it should be in the same order.
> - 2) Joins case probe side table should be sorted and join criteria should be same or less than sorted columns and it should be in the same order.
> - 3) bucket_count is 1 bucketed_by columns should be same or less than Grouping columns and it should be in the same order.
> - 4) bucket_count is more than 1 bucketed_by columns should be same as Grouping columns and it should be in the same order.
> - 5) In case of partition table, Grouping columns should contain all partitions in same order following by the subset of sorted by columns.
> - 6) When distinct is used, Grouping columns followed by a distinct column should be subset of sorted by columns.
>
> This can also be specified on a per-query basis using the `sort_based_aggregation_enabled` session property.
>
> **Note:** This is supported only for Hive connector.
## Regular Expression Function Properties
The following properties allow tuning the [regexp](../functions/regexp.md).
@ -878,7 +643,7 @@ helps with cache affinity scheduling.
> Auto-Vacuum enables the system to automatically manage vacuum jobs by constantly monitoring the tables which needs vacuum in order to maintain optimal performance.
> Engine gets the tables from data sources that are eligible for vacuum and trigger vacuum operation for those tables.
### `auto-vacuum.enabled`
### `auto-vacuum.enabled:`
> - **Type:** `boolean`
> - **Default value:** `false`
@ -927,118 +692,39 @@ helps with cache affinity scheduling.
>
> **Note:** This should be configured in all workers.
## Sort Base aggregation Properties
### `sort.prcnt-drivers-for-partial-aggr`
> - **Type:** `int`
> - **Default value:** `5`
>
> In Sort based aggregation percentage of number of drivers that are used for unfinalized/partial values.
> This can also be specified on a per-query basis using the `prcnt_drivers_for_partial_aggr` session property.
>
> **Note:** This should be configured on all nodes .
## Query Manager
### `query.remote-task.max-error-duration`
> - **Type:** `duration`
> - **Default value:** `5m`
>
> The maximum time coordinator waits for remote-task related error to be resolved before it's considered a failure.
>
> Note:
> For snapshot recovery `query.remote-task.max-error-duration` should be greater than `exchange.max-error-duration`.
## Query Recovery
### `recovery_enabled`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> This session property is used to enable or disable the recovery framework, which enables to restart/resume the query in case of failure.
## Distributed Snapshot
### `snapshot_enabled`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> This session property is enabled to capture snapshots during query execution, when recovery framework is enabled. Without recovery framework enabled this flag has no significance
> This session property is used to enable or disable the distributed snapshot functionality.
### `hetu.experimental.snapshot.profile`
> - **Type:** `string`
>
> This property defines the [filesystem](../develop/filesystem.md) profile used to stored snapshots. The corresponding profile must exist in `etc/filesystem`. For example, if this property is set as `hetu.experimental.snapshot.profile=snapshot-hdfs1`, a profile describing this filesystem `snapshot-hdfs1.properties` must be created in `etc/filesystem` with necessary information including authentication type, config, and keytabs (if applicable). Please refer to the [filesystem](../develop/filesystem.md) section for details.
> This property defines the file system profile used to stored snapshots. The corresponding profile must exist in `etc/filesystem`. For example, if this property is set as `hetu.experimental.snapshot.profile=snapshot-hdfs1`, a profile describing this filesystem `snapshot-hdfs1.properties` must be created in `etc/filesystem` with necessary information including authentication type, config, and keytabs (if applicable).
>
> This property is required if any query is executed with distributed snapshot turned on. It must be included in configuration files for all coordinators and all workers. The specified file system must be accessible by all workers, and they must be able to read from and write to the `/tmp/hetu/snapshot` folder in the specified file system.
>
> This is an experimental property. In the future it may be allowed to store snapshots in non-file-system locations, e.g. in a connector.
### `hetu.recovery.maxRetries`
### `hetu.snapshot.maxRetries`
> - **Type:** `int`
> - **Default value:** `10`
>
> This property defines the maximum number of error recovery attempts for a query. When the limit is reached, the query fails.
> This property defines the maxinum number of error recovery attempts for a query. When the limit is reached, the query fails.
>
> This can also be specified on a per-query basis using the `recovery_max_retries` session property.
> This can also be specified on a per-query basis using the `snapshot_max_retries` session property.
### `hetu.recovery.retryTimeout`
### `hetu.snapshot.retryTimeout`
> - **Type:** `duration`
> - **Default value:** `10m` (10 minutes)
>
> This property defines the maximum amount of time for the system to wait until all tasks are successfully restored. If any task is not ready within this timeout, then the recovery attempt is considered a failure, and the query will try to resume from an earlier snapshot if available.
> This property defines the maxinum amount of time for the system to wait until all tasks are successfully restored. If any task is not ready within this timeout, then the recovery attempt is considered a failure, and the query will try to resume from an earlier snapshot if available.
>
> This can also be specified on a per-query basis using the `recovery_retry_timeout` session property.
### `hetu.snapshot.useKryoSerialization`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Enables Kryo based serialization for snapshot, instead of default java serializer.
### `experimental.eliminate-duplicate-spill-files`
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Enables elimination of duplicate spill files storage as part of snapshot capture.
## HTTP Client Configurations
### `http.client.idle-timeout`
> - **Type:** `duration`
> - **Default value:** `30s` (30 seconds)
>
> This property defines the time for which a given http client shall stay connected without any operations performed over it.
> After the specified time elapse with no activity, then the client connection is closed and related resources are released.
>
> (Note: this parameter should be configured with higher time when in high load environment)
### `http.client.request-timeout`
> - **Type:** `duration`
> - **Default value:** `10s` (10 seconds)
>
> This property defines the time threshold for a given http client for which response should be received.
> After the configured time elapsed and no response received, then client connection consider that to be failure in submission of request.
>
> (Note: this parameter should be configured with higher time when in high load environment)
## Connector Properties configuration
### `case-insensitive-name-matching`
>
> - **Type:** `boolean`
> - **Default value:** `false`
>
> Case-insensitive matching between database and collection names. The default is case sensitive.
> This can also be specified on a per-query basis using the `snapshot_retry_timeout` session property.

Some files were not shown because too many files have changed in this diff Show More