Skip to content

fix(#6409): normalize WITH-setting keys, refuse duplicates everywhere, fix node identity for CASE/ORDER BY/INSERT SET - #6413

Merged
lvca merged 3 commits into
mainfrom
issue-6409
Aug 18, 2026
Merged

lvca merged 3 commits into
mainfrom
issue-6409

Conversation

@lvca

@lvca lvca commented Aug 18, 2026

Copy link
Copy Markdown
Member

Summary

Follow-ups from #6401 (merged as #6407), collected while asking, for each parser node, "does identity actually work here now". Fixes items 1-4 of #6409; item 5 is a documented cost, not a defect, so no code change.

  • Item 1 - IMPORT DATABASE, EXPORT DATABASE and BACKUP DATABASE built their WITH setting keys as a raw name parked in the node's inherited value slot, while REBUILD INDEX and REBUILD TYPE already built a proper new Expression(Identifier). All five now build the key the same way, and every reader recovers it the same way (toString()). This also removes the defensive raw-value read (and its CommandExecutionException fallback) in BackupDatabaseStatement that existed only because the old shape was fragile - the shape that, pre-fix(#6401): a hash code is a property of the value, and an expression's value is every field that carries one #6407, made a backup asked to be encrypted get written in clear.
  • Item 2 - only REBUILD TYPE refused a duplicate WITH setting; the other four silently accepted one, last one wins. A shared SQLASTBuilder#putSetting helper now refuses a repeat - keyed on the lowercased name, matching the equalsIgnoreCase every reader already uses to recognise a setting - in all five statements.
  • Item 3 - a sweep for parser nodes whose identity does not work, widening the corpus test Follow-ups from #6359: an untested rollback arm, an extraction now safe to do, and two defects in the SQL parser's node identity (one of them a broken hashCode contract) #6401 left as a starting point (Issue6401NodeIdentityTest#equalNodesAnswerEqualHashCodes). Confirmed and fixed:
    • ArrayRangeSelector (a[1..3]) had no getIdentityElements() at all - two parses compared unequal (under-match), exactly as Follow-ups from #6401: two shapes for a WITH settings key, a duplicate setting that means three different things, and a sweep for nodes whose identity does not work #6409 called out.
    • OrderByItem and InsertSetExpression are plain (non-SimpleNode) helper classes referenced from a parent's identity list, with no equals()/hashCode() of their own - same under-match, breaking identity for any statement carrying an ORDER BY or an INSERT ... SET.
    • CaseExpression had the opposite failure: no identity override of its own meant it inherited MathExpression's, which reads childExpressions/operators - fields CaseExpression never populates - so two structurally different CASE WHEN expressions over-matched as equal to each other. Confirmed with a throwaway reproduction before fixing (see differentCaseExpressionsAreNotTheSameExpression in the test).
  • Item 4 - SimpleNode.equals() indexed the other node's identity array by this node's length, with no guard. Harmless today because every override returns a fixed-length array literal, but a future override built conditionally would throw ArrayIndexOutOfBoundsException out of equals(). Added the length guard the issue suggested.
  • Item 5 - hashCode() being O(subtree) is an inherent, correctly-paid cost of hashing a tree, not a defect (per the issue's own text). No code change; nothing hashes a parsed node on a hot path today.

Better alternative to what the issue proposed

The issue floated normalizing item 1's key shape and centralizing item 2's duplicate guard as two separate, independent changes. This PR does both through one shared SQLASTBuilder#putSetting helper: since the key shape and the dedup-key derivation both start from the same Identifier, doing them in one place means there is exactly one spot that knows how a WITH setting key is built, for all five statements including REBUILD TYPE (which previously duplicated the guard logic inline). That is also the "best alternative" for item 3: rather than hand-auditing the ~67 getIdentityElements() overrides, the corpus test that #6401 already had was widened, which is what actually caught OrderByItem, InsertSetExpression and the CaseExpression over-match - none of which the issue text had identified.

Test plan

  • New Issue6409FollowupsTest: all five WITH-settings statements build the same key shape and round-trip through toString(); all five refuse a duplicate setting (case-sensitive and case-insensitive); distinct settings still work; SimpleNode.equals() doesn't throw on a variable-length identity array.
  • Widened Issue6401NodeIdentityTest#equalNodesAnswerEqualHashCodes with ArrayRangeSelector, ORDER BY, CASE WHEN, and all five WITH-settings statements; added differentCaseExpressionsAreNotTheSameExpression for the over-match direction.
  • Fixed two pre-existing tests (ImportDatabaseStatementTestParserTest, ExportDatabaseStatementTestParserTest) that read the old raw-value shape directly.
  • mvn -o -pl engine -am test on: the full com.arcadedb.query.sql.parser package (389 tests), the full ORDER BY suite across sql, sql.executor, index and select packages, SQLCaseTest, DatabaseAdminStatementsTest, RebuildTypeRepartitionTest - all green.
  • Full reactor mvn -o compile - green.

🔗 Closes #6409

…e always refuses, and identity holds for CASE, ORDER BY and INSERT SET

Follow-ups from #6401/#6407 collected while asking, for each parser node, "does identity actually work
here now":

- Item 1: IMPORT, EXPORT and BACKUP DATABASE built their WITH setting keys as a raw value parked in the
  node's inherited value slot, while REBUILD INDEX and REBUILD TYPE already built a proper identifier
  expression. All five now build the key the same way (new Expression(Identifier)), and every reader
  recovers it the same way (toString()), removing the defensive raw-value read in BackupDatabaseStatement
  that existed only because the old shape was fragile.
- Item 2: only REBUILD TYPE refused a duplicate WITH setting; the other four silently accepted one, last
  one wins. A shared SQLASTBuilder#putSetting helper now refuses a repeat - keyed on the lowercased name,
  matching the equalsIgnoreCase every reader already uses - in all five statements.
- Item 3: a sweep for parser nodes whose identity does not work, widening the corpus test #6401 left as a
  starting point. Confirmed and fixed: ArrayRangeSelector (a[1..3] under-matched, comparing unequal to
  itself), OrderByItem and InsertSetExpression (same under-match, breaking identity for any statement
  carrying an ORDER BY or an INSERT ... SET), and CaseExpression (the opposite failure: no identity
  override of its own meant it inherited MathExpression's, which reads fields CaseExpression never
  populates, so two structurally different CASE WHEN expressions over-matched as equal).
- Item 4: SimpleNode.equals() indexed the other node's identity array by this node's length with no
  guard; harmless today because every override returns a fixed-length array, but one built conditionally
  would throw ArrayIndexOutOfBoundsException out of equals(). Added the length guard.
- Item 5 (hashCode is now O(subtree)) is a documented cost, not a defect - no code change.
@lvca lvca self-assigned this Aug 18, 2026
@mergify

mergify Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

Went through the diff in detail (SQLASTBuilder, the five WITH-settings statements, ArrayRangeSelector, CaseExpression/CaseAlternative, OrderByItem, InsertSetExpression, SimpleNode) and cross-checked each claim in the description against the actual field lists and call sites rather than taking the PR body at face value. It holds up.

Correctness spot-checks that passed:

  • CaseExpression extends MathExpression and does not override getIdentityElements() before this PR - confirmed MathExpression.getIdentityElements() returns childExpressions/operators, both unpopulated by CaseExpression. The over-match bug as described is real, and the new override (caseExpression, alternatives, elseExpression) covers exactly the populated fields.
  • ArrayRangeSelector's new getIdentityElements() (from, to, newRange, included, fromSelector, toSelector) matches the class's full field list - no field left out that would cause a false-equal.
  • OrderByItem/InsertSetExpression are plain helper classes referenced from OrderBy.getIdentityElements() / InsertBody.equals() via List/Objects.equals(), so they do need their own equals/hashCode for the parent's identity to work at all - confirmed by reading both call sites. Field coverage in the new equals()/hashCode() matches each class's full field list.
  • The Expression(Identifier) -> toString() round-trip for the WITH-setting key actually works: Expression's toString(params, builder) delegates to mathExpression.toString(...) when rid/whereCondition/etc. are all null, so a plain identifier renders unquoted (encryptionKey, not "encryptionKey"), matching what the reflection-based setters in Backup/Import/ExportDatabaseStatement switch on.
  • ImportDatabaseStatement.toString(Map, StringBuilder) fix (entry.getKey().value -> entry.getKey().toString(params, builder)) is necessary, not just cosmetic: since the key's value slot is now always null (it's built via new Expression(Identifier)), the old line would have silently printed the literal string "null" for every setting name once item 1 landed. Good catch.
  • SimpleNode.equals()'s new length guard is placed after the existing ownElements.length == 0 short-circuit, so it doesn't change behavior for any of the ~67 existing fixed-arity overrides - only protects a future variable-arity one, as intended.

One documentation nit, no functional issue: the new SQLASTBuilder#putSetting Javadoc states the dedup key is lowercased "though every reader recognises a setting with equalsIgnoreCase" - that's only true for REBUILD INDEX/REBUILD TYPE. BackupDatabaseStatement's setting switch is case-sensitive (case "encryptionAlgorithm" ->, not equalsIgnoreCase), and Import/ExportDatabaseStatement just hand the map through by exact key. Lowercased dedup is still the right call defensively and doesn't misbehave here, but the comment overstates uniformity across the five statements - worth a tweak so a future reader doesn't assume BACKUP DATABASE WITH ENCRYPTIONKEY=... currently round-trips through the case-sensitive switch (it doesn't - it would hit the default branch and throw "Unsupported backup setting", independent of the dedup logic).

Test coverage: genuinely thorough - the new Issue6409FollowupsTest covers all four fixed items with both positive and negative cases (case-only duplicate detection, distinct settings still working, the round-trip through toString(), and a purpose-built VariableArityNode for the item-4 guard that a fixed-arity override could never exercise). The widened Issue6401NodeIdentityTest corpus plus the new differentCaseExpressionsAreNotTheSameExpression test correctly cover both the under-match and over-match directions - the latter is the one direction the corpus test (which only ever compares a query against itself) structurally cannot catch, and it's handled with a dedicated test.

I wasn't able to execute mvn test in this review sandbox (build commands require separate approval here), so this is a static review; the PR description's local test run report looks consistent with the code as written.

Overall: solid, well-scoped fix. No blocking issues found.

@codacy-production

codacy-production Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 6 complexity

Metric Results
Complexity 6

View in Codacy

🟢 Coverage 93.33% diff coverage · -6.54% coverage variation

Metric Results
Coverage variation ✅ -6.54% coverage variation
Diff coverage ✅ 93.33% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (2982f55) 161073 128139 79.55%
Head commit (a2d6227) 193617 (+32544) 141357 (+13218) 73.01% (-6.54%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#6413) 15 14 93.33%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

…tive readers

Review on #6413 caught it: the comment said every reader recognises a setting with
equalsIgnoreCase, which is only true for REBUILD INDEX and REBUILD TYPE.
BackupDatabaseStatement's setting switch is exact-case, and Import/ExportDatabaseStatement
hand the key through as-is to the integration-module setter, so for those three the
lowercased dedup is a defensive choice rather than a fix for an existing case-insensitive
read. No behavior change.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

I read through the diff in detail (SQLASTBuilder, the five WITH-settings statements, ArrayRangeSelector, CaseExpression/CaseAlternative, InsertSetExpression, OrderByItem, SimpleNode) and the new/updated tests. Solid, well-scoped follow-up. A few notes:

Code quality / correctness

  • SQLASTBuilder#putSetting is a good consolidation — one place now owns both the key shape and the dedup rule, and the javadoc's second commit (correcting the case-insensitivity claim for BackupDatabaseStatement/Import/ExportDatabaseStatement) is a nice bit of intellectual honesty rather than quietly leaving a misleading comment in place.
  • The CaseExpression#getIdentityElements() fix is the more interesting one of the four items — it's an over-match (two different CASE expressions compared equal via inherited empty MathExpression fields), not the under-match the issue text called out, and differentCaseExpressionsAreNotTheSameExpression is exactly the right kind of test to pin that direction since the corpus test only ever compares a query against itself.
  • SimpleNode.equals()'s new length guard is cheap, correct, and the VariableArityNode test is a good way to exercise a case that doesn't exist anywhere in the codebase yet.
  • Verified field-by-field that the new equals()/hashCode() overrides (CaseAlternative, InsertSetExpression, OrderByItem, ArrayRangeSelector#getIdentityElements) actually match the declared fields — no copy/paste mismatches.
  • BackupDatabaseStatement's removal of the raw-value fallback (with the CommandExecutionException) is a nice cleanup now that every producer builds the key the same way — no more silent fail-safe masking a future regression.

Pre-existing gap noticed (not introduced by this PR, out of scope for #6409 items 1-4)

Test coverage

  • Issue6409FollowupsTest covers all 4 items directly and the widened Issue6401NodeIdentityTest corpus is a good "spread of shapes" rather than an exhaustive walk — reasonable trade-off given ~67 getIdentityElements() overrides exist, as the PR description itself acknowledges.
  • The regression test for the historical BackupDatabaseStatement cleartext-encryption bug (importExportBackupSettingsRoundTripThroughToString) is a good addition given the history called out in the PR description.

Performance / security

  • No concerns. This is parser/AST-only, no hot-path involvement, and item 5 (O(subtree) hashCode()) is correctly left alone since nothing calls it on a hot path today.

Nothing blocking. Nice, tightly-scoped fix with good test coverage for each item.

Code review on this PR caught it: ImportDatabaseStatement#equals() only compared url,
and ExportDatabaseStatement#getIdentityElements() only listed url, so two statements
with the same URL but different WITH settings compared equal. For IMPORT DATABASE this
was the sharper case: a CSV import has no URL at all, so the settings are the statement.
BackupDatabaseStatement already included settings in its identity; the other two now
match it. Same over-match direction as the CaseExpression fix in this PR, on a statement
node instead of an expression node.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

Went through the diff in detail (couldn't execute mvn in this sandbox to confirm the test run, so this is a static/manual trace, not a build confirmation).

Correctness

The core changes hold up under a field-by-field trace:

  • SQLASTBuilder#putSetting is used consistently by all five WITH-settings statements (REBUILD INDEX, REBUILD TYPE, IMPORT DATABASE, EXPORT DATABASE, BACKUP DATABASE); dedup is keyed on the lowercased name while the stored key preserves original case, matching the existing equalsIgnoreCase readers.
  • entry.getKey().toString() correctly replaces the old raw-value read everywhere it's consumed (BackupDatabaseStatement, ExportDatabaseStatement, ImportDatabaseStatement, plus the two parser tests) - no leftover .value reads on settings keys remain in src/main.
  • New getIdentityElements()/equals()/hashCode() overrides (ArrayRangeSelector, CaseAlternative, CaseExpression, InsertSetExpression, OrderByItem) list every field the class actually populates - checked each against the class's field declarations and found no field omitted or extra.
  • The ImportDatabaseStatement/ExportDatabaseStatement identity now including settings is safe because Expression.getIdentityElements() was already made content-based in the prior PR (fix(#6401): a hash code is a property of the value, and an expression's value is every field that carries one #6407) - so Map<Expression,Expression>.equals()/hashCode() won't suffer from a stale identity-based key hash. Worth double-checking this chain held for BaseExpression/MathExpression too, since that's the one place a latent bug would hide (map lookups silently missing due to an unstable key hash) - but nothing in this diff touches that.
  • SimpleNode.equals()'s new length guard is a genuine, if currently dormant, defensive fix - correctly placed after the getClass() check so it only ever compares same-shaped nodes' arrays.

Style / process

  • Good adherence to CLAUDE.md conventions: final used throughout, no curly braces on the one-liner if guards, no new dependencies, Javadocs explain why rather than what.
  • Nice touch keeping the historical "cleartext backup" defect referenced in comments/tests as a regression guard rather than just fixing and moving on.
  • The PR bundles a genuine bug fix (item 1, the cleartext-backup-adjacent key shape), a hardening fix (item 2, duplicate settings), and a broader identity sweep (item 3/4) in one PR. Given the shared root cause (SQLASTBuilder#putSetting touches items 1+2 in one place, as the description argues), this is a reasonable bundling call rather than needless PR inflation - but it does make the diff review surface wider than any single item would need.

Test coverage

Solid - Issue6409FollowupsTest covers both the under-match and over-match directions, case-insensitive dedup, and the VariableArityNode regression test for item 4 is a nice way to exercise dead-but-important code without waiting for a future subclass to trip it. The widened Issue6401NodeIdentityTest corpus is a reasonable proxy for the ~67 getIdentityElements() overrides without hand-auditing all of them, though as the PR itself notes, it's a representative spread rather than exhaustive - any override not exercised by one of the corpus queries is still unverified either way.

Minor observations (non-blocking)

  • BackupDatabaseStatement's dedup is now case-insensitive even though its consuming switch is exact-case (documented deliberately in the Javadoc as "defensive, not a functional fix"). That's a reasonable call, just flagging it's a slight behavior change beyond the stated bug fixes: WITH compressionLevel = 1, COMPRESSIONLEVEL = 2 now fails to parse where before it would have silently kept the last one (which itself was arguably already broken given the exact-case switch would have only honored one of them anyway).
  • No functional issue found, but nothing in this PR runs a build/test cycle I can independently confirm from this environment - worth relying on the CI run for the final green light rather than the PR description's local run alone.

Overall: a well-scoped, well-tested follow-up. No bugs found in the static review.

@codecov

codecov Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.66667% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.92%. Comparing base (2982f55) to head (a2d6227).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...va/com/arcadedb/query/sql/antlr/SQLASTBuilder.java 86.66% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6413      +/-   ##
==========================================
+ Coverage   70.87%   70.92%   +0.04%     
==========================================
  Files        1855     1855              
  Lines      161073   161230     +157     
  Branches    33847    33865      +18     
==========================================
+ Hits       114158   114348     +190     
+ Misses      32975    32954      -21     
+ Partials    13940    13928      -12     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@lvca lvca added this to the 26.9.1 milestone Aug 18, 2026
@lvca
lvca merged commit e557d68 into main Aug 18, 2026
47 of 49 checks passed
@lvca
lvca deleted the issue-6409 branch August 18, 2026 21:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant