Skip to content

[Fix][Connector-V2][Jdbc] Add numeric_special_value_as_null option for PostgreSQL - #12792

Merged
davidzollo merged 3 commits into
apache:devfrom
siwen-yu:bugfix/jdbc-pg-numeric-special-value-as-null
Oct 18, 2026
Merged

davidzollo merged 3 commits into
apache:devfrom
siwen-yu:bugfix/jdbc-pg-numeric-special-value-as-null

Conversation

@siwen-yu

Copy link
Copy Markdown
Contributor

Purpose of this pull request

Reading a PostgreSQL numeric/decimal column that contains NaN, Infinity or
-Infinity aborts the whole job, because these special values have no BigDecimal
representation: the pgjdbc driver throws
PSQLException: Bad value for type BigDecimal : NaN in text transfer mode and a
ClassCastException in binary transfer mode (where the driver decodes the value into a
Double). A single such cell fails the entire job.

This PR adds an opt-in source option numeric_special_value_as_null (default false,
following the existing decimal_type_narrowing / int_type_narrowing pattern). When
enabled, NaN/Infinity/-Infinity values are read as null with a warning logged
instead of aborting the job. Unrelated driver errors are still rethrown, and the default
behavior is unchanged.

Closes #12790

Does this PR introduce any user-facing change?

Yes. A new JDBC source option numeric_special_value_as_null is added, documented in
docs/en/connectors/source/Jdbc.md and docs/zh/connectors/source/Jdbc.md. It only takes
effect for the PostgreSQL dialect (including the postgresLow compatible mode). The
default behavior is unchanged, so existing jobs are not affected unless they opt in.

How was this patch tested?

Unit tests added:

  • JdbcFieldTypeUtilsTest: normal value passthrough; NaN/Infinity/-Infinity narrowed
    to null when the option is enabled; binary-mode ClassCastException path; error kept
    when the option is disabled; unrelated errors still rethrown.
  • PostgresJdbcRowConverterTest: DECIMAL column with a normal value; NaN narrowed to
    null when enabled; error thrown when the option is disabled.

The full connector-jdbc test suite was run locally: 543 tests, the only failure
(VerticaDialectTest.testUpsertStatementByTableSchema) is pre-existing on a clean tree and
unrelated to this change.

Check list

  • If any new Jar binary package adding in your PR, please add License Notice according
    New License Guide
    (N/A, no new dependency)
  • If necessary, please update the documentation to describe the new feature. (en/zh
    Jdbc.md updated)
  • If necessary, please update incompatible-changes.md (N/A, no incompatible change,
    default behavior unchanged)
  • If you are contributing the connector code, please check that the following files are
    updated (N/A, no new connector, only a new source option in connector-jdbc)

@siwen-yu
siwen-yu force-pushed the bugfix/jdbc-pg-numeric-special-value-as-null branch from bf9b4b9 to d10c826 Compare October 15, 2026 09:15
…r PostgreSQL

Reading a numeric column whose value is NaN/Infinity/-Infinity failed with
"Bad value for type BigDecimal : NaN" (text protocol) or a ClassCastException
(binary protocol), because these special values have no BigDecimal
representation and the whole job aborted on a single such value.

Add an opt-in source option `numeric_special_value_as_null` (default false,
following the decimal_type_narrowing/int_type_narrowing pattern). When enabled,
NaN/Infinity/-Infinity values are read as null with a warning logged, so the
job can continue. The default behavior is unchanged.
@siwen-yu
siwen-yu force-pushed the bugfix/jdbc-pg-numeric-special-value-as-null branch from d10c826 to 9881d3e Compare October 15, 2026 09:52

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @siwen-yu, thank you for this contribution and for the careful description (the text-mode vs binary-mode failure explanation is very helpful). The option is opt-in, default-off and well-contained. I reviewed the full diff at the current head; there are no blocking issues, only a few improvements I would like to see.

What Problem Does This PR Solve?

