Skip to content

fix(plan): honor SET NULLIF and reader options in LOAD DATA INLINE - #32198

Merged
mergify[bot] merged 5 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-31232-main-11ad6689
Nov 5, 2026
Merged

mergify[bot] merged 5 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-31232-main-11ad6689

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Related to #31232

What this PR does / why we need it:

LOAD DATA INLINE silently ignored supported SET ... NULLIF clauses and
stored the raw values, and dropped LINES STARTING BY (input rejected with
20101), while the byte-identical file-backed LOAD DATA INFILE honored every
option. The same loss applied to FORMAT='jsonline' INLINE loads, to prepared
INLINE loads re-planned across a session sql_mode change, and — after the
transport fix — to CREATE EXTERNAL TABLE definitions whose SET clause
uses a row variable.

Root cause

  1. Plan-to-execution option transport (the reported defect). The planners
    serialize the parsed tree.ExternParam into TableDef.Createsql for
    file-backed scans, but getExternParam rebuilt INLINE parameters by hand
    from a small subset (Data, Format, IgnoredLines, Fields, JsonType),
    dropping NullMap (the SET sentinel rules) and Tail.Lines (prefix /
    terminator options). getColData applies param.Extern.NullMap when
    reading, so INLINE loads read rows with the mapping missing.
  2. Prepared-statement replans. Making the transport survive also has to
    keep repeated planning of the same retained AST correct: the column
    NULLIF expressions are consumed into the map during normalization, and a
    naive serializer left a half-consumed AST that a rebuilt plan could not
    re-normalize; row-variable (NULLIF(@v, literal)) wrappers similarly had
    to stay attached so every replan re-derives the __mo_load_user_var_ scan
    column and the assignment projection instead of falling back to the target
    column DEFAULT.
  3. External-table metadata. CREATE EXTERNAL TABLE calls the same
    InitNullMap normalization and then published the live statement param via
    json.Marshal into the catalog CREATE property. Retaining the
    row-variable wrapper put a live tree.Expr interface into that property —
    encoding/json cannot reconstruct it — so SHOW CREATE TABLE and every
    scan of the new table failed with
    json: cannot unmarshal object ... ExternParam.Tail.Assignments.0.Expr of type tree.Expr.

Exact changes

  • pkg/sql/plan/bind_load.go + pkg/sql/plan/build_load.go: the LOAD
    planners serialize a source param through the existing planning channel
    (marshalLoadSourceParam) for INLINE and INFILE alike; serialization works
    on a copy, stripping consumed column expressions so the parsed statement
    stays replayable; InitNullMap keeps the row-variable wrapper attached and
    recognizes an already-normalized statement by the explicit
    hasUnconsumedColumnNullIf scan.
  • pkg/sql/compile/compile.go: getExternParam unconditionally deserializes
    the saved source param and restores the INLINE payload/escape byte from the
    plan (ExternScan), so both scan types honor identical parsed options.
  • pkg/sql/plan/build_ddl.go: new marshalExternalTableParam — the CREATE
    EXTERNAL TABLE publish site serializes from a stripped copy (ColumnList
    dropped, assignment Exprs null), restoring the base published metadata
    shape (reader options + sentinel map, no expression interface) while the
    statement keeps its expressions for the rest of its planning session.
  • Tests: focused UTs in pkg/sql/plan and pkg/sql/compile and four BVT
    cases under test/distributed/cases/load_data/ (details below).

