You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2020/05/15 14:29:40 UTC

[GitHub] [flink] wuchong opened a new pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

wuchong opened a new pull request #12178:
URL: https://github.com/apache/flink/pull/12178


   
   <!--
   *Thank you very much for contributing to Apache Flink - we are happy that you want to help us improve Flink. To help the community review your contribution in the best possible way, please go through the checklist below, which will get the contribution into a shape in which it can be best reviewed.*
   
   *Please understand that we do not do this to make contributions to Flink a hassle. In order to uphold a high standard of quality for code contributions, while at the same time managing a large number of contributions, we need contributors to prepare the contributions well, and give reviewers enough contextual information for the review. Please also understand that contributions that do not follow this guide will take longer to review and thus typically be picked up with lower priority by the community.*
   
   ## Contribution Checklist
   
     - Make sure that the pull request corresponds to a [JIRA issue](https://issues.apache.org/jira/projects/FLINK/issues). Exceptions are made for typos in JavaDoc or documentation files, which need no JIRA issue.
     
     - Name the pull request in the form "[FLINK-XXXX] [component] Title of the pull request", where *FLINK-XXXX* should be replaced by the actual issue number. Skip *component* if you are unsure about which is the best component.
     Typo fixes that have no associated JIRA issue should be named following this pattern: `[hotfix] [docs] Fix typo in event time introduction` or `[hotfix] [javadocs] Expand JavaDoc for PuncuatedWatermarkGenerator`.
   
     - Fill out the template below to describe the changes contributed by the pull request. That will give reviewers the context they need to do the review.
     
     - Make sure that the change passes the automated tests, i.e., `mvn clean verify` passes. You can set up Travis CI to do that following [this guide](https://flink.apache.org/contributing/contribute-code.html#open-a-pull-request).
   
     - Each pull request should address only one issue, not mix up code from multiple issues.
     
     - Each commit in the pull request has a meaningful commit message (including the JIRA id)
   
     - Once all items of the checklist are addressed, remove the above text and this checklist, leaving only the filled out template below.
   
   
   **(The sections below can be removed for hotfixes of typos)**
   -->
   
   ## What is the purpose of the change
   
   Add new hbase connector implementation which uses new interfaces proposed by FLIP-95, e.g. DynamicTableSource, DynamicTableSink, and Factory.
   
   ## Brief change log
   
   - New `HBaseDynamicTableSource` and new `HBaseDynamicTableSink`.
   - New `HBaseDynamicTableFactory` which uses new connector options proposed by FLIP-122.
   - We reuses the implementation of `HBaseLookupFunction`.
   - Added `HBaseSerde` to support runtime conversion between `RowData` and HBase mutation.
   
   ## Verifying this change
   
   - Added `HBaseDynamicTableFactory` to unit test factory
   - Added new connector test in `HBaseConnectorITCase`
   
   
   ## Does this pull request potentially affect one of the following parts:
   
     - Dependencies (does it add or upgrade a dependency): (yes / **no**)
     - The public API, i.e., is any changed class annotated with `@Public(Evolving)`: (yes / **no**)
     - The serializers: (yes / **no** / don't know)
     - The runtime per-record code paths (performance sensitive): (yes / **no** / don't know)
     - Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Yarn/Mesos, ZooKeeper: (yes / **no** / don't know)
     - The S3 file system connector: (yes / **no** / don't know)
   
   ## Documentation
   
     - Does this pull request introduce a new feature? (yes / **no**)
     - If yes, how is the feature documented? (**not applicable** / docs / JavaDocs / not documented)
   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629283346


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455",
       "triggerID" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "triggerType" : "PUSH"
     }, {
       "hash" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1502",
       "triggerID" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "triggerType" : "PUSH"
     }, {
       "hash" : "1b75f1a3cdb3b9fb726c57bfe38d967eb9e60360",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1545",
       "triggerID" : "1b75f1a3cdb3b9fb726c57bfe38d967eb9e60360",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 963b94b236ed3760422a16e466f66bfc615e9312 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1502) 
   * 1b75f1a3cdb3b9fb726c57bfe38d967eb9e60360 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1545) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot commented on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629271621


   Thanks a lot for your contribution to the Apache Flink project. I'm the @flinkbot. I help the community
   to review your pull request. We will use this comment to track the progress of the review.
   
   
   ## Automated Checks
   Last check on commit 5634098665a7f8ed379d7c48a36146145fa58067 (Fri May 15 14:38:25 UTC 2020)
   
   **Warnings:**
    * No documentation files were touched! Remember to keep the Flink docs up to date!
   
   
   <sub>Mention the bot in a comment to re-run the automated checks.</sub>
   ## Review Progress
   
   * ❓ 1. The [description] looks good.
   * ❓ 2. There is [consensus] that the contribution should go into to Flink.
   * ❓ 3. Needs [attention] from.
   * ❓ 4. The change fits into the overall [architecture].
   * ❓ 5. Overall code [quality] is good.
   
   Please see the [Pull Request Review Guide](https://flink.apache.org/contributing/reviewing-prs.html) for a full explanation of the review process.<details>
    The Bot is tracking the review progress through labels. Labels are applied according to the order of the review items. For consensus, approval by a Flink committer of PMC member is required <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot approve description` to approve one or more aspects (aspects: `description`, `consensus`, `architecture` and `quality`)
    - `@flinkbot approve all` to approve all aspects
    - `@flinkbot approve-until architecture` to approve everything until `architecture`
    - `@flinkbot attention @username1 [@username2 ..]` to require somebody's attention
    - `@flinkbot disapprove architecture` to remove an approval you gave earlier
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] wuchong commented on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
wuchong commented on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629634627


   Added validate() and tests 


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot commented on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629283346


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 5634098665a7f8ed379d7c48a36146145fa58067 UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629283346


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455",
       "triggerID" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "triggerType" : "PUSH"
     }, {
       "hash" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 5634098665a7f8ed379d7c48a36146145fa58067 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455) 
   * 963b94b236ed3760422a16e466f66bfc615e9312 UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] rmetzger commented on a change in pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
rmetzger commented on a change in pull request #12178:
URL: https://github.com/apache/flink/pull/12178#discussion_r431074053



##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/source/HBaseRowDataInputFormat.java
##########
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase.source;
+
+import org.apache.flink.api.common.io.InputFormat;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.hbase.util.HBaseSerde;
+import org.apache.flink.connector.hbase.util.HBaseTableSchema;
+import org.apache.flink.table.data.RowData;
+
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.TableNotFoundException;
+import org.apache.hadoop.hbase.client.Connection;
+import org.apache.hadoop.hbase.client.ConnectionFactory;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+/**
+ * {@link InputFormat} subclass that wraps the access for HTables. Returns the result as {@link RowData}
+ */
+public class HBaseRowDataInputFormat extends AbstractTableInputFormat<RowData> {
+	private static final long serialVersionUID = 1L;
+	private static final Logger LOG = LoggerFactory.getLogger(HBaseRowDataInputFormat.class);
+
+	private final String tableName;
+	private final HBaseTableSchema schema;
+	private final String nullStringLiteral;
+
+	private transient HBaseSerde serde;
+
+	private transient org.apache.hadoop.conf.Configuration conf;
+
+	public HBaseRowDataInputFormat(
+			org.apache.hadoop.conf.Configuration conf,
+			String tableName,
+			HBaseTableSchema schema,
+			String nullStringLiteral) {
+		this.tableName = tableName;
+		this.conf = conf;
+		this.schema = schema;
+		this.nullStringLiteral = nullStringLiteral;
+	}
+
+	@Override
+	public void configure(Configuration parameters) {
+		LOG.info("Initializing HBase configuration.");
+		this.serde = new HBaseSerde(schema, nullStringLiteral);
+		connectToTable();
+		if (table != null) {
+			scan = getScanner();
+		}
+	}
+
+	@Override
+	protected Scan getScanner() {
+		return serde.createScan();
+	}
+
+	@Override
+	public String getTableName() {
+		return tableName;
+	}
+
+	@Override
+	protected RowData mapResultToOutType(Result res) {
+		return serde.convertToRow(res);
+	}
+
+	private void connectToTable() {
+
+		if (this.conf == null) {
+			this.conf = HBaseConfiguration.create();

Review comment:
       For context: https://issues.apache.org/jira/browse/FLINK-17968




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] wuchong commented on a change in pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
wuchong commented on a change in pull request #12178:
URL: https://github.com/apache/flink/pull/12178#discussion_r426120819



##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/sink/HBaseDynamicTableSink.java
##########
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase.sink;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.connector.hbase.options.HBaseOptions;
+import org.apache.flink.connector.hbase.options.HBaseWriteOptions;
+import org.apache.flink.connector.hbase.util.HBaseTableSchema;
+import org.apache.flink.table.connector.ChangelogMode;
+import org.apache.flink.table.connector.sink.DynamicTableSink;
+import org.apache.flink.table.connector.sink.SinkFunctionProvider;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.types.RowKind;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.HConstants;
+
+/**
+ * HBase table sink implementation.
+ */
+@Internal
+public class HBaseDynamicTableSink implements DynamicTableSink {
+
+	private final HBaseTableSchema hbaseTableSchema;
+	private final HBaseOptions hbaseOptions;
+	private final HBaseWriteOptions writeOptions;
+
+	public HBaseDynamicTableSink(
+			HBaseTableSchema hbaseTableSchema,
+			HBaseOptions hbaseOptions,
+			HBaseWriteOptions writeOptions) {
+		this.hbaseTableSchema = hbaseTableSchema;
+		this.hbaseOptions = hbaseOptions;
+		this.writeOptions = writeOptions;
+	}
+
+	@Override
+	public SinkRuntimeProvider getSinkRuntimeProvider(Context context) {
+		Configuration hbaseClientConf = HBaseConfiguration.create();
+		hbaseClientConf.set(HConstants.ZOOKEEPER_QUORUM, hbaseOptions.getZkQuorum());
+		hbaseOptions.getZkNodeParent().ifPresent(v -> hbaseClientConf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, v));
+		HBaseSinkFunction<RowData> sinkFunction = new HBaseSinkFunction<>(
+			hbaseOptions.getTableName(),
+			hbaseClientConf,
+			new RowDataToMutationConverter(hbaseTableSchema),
+			writeOptions.getBufferFlushMaxSizeInBytes(),
+			writeOptions.getBufferFlushMaxRows(),
+			writeOptions.getBufferFlushIntervalMillis());
+		return SinkFunctionProvider.of(sinkFunction);
+	}
+
+	@Override
+	public ChangelogMode getChangelogMode(ChangelogMode requestedMode) {
+		// UPSERT mode
+		ChangelogMode.Builder builder = ChangelogMode.newBuilder();
+		for (RowKind kind : requestedMode.getContainedKinds()) {
+			if (kind != RowKind.UPDATE_BEFORE) {
+				builder.addContainedKind(kind);

Review comment:
       We discussed about adding more utilities into `ChangelogMode`, but at last, we want to keep the `ChangelogMode` clean and simple at the first stage. 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629283346


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455",
       "triggerID" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 5634098665a7f8ed379d7c48a36146145fa58067 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] wuchong commented on a change in pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
wuchong commented on a change in pull request #12178:
URL: https://github.com/apache/flink/pull/12178#discussion_r426120300



##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/util/HBaseSerde.java
##########
@@ -0,0 +1,371 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase.util;
+
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.LogicalType;
+
+import org.apache.hadoop.hbase.client.Delete;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.util.Bytes;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.util.Arrays;
+
+import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getPrecision;
+import static org.apache.flink.util.Preconditions.checkArgument;
+
+/**
+ * Utilities for HBase serialization and deserialization.
+ */
+public class HBaseSerde implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+	private static final byte[] EMPTY_BYTES = new byte[]{};
+
+	// row key index in output row
+	private final int rowkeyIndex;
+
+	// family keys
+	private final byte[][] families;
+	// qualifier keys
+	private final byte[][][] qualifiers;
+
+	private final int fieldLength;
+
+	private GenericRowData reusedRow;
+	private GenericRowData[] reusedFamilyRows;
+
+	private final FieldEncoder keyEncoder;
+	private final FieldDecoder keyDecoder;
+	private final FieldEncoder[][] qualifierEncoders;
+	private final FieldDecoder[][] qualifierDecoders;
+
+	public HBaseSerde(HBaseTableSchema hbaseSchema) {
+		this.families = hbaseSchema.getFamilyKeys();
+		this.rowkeyIndex = hbaseSchema.getRowKeyIndex();
+		LogicalType rowkeyType = hbaseSchema.getRowKeyDataType().map(DataType::getLogicalType).orElse(null);
+
+		// field length need take row key into account if it exists.
+		checkArgument(rowkeyIndex != -1 && rowkeyType != null, "row key is not set.");
+		this.fieldLength = families.length + 1;
+
+		// prepare output rows
+		this.reusedRow = new GenericRowData(fieldLength);
+		this.reusedFamilyRows = new GenericRowData[families.length];
+
+		// row key should never be null
+		this.keyEncoder = createFieldEncoder(rowkeyType);
+		this.keyDecoder = createFieldDecoder(rowkeyType);
+
+		this.qualifiers = new byte[families.length][][];
+		this.qualifierEncoders = new FieldEncoder[families.length][];
+		this.qualifierDecoders = new FieldDecoder[families.length][];
+		String[] familyNames = hbaseSchema.getFamilyNames();
+		for (int f = 0; f < families.length; f++) {
+			this.qualifiers[f] = hbaseSchema.getQualifierKeys(familyNames[f]);
+			DataType[] dataTypes = hbaseSchema.getQualifierDataTypes(familyNames[f]);
+			this.qualifierEncoders[f] = Arrays.stream(dataTypes)
+				.map(DataType::getLogicalType)
+				.map(HBaseSerde::createNullableFieldEncoder)
+				.toArray(FieldEncoder[]::new);
+			this.qualifierDecoders[f] = Arrays.stream(dataTypes)
+				.map(DataType::getLogicalType)
+				.map(HBaseSerde::createNullableFieldDecoder)
+				.toArray(FieldDecoder[]::new);
+			this.reusedFamilyRows[f] = new GenericRowData(dataTypes.length);
+		}
+	}
+
+	/**
+	 * Returns an instance of Put that writes record to HBase table.
+	 *
+	 * @return The appropriate instance of Put for this use case.
+	 */
+	public @Nullable Put createPutMutation(RowData row) {
+		byte[] rowkey = keyEncoder.encode(row, rowkeyIndex);
+		if (rowkey.length == 0) {
+			// drop dirty records, rowkey shouldn't be zero length
+			return null;
+		}
+		// upsert
+		Put put = new Put(rowkey);
+		for (int i = 0; i < fieldLength; i++) {
+			if (i != rowkeyIndex) {
+				int f = i > rowkeyIndex ? i - 1 : i;
+				// get family key
+				byte[] familyKey = families[f];
+				RowData familyRow = row.getRow(i, qualifiers[f].length);
+				for (int q = 0; q < this.qualifiers[f].length; q++) {
+					// get quantifier key
+					byte[] qualifier = qualifiers[f][q];
+					// serialize value
+					byte[] value = qualifierEncoders[f][q].encode(familyRow, q);
+					put.addColumn(familyKey, qualifier, value);
+				}
+			}
+		}
+		return put;
+	}
+
+	/**
+	 * Returns an instance of Delete that remove record from HBase table.
+	 *
+	 * @return The appropriate instance of Delete for this use case.
+	 */
+	public @Nullable Delete createDeleteMutation(RowData row) {
+		byte[] rowkey = keyEncoder.encode(row, rowkeyIndex);
+		if (rowkey.length == 0) {
+			// drop dirty records, rowkey shouldn't be zero length
+			return null;

Review comment:
       I don't think we should throw exception here by default. Otherwise, it's meaningless to add this condition. IMO, this is a behavior of the storage (not accept empty key). If there is a need to see the exception, we can add an option in the future.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629283346


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455",
       "triggerID" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "triggerType" : "PUSH"
     }, {
       "hash" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1502",
       "triggerID" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 5634098665a7f8ed379d7c48a36146145fa58067 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455) 
   * 963b94b236ed3760422a16e466f66bfc615e9312 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1502) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629283346


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455",
       "triggerID" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "triggerType" : "PUSH"
     }, {
       "hash" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1502",
       "triggerID" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "triggerType" : "PUSH"
     }, {
       "hash" : "1b75f1a3cdb3b9fb726c57bfe38d967eb9e60360",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1545",
       "triggerID" : "1b75f1a3cdb3b9fb726c57bfe38d967eb9e60360",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 1b75f1a3cdb3b9fb726c57bfe38d967eb9e60360 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1545) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] wuchong commented on a change in pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
wuchong commented on a change in pull request #12178:
URL: https://github.com/apache/flink/pull/12178#discussion_r431550017



##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/source/HBaseRowDataInputFormat.java
##########
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase.source;
+
+import org.apache.flink.api.common.io.InputFormat;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.hbase.util.HBaseSerde;
+import org.apache.flink.connector.hbase.util.HBaseTableSchema;
+import org.apache.flink.table.data.RowData;
+
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.TableNotFoundException;
+import org.apache.hadoop.hbase.client.Connection;
+import org.apache.hadoop.hbase.client.ConnectionFactory;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+/**
+ * {@link InputFormat} subclass that wraps the access for HTables. Returns the result as {@link RowData}
+ */
+public class HBaseRowDataInputFormat extends AbstractTableInputFormat<RowData> {
+	private static final long serialVersionUID = 1L;
+	private static final Logger LOG = LoggerFactory.getLogger(HBaseRowDataInputFormat.class);
+
+	private final String tableName;
+	private final HBaseTableSchema schema;
+	private final String nullStringLiteral;
+
+	private transient HBaseSerde serde;
+
+	private transient org.apache.hadoop.conf.Configuration conf;
+
+	public HBaseRowDataInputFormat(
+			org.apache.hadoop.conf.Configuration conf,
+			String tableName,
+			HBaseTableSchema schema,
+			String nullStringLiteral) {
+		this.tableName = tableName;
+		this.conf = conf;
+		this.schema = schema;
+		this.nullStringLiteral = nullStringLiteral;
+	}
+
+	@Override
+	public void configure(Configuration parameters) {
+		LOG.info("Initializing HBase configuration.");
+		this.serde = new HBaseSerde(schema, nullStringLiteral);
+		connectToTable();
+		if (table != null) {
+			scan = getScanner();
+		}
+	}
+
+	@Override
+	protected Scan getScanner() {
+		return serde.createScan();
+	}
+
+	@Override
+	public String getTableName() {
+		return tableName;
+	}
+
+	@Override
+	protected RowData mapResultToOutType(Result res) {
+		return serde.convertToRow(res);
+	}
+
+	private void connectToTable() {
+
+		if (this.conf == null) {
+			this.conf = HBaseConfiguration.create();

Review comment:
       Yes. FLINK-17932 also reported this. We should fix it. 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] danny0405 commented on a change in pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
danny0405 commented on a change in pull request #12178:
URL: https://github.com/apache/flink/pull/12178#discussion_r426141506



##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/HBaseDynamicTableFactory.java
##########
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase;
+
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.ConfigOptions;
+import org.apache.flink.configuration.MemorySize;
+import org.apache.flink.connector.hbase.options.HBaseOptions;
+import org.apache.flink.connector.hbase.options.HBaseWriteOptions;
+import org.apache.flink.connector.hbase.sink.HBaseDynamicTableSink;
+import org.apache.flink.connector.hbase.source.HBaseDynamicTableSource;
+import org.apache.flink.connector.hbase.util.HBaseTableSchema;
+import org.apache.flink.table.api.TableSchema;
+import org.apache.flink.table.connector.sink.DynamicTableSink;
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.factories.DynamicTableSinkFactory;
+import org.apache.flink.table.factories.DynamicTableSourceFactory;
+import org.apache.flink.table.factories.FactoryUtil.TableFactoryHelper;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.HConstants;
+
+import java.time.Duration;
+import java.util.HashSet;
+import java.util.Set;
+
+import static org.apache.flink.table.factories.FactoryUtil.createTableFactoryHelper;
+
+/**
+ * HBase connector factory.
+ */
+public class HBaseDynamicTableFactory implements DynamicTableSourceFactory, DynamicTableSinkFactory {
+
+	private static final String IDENTIFIER = "hbase-1.4";
+
+	private static final ConfigOption<String> TABLE_NAME = ConfigOptions
+		.key("table-name")
+		.stringType()
+		.noDefaultValue()
+		.withDescription("Required. It defines the HBase table name.");
+
+	private static final ConfigOption<String> ZOOKEEPER_QUORUM = ConfigOptions
+		.key("zookeeper.quorum")
+		.stringType()
+		.noDefaultValue()
+		.withDescription("Required. It defines HBase Zookeeper quorum.");
+
+	private static final ConfigOption<String> ZOOKEEPER_ZNODE_PARENT = ConfigOptions
+		.key("zookeeper.znode-parent")
+		.stringType()
+		.defaultValue("/hbase")
+		.withDescription("Optional. The root dir in Zookeeper for HBase cluster, default value is '/hbase'");
+
+	private static final ConfigOption<String> NULL_STRING_LITERAL = ConfigOptions
+		.key("null-string-literal")
+		.stringType()
+		.defaultValue("null")
+		.withDescription("Optional. Representation for null values for string fields. (\"null\" by default). " +
+			"HBase connector encode/decode empty bytes as null values except string types.");
+
+	private static final ConfigOption<MemorySize> SINK_BUFFER_FLUSH_MAX_SIZE = ConfigOptions
+		.key("sink.buffer-flush.max-size")
+		.memoryType()
+		.defaultValue(MemorySize.parse("2mb"))
+		.withDescription("Optional. Writing option, determines how many size in memory of " +
+			"buffered rows to insert per round trip. This can help performance on writing " +
+			"to JDBC database. The default value is '2mb'.");
+
+	private static final ConfigOption<Integer> SINK_BUFFER_FLUSH_MAX_ROWS = ConfigOptions
+		.key("sink.buffer-flush.max-rows")
+		.intType()
+		.noDefaultValue()
+		.withDescription("Optional. Writing option, determines how many rows to insert " +
+			"per round trip. This can help performance on writing to JDBC database. " +
+			"No default value, i.e. the default flushing is not depends on the number of buffered rows.");
+
+	private static final ConfigOption<Duration> SINK_BUFFER_FLUSH_INTERVAL = ConfigOptions
+		.key("sink.buffer-flush.interval")
+		.durationType()
+		.noDefaultValue()
+		.withDescription("Optional. Writing option, sets a flush interval flushing " +
+			"buffered requesting if the interval passes, in milliseconds. Default value is '0s', " +
+			"which means no asynchronous flush thread will be scheduled.");
+
+	@Override
+	public DynamicTableSource createDynamicTableSource(Context context) {
+		TableFactoryHelper helper = createTableFactoryHelper(this, context);
+		String hTableName = helper.getOptions().get(TABLE_NAME);
+		// create default configuration from current runtime env (`hbase-site.xml` in classpath) first,
+		Configuration hbaseClientConf = HBaseConfiguration.create();

Review comment:
       `helper.validate()` ?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] wuchong closed pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
wuchong closed pull request #12178:
URL: https://github.com/apache/flink/pull/12178


   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629283346


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455",
       "triggerID" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 5634098665a7f8ed379d7c48a36146145fa58067 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] flinkbot edited a comment on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629283346


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "status" : "FAILURE",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455",
       "triggerID" : "5634098665a7f8ed379d7c48a36146145fa58067",
       "triggerType" : "PUSH"
     }, {
       "hash" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1502",
       "triggerID" : "963b94b236ed3760422a16e466f66bfc615e9312",
       "triggerType" : "PUSH"
     }, {
       "hash" : "1b75f1a3cdb3b9fb726c57bfe38d967eb9e60360",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "1b75f1a3cdb3b9fb726c57bfe38d967eb9e60360",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 5634098665a7f8ed379d7c48a36146145fa58067 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1455) 
   * 963b94b236ed3760422a16e466f66bfc615e9312 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=1502) 
   * 1b75f1a3cdb3b9fb726c57bfe38d967eb9e60360 UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] wuchong commented on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
wuchong commented on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629591752


   Resolve conflicts and address comments. 


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] wuchong commented on pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
wuchong commented on pull request #12178:
URL: https://github.com/apache/flink/pull/12178#issuecomment-629662994


   The failed case is KafkaProducerTestBase.testExactlyOnce which is a known issue.
   
   Merging this one...


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] rmetzger commented on a change in pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
rmetzger commented on a change in pull request #12178:
URL: https://github.com/apache/flink/pull/12178#discussion_r431073634



##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/source/HBaseRowDataInputFormat.java
##########
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase.source;
+
+import org.apache.flink.api.common.io.InputFormat;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.hbase.util.HBaseSerde;
+import org.apache.flink.connector.hbase.util.HBaseTableSchema;
+import org.apache.flink.table.data.RowData;
+
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.TableNotFoundException;
+import org.apache.hadoop.hbase.client.Connection;
+import org.apache.hadoop.hbase.client.ConnectionFactory;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+/**
+ * {@link InputFormat} subclass that wraps the access for HTables. Returns the result as {@link RowData}
+ */
+public class HBaseRowDataInputFormat extends AbstractTableInputFormat<RowData> {
+	private static final long serialVersionUID = 1L;
+	private static final Logger LOG = LoggerFactory.getLogger(HBaseRowDataInputFormat.class);
+
+	private final String tableName;
+	private final HBaseTableSchema schema;
+	private final String nullStringLiteral;
+
+	private transient HBaseSerde serde;
+
+	private transient org.apache.hadoop.conf.Configuration conf;
+
+	public HBaseRowDataInputFormat(
+			org.apache.hadoop.conf.Configuration conf,
+			String tableName,
+			HBaseTableSchema schema,
+			String nullStringLiteral) {
+		this.tableName = tableName;
+		this.conf = conf;
+		this.schema = schema;
+		this.nullStringLiteral = nullStringLiteral;
+	}
+
+	@Override
+	public void configure(Configuration parameters) {
+		LOG.info("Initializing HBase configuration.");
+		this.serde = new HBaseSerde(schema, nullStringLiteral);
+		connectToTable();
+		if (table != null) {
+			scan = getScanner();
+		}
+	}
+
+	@Override
+	protected Scan getScanner() {
+		return serde.createScan();
+	}
+
+	@Override
+	public String getTableName() {
+		return tableName;
+	}
+
+	@Override
+	protected RowData mapResultToOutType(Result res) {
+		return serde.convertToRow(res);
+	}
+
+	private void connectToTable() {
+
+		if (this.conf == null) {
+			this.conf = HBaseConfiguration.create();

Review comment:
       Is it possible that we are always in this case, because `this.conf` is transient?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] wuchong commented on a change in pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
wuchong commented on a change in pull request #12178:
URL: https://github.com/apache/flink/pull/12178#discussion_r426120337



##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/util/HBaseSerde.java
##########
@@ -0,0 +1,371 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase.util;
+
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.LogicalType;
+
+import org.apache.hadoop.hbase.client.Delete;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.util.Bytes;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.util.Arrays;
+
+import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getPrecision;
+import static org.apache.flink.util.Preconditions.checkArgument;
+
+/**
+ * Utilities for HBase serialization and deserialization.
+ */
+public class HBaseSerde implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+	private static final byte[] EMPTY_BYTES = new byte[]{};
+
+	// row key index in output row
+	private final int rowkeyIndex;
+
+	// family keys
+	private final byte[][] families;
+	// qualifier keys
+	private final byte[][][] qualifiers;
+
+	private final int fieldLength;
+
+	private GenericRowData reusedRow;
+	private GenericRowData[] reusedFamilyRows;
+
+	private final FieldEncoder keyEncoder;
+	private final FieldDecoder keyDecoder;
+	private final FieldEncoder[][] qualifierEncoders;
+	private final FieldDecoder[][] qualifierDecoders;
+
+	public HBaseSerde(HBaseTableSchema hbaseSchema) {
+		this.families = hbaseSchema.getFamilyKeys();
+		this.rowkeyIndex = hbaseSchema.getRowKeyIndex();
+		LogicalType rowkeyType = hbaseSchema.getRowKeyDataType().map(DataType::getLogicalType).orElse(null);
+
+		// field length need take row key into account if it exists.
+		checkArgument(rowkeyIndex != -1 && rowkeyType != null, "row key is not set.");
+		this.fieldLength = families.length + 1;
+
+		// prepare output rows
+		this.reusedRow = new GenericRowData(fieldLength);
+		this.reusedFamilyRows = new GenericRowData[families.length];
+
+		// row key should never be null
+		this.keyEncoder = createFieldEncoder(rowkeyType);
+		this.keyDecoder = createFieldDecoder(rowkeyType);
+
+		this.qualifiers = new byte[families.length][][];
+		this.qualifierEncoders = new FieldEncoder[families.length][];
+		this.qualifierDecoders = new FieldDecoder[families.length][];
+		String[] familyNames = hbaseSchema.getFamilyNames();
+		for (int f = 0; f < families.length; f++) {
+			this.qualifiers[f] = hbaseSchema.getQualifierKeys(familyNames[f]);
+			DataType[] dataTypes = hbaseSchema.getQualifierDataTypes(familyNames[f]);
+			this.qualifierEncoders[f] = Arrays.stream(dataTypes)
+				.map(DataType::getLogicalType)
+				.map(HBaseSerde::createNullableFieldEncoder)
+				.toArray(FieldEncoder[]::new);
+			this.qualifierDecoders[f] = Arrays.stream(dataTypes)
+				.map(DataType::getLogicalType)
+				.map(HBaseSerde::createNullableFieldDecoder)
+				.toArray(FieldDecoder[]::new);
+			this.reusedFamilyRows[f] = new GenericRowData(dataTypes.length);
+		}
+	}
+
+	/**
+	 * Returns an instance of Put that writes record to HBase table.
+	 *
+	 * @return The appropriate instance of Put for this use case.
+	 */
+	public @Nullable Put createPutMutation(RowData row) {
+		byte[] rowkey = keyEncoder.encode(row, rowkeyIndex);
+		if (rowkey.length == 0) {
+			// drop dirty records, rowkey shouldn't be zero length
+			return null;
+		}
+		// upsert
+		Put put = new Put(rowkey);
+		for (int i = 0; i < fieldLength; i++) {
+			if (i != rowkeyIndex) {
+				int f = i > rowkeyIndex ? i - 1 : i;
+				// get family key
+				byte[] familyKey = families[f];
+				RowData familyRow = row.getRow(i, qualifiers[f].length);
+				for (int q = 0; q < this.qualifiers[f].length; q++) {
+					// get quantifier key
+					byte[] qualifier = qualifiers[f][q];
+					// serialize value
+					byte[] value = qualifierEncoders[f][q].encode(familyRow, q);
+					put.addColumn(familyKey, qualifier, value);
+				}
+			}
+		}
+		return put;
+	}
+
+	/**
+	 * Returns an instance of Delete that remove record from HBase table.
+	 *
+	 * @return The appropriate instance of Delete for this use case.
+	 */
+	public @Nullable Delete createDeleteMutation(RowData row) {
+		byte[] rowkey = keyEncoder.encode(row, rowkeyIndex);
+		if (rowkey.length == 0) {
+			// drop dirty records, rowkey shouldn't be zero length
+			return null;
+		}
+		// delete
+		Delete delete = new Delete(rowkey);
+		for (int i = 0; i < fieldLength; i++) {
+			if (i != rowkeyIndex) {
+				int f = i > rowkeyIndex ? i - 1 : i;
+				// get family key
+				byte[] familyKey = families[f];
+				for (int q = 0; q < this.qualifiers[f].length; q++) {
+					// get quantifier key
+					byte[] qualifier = qualifiers[f][q];
+					delete.addColumn(familyKey, qualifier);
+				}
+			}
+		}
+		return delete;
+	}
+
+	/**
+	 * Returns an instance of Scan that retrieves the required subset of records from the HBase table.
+	 *
+	 * @return The appropriate instance of Scan for this use case.
+	 */
+	public Scan createScan() {
+		Scan scan = new Scan();
+		for (int f = 0; f < families.length; f++) {
+			byte[] family = families[f];
+			for (int q = 0; q < qualifiers[f].length; q++) {
+				byte[] quantifier = qualifiers[f][q];
+				scan.addColumn(family, quantifier);
+			}
+		}
+		return scan;
+	}
+
+	/**
+	 * Converts HBase {@link Result} into {@link RowData}.
+	 */
+	public RowData convertToRow(Result result) {
+		Object rowkey = keyDecoder.decode(result.getRow());
+		for (int i = 0; i < fieldLength; i++) {
+			if (rowkeyIndex == i) {
+				reusedRow.setField(rowkeyIndex, rowkey);
+			} else {
+				int f = (rowkeyIndex != -1 && i > rowkeyIndex) ? i - 1 : i;
+				// get family key
+				byte[] familyKey = families[f];
+				GenericRowData familyRow = reusedFamilyRows[f];
+				for (int q = 0; q < this.qualifiers[f].length; q++) {
+					// get quantifier key
+					byte[] qualifier = qualifiers[f][q];
+					// read value
+					byte[] value = result.getValue(familyKey, qualifier);
+					familyRow.setField(q, qualifierDecoders[f][q].decode(value));
+				}
+				reusedRow.setField(i, familyRow);
+			}
+		}
+		return reusedRow;
+	}
+
+	// ------------------------------------------------------------------------------------
+	// HBase Runtime Encoders
+	// ------------------------------------------------------------------------------------
+
+	/**
+	 * Runtime encoder that encodes a specified field in {@link RowData} into byte[].
+	 */
+	@FunctionalInterface
+	private interface FieldEncoder extends Serializable {
+		byte[] encode(RowData row, int pos);
+	}
+
+	private static FieldEncoder createNullableFieldEncoder(LogicalType fieldType) {
+		final FieldEncoder encoder = createFieldEncoder(fieldType);
+		if (fieldType.isNullable()) {
+			return (row, pos) -> {
+				if (row.isNullAt(pos)) {
+					return EMPTY_BYTES;
+				} else {

Review comment:
       I will use "null" which is also used in elasticsearch `null-key-literal`.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [flink] danny0405 commented on a change in pull request #12178: [FLINK-17028][hbase] Introduce a new HBase connector with new property keys

Posted by GitBox <gi...@apache.org>.
danny0405 commented on a change in pull request #12178:
URL: https://github.com/apache/flink/pull/12178#discussion_r426112993



##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/sink/HBaseDynamicTableSink.java
##########
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase.sink;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.connector.hbase.options.HBaseOptions;
+import org.apache.flink.connector.hbase.options.HBaseWriteOptions;
+import org.apache.flink.connector.hbase.util.HBaseTableSchema;
+import org.apache.flink.table.connector.ChangelogMode;
+import org.apache.flink.table.connector.sink.DynamicTableSink;
+import org.apache.flink.table.connector.sink.SinkFunctionProvider;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.types.RowKind;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.HConstants;
+
+/**
+ * HBase table sink implementation.
+ */
+@Internal
+public class HBaseDynamicTableSink implements DynamicTableSink {
+
+	private final HBaseTableSchema hbaseTableSchema;
+	private final HBaseOptions hbaseOptions;
+	private final HBaseWriteOptions writeOptions;
+
+	public HBaseDynamicTableSink(
+			HBaseTableSchema hbaseTableSchema,
+			HBaseOptions hbaseOptions,
+			HBaseWriteOptions writeOptions) {
+		this.hbaseTableSchema = hbaseTableSchema;
+		this.hbaseOptions = hbaseOptions;
+		this.writeOptions = writeOptions;
+	}
+
+	@Override
+	public SinkRuntimeProvider getSinkRuntimeProvider(Context context) {
+		Configuration hbaseClientConf = HBaseConfiguration.create();
+		hbaseClientConf.set(HConstants.ZOOKEEPER_QUORUM, hbaseOptions.getZkQuorum());
+		hbaseOptions.getZkNodeParent().ifPresent(v -> hbaseClientConf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, v));
+		HBaseSinkFunction<RowData> sinkFunction = new HBaseSinkFunction<>(
+			hbaseOptions.getTableName(),
+			hbaseClientConf,
+			new RowDataToMutationConverter(hbaseTableSchema),
+			writeOptions.getBufferFlushMaxSizeInBytes(),
+			writeOptions.getBufferFlushMaxRows(),
+			writeOptions.getBufferFlushIntervalMillis());
+		return SinkFunctionProvider.of(sinkFunction);
+	}
+
+	@Override
+	public ChangelogMode getChangelogMode(ChangelogMode requestedMode) {
+		// UPSERT mode
+		ChangelogMode.Builder builder = ChangelogMode.newBuilder();
+		for (RowKind kind : requestedMode.getContainedKinds()) {
+			if (kind != RowKind.UPDATE_BEFORE) {
+				builder.addContainedKind(kind);

Review comment:
       Maybe we can have some utils like `ChangelogMode.exclude(RowKind)`, many upserts sink would reuse that.

##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/util/HBaseSerde.java
##########
@@ -0,0 +1,371 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase.util;
+
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.LogicalType;
+
+import org.apache.hadoop.hbase.client.Delete;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.util.Bytes;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.util.Arrays;
+
+import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getPrecision;
+import static org.apache.flink.util.Preconditions.checkArgument;
+
+/**
+ * Utilities for HBase serialization and deserialization.
+ */
+public class HBaseSerde implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+	private static final byte[] EMPTY_BYTES = new byte[]{};
+
+	// row key index in output row
+	private final int rowkeyIndex;
+
+	// family keys
+	private final byte[][] families;
+	// qualifier keys
+	private final byte[][][] qualifiers;
+
+	private final int fieldLength;
+
+	private GenericRowData reusedRow;
+	private GenericRowData[] reusedFamilyRows;
+
+	private final FieldEncoder keyEncoder;
+	private final FieldDecoder keyDecoder;
+	private final FieldEncoder[][] qualifierEncoders;
+	private final FieldDecoder[][] qualifierDecoders;
+
+	public HBaseSerde(HBaseTableSchema hbaseSchema) {
+		this.families = hbaseSchema.getFamilyKeys();
+		this.rowkeyIndex = hbaseSchema.getRowKeyIndex();
+		LogicalType rowkeyType = hbaseSchema.getRowKeyDataType().map(DataType::getLogicalType).orElse(null);
+
+		// field length need take row key into account if it exists.
+		checkArgument(rowkeyIndex != -1 && rowkeyType != null, "row key is not set.");
+		this.fieldLength = families.length + 1;
+
+		// prepare output rows
+		this.reusedRow = new GenericRowData(fieldLength);
+		this.reusedFamilyRows = new GenericRowData[families.length];
+
+		// row key should never be null
+		this.keyEncoder = createFieldEncoder(rowkeyType);
+		this.keyDecoder = createFieldDecoder(rowkeyType);
+
+		this.qualifiers = new byte[families.length][][];
+		this.qualifierEncoders = new FieldEncoder[families.length][];
+		this.qualifierDecoders = new FieldDecoder[families.length][];
+		String[] familyNames = hbaseSchema.getFamilyNames();
+		for (int f = 0; f < families.length; f++) {
+			this.qualifiers[f] = hbaseSchema.getQualifierKeys(familyNames[f]);
+			DataType[] dataTypes = hbaseSchema.getQualifierDataTypes(familyNames[f]);
+			this.qualifierEncoders[f] = Arrays.stream(dataTypes)
+				.map(DataType::getLogicalType)
+				.map(HBaseSerde::createNullableFieldEncoder)
+				.toArray(FieldEncoder[]::new);
+			this.qualifierDecoders[f] = Arrays.stream(dataTypes)
+				.map(DataType::getLogicalType)
+				.map(HBaseSerde::createNullableFieldDecoder)
+				.toArray(FieldDecoder[]::new);
+			this.reusedFamilyRows[f] = new GenericRowData(dataTypes.length);
+		}
+	}
+
+	/**
+	 * Returns an instance of Put that writes record to HBase table.
+	 *
+	 * @return The appropriate instance of Put for this use case.
+	 */
+	public @Nullable Put createPutMutation(RowData row) {
+		byte[] rowkey = keyEncoder.encode(row, rowkeyIndex);
+		if (rowkey.length == 0) {
+			// drop dirty records, rowkey shouldn't be zero length
+			return null;
+		}
+		// upsert
+		Put put = new Put(rowkey);
+		for (int i = 0; i < fieldLength; i++) {
+			if (i != rowkeyIndex) {
+				int f = i > rowkeyIndex ? i - 1 : i;
+				// get family key
+				byte[] familyKey = families[f];
+				RowData familyRow = row.getRow(i, qualifiers[f].length);
+				for (int q = 0; q < this.qualifiers[f].length; q++) {
+					// get quantifier key
+					byte[] qualifier = qualifiers[f][q];
+					// serialize value
+					byte[] value = qualifierEncoders[f][q].encode(familyRow, q);
+					put.addColumn(familyKey, qualifier, value);
+				}
+			}
+		}
+		return put;
+	}
+
+	/**
+	 * Returns an instance of Delete that remove record from HBase table.
+	 *
+	 * @return The appropriate instance of Delete for this use case.
+	 */
+	public @Nullable Delete createDeleteMutation(RowData row) {
+		byte[] rowkey = keyEncoder.encode(row, rowkeyIndex);
+		if (rowkey.length == 0) {
+			// drop dirty records, rowkey shouldn't be zero length
+			return null;

Review comment:
       Should we throw here ?

##########
File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/util/HBaseSerde.java
##########
@@ -0,0 +1,371 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.flink.connector.hbase.util;
+
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.LogicalType;
+
+import org.apache.hadoop.hbase.client.Delete;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.util.Bytes;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.util.Arrays;
+
+import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getPrecision;
+import static org.apache.flink.util.Preconditions.checkArgument;
+
+/**
+ * Utilities for HBase serialization and deserialization.
+ */
+public class HBaseSerde implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+	private static final byte[] EMPTY_BYTES = new byte[]{};
+
+	// row key index in output row
+	private final int rowkeyIndex;
+
+	// family keys
+	private final byte[][] families;
+	// qualifier keys
+	private final byte[][][] qualifiers;
+
+	private final int fieldLength;
+
+	private GenericRowData reusedRow;
+	private GenericRowData[] reusedFamilyRows;
+
+	private final FieldEncoder keyEncoder;
+	private final FieldDecoder keyDecoder;
+	private final FieldEncoder[][] qualifierEncoders;
+	private final FieldDecoder[][] qualifierDecoders;
+
+	public HBaseSerde(HBaseTableSchema hbaseSchema) {
+		this.families = hbaseSchema.getFamilyKeys();
+		this.rowkeyIndex = hbaseSchema.getRowKeyIndex();
+		LogicalType rowkeyType = hbaseSchema.getRowKeyDataType().map(DataType::getLogicalType).orElse(null);
+
+		// field length need take row key into account if it exists.
+		checkArgument(rowkeyIndex != -1 && rowkeyType != null, "row key is not set.");
+		this.fieldLength = families.length + 1;
+
+		// prepare output rows
+		this.reusedRow = new GenericRowData(fieldLength);
+		this.reusedFamilyRows = new GenericRowData[families.length];
+
+		// row key should never be null
+		this.keyEncoder = createFieldEncoder(rowkeyType);
+		this.keyDecoder = createFieldDecoder(rowkeyType);
+
+		this.qualifiers = new byte[families.length][][];
+		this.qualifierEncoders = new FieldEncoder[families.length][];
+		this.qualifierDecoders = new FieldDecoder[families.length][];
+		String[] familyNames = hbaseSchema.getFamilyNames();
+		for (int f = 0; f < families.length; f++) {
+			this.qualifiers[f] = hbaseSchema.getQualifierKeys(familyNames[f]);
+			DataType[] dataTypes = hbaseSchema.getQualifierDataTypes(familyNames[f]);
+			this.qualifierEncoders[f] = Arrays.stream(dataTypes)
+				.map(DataType::getLogicalType)
+				.map(HBaseSerde::createNullableFieldEncoder)
+				.toArray(FieldEncoder[]::new);
+			this.qualifierDecoders[f] = Arrays.stream(dataTypes)
+				.map(DataType::getLogicalType)
+				.map(HBaseSerde::createNullableFieldDecoder)
+				.toArray(FieldDecoder[]::new);
+			this.reusedFamilyRows[f] = new GenericRowData(dataTypes.length);
+		}
+	}
+
+	/**
+	 * Returns an instance of Put that writes record to HBase table.
+	 *
+	 * @return The appropriate instance of Put for this use case.
+	 */
+	public @Nullable Put createPutMutation(RowData row) {
+		byte[] rowkey = keyEncoder.encode(row, rowkeyIndex);
+		if (rowkey.length == 0) {
+			// drop dirty records, rowkey shouldn't be zero length
+			return null;
+		}
+		// upsert
+		Put put = new Put(rowkey);
+		for (int i = 0; i < fieldLength; i++) {
+			if (i != rowkeyIndex) {
+				int f = i > rowkeyIndex ? i - 1 : i;
+				// get family key
+				byte[] familyKey = families[f];
+				RowData familyRow = row.getRow(i, qualifiers[f].length);
+				for (int q = 0; q < this.qualifiers[f].length; q++) {
+					// get quantifier key
+					byte[] qualifier = qualifiers[f][q];
+					// serialize value
+					byte[] value = qualifierEncoders[f][q].encode(familyRow, q);
+					put.addColumn(familyKey, qualifier, value);
+				}
+			}
+		}
+		return put;
+	}
+
+	/**
+	 * Returns an instance of Delete that remove record from HBase table.
+	 *
+	 * @return The appropriate instance of Delete for this use case.
+	 */
+	public @Nullable Delete createDeleteMutation(RowData row) {
+		byte[] rowkey = keyEncoder.encode(row, rowkeyIndex);
+		if (rowkey.length == 0) {
+			// drop dirty records, rowkey shouldn't be zero length
+			return null;
+		}
+		// delete
+		Delete delete = new Delete(rowkey);
+		for (int i = 0; i < fieldLength; i++) {
+			if (i != rowkeyIndex) {
+				int f = i > rowkeyIndex ? i - 1 : i;
+				// get family key
+				byte[] familyKey = families[f];
+				for (int q = 0; q < this.qualifiers[f].length; q++) {
+					// get quantifier key
+					byte[] qualifier = qualifiers[f][q];
+					delete.addColumn(familyKey, qualifier);
+				}
+			}
+		}
+		return delete;
+	}
+
+	/**
+	 * Returns an instance of Scan that retrieves the required subset of records from the HBase table.
+	 *
+	 * @return The appropriate instance of Scan for this use case.
+	 */
+	public Scan createScan() {
+		Scan scan = new Scan();
+		for (int f = 0; f < families.length; f++) {
+			byte[] family = families[f];
+			for (int q = 0; q < qualifiers[f].length; q++) {
+				byte[] quantifier = qualifiers[f][q];
+				scan.addColumn(family, quantifier);
+			}
+		}
+		return scan;
+	}
+
+	/**
+	 * Converts HBase {@link Result} into {@link RowData}.
+	 */
+	public RowData convertToRow(Result result) {
+		Object rowkey = keyDecoder.decode(result.getRow());
+		for (int i = 0; i < fieldLength; i++) {
+			if (rowkeyIndex == i) {
+				reusedRow.setField(rowkeyIndex, rowkey);
+			} else {
+				int f = (rowkeyIndex != -1 && i > rowkeyIndex) ? i - 1 : i;
+				// get family key
+				byte[] familyKey = families[f];
+				GenericRowData familyRow = reusedFamilyRows[f];
+				for (int q = 0; q < this.qualifiers[f].length; q++) {
+					// get quantifier key
+					byte[] qualifier = qualifiers[f][q];
+					// read value
+					byte[] value = result.getValue(familyKey, qualifier);
+					familyRow.setField(q, qualifierDecoders[f][q].decode(value));
+				}
+				reusedRow.setField(i, familyRow);
+			}
+		}
+		return reusedRow;
+	}
+
+	// ------------------------------------------------------------------------------------
+	// HBase Runtime Encoders
+	// ------------------------------------------------------------------------------------
+
+	/**
+	 * Runtime encoder that encodes a specified field in {@link RowData} into byte[].
+	 */
+	@FunctionalInterface
+	private interface FieldEncoder extends Serializable {
+		byte[] encode(RowData row, int pos);
+	}
+
+	private static FieldEncoder createNullableFieldEncoder(LogicalType fieldType) {
+		final FieldEncoder encoder = createFieldEncoder(fieldType);
+		if (fieldType.isNullable()) {
+			return (row, pos) -> {
+				if (row.isNullAt(pos)) {
+					return EMPTY_BYTES;
+				} else {

Review comment:
       For string, use a 'N/A' seems better which has no conflicts with empty string `""`.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org