nacz0 opened a new issue, #41843:
URL: https://github.com/apache/beam/issues/41843

   ### What happened?
   
   ### What happened?
   
   `JdbcIO.readWithPartitions()` never reads rows where the partition column is 
NULL. Every partition runs the same query:
   
   ```sql
   select * from <table> where <column> >= ? and <column> < ?
   ```
   
   
([`JdbcIO.java#L1706`](https://github.com/apache/beam/blob/91c391fb67d342c20dbe4fa167e8fd5a60ecb743/sdks/java/io/jdbc/src/main/java/org/apache/beam/sdk/io/jdbc/JdbcIO.java#L1706))
   
   A NULL never satisfies either comparison, so those rows are in no partition. 
The pipeline succeeds and the rows are missing from the output, with no error 
or warning.
   
   When every value in the column is NULL and bounds are auto-inferred, `SELECT 
min(c), max(c)` returns `(NULL, NULL)`:
   
   - **Long** 
([`JdbcUtil.java#L535-L537`](https://github.com/apache/beam/blob/91c391fb67d342c20dbe4fa167e8fd5a60ecb743/sdks/java/io/jdbc/src/main/java/org/apache/beam/sdk/io/jdbc/JdbcUtil.java#L535-L537)):
 `ResultSet.getLong` turns the NULLs into `0`, producing the single range `[0, 
1)`, so the read silently returns 0 rows.
   - **DateTime** 
([`JdbcUtil.java#L585-L592`](https://github.com/apache/beam/blob/91c391fb67d342c20dbe4fa167e8fd5a60ecb743/sdks/java/io/jdbc/src/main/java/org/apache/beam/sdk/io/jdbc/JdbcUtil.java#L585-L592)):
 `checkArgumentNotNull(resultSet.getTimestamp(1))` throws a bare 
`IllegalArgumentException` (with `null` message). The same crash also occurs on 
an empty table (with explicit `withLowerBound`/`withUpperBound`, it silently 
returns 0 rows instead).
   
   Every partition column type is affected (`Long`, `DateTime`, and custom 
`JdbcReadWithPartitionsHelper` implementations), because the `WHERE` clause is 
hardcoded in `ReadWithPartitions.expand()`. The same transform backs Java 
`JdbcIO.readWithPartitions()`, Python `ReadFromJdbc` (`JdbcSchemaIOProvider`), 
and Beam YAML / Managed IO (`JdbcReadSchemaTransformProvider`, 
`ReadFromPostgres`, `ReadFromMySql`, etc.).
   
   Reproduced with Beam 2.77.0 (Python 3.12 SDK, DirectRunner, 
`apache/beam_java_expansion_service:2.77.0`, `apache/beam_java17_sdk:2.77.0`, 
PostgreSQL 16) and on `master` (`91c391fb`, unchanged since 2.77.0 and 2.78.0) 
using the Java SDK (`DirectRunner`) against PostgreSQL 16 and embedded Apache 
Derby (`Long`, `DateTime`, and custom `String` helpers). The same behavior also 
showed up on MySQL, SQL Server, and Oracle.
   
   ```sql
   CREATE TABLE items (id INT, name TEXT);
   INSERT INTO items SELECT g, 'item ' || g FROM generate_series(1, 10) g;
   INSERT INTO items VALUES (NULL, 'no id');            -- 11 rows
   
   CREATE TABLE all_null (id INT, name TEXT);
   INSERT INTO all_null VALUES (NULL, 'a'), (NULL, 'b'), (NULL, 'c');   -- 3 
rows
   ```
   
   ```python
   import apache_beam as beam
   from apache_beam.io.jdbc import ReadFromJdbc
   from apache_beam.metrics import Metrics
   from apache_beam.metrics.metric import MetricsFilter
   
   
   def count_rows(table, **partitioning):
       p = beam.Pipeline()
       (
           p
           | ReadFromJdbc(
               table_name=table,
               driver_class_name="org.postgresql.Driver",
               jdbc_url="jdbc:postgresql://localhost:5432/db",
               username="postgres",
               password="postgres",
               **partitioning,
           )
           | beam.Map(lambda row: Metrics.counter("repro", "rows").inc())
       )
       result = p.run()
       result.wait_until_finish()
       counters = 
result.metrics().query(MetricsFilter().with_name("rows"))["counters"]
       return sum(c.committed for c in counters)
   
   
   for table in ("items", "all_null"):
       print(table, count_rows(table), count_rows(table, partition_column="id", 
partitions=4))
   ```
   
   The JDBC URL must be reachable from the Java worker container, for example 
`host.docker.internal` instead of `localhost` when the database runs on the 
host.
   
   | Table | Without `partition_column` | With `partition_column="id"`, 4 
partitions |
   |---|---|---|
   | `items` | 11 rows | 10 rows |
   | `all_null` | 3 rows | 0 rows |
   
   The Java API behaves the same, because Python `ReadFromJdbc` expands to 
`JdbcIO.readWithPartitions()` with `Long` ranges (and `DateTime` crashes with 
`IllegalArgumentException` on an all-NULL or empty table).
   
   #### Expected behavior
   
   A partitioned read returns the same rows as an unpartitioned read of the 
same table (matching the `JdbcIO` Javadoc: *"Beam supports partitioned reading 
of all data from a table"*, 
[`JdbcIO.java#L216`](https://github.com/apache/beam/blob/91c391fb67d342c20dbe4fa167e8fd5a60ecb743/sdks/java/io/jdbc/src/main/java/org/apache/beam/sdk/io/jdbc/JdbcIO.java#L216)).
 A nullable partition column is common, e.g. a foreign key or an optional 
numeric/timestamp column.
   
   Possible fixes:
   - Read NULL rows with one additional query (`select * from <table> where 
<column> is null`) and flatten them into the output. The same query works as a 
workaround in user code.
   - Or add `or <column> is null` to the first range, as Spark's JDBC source 
does (`JDBCRelation.columnPartition`). That requires a per-range query since 
all ranges currently share one parameterized statement.
   - In either case, skip range generation when auto-inferred `min`/`max` are 
NULL (e.g. `HAVING min(c) IS NOT NULL` or null-aware `mapRow`) so all-NULL and 
empty tables emit 0 range partitions instead of crashing `DateTime` or querying 
`[0, 1)` for `Long`.
   
   If dropping NULL rows is intended (or reading them should be configurable 
due to the extra query, e.g. on Oracle where B-tree indexes do not store 
NULLs), the Javadoc of `readWithPartitions` and `withPartitionColumn` should 
document it.
   
   A related question: with explicit `withLowerBound` / `withUpperBound`, rows 
outside `[lower, upper]` are not read either (both bounds are inclusive, unlike 
Spark where bounds only set strides). Neither method currently has Javadoc 
([`JdbcIO.java#L1557-L1563`](https://github.com/apache/beam/blob/91c391fb67d342c20dbe4fa167e8fd5a60ecb743/sdks/java/io/jdbc/src/main/java/org/apache/beam/sdk/io/jdbc/JdbcIO.java#L1557-L1563)).
 If filtering to `[lower, upper]` is intended, it would be helpful to document 
that too (and whether NULL rows should be included when explicit bounds are 
set).
   
   
   ### Issue Priority
   
   Priority: 2 (default / most bugs should be filed as P2)
   
   ### Issue Components
   
   - [x] Component: Python SDK
   - [x] Component: Java SDK
   - [ ] Component: Go SDK
   - [ ] Component: Typescript SDK
   - [x] Component: IO connector
   - [x] Component: Beam YAML
   - [ ] Component: Beam examples
   - [ ] Component: Beam playground
   - [ ] Component: Beam katas
   - [ ] Component: Website
   - [ ] Component: Infrastructure
   - [ ] Component: Spark Runner
   - [ ] Component: Flink Runner
   - [ ] Component: Prism Runner
   - [ ] Component: Hazelcast Jet Runner
   - [ ] Component: Google Cloud Dataflow Runner


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