Issue-to-test proof

  • INLINE CSV SET flag=NULLIF(flag,0) stores NULL for 0 (file-backed pair
    does the same); the no-SET control keeps raw values; unsupported SET stays
    rejected with 20105 and inserts nothing —
    UT TestInlineLoadSerializesSourceParam, TestGetExternParamReconstructsInlineSourceParam; BVT
    issue_31232_inline_load_options (50/50).
  • INLINE JSONLINE (jsondata='object') applies the same mapping; prefix
    LINES STARTING BY, IGNORE n LINES and explicit ESCAPED BY compose with
    it; the inline omitted-escape default (backslash byte is literal data)
    stays byte-compatible —
    UT TestInlineLoadEscapeBytePlanning, TestInlineLoadEscapeByte; BVT
    issue_31232_inline_escape (35/35).
  • Prepared inline LOAD with unchanged sql_mode (plan reused) and with
    ONLY_FULL_GROUP_BY flipped between PREPARE and EXECUTE (plan rebuilt)
    both keep the mapping: column form and row-variable form
    ((id, @v) + SET payload=NULLIF(@v,'sentinel') never substitutes the
    target DEFAULT) —
    UT TestSerializedSourceParamSurvivesReplan,
    TestSerializedSourceParamSurvivesUserVariableReplan (both planner surfaces);
    BVT issue_31232_prepare_rebuild (26/26).
  • CREATE EXTERNAL TABLE ... SET flag=NULLIF(@v,'sentinel') (base-accepted
    form) stays fully usable: SHOW CREATE TABLE renders, SELECT scans (the
    row-variable form is inert at scan time — external tables have no load
    column list — so raw values read back), DROP leaves no residue; the column
    form keeps its live sentinel mapping —
    UT TestCreateExternalTableParamMetadataRoundTrips; BVT
    issue_31232_external_table_metadata (16/16, run twice).
  • Pre-fix RED for each item above was demonstrated live and/or in UT on the
    pre-fix code (e.g. the external-table witness CREATE succeeded then
    SHOW CREATE/SELECT failed with the json decode error; the inline SET stored
    (1,'alpha',0) where NULL was expected).

Test commands

Focused (exact selections, mo-cgo-test wraps go test):

mo-cgo-test -count=1 -run 'TestCreateExternalTableParamMetadataRoundTrips|TestSerializedSourceParamSurvivesUserVariableReplan|TestSerializedSourceParamSurvivesReplan|TestInlineLoadSerializesSourceParam|TestInlineLoadEscapeBytePlanning|TestIssue29849|TestLoadNullIfCollate|TestExternalNullIfCollated' ./pkg/sql/plan
mo-cgo-test -count=1 -run 'TestGetExternParamReconstructsInlineSourceParam|TestInlineLoadEscapeByte' ./pkg/sql/compile

Unfiltered owning packages:

mo-cgo-test -count=1 -timeout=3600s ./pkg/sql/plan ./pkg/sql/compile

BVT (mo-tester, comparison mode; path points at the case file):

java io.mo.Tester path=test/distributed/cases/load_data/issue_31232_inline_load_options.sql method=run
java io.mo.Tester path=test/distributed/cases/load_data/issue_31232_inline_escape.sql method=run
java io.mo.Tester path=test/distributed/cases/load_data/issue_31232_prepare_rebuild.sql method=run
java io.mo.Tester path=test/distributed/cases/load_data/issue_31232_external_table_metadata.sql method=run

All of the above passed on the committed source (focused: ok; packages: both
ok with no failing tests; BVT: 50/50, 35/35, 26/26, 16/16×2 at 100%).

Residual risks

  • LOAD DATA SET remains limited to NULLIF(column, literal) /
    NULLIF(@variable, literal) (20105 otherwise); this PR does not extend the
    supported SET grammar.
  • For catalog external tables the row-variable SET form is accepted but inert
    at scan time (no load column list exists); the column form is what scans
    apply. SHOW CREATE TABLE for read-only external tables masks FILEPATH
    (pre-existing behavior, unchanged).
  • Two pre-existing formatting-drift files in pkg/sql/plan
    (apply_indices_score_expr_test.go, visit_plan_rule_test.go) are
    committed-at-base drift and are intentionally untouched by this PR.
  • Existing legacy result files load_data_set_null.sql and
    load_data_jsonline.test carry older metadata expectations that this PR
    does not regenerate; broader suite validation is left to repository CI as
    usual.

Rebase note (conflict resolution against upstream main)

