Repository navigation
feat(sql): support composite functional indexes - #29472
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
fengttt
left a comment
There was a problem hiding this comment.
Why limit this to single expression index? It is a secondary index, we support secondary index on a few columns, therefore, support one single expression vs supporting several expressions should be mostly the same. Mixing expression and column should be treated the same way, as a column ref is a single expression anyway.
aunjgr
left a comment
There was a problem hiding this comment.
Re-reviewed head 3d4ad81e14ab7660dbb247eb8bd54472fa7fe976, including the v107 repair and the complete functional-expression persistence/replay path. REQUEST_CHANGES for one remaining P2.
The previous capability finding is closed: current main ends at v106, and this head consistently uses the fresh v107 for functional-index authoring, the 4.0.13 STATISTICS upgrade and its handler. The positive composite fixture now uses v107 and the current-main v106 rejection control remains.
[P2] Preserve string literals when saving functional expression SQL (pkg/sql/plan/functional_index.go:249-251, also the rewrite at :379). OriginString is rendered with only tree.WithQuoteIdentifier(). That formatter leaves P_char literals unquoted. I ran a parser/formatter probe using this head's exact call:
input: lower('AbC')
saved expression: lower(AbC)
reparsed argument type: *tree.UnresolvedName
The eligibility checks admit literals and LOWER/UPPER over VARCHAR. SHOW CREATE emits this OriginString verbatim (build_show_util.go:407-413), and COPY/LIKE/checkpoint reconstruction replay it. An accepted index such as INDEX ix ((lower('AbC'))) is therefore rendered as an identifier expression: replay fails when there is no abc column, or changes the definition from a constant to lower(abc) when such a column exists. This breaks definition round-trip and can change the generated index key after COPY.
Use the existing persistence-safe expression rendering at both OriginString producers, preserving literal bytes and keeping the replay inside the admitted expression subset. Extend the current DDL round-trip/lifecycle tests with a string literal, a same-named source-column control, quotes/backslashes and SQL-mode changes; compare the bound expression/value before and after SHOW/LIKE/COPY rather than only checking that parsing succeeds.
The parser/formatter probe completed on the reviewed source with the installed jemalloc dependency; I did not execute an end-to-end CREATE/LIKE SQL reproduction or rerun the full planner suite. The claim above follows from that observed AST change and the traced authoring/SHOW/replay consumers. Current CI remains in progress and is separate from this correctness finding.
Nonblocking PR-description cleanup: the body still says authoring v105, a 4.0.11/v101 STATISTICS upgrade and a v104 allocation. The source now uses v107 and 4.0.13/v107; update the description to the final contract.
|
Implemented the latest P2 in commit
Validation on macOS/arm64: |
|
Re-reviewed exact latest head The previous string-literal persistence finding is closed. Both Independent real-MySQL-client reproduction on a fresh one-CN embedded cluster:
The earlier protocol-allocation and composite-fixture issues also remain fixed: authoring and the 4.0.13 STATISTICS upgrade use MORPC 107, above the current-base 106, and the positive composite fixture uses 107. The PR description now reflects that contract. Fresh exact-head validation on native macOS:
Non-blocking test improvement: the newly added lifecycle subtest checks rendered definitions and successful LIKE/COPY replay, but does not insert rows and assert the backing values. Consider incorporating the value oracle above so a future replay that parses successfully but changes a constant into a source-column expression is caught automatically. Scope limits: this does not approve general MySQL functional-expression parity, JSON functional indexes, range/covering access, online COPY, or guaranteed prepared-parameter matching. Full distributed BVT, full repository tests, old-binary upgrade and mixed-version execution were not run. Latest-head CI was still pending when checked; skipped upgrade jobs are not compatibility evidence. |
There was a problem hiding this comment.
Re-reviewed exact head 856911b against declared base 1a00887. No remaining blocking finding; approve the documented initial functional-index subset.
The previous string-literal persistence finding is closed. Both OriginString producers now use single-quoted, mode-independent literal rendering, and the eligibility extension is limited to binary-form text literals needed for replay. My exact-head parser/formatter probe confirms lower('AbC'), embedded quotes and backslashes retain literal syntax rather than becoming column references; backslashes render as cast(0x615c62 as varchar).
Read all changes since the previously reviewed 3d4ad81 revision, traced the formatter and replay consumers, and reused the existing review of unchanged feature closures. Exact-head author validation reports targeted planner/compiler/checkpoint/upgrade tests and all functional SQL integration scenarios passing, plus an actual backing-value challenge across SHOW CREATE replay, LIKE, COPY and source rename under NO_BACKSLASH_ESCAPES. Those end-to-end runs were not rerun locally in this pass. Required CI is green; skipped upgrade jobs are not counted as upgrade proof. The earlier v107 capability correction remains intact.
Nonblocking test improvement: incorporate the reported actual backing-value oracle into the committed literal lifecycle regression; it currently checks definitions and successful replay, rather than inserted-row values after LIKE/COPY. This is not a remaining correctness blocker. No production changes were made during review.
LeftHandCold
left a comment
There was a problem hiding this comment.
Reviewed exact head 712548df84fda5d50a88580f366251efe6b54666 against base/merge-base 56478b6a570a4612db643d65e182703b79916b65. REQUEST_CHANGES: one independently reproduced wrong-result blocker.
[P1] Rebuild a functional index replaced under the same name in one COPY ALTER.
Location: build_alter_table.go:372-380.
The new DROP INDEX branch removes the definition and its backing columns without recording that this index identity was replaced. If the same ALTER adds another ix, the later SkipIndexesCopy calculation (lines 560-572) still marks the original name as unaffected. The copy INSERT skips index maintenance (bind_insert.go:3670), and cloneUnaffectedIndexes matches the old and new indexes by name and clones the old keys. The base row's generated value and SHOW CREATE reflect the new expression, while the physical index retains the old expression's values.
Reproduced through a real MySQL client using this exact head's Linux CI artifact (BUILD_INFO and --version verified), on a fresh isolated one-CN/TN/log-service instance:
CREATE TABLE t(id INT PRIMARY KEY, v INT, INDEX ix((v+1)));
INSERT INTO t VALUES(1,10),(2,20);
ALTER TABLE t DROP INDEX ix, ADD INDEX ix((v+2));
SELECT id FROM t WHERE v+2=12; -- actual: empty; expected: 1
SELECT id FROM t FORCE INDEX(ix) WHERE v+2=12; -- actual: empty
SELECT id FROM t IGNORE INDEX(ix) WHERE v+2=12; -- actual: 1EXPLAIN confirms an Index Table Scan on t.ix. The base backing values are 12 and 22, but the physical index still contains the serialized old 11 and 21 keys. The mismatch also reproduces from a fresh connection. Reversing the ADD/DROP clause order reproduces it; replacing with a different index name, issuing DROP and CREATE separately, and recreating the same expression under the same name are passing controls. This is a silent SQL wrong result after a successful DDL, not merely a missing optimization.
Track dropped/replaced index identities when deciding reuse, and exclude same-statement replacements from both skipped maintenance and old-index cloning. Add this counterexample to the existing composite lifecycle fixture, asserting actual index access and index/full-scan agreement before any subsequent DML; preserve the different-name and unchanged-expression controls.
Review coverage/evidence:
- Read all 38 changed files/hunks and traced DDL ownership/rebinding, generated DML/FK consumers, equality matching/residuals, SHOW/STATISTICS, checkpoint reconstruction and the v107/4.0.13 gates. The existing hidden-generated-column/COPY design remains appropriate. Previous protocol and literal-persistence findings remain closed.
- CI run 37768605480 is successful on this exact head. Downloaded UT evidence confirms all three functional SQL integration scenarios passed. The pessimistic BVT execution log confirms
ddl/functional_index.sqlran: 41/41 successful, zero failed/ignored/abnormal. Those existing scenarios miss the same-name replacement above. - Independent actual-value literal replay across LIKE/COPY under
NO_BACKSLASH_ESCAPESpassed, including same-named source-column, quote and backslash controls.git diff --checkpassed. No production changes were made; probe databases were removed and cleanup verified. - Lifecycle audit: planner metadata is privately copied; internal COPY SQL shares the outer transaction; temporary maps are statement-scoped, and this patch adds no independent worker/wait queue. The blocker is incorrect index reuse, rather than a newly confirmed cleanup or concurrency defect.
- Skipped upgrade jobs are not compatibility proof. No live mixed-version rollout or live checkpoint export/restore was performed in this review.
…ex' into codex/issue-29300-functional-index
|
已同步当前 修复 reviewer 指出的同名 functional index 替换问题:同一条 新增回归覆盖:
本地验证通过:
新 head 的 CI 正在重新运行。 |
|
Addressed the latest same-name replacement finding in commit
Validation: |
|
Re-reviewed exact head The same-name DROP/ADD wrong-result finding is closed. Recording dropped functional-index identities and forcing Independent real-MySQL-client validation on a fresh one-CN embedded cluster built from this exact head: CREATE TABLE t(id INT PRIMARY KEY,v INT,INDEX ix((v+1)));
INSERT INTO t VALUES(1,10),(2,20);
ALTER TABLE t DROP INDEX ix,ADD INDEX ix((v+2));
SELECT COUNT(*) FROM t FORCE INDEX(ix) WHERE v+2=12; -- 1
SELECT COUNT(*) FROM t IGNORE INDEX(ix) WHERE v+2=12; -- 1EXPLAIN confirms an actual Index Table Scan. The same oracle passes for reversed ADD/DROP clause order and a replacement named I also reran the independent literal-value oracle: a mixed index with Fresh exact-head checks: all Scope: incremental review of the latest replacement repair/main integration, with earlier protocol/literal/ownership closures cross-checked. This does not claim general MySQL functional-index parity, online COPY, or guaranteed range/covering/prepared-parameter matching. No full repository local suite, mixed-version rollout or live checkpoint export/restore was run. No production source edits were made. The earlier suggestion to commit actual literal backing-value assertions remains non-blocking. |
LeftHandCold
left a comment
There was a problem hiding this comment.
APPROVE — reviewed head 3ab10ef70621fba01c0b0fa95a98770c0fe92e24 against base/merge-base 83d82b8ee0cd694e0c6a7146902d74ae4dfb415a. No remaining blocking finding. This supersedes my request-changes review on 712548df84 for same-name functional-index replacement.
The wrong-result path is closed: DROP records the canonical index identity, and the final COPY options explicitly set the original index's SkipIndexesCopy entry to false. I traced both consumers: the replacement INSERT now maintains its new index, and cloneUnaffectedIndexes excludes the dropped index before constructing its clone set. Deferred ADD binding preserves clause-order independence; canonical name matching also handles case variants. The committed regression checks indexed/full-scan agreement immediately after ALTER, proves actual Index Table Scan, and includes different-name and unchanged-expression controls.
Coverage: read all 37 changed files/hunks and checked the current design against the earlier design/review decisions. Traced expression eligibility and per-part ownership, COPY/drop/rename/rebind, generated INSERT/UPDATE/FK row images, equality matching with base-row residuals, SHOW/STATISTICS, checkpoint reconstruction, and the MORPC 107 / 4.0.13 upgrade gates. Checked relevant changes merged from main against these consumers. Earlier literal-persistence, legacy-prefix and source-map isolation fixes remain intact. The implementation continues to reuse existing generated-column, secondary-index and transactional COPY ownership; it adds no independent worker or wait queue.
Validation reused from exact-head CI run 37796348039, after inspecting downloaded execution evidence:
- Required CI is successful. Linux/x86 UT, Linux/arm64 SCA, shared build, coverage, Connector/J and both distributed BVT lanes pass.
- UT summary explicitly records
TestFunctionalCompositeIndexLifecyclePASS (16.99s),TestFunctionalIndexCascadeAndRenamePASS (12.39s), andTestFunctionalIndexLifecyclePASS (5.94s). - UT checkpoints confirm all eight planner shards completed successfully; the successful light race-test invocation includes compiler, checkpointtool, bootstrap/4.0.13, cnservice and sysview packages.
- The compose execution artifact confirms
ddl/functional_index.sqlactually ran: 41 total, 41 successful, zero failed/ignored/abnormal. - Locally, the full PR range passes
git diff --check; the isolated review checkout has no source modifications.
Scope limits: I reused CI and recorded author evidence rather than rerunning service tests locally in this pass. Skipped upgrade jobs are not mixed-version proof; no live mixed-version rollout or checkpoint export/restore was performed here. Approval covers the documented initial functional-index subset, including its COPY rebuild cost, rather than broader expression/range/covering support. The existing suggestion to add materialized literal-value assertions to the committed lifecycle test remains nonblocking.
Merge Queue Status
This pull request spent 41 seconds in the queue, with no time running CI. ReasonPull request #29472 has been dequeued Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.
HintYou should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it. Waiting for any of
All conditions
Tick the box to put this pull request back in the merge queue (same as
|
What type of PR is this?
Which issue(s) this PR fixes:
Related to #29300 and #28053. This is an independent implementation, not a continuation of draft #28274. It intentionally does not close #29300: the report does not identify the exact failing InvenTree expression, and this increment does not support all MySQL functional expressions.
What this PR does / why we need it:
Add named, non-unique BTREE functional indexes on ordinary persistent tables, including multiple expressions and mixed ordinary-column/expression key parts:
Implementation
Lower each eligible expression key part to its own index-owned hidden generated column; retain ordinary-column parts directly and preserve key order. Reuse generated-column evaluation and secondary-index maintenance. Key-position ownership supports repeated expressions without collisions and preserves existing single-expression naming.
Validate all expression parts before publishing hidden columns. Validate persisted ownership, expression types and orphan columns; reject explicit writes to backing columns.
Use atomic COPY ALTER for standalone index creation/addition/removal and source-column MODIFY/CHANGE/RENAME. Rebind against the final schema so reordering or widening cannot leave stale key types. DROP removes every hidden column owned by that index.
RENAME/renaming CHANGE rewrites only owned expression identifier AST nodes before COPY replay; ordinary generated/default dependency guards remain.
Parent FK CASCADE/SET NULL recomputes affected owned functional values from the final child row image before recursive actions and existing index maintenance. Unrelated functional values remain unchanged; ordinary generated/ON UPDATE restrictions are not relaxed.
Keep backing values before synthesized composite keys and retain them in PRE_INSERT's materialized column list. INSERT IGNORE's auto-increment marker uses the same width, including hidden generated values.
Match typed equality predicates to persisted expressions, use equality index backfill, and retain original base-row residuals. Covering/range functional access is not enabled.
Expose each expression through SHOW CREATE/SHOW INDEX/STATISTICS and preserve mixed/composite keys in LIKE and checkpoint reconstruction. Checkpoint expression maps are deep-copied and reject missing backing expressions.
Gate authoring with MORPC v107. Existing STATISTICS views are refreshed through the dedicated 4.0.13 tenant upgrade, which runs at protocol v107.
DROP COLUMN of an ordinary index part rebases surviving expression ownership to the new key ordinals before COPY replay; dropping an expression source remains rejected.
Scope and costs
The safe allowlist covers integer
+,-,*,abs, CHAR/VARCHARlower/upper, identity casts and same-signedness integer widening. Generated dependencies are checked recursively. JSON extraction/conversion, temporal/session-dependent expressions, UNIQUE functional indexes, prefixes/directions, INCLUDE, special algorithms and temporary/cluster/external tables remain unsupported. Prepared statements remain valid but parameter predicates are not guaranteed index matching.COPY operations rebuild the table; this is not online/in-place index construction. No performance claim is made. See
docs/design/20260929-functional-index-initial-support.mdfor the precise boundary.Validation
Current multi-part change, native macOS/arm64:
Latest DROP COLUMN validation:
Earlier FK/rename reviewer-fix validation:
TestFunctionalSQL integration tests passed (15.671 s): both FK/index creation orders, dependent/unrelated CASCADE, SET NULL, self/recursive actions, composite primary-key changes, rollback, overflow atomicity and connection recovery, RENAME/CHANGE widening/reorder, SHOW/STATISTICS/LIKE and index/full-scan comparison. Composite primary/cluster-key, keyless and auto-increment INSERT IGNORE controls also pass.Prior multi-part validation (unchanged checkpoint paths):
Historical initial-version evidence (Linux/arm64 Docker, before this multi-part revision): production build, complete checkpoint/sysview/v4.0.11 tests, single-expression client lifecycle, real-client BVT statements and restart/persisted-metadata smoke passed. These are not claimed as fresh multi-part Linux validation.
Remote CI and distributed/platform matrix validation remain pending.
Landing coordination
Current main assigns MORPC v105 to lock-service drain and v106 to CDC; this branch uses fresh cumulative MORPC v107 for functional-index metadata and the 4.0.13 STATISTICS upgrade. Keep this ordering when landing related protocol changes. A protocol number must not be reused independently by two deployed binaries, because that does not establish rolling-upgrade compatibility.