User pain point: A PostgreSQL numeric/decimal cell holding NaN, Infinity or -Infinity makes the JDBC source fail the whole job, because the pgjdbc driver cannot turn it into a BigDecimal (PSQLException: Bad value for type BigDecimal : NaN in text mode, ClassCastException in binary mode) (#12790).

Fix approach: Add a source option numeric_special_value_as_null (default false). It is carried via JdbcConnectionConfig -> JdbcDialectLoader.load(..., config) -> PostgresDialectFactory.create(...) -> PostgresDialect(fieldIde, flag) -> PostgresJdbcRowConverter(flag) -> JdbcFieldTypeUtils.getBigDecimal(rs, idx, flag). When the flag is on and getBigDecimal throws, the raw string is inspected and, if it is one of the three special values, null is returned with a warning.

One-sentence summary: Let users opt in to reading PostgreSQL numeric special values as null instead of aborting the job.

Before / after:

-- PostgreSQL: INSERT INTO t(v) VALUES ('NaN');   -- v numeric
before: job fails with PSQLException: Bad value for type BigDecimal : NaN
after (numeric_special_value_as_null = true): row is emitted with v = null, WARN logged

1. Code Change Review

1.1 Core Logic Analysis

The runtime path for the normal user path (Jdbc source reading from PostgreSQL) is:

JdbcSourceFactory (optionRule lists the new option)
  -> JdbcSourceConfig / JdbcConnectionConfig.of(config)  (numericSpecialValueAsNull read from options)
  -> JdbcSourceReader -> JdbcInputFormat ctor (JdbcInputFormat.java:77)
       -> JdbcDialectLoader.load(url, dialect, compatibleMode, jdbcConnectionConfig)
       -> PostgresDialectFactory.create(compatibleMode, fieldIde, cfg)   [postgresLow -> PostgresLowDialect]
       -> jdbcDialect.getRowConverter() -> new PostgresJdbcRowConverter(flag)
  -> per row: PostgresJdbcRowConverter.toInternal, case DECIMAL
       -> JdbcFieldTypeUtils.getBigDecimal(rs, idx, flag)
            try rs.getBigDecimal
            catch SQLException | ClassCastException -> flag && rs.getString in {NaN, Infinity, -Infinity} ? null : rethrow

Key Findings:

  • The default path (flag=false) calls rs.getBigDecimal and rethrows exactly as before, so default behavior is unchanged.
  • The new JdbcDialectLoader.load(url, dialect, compatibleMode, config) overload and JdbcDialectFactory.create(..., config) default method already exist on dev, so no shared API is changed.
  • The fix only takes effect in JdbcInputFormat; other dialect loads (for example ChunkSplitter.java:69) still use the no-config overload, which is fine for row conversion but worth knowing.
  • Special values become null, which is indistinguishable from a real SQL NULL downstream (documented, but see Issue 3).
  • Warning is logged per cell (see Issue 2).

1.2 Compatibility Impact

Fully compatible. New option is optional with default false; the 2-arg PostgresDialect(String) and no-arg converter constructors are kept; PostgresDialectFactory.create(compatibleMode, fieldIde) is unchanged. No incompatible-changes.md entry needed.

1.3 Performance / Side-Effect Analysis

Hot path adds a try/catch around getBigDecimal, which has no cost unless an exception is thrown. When special values are frequent and the option is on, each such cell costs an exception plus a getString plus a warn log (Issue 2).

1.4 Error Handling and Logging

Issue 1: New option is missing from the option tables in both Jdbc docs

  • Location: docs/en/connectors/source/Jdbc.md (option table around line 173-174), docs/zh/connectors/source/Jdbc.md (around line 170)
  • Problem: decimal_type_narrowing and int_type_narrowing each have a row in the main options table and a detail section; this PR only adds the detail section.
  • Potential risk: users scanning the table will not discover the option.
  • Best improvement: add a row (Boolean, No, default false, short description, "Please refer to numeric_special_value_as_null below") in en and zh.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 2: One WARN log per special-value cell can flood the logs at scale

  • Location: JdbcFieldTypeUtils.java:119 (log.warn(...) in getBigDecimal)
  • Problem: the message is emitted for every offending cell. In a large table with many NaN cells (the job-scale systems SeaTunnel targets) this produces unbounded log volume from a hot per-row path, and the message does not include table or column name, so it is also hard to act on.
  • Potential risk: log disk pressure and slowed reads; operators cannot tell which column is affected.
  • Best improvement: log the first occurrence per converter (or per column) at WARN and then count silently (or log every N), and include the column label from ResultSetMetaData in the message.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 3: Verification relies only on mocked driver exceptions

  • Location: JdbcFieldTypeUtilsTest.java, PostgresJdbcRowConverterTest.java
  • Problem: the unit tests throw hand-built PSQLException / ClassCastException from a mocked ResultSet. They do verify the branch logic, but nothing proves that real pgjdbc 42.4.3 throws these in text and binary mode and that getString then returns NaN / Infinity / -Infinity for the same column. JdbcPostgresIT exists in the repo and is the natural place for a case with NaN, Infinity and -Infinity rows (PostgreSQL 14+ image for infinity), ideally also with binaryTransfer=true in the URL.
  • Potential risk: a driver-version difference (for example a different exception type) would make the option silently ineffective, and the unit tests would stay green.
  • Best improvement: extend JdbcPostgresIT (or add a small IT config) reading a numeric column containing the three special values with the option on and off.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 4: Option is silently ignored by non-PostgreSQL dialects and by the splitter dialect

  • Location: JdbcCommonOptions.java (description), ChunkSplitter.java:69
  • Problem: the option is accepted for every JDBC source but only PostgreSQL / postgresLow honour it; ChunkSplitter builds its own dialect without the config. A numeric split column containing NaN would still fail in the split-range query path.
  • Potential risk: low, user confusion only.
  • Best improvement: keep the "Only support for PostgreSQL at now" wording in the table row (Issue 1) and mention the limitation for split columns.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Apache headers are in place, the new public util method has a clear Javadoc, @Slf4j is used, formatting looks consistent. Constructor chaining in PostgresDialect is clean.

2.2 Test Coverage and Test Stability

Seven util tests and three converter tests cover: normal value, NaN / Infinity / -Infinity, binary-mode ClassCastException, flag off keeps the original exception (assertSame), unrelated SQLException rethrown. They would fail if the flag check, the special-value match or the rethrow were removed. Stability rating: Stable (pure Mockito, no sleeps, ports, or shared statics). Gap: no real-driver coverage (Issue 3).

2.3 Documentation Updates

en and zh detail sections are added and match the code (name, default false, PostgreSQL only). The options table rows are missing (Issue 1). The eg: example only shows the option, not the effect; optional.

3. Architectural Soundness

3.1 Elegance

Long-term-acceptable and follows the existing decimal_type_narrowing / int_type_narrowing pattern; flow through the dialect factory avoids touching shared converters.

3.2 Maintainability

Reasonable. Note that the extra constructor overloads are only needed for PostgreSQL.

3.3 Extensibility

Other PostgreSQL-compatible dialects (for example Kingbase, mentioned in the Javadoc) would need their own wiring; the Javadoc mention could be softened so it does not suggest coverage.

3.4 Historical-Version Compatibility

Old job configs are unaffected (option absent -> default false). No state, serialization or checkpoint format changes: JdbcConnectionConfig is serializable and gains one boolean with a default, so restored splits keep working.

4. Issue Summary

Number Issue Location Severity
1 Option missing from options tables (en/zh) docs/*/connectors/source/Jdbc.md Medium
2 Per-cell WARN log, no column name JdbcFieldTypeUtils.java:119 Medium
3 No real-driver (text/binary) IT coverage JdbcPostgresIT / unit tests Medium
4 Splitter dialect / other dialects ignore the option ChunkSplitter.java:69 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed
    • No blocking issues found. CI on this head was still queued when I reviewed.
  2. Recommended fixes - non-blocking
    • Issues 1, 2 and 3 (docs table, log throttling with column name, a real PostgreSQL IT); Issue 4 as a doc note.

Overall assessment: safe, opt-in, default-compatible change that solves a real production pain. With the docs rows, log throttling and one IT case it would be in very good shape. Thanks again for the contribution.

…value_as_null

- Log the first numeric special value per column at WARN (with column label)
  in PostgresJdbcRowConverter and stay silent afterwards, instead of one
  warning per cell; JdbcFieldTypeUtils keeps the conversion and only reports
  special values via the new isNumericSpecialValue helper
- Add a unit test for the per-column log throttling
- Add JdbcPostgresIT e2e cases for text protocol, binary protocol and default
  behavior, guarded by server_version_num >= 140000
- Document the option in the en/zh options tables and the split range query
  limitation
@github-actions github-actions Bot added the e2e label Oct 16, 2026
@siwen-yu

Copy link
Copy Markdown
Contributor Author

@DanielLeens Thanks for the thorough review! I’ll update the English and Chinese option tables, improve the warning log strategy, and add PostgreSQL integration tests to cover the actual JDBC driver behavior. For point 4, I’ll clearly document the supported scope and the chunk-splitting limitation. Thanks again for the helpful suggestions!

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick and complete update! I re-reviewed the latest head (b61f07a) against my previous round on 9881d3e.

What Problem Does This PR Solve?

User pain point: A PostgreSQL numeric cell holding NaN, Infinity or -Infinity aborts the whole JDBC source job, because pgjdbc cannot turn it into a BigDecimal (PSQLException: Bad value for type BigDecimal : NaN in text mode, ClassCastException in binary mode) (#12790).

Fix approach: Add an opt-in, default-off source option numeric_special_value_as_null, carried JdbcConnectionConfig -> JdbcDialectLoader -> PostgresDialectFactory -> PostgresDialect -> PostgresJdbcRowConverter, which reads those three values as null.

One-sentence summary: Let users opt in to reading PostgreSQL numeric special values as null instead of failing the job.

1. Code Change Review

1.1 Core Logic Analysis

All four items from my previous round are addressed:

  • Issue 1 (options tables): added to both docs/en and docs/zh Jdbc.md, and the text matches the code (name, default false, PostgreSQL only).
  • Issue 2 (log volume): PostgresJdbcRowConverter.getDecimalValue now logs once per column (ConcurrentHashMap.newKeySet() guarded by shouldLogNumericSpecialValue) and includes the column label from ResultSetMetaData. The hot path is bounded.
  • Issue 3 (real driver coverage): three JdbcPostgresIT cases with real pgjdbc: text mode, binaryTransfer=true, and the default (flag off) case that must fail the job. The container image is postgis/postgis without a tag, i.e. a current PostgreSQL, and the tests skip via assumeNumericInfinitySupported() below PG 14, so on the CI image they should run. They assert that NaN, Infinity, -Infinity and a real SQL NULL all end up null and that 123.45 is unchanged.
  • Issue 4 (splitter and other dialects): documented in both languages (the note says it does not apply to split range queries and that only PostgreSQL and postgresLow honour it).

The default path is unchanged: with the flag off, getBigDecimal(rs, idx, false) rethrows the original exception, and unrelated errors are rethrown even when the flag is on.

Remaining small items (all non-blocking):

  • Low: getDecimalValue calls isNumericSpecialValue (an extra getString) for every SQL NULL decimal cell when the flag is on, because value == null is also true for a genuine NULL. It is cheap, but it sits on the per-row path; checking rs.wasNull() first, or letting the util tell "special value" from "NULL", would avoid it.
  • Low: the once-per-column log key is only the column index, and JdbcInputFormat uses one converter for all tables of the source. In a multi-table source, a special value in column 2 of table B is not logged if column 2 of table A already logged. Keying by table plus column would fix it.
  • Low: testNumericSpecialValueFailsJobByDefault only asserts a non-zero exit code, so it would also pass if the job failed for an unrelated reason. If the container result exposes stderr, asserting the Bad value for type BigDecimal text would make it a precise guard of the default behavior.
  • Low (inference, not verified): whether binaryTransfer=true makes pgjdbc request binary results on the first execution of this query depends on the driver's prepare threshold. If it does not, the binary test would silently exercise the text path; adding prepareThreshold=-1 to that URL would remove the doubt.

1.2 Compatibility Impact

Fully compatible. The option is optional with default false; JdbcConnectionConfig gains one serializable boolean with a default, so restored splits and old job configs are unaffected.

1.3 Performance / Side-Effect Analysis

Flag off: no extra work. Flag on: only the failure path (and the NULL case noted above) does extra work. Log volume is now bounded.

1.4 Error Handling and Logging

No blocking issues found. Errors are rethrown unless the raw value is exactly one of the three special values.

2. Code Quality Assessment

2.1 Coding Standards

Javadoc is clear, @Slf4j is used, and the new files carry the license header.

2.2 Test Coverage and Test Stability

Unit tests (mocked) plus the new real-driver ITs cover both transfer modes, the flag-off behavior and unrelated errors. Stability rating: Stable for the unit tests; Risk present (minor, see the last two Low items) for the ITs, with no Thread.sleep or fixed ports added.

2.3 Documentation Updates

en and zh are consistent and match the code.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix that follows the existing decimal_type_narrowing / int_type_narrowing pattern.

3.2 Maintainability

Clear; extra constructor overloads are limited to PostgreSQL.

3.3 Extensibility

Other PostgreSQL-compatible dialects would need their own wiring; the docs now say so.

3.4 Historical-Version Compatibility

Compatible; no state or serialization change.

4. Issue Summary

Number Issue Location Severity Status
1 Options table rows docs/*/connectors/source/Jdbc.md Medium Fixed
2 Per-cell WARN log PostgresJdbcRowConverter.java Medium Fixed
3 No real-driver IT JdbcPostgresIT.java Medium Fixed
4 Splitter/other dialects ignore option docs Low Fixed (documented)
5 Extra getString on NULL cells; log key is column index only; weak default-IT assertion PostgresJdbcRowConverter.java, JdbcPostgresIT.java Low Optional

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers - must be fixed
  2. Recommended fixes - non-blocking
    • Issue 5 items, at your discretion.

Overall assessment: safe, opt-in and default-compatible, with real-driver coverage now in place. Thanks for addressing every point so thoroughly. Once CI finishes green I am happy to approve.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the current head 1028469682e9 against dev (17 files, including PostgreSQL text/binary-path unit tests and JDBC PostgreSQL E2E coverage).

The new source-only option is wired end-to-end: JdbcSourceFactory accepts it, JdbcConnectionConfig preserves the default false, JdbcInputFormat passes the config into dialect loading, and only PostgreSQL/PostgresLow dialects opt into the converter behavior. getBigDecimal keeps the original exception for every non-special value and for the default setting; when enabled, it additionally verifies the raw value before mapping only NaN, Infinity, and -Infinity to null. This avoids swallowing genuine JDBC failures.

I also checked the binary-driver ClassCastException path, warning rate limiting, English/Chinese option documentation, and the three E2E configurations. The tests cover normal values, each special literal, default compatibility, and text/binary conversion. No source-level blocker found.

CI: the current Build check is green.

Conclusion: ready from my code-review perspective. A maintainer with repository permission can apply the final approval.

@davidzollo davidzollo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1
LGTM

Thanks for your contribution! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here!

Please ignore the following message if you have joined in the Slack~

To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack

This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄

@davidzollo
davidzollo added this pull request to the merge queue Oct 18, 2026
Merged via the queue into apache:dev with commit d99736f Oct 18, 2026
3 checks passed
Asthenia0412 added a commit to Asthenia0412/seatunnel that referenced this pull request Oct 18, 2026
…r PostgreSQL (apache#12792)

Co-authored-by: yusiwen <yusiwen@jxcc.com>

Signed-off-by: Asthenia0412 <Asthenia0412@users.noreply.github.com>
@siwen-yu
siwen-yu deleted the bugfix/jdbc-pg-numeric-special-value-as-null branch October 19, 2026 00:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] [connector-jdbc] Reading PostgreSQL numeric NaN/Infinity aborts the job with "Bad value for type BigDecimal"

3 participants