Upstream main refactored the LOAD prescan/serialization into a shared
prepareLoadScan helper (pkg/sql/plan/bind_load.go, used by both planner
surfaces), and widened validateLoadSetAssignments with a tableDef
argument (hidden-storage-column rejection). The rebase keeps upstream's
prepareLoadScan structure and resolves it semantically with this PR:

  • prepareLoadScan now serializes through the copy-based
    marshalLoadSourceParam channel for INLINE and INFILE alike; the
    ScanType != INLINE file-only guard is gone, and the old in-place
    clearing of Tail.ColumnList/Tail.Assignments before serialization is
    replaced by the copy-based stripping, so the retained PREPARE AST keeps
    its column list and assignment trees for replans.
  • Upstream's new TestPrepareLoadScanPrescanAndFailure expectation that
    Tail.ColumnList is cleared after the scan was updated to the retained
    AST contract (require.Len(..., 1); cleared-transport invariant is
    instead asserted by deserializing Createsql), since the clearing is
    what this PR removes by design.
  • The PR's issue_31232_replan_source_param_test.go passes the mock
    nation table def to the widened validateLoadSetAssignments.

The stale pre-upgrade-bump thirdparties usearch artifacts
(usearch-2.26.5-20261030 shipped by upstream) were rebuilt locally via
make cgo so the rebased head compiles. Affected tests were re-run after
the resolution: the focused selection (all issue UTs, downstream/upstream
prescan and TestDependent* suites) and the unfiltered owning packages
pkg/sql/plan and pkg/sql/compile both pass locally; BVT reruns are
left to repository CI.

CI fix (0cbe119): environment-neutral BVT show-create assertions

The pessimistic-BVT job failed on this PR's new
issue_31232_external_table_metadata case because the recorded
show create table result pinned an exact INFILE{...} rendering whose
FILEPATH is environment-specific (the runner's absolute path differs
from any local recording). Both assertions now use mo-tester
-- @regex directives (the repo's established convention, as in
test/distributed/cases/dml/show/show_create_table.sql) to match the
deterministic parts and a wildcarded resource path, plus a negative
guard that rejects an emptied FILEPATH. The recorded .result lines
now follow the $resources convention. The coverage job's failure was
downstream of the same BVT failure (coverage merge blocked because the
pessimistic producer did not publish a profile); no Go code changed in
this follow-up commit.

CI fix (a3a865e): repair invalid mo-tester @regex directives

