fix(planner): Reject null in not null columns on update #28689
<!-- Generated by sourcery-ai[bot]: start review_guide -->
Reviewer's Guide
The planner now rejects NULL values assigned to NOT NULL columns during UPDATE, shares the validation and error construction with MERGE, and resolves fail functions from the configured default namespace so MERGE works with native sidecars. Java and native Iceberg tests cover rejected writes, no-match behavior, and sidecar-enabled execution.
Sequence diagram for NOT NULL validation in UPDATE and MERGE
sequenceDiagram
participant Planner as QueryPlanner
participant Plan as PlannedWrite
participant Fail as DefaultNamespace.fail
alt UPDATE assigns a NOT NULL column
Planner->>Planner: checkNotNullUpdatedColumns
Planner->>Planner: failIfNull
Planner->>Plan: Add checked projection
Plan->>Fail: Evaluate fail when value is NULL
else MERGE writes a NOT NULL column
Planner->>Planner: checkNotNullColumns
Planner->>Planner: failIfNull
Plan->>Fail: Evaluate fail when value is NULL
end
File-Level Changes
| Change | Details | Files |
| ------ | ------- | ----- |
| Adds planner-time validation for UPDATE assignments to NOT NULL columns and reuses the existing validation behavior. | <ul><li>Collects updated column names alongside assignment expressions.</li><li>Wraps projected values for non-nullable updated columns with a shared NULL-checking failure expression.</li><li>Preserves updates that affect no rows and allows nullable columns to receive NULL.</li></ul> | presto-main-base/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java |
| Centralizes NOT NULL error construction and resolves the fail function through the configured default namespace. | <ul><li>Refactors MERGE validation to use the shared fail-if-null helper.</li><li>Replaces hardcoded presto.default.fail references for NOT NULL and multiple-match MERGE errors.</li><li>Enables MERGE execution with native sidecars.</li></ul> | presto-main-base/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java |
| Expands Java and native Iceberg coverage for NOT NULL behavior across UPDATE and MERGE. | <ul><li>Tests rejected NULL assignments, conditional expressions, and successful no-match operations.</li><li>Verifies existing rows remain unchanged after rejected updates.</li><li>Runs native coverage with configurable sidecar enablement and checks successful MERGE insert behavior.</li></ul> | presto-iceberg/src/test/java/com/facebook/presto/iceberg/IcebergDistributedTestBase.java<br/>presto-native-tests/src/test/java/com/facebook/presto/nativetests/iceberg/TestIcebergUpdateAndMergeNotNull.java |
---
<details>
<summary>Tips and commands</summary>
Interacting with Sourcery
@sourcery-ai review on the pull request.issue from a review comment by replying to it. You can also reply to a
review comment with
@sourcery-ai issue to create an issue from it.@sourcery-ai anywhere in the pullrequest title to generate a title at any time. You can also comment
@sourcery-ai title on the pull request to (re-)generate the title at any time.@sourcery-ai summary anywhere inthe pull request body to generate a PR summary at any time exactly where you
want it. You can also comment
@sourcery-ai summary on the pull request to(re-)generate the summary at any time.
@sourcery-ai guide on the pullrequest to (re-)generate the reviewer's guide at any time.
@sourcery-ai resolve on thepull request to resolve all Sourcery comments. Useful if you've already
addressed all the comments and don't want to see them anymore.
@sourcery-ai dismiss on the pullrequest to dismiss all existing Sourcery reviews. Especially useful if you
want to start fresh with a new review - don't forget to comment
@sourcery-ai review to trigger a new review!Customizing Your Experience
Access your dashboard to:
summary, the reviewer's guide, and others.
Getting Help
</details>
<!-- Generated by sourcery-ai[bot]: end review_guide -->
These lists are built in table-column order, but the native UPDATE path still passes targetColumnNames (assignment order) into planUpdateAsMerge, which indexes orderedColumnValues with that list. Thus UPDATE ... SET b = NULL, a = ... on (a, b NOT NULL) can validate the NULL as b but write it into a, allowing the NOT NULL assignment to succeed while swapping values. Pass orderedColumnNames to the native path (and use that name in the helper), and add a reordered-SET regression test; otherwise the new guard does not enforce the advertised behavior for native UPDATE.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
The native UPDATE path can misapply reordered assignments and bypass NOT NULL enforcement; fix the column ordering and add regression coverage.
<details open>
<summary><strong>1 open issue</strong></summary>
</details>
<details>
<summary><strong>What changed in this PR</strong></summary>
Adds NOT NULL enforcement for UPDATE and reuses the active default namespace for MERGE failure handling.
Changes:
MERGE compatibility.| File | Summary |
|---|---|
| presto-native-tests/src/test/java/com/facebook/presto/nativetests/iceberg/TestIcebergUpdateAndMergeNotNull.java | Adds native UPDATE and MERGE coverage. |
| presto-main-base/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java | Implements shared null validation and namespace resolution. |
| presto-iceberg/src/test/java/com/facebook/presto/iceberg/IcebergDistributedTestBase.java | Adds Java UPDATE constraint tests. |
</details>
<sub>Review effort: Lite</sub>
<!-- ccr-overview-v2 -->
🔵 Needs a closer look
The change spans planner behavior, native execution, and multiple test suites, warranting final human review.
No open issues 🎉
<details>
<summary><strong>1 resolved since last review</strong></summary>
</details>
<sub>Review effort: Lite</sub>
@sourcery-ai review
⚪ Low · Malformed error punctuation passes
When an update error contains a different character, or no character, after column, the three assertQueryFails calls at lines 3557–3559 pass their expected text as regexes, so the unescaped . after column matches any character and accepts an error message missing the required period.
Escape the literal period in each expected message, as the native test's notNullError helper does.
<details>
<summary>Prompt for AI agents</summary>
~~~markdown
In presto-iceberg/src/test/java/com/facebook/presto/iceberg/IcebergDistributedTestBase.java at lines 3557-3559:
Malformed error punctuation passes
When an update error contains a different character, or no character, after column, the three assertQueryFails calls at lines 3557–3559 pass their expected text as regexes, so the unescaped . after column matches any character and accepts an error message missing the required period.
Escape the literal period in each expected message, as the native test's notNullError helper does.
~~~
</details>
✅ Addressed in df0dbb63391709c84c2e2c973526fca6a6b35bbf: The three expected error strings now escape the period after “column” as \. so the assertions require the literal punctuation.
Hey - I've found 1 issue
<details>
<summary>Prompt for AI Agents</summary>
~~~markdown
Please address the comments from this code review:
Individual Comments
Comment 1
<location path="presto-iceberg/src/test/java/com/facebook/presto/iceberg/IcebergDistributedTestBase.java" line_range="3557-3559" />
<code_context>
+ assertUpdate("CREATE TABLE " + tableName + " (a BIGINT, b BIGINT NOT NULL, c BIGINT NOT NULL)");
+ assertUpdate("INSERT INTO " + tableName + " VALUES (1, 2, 3), (4, 5, 6)", 2);
+
+ assertQueryFails("UPDATE " + tableName + " SET b = NULL WHERE a = 1", "NULL value not allowed for NOT NULL column. Table: " + tableName + " Column: b");
+ assertQueryFails("UPDATE " + tableName + " SET c = NULL", "NULL value not allowed for NOT NULL column. Table: " + tableName + " Column: c");
+ assertQueryFails("UPDATE " + tableName + " SET c = IF(a = 4, NULL, c)", "NULL value not allowed for NOT NULL column. Table: " + tableName + " Column: c");
+ assertQuery("SELECT a, b, c FROM " + tableName, "VALUES (1, 2, 3), (4, 5, 6)");
+
</code_context>
<issue_to_address>
Malformed error punctuation passes
When an update error contains a different character, or no character, after column, the three assertQueryFails calls at lines 3557–3559 pass their expected text as regexes, so the unescaped . after column matches any character and accepts an error message missing the required period.
Escape the literal period in each expected message, as the native test's notNullError helper does.
</issue_to_address>
~~~
</details>
***
<details>
<summary>Sourcery is free for open source - if you like our reviews please consider sharing them ✨</summary>
</details>
Fixed in df0dbb6: the period is now escaped in all three assertions, matching notNullError.
Thanks @Joe-Abraham.
Suggestions
1. Describe the column-order fix in the commit, or split it out. In planUpdateAsMerge, the change from targetColumnNames to orderedColumnNames fixes native UPDATE writing values to the wrong columns whenever the SET order differs from table order. That's a data-correctness bug that deserves its own release note. Right now it ships under "reject null in not null columns on update" with no commit body.
2. Describe the namespace change too. Moving from presto.default to getDefaultNamespace() also changes MERGE's multiple-match error, which is unrelated to NOT NULL. One sentence in the commit body saying why (native sidecar namespaces) would help.
3. Rename the overload. There are now two checkNotNullColumns methods with different shapes and meanings: one wraps a single Expression for MERGE, the other rewrites a PlanAndMappings for UPDATE. Something like checkNotNullUpdatedColumns would make the call sites easier to read.
4. Add a test for an UPDATE that matches no rows: UPDATE t SET b = NULL WHERE a = 999 should succeed with 0 rows. The folding analysis above says it does, but pinning it down guards against a future optimizer that folds fail() eagerly. The same applies to MERGE.
Nits
- The checkNotNullColumns(Update node, ...) signature.
- The assignments.put(checkedVariable, rowExpression(failIfNull(...))) line. Pulling metadata.getFunctionAndTypeManager().getDefaultNamespace() into a local before the loop also stops it being recomputed for every column.
@nmahadevuni I've pushed changes for these:
1. I moved the column-order fix into its own PR, #28690.
2. PRs here get squash-merged, so I put the reason for the namespace change in the PR description, which becomes the commit message.
3. Renamed it to checkNotNullUpdatedColumns.
4. Added the no-match cases for both UPDATE and MERGE, in the Java and the native tests. They pass with the sidecar on and off.
I also wrapped the long lines and moved the namespace lookup out of the loop. I kept randomTableSuffix() because that's what the rest of IcebergDistributedTestBase uses.
Thanks @Joe-Abraham, this looks good. Reusing failIfNull for both UPDATE and MERGE keeps the error in one place, and resolving fail through the default namespace is the right fix for the sidecar. A few small suggestions, mostly on simplicity and test coverage.
Code
1. QueryPlanner.java:1066: Assignments.builder().putAll(identityAssignments(subPlan.getRoot().getOutputVariables())) (from AssignmentUtils) is shorter than the stream().collect(toImmutableMap(Function.identity(), Function.identity())) form. LogicalPlanner already uses it. I see the same stream form at line 1274, so feel free to skip this if you'd rather match the file.
2. QueryPlanner.java:1050: checkNotNullUpdatedColumns only uses node for node.getTable().getName(). Passing a QualifiedName tableName would make the helper's inputs clearer and match how failIfNull is called.
3. QueryPlanner.java:492: nesting the coerce(...) call inside the checkNotNullUpdatedColumns(...) arguments makes the order of the two steps harder to see. Something like this reads better:
PlanAndMappings coerced = coerce(builder, orderedColumnValues, analysis, idAllocator, variableAllocator, metadata);
PlanAndMappings planAndMappings = checkNotNullUpdatedColumns(node.getTable().getName(), coerced, orderedColumnNames, orderedColumnValues, updatedColumnMetadata);
4. QueryPlanner.java:1050: columnNames and columnValues are parallel lists that only line up because they are built together in plan(Update). A short note in the Javadoc saying they must be in the same (table column) order would help the next reader. The Javadoc could also mention that the method adds a ProjectNode and returns new mappings for the checked values, since that isn't obvious from "Wraps the SET value...".
Tests
5. The PR also changes the namespace for MERGE's multiple-match error, but no test runs that path on the sidecar. Could you add a case to TestIcebergUpdateAndMergeNotNull (or a MERGE test next to it) where two source rows match one target row and the query fails with One or more rows in the target table matched multiple source rows? Without it, a regression in that part of the fix wouldn't be caught.
6. IcebergDistributedTestBase.testUpdateNullIntoNotNullColumn: two UPDATE cases would be worth adding:
- Several columns in the SET list in a different order from the table, e.g. SET c = NULL, b = 7 WHERE a = 1. The error should name c. This checks that the name and value lists stay matched in checkNotNullUpdatedColumns.
- A value that needs coercion, e.g. SET b = CAST(NULL AS INTEGER) on the BIGINT NOT NULL column. This checks that the null check still applies after coerce.
7. testMergeNonNullableColumns covers an implicit NULL from a WHEN NOT MATCHED THEN INSERT (nation_name) ... that leaves out the column, and a NULL produced by TRY(5/0). The native testMergeIntoNotNullColumn has neither. Adding the implicit-NULL insert there would test the MergeInsert branch of checkNotNullColumns on the sidecar too.
@aditi-pandit Thanks, I've pushed de0b816 with these:
checkNotNullUpdatedColumns now takes the table name, coerce runs into its own local first, and the Javadoc says what the method adds and that the two lists must be in table column order.testMergeMultipleSourceRowsMatch to the native test. It fails on the sidecar if the multiple-match fail goes back to presto.default.SET c = NULL, b = 7 case and the CAST(NULL AS INTEGER) case.For 1, I kept the stream form since the rest of the file uses it.
The native tests pass with the sidecar on and off.
Thanks @Joe-Abraham. You will need to rebase these changes though.
Thank you @aditi-pandit
aditi-pandit
Joe-Abraham
Description
UPDATElet you set aNOT NULLcolumn toNULL.INSERTandMERGEalready block this, and nowUPDATEdoes too.I also made
MERGEreuse the same check, so the code lives in one place. It now looks up thefailfunction in the default namespace rather than hardcodingpresto.default, which fixesMERGEon native clusters with the sidecar. The same change applies toMERGE's multiple-match error, which used the same hardcoded name.Motivation and Context
A
NULLin aNOT NULLcolumn breaks reads later. On Iceberg with Parquet, the read fails. With ORC,WHERE col IS NULLdoesn't find the row.With the native sidecar, every
MERGEfailed becausepresto.default.faildoesn't exist there.This was split out of #28040 during review.
Impact
UPDATEthat sets aNOT NULLcolumn toNULLnow fails, with the same error asMERGE.MERGEworks on native clusters with the sidecar.Test Plan
UPDATEwithNULLon aNOT NULLcolumn.UPDATEandMERGE, run with the sidecar on and off.UPDATEandMERGEthat set aNOT NULLcolumn toNULLbut match no rows succeed, in both the Java and native tests.UPDATEandMERGEtests still pass.UPDATEthat writes rows. Locally, any nativeUPDATEthat writes rows fails at commit withContent offset is required for DV: the worker sends deletion vectors that the coordinator commits as plain position deletes. That is a separate bug.Contributor checklist
Release Notes
Please follow release notes guidelines and fill in the release notes below.
Summary by Sourcery
Enforce NOT NULL constraints for UPDATE and make MERGE validation compatible with native sidecar deployments.
Bug Fixes:
Enhancements:
Tests: