Copilot commented on code in PR #162:
URL: https://github.com/apache/hbase-connectors/pull/162#discussion_r3885914856


##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseScanBuilder.scala:
##########
@@ -0,0 +1,87 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.hbase.spark.Logging
+import org.apache.spark.sql.connector.read.{Scan, ScanBuilder, 
SupportsPushDownFilters, SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.yetus.audience.InterfaceAudience
+import scala.collection.mutable.ListBuffer
+
+/**
+ * This is a new class in the spark4 module.
+ * Implements ScanBuilder, SupportsPushDownFilters, and 
SupportsPushDownRequiredColumns.
+ * This is where Catalyst negotiates with the connector. Spark calls 
pushFilters() with
+ * candidate predicates and the builder accepts what it can handle and returns 
the rest.
+ * Spark calls pruneColumns() to say which columns it actually needs.
+ * Then build() produces the final scan plan.
+ *
+ * In the spark 3 V1 model, this negotiation happened implicitly via
+ * PrunedFilteredScan.buildScan(requiredColumns, filters) as a single method 
call with no back-and-forth.
+ *
+ * @param schema
+ * @param properties
+ */
[email protected]
+class HBaseScanBuilder(schema: StructType, properties: Map[String, String])
+    extends ScanBuilder
+    with SupportsPushDownFilters
+    with SupportsPushDownRequiredColumns
+    with Logging {
+
+  private val catalog = HBaseTableCatalog(properties)
+  private val encoderClsName =
+    properties.getOrElse(HBaseSparkConf.QUERY_ENCODER, 
HBaseSparkConf.DEFAULT_QUERY_ENCODER)
+  @transient private val encoder = JavaBytesEncoder.create(encoderClsName)
+
+  private var _pushedFilters: Array[Filter] = Array.empty
+  private var requiredSchema: StructType = schema
+
+  override def pushFilters(filters: Array[Filter]): Array[Filter] = {

Review Comment:
   When `hbase.spark.pushdown.columnfilter=false`, these filters are still 
reported to Spark as fully handled, but `HBasePartitionReader` deliberately 
installs no server-side filter. Non-row-key predicates are then never 
evaluated, so filtered queries return unfiltered rows. Return all filters as 
unsupported (or implement client-side evaluation) when pushdown is disabled.



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseBatch.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.spark.{HBaseConnectionCache, Logging}
+import org.apache.spark.sql.connector.read.{Batch, InputPartition, 
PartitionReaderFactory}
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.yetus.audience.InterfaceAudience
+
+/**
+ * This is a new class in the spark4 module. Implements Batch.
+ * Responsible for physical planning: splits the read into partitions.
+ * Calls RegionLocator.getStartEndKeys() to discover HBase regions,
+ * intersects them with the row key filter's scan ranges, and produces an 
array of InputPartition objects.
+ *
+ * In the spark 3 DS V1 model, this logic was inside 
HBaseTableScanRDD.getPartitions().
+ *
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param rowKeyFilter
+ * @param pushedFilters
+ * @param encoderClsName
+ */
[email protected]
+class HBaseBatch(
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    rowKeyFilter: RowKeyFilter,
+    pushedFilters: Array[Filter],
+    encoderClsName: String)
+    extends Batch
+    with Logging {
+
+  override def planInputPartitions(): Array[InputPartition] = {
+    val conf = HBaseConfiguration.create()
+    val configResources = properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION)
+    configResources.foreach(_.split(",").foreach(r => conf.addResource(new 
Path(r))))
+
+    val connection = HBaseConnectionCache.getConnection(conf)
+    try {
+      val tableName = s"${catalog.namespace}:${catalog.name}"
+      val regionLocator = 
connection.getRegionLocator(TableName.valueOf(tableName))
+      try {
+        val keys = regionLocator.getStartEndKeys
+        val startKeys = keys.getFirst
+        val endKeys = keys.getSecond
+
+        val regions = startKeys.zip(endKeys).zipWithIndex.map { case ((start, 
end), idx) =>
+          HBaseRegion(idx, Some(start), Some(end))
+        }
+
+        val scanRanges = rowKeyFilter.ranges.toSeq
+        val points = rowKeyFilter.points.toSeq
+
+        if (scanRanges.isEmpty && points.isEmpty) {
+          regions.map { region =>
+            HBaseInputPartition(
+              region.index,
+              region.start.orNull,
+              region.end.orNull): InputPartition
+          }
+        } else {
+          regions.flatMap { region =>
+            val regionRange = Range(region)
+            val intersectedRanges = Ranges.and(regionRange, scanRanges.map { 
sr =>
+              Range(
+                Option(sr.lowerBound).filter(_.nonEmpty).map(Bound(_, 
sr.isLowerBoundEqualTo)),
+                Option(sr.upperBound).map(Bound(_, sr.isUpperBoundEqualTo)))
+            })
+            val intersectedPoints = Points.and(regionRange, points.toSeq)
+
+            if (intersectedRanges.nonEmpty || intersectedPoints.nonEmpty) {
+              val startRow = 
intersectedRanges.headOption.flatMap(_.lower).map(_.b)
+                .orElse(intersectedPoints.headOption)
+                .orElse(region.start)
+                .orNull
+              val stopRow = 
intersectedRanges.lastOption.flatMap(_.upper).map(_.b)
+                
.orElse(intersectedPoints.lastOption.map(Utils.incrementByteArray))
+                .orElse(region.end)

Review Comment:
   This constructs one scan envelope by preferring range endpoints over point 
endpoints and assumes the ranges are ordered. A valid union such as `key < 'b' 
OR key = 'z'` stops at `b` and never visits `z`; `key > 'y' OR key = 'a'` 
similarly starts after `a`, and reversed disjoint ranges can even produce start 
> stop. Plan each disjoint range/point separately, or compute an envelope from 
the true minimum and maximum of all intersections.



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseScanBuilder.scala:
##########
@@ -0,0 +1,87 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.hbase.spark.Logging
+import org.apache.spark.sql.connector.read.{Scan, ScanBuilder, 
SupportsPushDownFilters, SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.yetus.audience.InterfaceAudience
+import scala.collection.mutable.ListBuffer
+
+/**
+ * This is a new class in the spark4 module.
+ * Implements ScanBuilder, SupportsPushDownFilters, and 
SupportsPushDownRequiredColumns.
+ * This is where Catalyst negotiates with the connector. Spark calls 
pushFilters() with
+ * candidate predicates and the builder accepts what it can handle and returns 
the rest.
+ * Spark calls pruneColumns() to say which columns it actually needs.
+ * Then build() produces the final scan plan.
+ *
+ * In the spark 3 V1 model, this negotiation happened implicitly via
+ * PrunedFilteredScan.buildScan(requiredColumns, filters) as a single method 
call with no back-and-forth.
+ *
+ * @param schema
+ * @param properties
+ */
[email protected]
+class HBaseScanBuilder(schema: StructType, properties: Map[String, String])
+    extends ScanBuilder
+    with SupportsPushDownFilters
+    with SupportsPushDownRequiredColumns
+    with Logging {
+
+  private val catalog = HBaseTableCatalog(properties)
+  private val encoderClsName =
+    properties.getOrElse(HBaseSparkConf.QUERY_ENCODER, 
HBaseSparkConf.DEFAULT_QUERY_ENCODER)
+  @transient private val encoder = JavaBytesEncoder.create(encoderClsName)
+
+  private var _pushedFilters: Array[Filter] = Array.empty
+  private var requiredSchema: StructType = schema
+
+  override def pushFilters(filters: Array[Filter]): Array[Filter] = {
+    val supported = new ListBuffer[Filter]()
+    val unsupported = new ListBuffer[Filter]()
+
+    filters.foreach {
+      case f @ EqualTo(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ LessThan(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ GreaterThan(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ LessThanOrEqual(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ GreaterThanOrEqual(attr, _) if catalog.sMap.map.contains(attr) 
=> supported += f
+      case f @ StringStartsWith(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ IsNull(attr) if catalog.sMap.map.contains(attr) => supported += 
f
+      case f @ IsNotNull(attr) if catalog.sMap.map.contains(attr) => supported 
+= f
+      case f @ Or(_, _) => supported += f
+      case f @ And(_, _) => supported += f

Review Comment:
   `And` and `Or` are accepted without recursively checking their children. For 
example, `And(EqualTo("name", "Alice"), EqualTo("unknown", "x"))` is reported 
as fully pushed; the unknown child becomes `PassThroughLogicExpression`, so 
Spark does not re-evaluate it and rows matching only `name` are returned. 
Accept a compound filter only when every child is supported and references a 
catalog field.



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseBatch.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.spark.{HBaseConnectionCache, Logging}
+import org.apache.spark.sql.connector.read.{Batch, InputPartition, 
PartitionReaderFactory}
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.yetus.audience.InterfaceAudience
+
+/**
+ * This is a new class in the spark4 module. Implements Batch.
+ * Responsible for physical planning: splits the read into partitions.
+ * Calls RegionLocator.getStartEndKeys() to discover HBase regions,
+ * intersects them with the row key filter's scan ranges, and produces an 
array of InputPartition objects.
+ *
+ * In the spark 3 DS V1 model, this logic was inside 
HBaseTableScanRDD.getPartitions().
+ *
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param rowKeyFilter
+ * @param pushedFilters
+ * @param encoderClsName
+ */
[email protected]
+class HBaseBatch(
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    rowKeyFilter: RowKeyFilter,
+    pushedFilters: Array[Filter],
+    encoderClsName: String)
+    extends Batch
+    with Logging {
+
+  override def planInputPartitions(): Array[InputPartition] = {
+    val conf = HBaseConfiguration.create()
+    val configResources = properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION)
+    configResources.foreach(_.split(",").foreach(r => conf.addResource(new 
Path(r))))
+
+    val connection = HBaseConnectionCache.getConnection(conf)
+    try {
+      val tableName = s"${catalog.namespace}:${catalog.name}"
+      val regionLocator = 
connection.getRegionLocator(TableName.valueOf(tableName))
+      try {
+        val keys = regionLocator.getStartEndKeys
+        val startKeys = keys.getFirst
+        val endKeys = keys.getSecond
+
+        val regions = startKeys.zip(endKeys).zipWithIndex.map { case ((start, 
end), idx) =>
+          HBaseRegion(idx, Some(start), Some(end))
+        }
+
+        val scanRanges = rowKeyFilter.ranges.toSeq
+        val points = rowKeyFilter.points.toSeq
+
+        if (scanRanges.isEmpty && points.isEmpty) {
+          regions.map { region =>
+            HBaseInputPartition(
+              region.index,
+              region.start.orNull,
+              region.end.orNull): InputPartition
+          }
+        } else {
+          regions.flatMap { region =>
+            val regionRange = Range(region)
+            val intersectedRanges = Ranges.and(regionRange, scanRanges.map { 
sr =>
+              Range(
+                Option(sr.lowerBound).filter(_.nonEmpty).map(Bound(_, 
sr.isLowerBoundEqualTo)),
+                Option(sr.upperBound).map(Bound(_, sr.isUpperBoundEqualTo)))
+            })

Review Comment:
   An inclusive singleton range is lost here: `Ranges.and` only retains 
intersections whose lower bound is strictly less than the upper bound, so `key 
>= x AND key <= x` produces no input partition even though `x` should match. 
The intersection logic must retain equal endpoints when both bounds are 
inclusive (and partition planning must then make the exclusive HBase stop row 
include `x`).



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBasePartitionReader.scala:
##########
@@ -0,0 +1,317 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{CellUtil, HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.client.{Result, ResultScanner, Scan}
+import org.apache.hadoop.hbase.spark.{AndLogicExpression, 
DynamicLogicExpression,
+  EqualLogicExpression, GreaterThanLogicExpression, 
GreaterThanOrEqualLogicExpression,
+  HBaseConnectionCache, IsNullLogicExpression, LessThanLogicExpression,
+  LessThanOrEqualLogicExpression, Logging, OrLogicExpression, 
PassThroughLogicExpression,
+  PushdownMappedField, SmartConnection, SparkSQLPushDownFilter, 
StartsWithLogicExpression}
+import org.apache.hadoop.hbase.util.Bytes
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.GenericInternalRow
+import org.apache.spark.sql.connector.read.PartitionReader
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+import org.apache.yetus.audience.InterfaceAudience
+import scala.collection.mutable.ListBuffer
+import scala.jdk.CollectionConverters._
+
+/**
+ * This is a new class in the spark4 module. Extends 
PartitionReader[InternalRow] for reading data from HBase regions.
+ * The actual execution: opens an HBase scanner on the partition's range, 
attaches the SparkSQLPushDownFilter,
+ * reads Result objects, and converts them to InternalRow. Implements 
next()/get()/close().
+ *
+ *
+ * In the spark 3 DS V1 model, this logic was inside DefaultSource.buildScan()
+ * which returned an RDD[Row] with its own compute() method.
+ *
+ * @param partition
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param pushedFilters
+ * @param encoderClsName
+ * @param usePushDownColumnFilter
+ */
[email protected]
+class HBasePartitionReader(
+    partition: HBaseInputPartition,
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    pushedFilters: Array[Filter],
+    encoderClsName: String,
+    usePushDownColumnFilter: Boolean)
+    extends PartitionReader[InternalRow]
+    with Logging {
+
+  private val conf = HBaseConfiguration.create()
+  private val configResources = 
properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION)
+  configResources.foreach(_.split(",").foreach(r => conf.addResource(new 
Path(r))))
+
+  private val connection: SmartConnection = 
HBaseConnectionCache.getConnection(conf)
+  private val tableName = s"${catalog.namespace}:${catalog.name}"
+  private val table = connection.getTable(TableName.valueOf(tableName))
+
+  private val scanner: ResultScanner = {
+    val scan = new Scan()
+
+    if (partition.startRow != null && partition.startRow.nonEmpty) {
+      scan.withStartRow(partition.startRow)
+    }
+    if (partition.stopRow != null && partition.stopRow.nonEmpty) {
+      scan.withStopRow(partition.stopRow)
+    }
+
+    val blockCacheEnable = properties
+      .get(HBaseSparkConf.QUERY_CACHEBLOCKS)
+      .map(_.toBoolean)
+      .getOrElse(HBaseSparkConf.DEFAULT_QUERY_CACHEBLOCKS)
+    scan.setCacheBlocks(blockCacheEnable)
+
+    properties.get(HBaseSparkConf.QUERY_CACHEDROWS).map(_.toInt).foreach { 
rows =>
+      if (rows > 0) scan.setCaching(rows)
+    }
+    properties.get(HBaseSparkConf.QUERY_BATCHSIZE).map(_.toInt).foreach { 
batch =>
+      if (batch > 0) scan.setBatch(batch)
+    }
+
+    val requiredFields = 
requiredSchema.fieldNames.map(catalog.sMap.getField(_))
+    val filterFields = extractFilterFields(pushedFilters)
+    val scanFields = (requiredFields ++ 
filterFields).distinct.filterNot(_.isRowKey)
+
+    scanFields.foreach { f =>
+      scan.addColumn(f.cfBytes, f.colBytes)
+    }
+
+    if (usePushDownColumnFilter && pushedFilters.nonEmpty) {
+      val valueArray = buildValueArray()
+      val dynamicLogicExpression = buildDynamicLogicExpression()
+      if (dynamicLogicExpression != null) {
+        val allFilterFields = (requiredFields ++ filterFields).distinct
+        val columnMappings = allFilterFields.map { field =>
+          new PushdownMappedField {
+            override def colName(): String = field.colName
+            override def cfBytes(): Array[Byte] = field.cfBytes
+            override def colBytes(): Array[Byte] = field.colBytes
+          }
+        }
+        val pushDownFilter = new SparkSQLPushDownFilter(
+          dynamicLogicExpression,
+          valueArray,
+          columnMappings.toList.asJava,
+          encoderClsName)
+        scan.setFilter(pushDownFilter)
+      }
+    }
+
+    table.getScanner(scan)
+  }
+
+  private var currentResult: Result = _
+
+  override def next(): Boolean = {
+    currentResult = scanner.next()
+    currentResult != null
+  }
+
+  override def get(): InternalRow = {
+    val fields = requiredSchema.fieldNames.map(catalog.sMap.getField(_))
+    val rowKey = currentResult.getRow
+    catalog.dynSetupRowKey(rowKey)
+    val keyFields = catalog.getRowKey
+
+    val keyValues = parseRowKey(rowKey, keyFields)
+    val values = new Array[Any](fields.length)
+
+    fields.zipWithIndex.foreach { case (field, idx) =>
+      if (field.isRowKey) {
+        values(idx) = convertToInternalRow(keyValues.get(field).orNull, 
field.dt)
+      } else {
+        val cell = currentResult.getColumnLatestCell(
+          Bytes.toBytes(field.cf), Bytes.toBytes(field.col))
+        if (cell == null || cell.getValueLength == 0) {
+          values(idx) = null
+        } else {
+          val v = CellUtil.cloneValue(cell)
+          val scalaValue = field.dt match {
+            case BinaryType => v
+            case _ => Utils.hbaseFieldToScalaType(field, v, 0, v.length)
+          }
+          values(idx) = convertToInternalRow(scalaValue, field.dt)
+        }
+      }
+    }
+    new GenericInternalRow(values)
+  }
+
+  override def close(): Unit = {
+    if (scanner != null) scanner.close()
+    if (table != null) table.close()
+    if (connection != null) connection.close()
+  }
+
+  private def convertToInternalRow(value: Any, dataType: DataType): Any = {
+    if (value == null) return null
+    dataType match {
+      case StringType => UTF8String.fromString(value.asInstanceOf[String])
+      case _ => value
+    }

Review Comment:
   Only strings are converted to Catalyst's internal representation. 
`Utils.hbaseFieldToScalaType` returns `java.sql.Date`, `java.sql.Timestamp`, 
and `java.math.BigDecimal`, but `InternalRow` requires an epoch-day `Int`, a 
microsecond `Long`, and Spark `Decimal`; consumers will fail when reading these 
catalog-supported types. Convert every value with the data type's Catalyst 
converter rather than handling only `StringType`.



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseBatch.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.spark.{HBaseConnectionCache, Logging}
+import org.apache.spark.sql.connector.read.{Batch, InputPartition, 
PartitionReaderFactory}
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.yetus.audience.InterfaceAudience
+
+/**
+ * This is a new class in the spark4 module. Implements Batch.
+ * Responsible for physical planning: splits the read into partitions.
+ * Calls RegionLocator.getStartEndKeys() to discover HBase regions,
+ * intersects them with the row key filter's scan ranges, and produces an 
array of InputPartition objects.
+ *
+ * In the spark 3 DS V1 model, this logic was inside 
HBaseTableScanRDD.getPartitions().
+ *
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param rowKeyFilter
+ * @param pushedFilters
+ * @param encoderClsName
+ */
[email protected]
+class HBaseBatch(
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    rowKeyFilter: RowKeyFilter,
+    pushedFilters: Array[Filter],
+    encoderClsName: String)
+    extends Batch
+    with Logging {
+
+  override def planInputPartitions(): Array[InputPartition] = {
+    val conf = HBaseConfiguration.create()
+    val configResources = properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION)
+    configResources.foreach(_.split(",").foreach(r => conf.addResource(new 
Path(r))))
+
+    val connection = HBaseConnectionCache.getConnection(conf)
+    try {
+      val tableName = s"${catalog.namespace}:${catalog.name}"
+      val regionLocator = 
connection.getRegionLocator(TableName.valueOf(tableName))
+      try {
+        val keys = regionLocator.getStartEndKeys
+        val startKeys = keys.getFirst
+        val endKeys = keys.getSecond
+
+        val regions = startKeys.zip(endKeys).zipWithIndex.map { case ((start, 
end), idx) =>
+          HBaseRegion(idx, Some(start), Some(end))
+        }
+
+        val scanRanges = rowKeyFilter.ranges.toSeq
+        val points = rowKeyFilter.points.toSeq
+
+        if (scanRanges.isEmpty && points.isEmpty) {
+          regions.map { region =>
+            HBaseInputPartition(
+              region.index,
+              region.start.orNull,
+              region.end.orNull): InputPartition
+          }
+        } else {
+          regions.flatMap { region =>
+            val regionRange = Range(region)
+            val intersectedRanges = Ranges.and(regionRange, scanRanges.map { 
sr =>
+              Range(
+                Option(sr.lowerBound).filter(_.nonEmpty).map(Bound(_, 
sr.isLowerBoundEqualTo)),
+                Option(sr.upperBound).map(Bound(_, sr.isUpperBoundEqualTo)))
+            })
+            val intersectedPoints = Points.and(regionRange, points.toSeq)
+
+            if (intersectedRanges.nonEmpty || intersectedPoints.nonEmpty) {
+              val startRow = 
intersectedRanges.headOption.flatMap(_.lower).map(_.b)
+                .orElse(intersectedPoints.headOption)
+                .orElse(region.start)
+                .orNull
+              val stopRow = 
intersectedRanges.lastOption.flatMap(_.upper).map(_.b)

Review Comment:
   The upper bound's inclusivity is discarded when it becomes HBase's exclusive 
`stopRow`. Consequently a predicate such as `key <= 'row010'` stops before 
`row010`. Convert an inclusive upper bound to the byte sequence immediately 
after the bound, as the Spark 3 path does.



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseTableProvider.scala:
##########
@@ -0,0 +1,74 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import java.util
+import org.apache.spark.sql.connector.catalog.{Table, TableProvider}
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.sources.DataSourceRegister
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.yetus.audience.InterfaceAudience
+import scala.jdk.CollectionConverters._
+
+/**
+ * This is a new class in the spark4 module, and is the entry point for 
sparkSQL in spark 4 DataSource V2.
+ * It's the equivalent to what DefaultSource (a RelationProvider) was in spark 
3 DataSource V1.
+ *
+ * Implements DS V2 TableProvider and DataSourceRegister, so when you call:
+ * <code>
+ *  ...
+ *    
spark.read.format("org.apache.hadoop.hbase.spark.datasources.HBaseTableProvider")
+ *  ...
+ * </code>
+ *
+ * Spark instantiates this class and calls its getTable() method. In V1, 
DefaultSource.createRelation() returned a
+ * BaseRelation directly, but now in V2, it returns an HBaseTable object that 
describes the table's capabilities.
+ *
+ * Alternatively, it overrides shortName() to provide a short name "hbase" for 
this data source, so you can also call:
+ * <code>
+ *  ...
+ *    spark.read.format("hbase")
+ *  ...
+ * </code>
+ *
+ *
+ */
[email protected]
+class HBaseTableProvider extends TableProvider with DataSourceRegister {
+
+  /**
+   * Short name of the data source, used to allow users to specify 
format("hbase")
+   * as a short name for 
format("org.apache.hadoop.hbase.spark.datasources.HBaseTableProvider").
+   * @return
+   */
+  override def shortName(): String = "hbase"

Review Comment:
   Implementing `DataSourceRegister` and returning `"hbase"` does not by itself 
make the alias discoverable: Spark loads short names through `ServiceLoader`, 
but this module has no 
`META-INF/services/org.apache.spark.sql.sources.DataSourceRegister` entry. Thus 
`.format("hbase")` promised by this API fails while the test only exercises the 
fully qualified class name. Add the provider service descriptor (and an alias 
integration test).



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBasePartitionReader.scala:
##########
@@ -0,0 +1,317 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{CellUtil, HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.client.{Result, ResultScanner, Scan}
+import org.apache.hadoop.hbase.spark.{AndLogicExpression, 
DynamicLogicExpression,
+  EqualLogicExpression, GreaterThanLogicExpression, 
GreaterThanOrEqualLogicExpression,
+  HBaseConnectionCache, IsNullLogicExpression, LessThanLogicExpression,
+  LessThanOrEqualLogicExpression, Logging, OrLogicExpression, 
PassThroughLogicExpression,
+  PushdownMappedField, SmartConnection, SparkSQLPushDownFilter, 
StartsWithLogicExpression}
+import org.apache.hadoop.hbase.util.Bytes
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.GenericInternalRow
+import org.apache.spark.sql.connector.read.PartitionReader
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+import org.apache.yetus.audience.InterfaceAudience
+import scala.collection.mutable.ListBuffer
+import scala.jdk.CollectionConverters._
+
+/**
+ * This is a new class in the spark4 module. Extends 
PartitionReader[InternalRow] for reading data from HBase regions.
+ * The actual execution: opens an HBase scanner on the partition's range, 
attaches the SparkSQLPushDownFilter,
+ * reads Result objects, and converts them to InternalRow. Implements 
next()/get()/close().
+ *
+ *
+ * In the spark 3 DS V1 model, this logic was inside DefaultSource.buildScan()
+ * which returned an RDD[Row] with its own compute() method.
+ *
+ * @param partition
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param pushedFilters
+ * @param encoderClsName
+ * @param usePushDownColumnFilter
+ */
[email protected]
+class HBasePartitionReader(
+    partition: HBaseInputPartition,
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    pushedFilters: Array[Filter],
+    encoderClsName: String,
+    usePushDownColumnFilter: Boolean)
+    extends PartitionReader[InternalRow]
+    with Logging {
+
+  private val conf = HBaseConfiguration.create()
+  private val configResources = 
properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION)
+  configResources.foreach(_.split(",").foreach(r => conf.addResource(new 
Path(r))))
+
+  private val connection: SmartConnection = 
HBaseConnectionCache.getConnection(conf)
+  private val tableName = s"${catalog.namespace}:${catalog.name}"
+  private val table = connection.getTable(TableName.valueOf(tableName))
+
+  private val scanner: ResultScanner = {
+    val scan = new Scan()
+
+    if (partition.startRow != null && partition.startRow.nonEmpty) {
+      scan.withStartRow(partition.startRow)
+    }
+    if (partition.stopRow != null && partition.stopRow.nonEmpty) {
+      scan.withStopRow(partition.stopRow)
+    }
+
+    val blockCacheEnable = properties
+      .get(HBaseSparkConf.QUERY_CACHEBLOCKS)
+      .map(_.toBoolean)
+      .getOrElse(HBaseSparkConf.DEFAULT_QUERY_CACHEBLOCKS)
+    scan.setCacheBlocks(blockCacheEnable)

Review Comment:
   The Spark 4 read path never applies the existing `TIMESTAMP`, 
`TIMERANGE_START`/`TIMERANGE_END`, or `MAX_VERSIONS` options to this `Scan`. 
Supplying those documented connector options therefore silently reads the 
latest data across the default version window instead of the requested 
timestamp/range. Port the Spark 3 `handleTimeSemantics` validation and scan 
configuration here.



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBasePartitionReader.scala:
##########
@@ -0,0 +1,317 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{CellUtil, HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.client.{Result, ResultScanner, Scan}
+import org.apache.hadoop.hbase.spark.{AndLogicExpression, 
DynamicLogicExpression,
+  EqualLogicExpression, GreaterThanLogicExpression, 
GreaterThanOrEqualLogicExpression,
+  HBaseConnectionCache, IsNullLogicExpression, LessThanLogicExpression,
+  LessThanOrEqualLogicExpression, Logging, OrLogicExpression, 
PassThroughLogicExpression,
+  PushdownMappedField, SmartConnection, SparkSQLPushDownFilter, 
StartsWithLogicExpression}
+import org.apache.hadoop.hbase.util.Bytes
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.GenericInternalRow
+import org.apache.spark.sql.connector.read.PartitionReader
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+import org.apache.yetus.audience.InterfaceAudience
+import scala.collection.mutable.ListBuffer
+import scala.jdk.CollectionConverters._
+
+/**
+ * This is a new class in the spark4 module. Extends 
PartitionReader[InternalRow] for reading data from HBase regions.
+ * The actual execution: opens an HBase scanner on the partition's range, 
attaches the SparkSQLPushDownFilter,
+ * reads Result objects, and converts them to InternalRow. Implements 
next()/get()/close().
+ *
+ *
+ * In the spark 3 DS V1 model, this logic was inside DefaultSource.buildScan()
+ * which returned an RDD[Row] with its own compute() method.
+ *
+ * @param partition
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param pushedFilters
+ * @param encoderClsName
+ * @param usePushDownColumnFilter
+ */
[email protected]
+class HBasePartitionReader(
+    partition: HBaseInputPartition,
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    pushedFilters: Array[Filter],
+    encoderClsName: String,
+    usePushDownColumnFilter: Boolean)
+    extends PartitionReader[InternalRow]
+    with Logging {
+
+  private val conf = HBaseConfiguration.create()
+  private val configResources = 
properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION)
+  configResources.foreach(_.split(",").foreach(r => conf.addResource(new 
Path(r))))
+
+  private val connection: SmartConnection = 
HBaseConnectionCache.getConnection(conf)
+  private val tableName = s"${catalog.namespace}:${catalog.name}"
+  private val table = connection.getTable(TableName.valueOf(tableName))
+
+  private val scanner: ResultScanner = {
+    val scan = new Scan()
+
+    if (partition.startRow != null && partition.startRow.nonEmpty) {
+      scan.withStartRow(partition.startRow)
+    }
+    if (partition.stopRow != null && partition.stopRow.nonEmpty) {
+      scan.withStopRow(partition.stopRow)
+    }
+
+    val blockCacheEnable = properties
+      .get(HBaseSparkConf.QUERY_CACHEBLOCKS)
+      .map(_.toBoolean)
+      .getOrElse(HBaseSparkConf.DEFAULT_QUERY_CACHEBLOCKS)
+    scan.setCacheBlocks(blockCacheEnable)
+
+    properties.get(HBaseSparkConf.QUERY_CACHEDROWS).map(_.toInt).foreach { 
rows =>
+      if (rows > 0) scan.setCaching(rows)
+    }
+    properties.get(HBaseSparkConf.QUERY_BATCHSIZE).map(_.toInt).foreach { 
batch =>
+      if (batch > 0) scan.setBatch(batch)
+    }
+
+    val requiredFields = 
requiredSchema.fieldNames.map(catalog.sMap.getField(_))
+    val filterFields = extractFilterFields(pushedFilters)
+    val scanFields = (requiredFields ++ 
filterFields).distinct.filterNot(_.isRowKey)
+
+    scanFields.foreach { f =>
+      scan.addColumn(f.cfBytes, f.colBytes)
+    }
+
+    if (usePushDownColumnFilter && pushedFilters.nonEmpty) {
+      val valueArray = buildValueArray()
+      val dynamicLogicExpression = buildDynamicLogicExpression()
+      if (dynamicLogicExpression != null) {
+        val allFilterFields = (requiredFields ++ filterFields).distinct
+        val columnMappings = allFilterFields.map { field =>
+          new PushdownMappedField {
+            override def colName(): String = field.colName
+            override def cfBytes(): Array[Byte] = field.cfBytes
+            override def colBytes(): Array[Byte] = field.colBytes
+          }
+        }
+        val pushDownFilter = new SparkSQLPushDownFilter(
+          dynamicLogicExpression,
+          valueArray,
+          columnMappings.toList.asJava,
+          encoderClsName)
+        scan.setFilter(pushDownFilter)
+      }
+    }
+
+    table.getScanner(scan)
+  }
+
+  private var currentResult: Result = _
+
+  override def next(): Boolean = {
+    currentResult = scanner.next()
+    currentResult != null
+  }
+
+  override def get(): InternalRow = {
+    val fields = requiredSchema.fieldNames.map(catalog.sMap.getField(_))
+    val rowKey = currentResult.getRow
+    catalog.dynSetupRowKey(rowKey)
+    val keyFields = catalog.getRowKey

Review Comment:
   `dynSetupRowKey` mutates each variable-length `Field.length`. After the 
first row, later calls see a non-negative length and reuse it, so rows with a 
different string/binary key length are parsed using the first row's size. 
`parseRowKey` already handles `length == -1` per row; avoid mutating the shared 
catalog before parsing.



-- 
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.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to