The PROXY multi-CN Compose BVT run (41942948439, job 126972490914)
aborted with Invalid regex pattern 'INFILE\\{'FILEPATH'='',': Illegal repetition near index 7 from ScriptParser.parseRegexFlag:
mo-tester compiles the quoted -- @regex content literally, and the
double-backslash escapes over-escaped (\\{ never compiled as a brace
escape; \\. would only match a literal backslash before the dot),
crashing the runner at script-parse time before the suite could run.
The four affected directives in
issue_31232_external_table_metadata.sql now use repository-standard
character-class escaping ([{], [.]). All twelve directives were
verified to compile under java.util.regex and hold against the
recorded SHOW CREATE output (include=true found, include=false not
found); SQL statements and expected results are unchanged.

LOAD DATA INLINE rebuilt its execution ExternParam from a hand-written
subset of the parsed options, dropping the SET NULLIF sentinel map and
the LINES options that file-backed loads publish through the serialized
source param, so inline loads silently stored raw values for supported
SET mappings, lost the line prefix, and rejected their input. INLINE now
shares the same serialized source-param channel as INFILE and restores
it at execution, preserving the established inline escape-byte default.

Prepared statements keep normalizing and re-deriving those rules on every
replan: the transport serializes from a stripped copy of consumed column
expressions, while the row-variable wrapper stays attached to the
statement so a rebuilt plan keeps the row-variable scan column and the
assignment projection instead of falling back to the target default
(prepared inline loads that change sql_mode between PREPARE and EXECUTE).

CREATE EXTERNAL TABLE shares the same InitNullMap normalization and
published the live statement param into its catalog CREATE property
metadata. With the wrapper now retained, that property carried a
non-reconstructible expression interface and made SHOW CREATE TABLE and
every scan of the new table fail on the json decode. The publish site
now serializes from a stripped copy too, restoring the base metadata
shape: the definition keeps reader options and the sentinel map, and
never persists an expression interface.

Related to matrixorigin#31232
…nt-neutral

The recorded show-create result embedded an environment-specific INFILE
rendering, so the pessimistic BVT failed on CI where the absolute runner
path differs. Switch both show create table assertions to mo-tester
-- @regex directives (repo convention, e.g. dml/show/show_create_table.sql)
and drop the empty-FILEPATH rendering from the recorded result.
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH XuPeng-SH 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.

mo-bot review · mo-bot-local · review

Commit: a3a865e8f2c1ebc94a8aa30575166b5e0ab3fe26

Assessment: approve

The fix reuses the existing source-parameter transport for INLINE, keeps the retained AST replayable, and preserves external-table metadata decoding. No actionable correctness or design defects found.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Reviewed all 24 changed files and affected planner, prepared-rebuild, reader and catalog consumers.

  • Reused successful frozen-head CI: native build, Ubuntu UT, arm64 SCA, coverage, and PROXY/pessimistic multi-CN BVT.

  • Local Java probe passed all 12 regex directives and 30 positive/negative assertions.

  • Source, patch and formatting audit passed; four receipts and both discussion entries reconciled. Checkout unchanged.

Limitations:

  • Raw CI/author execution logs were unavailable; Go and SQL/BVT suites were not rerun locally.

  • The local Java probe validates assertion syntax and guards, not server behavior.

@mergify mergify Bot added the queued label Nov 5, 2026
@mergify

mergify Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

❌ Left the queue · checks failed

1 h 29 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Thu 5 Nov, 03:13 · rule main · triggered by rule Automatic queue on approval for main
  • ❌ Checks failed · in place
  • 🚫 Left the queue 04:43 · 577c1ac

The failure is in this pull request. It failed tested alone on top of main.

Reason

The merge conditions cannot be satisfied due to failing checks

  • CI Required

To get back in the queue

  • Push a fix: the pull request is queued again once its queue conditions match.
  • If the failure is a flake, tick the box below to queue it again as it is.

Merge conditions not met when it left the queue

  • any of · required by GitHub branch protection:
    • check-neutral = CI Required
    • check-skipped = CI Required
    • check-success = CI Required

Requeue requested — the merge queue status continues in this comment ↓.

2 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection

Times in UTC · dashboard · how the merge queue works

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Unresolved unrelated CI blockers tracked in existing issues

The failed required check CI Required on run 41960295112 (attempt 1, head 577c1ac) is driven by the UT Test on Ubuntu/x86 job. Its three failing test cases are unrelated to this PR's diff (LOAD DATA inline plan/compile handling only):

The failed jobs were rerun once for attempt 1 (gh run rerun 41960295112 --failed). No changes were made to this PR to mask these failures.

@mergify

mergify Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as 1d51125 at 08:09 UTC

2 h 9 min in the queue, 1 h 16 min of it CI.

So far

  • ✅ Entered the queue Thu 5 Nov, 06:00 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Passed · in place
  • ✅ Merged 08:09 · 1d51125 · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

@mergify mergify Bot removed the dequeued label Nov 5, 2026

@aunjgr aunjgr 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 all 24 changed files and the LOAD planning, assignment validation, retained-AST replay and external-table metadata consumers. INLINE now reconstructs reader options through the shared serialized-source channel while retaining its established escape-byte behavior. Copy-based publication keeps PREPARE's column/assignment state replayable, and external-table properties exclude non-decodable expression interfaces without losing column NULLIF mappings.

The tests independently cover actual loaded values, file/inline controls, omitted/custom escapes, unsupported SET rejection, mode-driven prepared replans and external-table SHOW CREATE/readback. No blocking findings. Reused latest-head green CI (including both BVT modes) and the source-bound focused/owning-package evidence in the PR; no local tests were rerun.

This branch was previously deployed

1 inactive deployment
ci — 95202c76 Deployed Nov 5, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants