Skip to content

fix view select star - #26964

Merged
XuPeng-SH merged 32 commits into
matrixorigin:mainfrom
daviszhen:0811-fix-select-star
Aug 16, 2026
Merged

XuPeng-SH merged 32 commits into
matrixorigin:mainfrom
daviszhen:0811-fix-select-star

Conversation

@daviszhen

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:

issue #26957

What this PR does / why we need it:

此分支主要修复 View SELECT * 的列集合不稳定问题。

修改内容:

  • 创建/替换 View 时,如果 View body 使用 SELECT * / table.*,在 planner bind 阶段捕获已经展开后的 select-list。

  • 持久化 View 时把 * 改写成显式列引用,例如:

    • 原来:create view v as select * from t
    • 现在持久化为:create view v as select \t.a, t.bfromt``
  • 同步更新 ViewData.Stmt 和 mo_catalog.mo_tables.rel_createsql,避免后续查询、SHOW CREATE、dump/restore 再按基表当前 schema 重新展开 *。

  • 保留非 star View 的原始 SQL 行为不变。

  • 增加反向保护:COUNT(*) 不会被误判为需要展开的 View 输出列。

  • 补充 UT,验证:

    • star View 持久化后不再含 *
    • 基表新增列后,SELECT * FROM view 仍只返回创建时列
    • 新增列不能通过 View 访问
    • COUNT(*) 不被重写
  • 补充 BVT,覆盖:

    • ADD FIRST / ADD AFTER 后 View 结果列不变
    • explicit view column list 保持稳定
    • information_schema.columns、CTAS、INSERT SELECT、nested view 形状一致
    • 未选中列 rename/drop 不影响 View

@daviszhen
daviszhen requested a review from a user August 11, 2026 08:48
@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.

Deep review at exact head 87a41a6836f5b9d53f3029debab83d2805a586a0 found correctness and performance blockers:

  1. SAMPLE(*) is classified as an ordinary star by selectExprHasStar, but stableViewSQLWithExpandedStars replaces the entire select list with expandedSelectList. This drops the sampling operator from the persisted view definition. I reproduced with CREATE VIEW v_sample AS SELECT SAMPLE(*, 100 PERCENT) FROM nation: the stored statement becomes create view v_sample as select nation.n_nationkey, ... from nation, so subsequent reads execute an ordinary full projection rather than the requested sample. Star expansion must preserve the surrounding SampleExpr semantics (or exclude this syntax from this rewrite until it can be transformed correctly), with a create/rebind regression.

  2. The fix does not cover stars under a top-level set operation. bindSelect returns directly from the *tree.UnionClause case before assigning ctx.expandedSelectList, and viewSelectHasStar does not traverse UnionClause. I reproduced CREATE VIEW v_union AS SELECT * FROM nation UNION ALL SELECT * FROM nation; ViewData.Stmt still contains both stars. Adding a base-table column therefore still changes that view schema (or can make unequal branches fail). Please make the rewrite structurally cover every result-producing branch/set-op and test ALTER TABLE after UNION/UNION ALL views.

  3. ctx.expandedSelectList = cloneTreeSelectExprs(selectList) runs unconditionally for every SELECT query block, including normal queries and nested subqueries, and reflectively deep-clones even explicit expression lists that will never be used. That adds allocation/CPU to the global planner hot path for a CREATE/ALTER VIEW-only feature. Gate capture on an explicit view-DDL builder option/callback so ordinary SELECT planning pays no cost; add an allocation/benchmark check if needed.

  4. The BVT failures are deterministic consequences of the patch, not environment noise. At least database/create_table_like.sql, three pessimistic_transaction/clone/clone.sql assertions, statement-query-type cases, and information_schema view-definition assertions still expect the old stored/show definition. Decide the compatibility contract, then update all affected fixtures (and avoid unrelated whole-file output-format churn). Both standalone pessimistic and compose proxy BVT must be clean.

The core direction—freezing ordinary view wildcard outputs at creation—is correct, but the rewrite boundary must preserve every non-star operator, cover set operations, and avoid taxing all SELECTs.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Fixed in commit 2b17cea6e5.

  • Star detection now traverses WITH CTE definitions, including recursive CTEs and set-operation branches.
  • View SQL rewriting clones the WITH/CTE AST and recursively freezes every captured SELECT * while preserving non-SELECT CTE statements.
  • Added test/distributed/cases/view/view_star_cte_static_columns.sql and its result file, covering CREATE VIEW, ALTER VIEW, recursive CTE + UNION, and rebinding after a base-table column is added.

Validation:

  • Full pkg/sql/plan tests passed.
  • Focused Race tests for CTE/view-star rewriting passed.
  • git diff --check passed.

The new BVT checks are running on the pushed head.

@aptend aptend 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.

Re-review of 503792bdbe49479894d076c5e2ff12289205a4c6: the earlier SAMPLE/UNION/hot-path/CTE issues are addressed, but one blocking AST-coverage gap remains.

[P1] Expand stars inside expression subqueries before persisting the view SQL. The current detection/rewrite walks select lists, WITH branches, unions, and FROM table expressions, but it does not descend through expression nodes in the projection/predicates (and similarly other expression-bearing clauses). On this exact head I reproduced both:

  • create view v_nested as select (select * from one_col) as x
  • create view v_nested as select n_nationkey from nation where n_nationkey in (select * from one_col)

with a one-column one_col table. Both successfully create the view and persist the literal * in ViewData.Stmt. After the source acquires another column, the scalar/IN subquery can return two columns, so the saved view no longer has stable semantics and may fail to rebind with “operand should contain 1 column”. Please extend star detection plus clone/rewrite through subquery expressions in all expression-bearing query positions, and add create/alter/rebind regressions for these cases.

Validation: focused view-star tests pass; full ./pkg/sql/plan passes under the repository CGo/thirdparties environment. The two temporary counterexamples above fail because the persisted SQL still contains *.

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

Deep re-review of exact head 048d5cbc9c3a00c08d192a30632e4a4868bf25ab: the prior SAMPLE/UNION/hot-path/CTE and SELECT/WHERE expression-subquery blockers are fixed, but one AST-coverage correctness gap remains.\n\n[P1] Rewrite subqueries inside JOIN ... ON conditions before persisting the view. tableExprHasStar and viewTableExprWithExpandedStars recurse through JoinTableExpr.Left and .Right, but neither inspects or clones/replaces JoinTableExpr.Cond (OnJoinCond.Expr). Therefore a wildcard reachable only through ON is not detected and the entire saved SQL remains dynamic.\n\nI reproduced on this exact head with a one-column one_col table:\n\nsql\nCREATE VIEW v_join_star AS\nSELECT n.n_nationkey\nFROM nation n JOIN region r\n ON n.n_regionkey = r.r_regionkey\n AND n.n_nationkey IN (SELECT * FROM one_col);\n\n\nViewData.Stmt is persisted verbatim with SELECT *. After adding a second column to one_col, reparsing and binding that persisted definition fails with invalid input: subquery returns more than 1 column. Thus the view is still schema-unstable even though the equivalent SELECT-list and WHERE shapes are now covered.\n\nPlease traverse and rewrite the ON expression (while preserving USING/NATURAL conditions), and add CREATE/ALTER plus post-ALTER rebind regressions. It is also worth auditing other expression-bearing TableExpr implementations, especially table-function arguments, so this does not become another one-clause-at-a-time fix.\n\nValidation: all existing focused view-star tests and the full ./pkg/sql/plan package pass; the temporary exact-head counterexample above fails only at the expected post-schema-change rebind.

@daviszhen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH addressed the remaining P1 from the latest review in commit 15af818f9cd8df671b902cd0481c413811fc9169.

Changes made:

  • Traversed JoinTableExpr.Cond and rewrote OnJoinCond.Expr, so subqueries under JOIN ... ON are now included in the persisted view-star expansion path.
  • Preserved USING / NATURAL join conditions unchanged.
  • Added TableFunction.Func expression traversal while auditing adjacent table-expression carriers.
  • Restored top-level ORDER BY / LIMIT / TIMEWINDOW expression rewrite coverage after merging latest main.
  • Added create/alter/rebind regressions for the reported JOIN ... ON ... IN (SELECT * FROM one_col) shape.
  • Added BVT coverage in view_star_static_columns.sql/result for create, alter, and source-table-add-column stability.

Local validation:

  • go test ./pkg/sql/plan -run 'TestGenViewTableDefPersistsExpandedExpressionSubqueryStars|TestBuildAlterViewPersistsExpandedJoinOnSubqueryStars|TestStableViewSQLWithExpandedStarsRewritesAlterExpressionSubquery|TestStableViewStarHelpersRewriteCTEUnionAndRecursiveBranches|TestGenViewTableDefPersistsExpandedCTEStars|TestGenViewTableDefPersistsExpandedUnionStars|TestGenViewTableDefPersistsExpandedStarSelectList|TestGenViewTableDefPreservesSampleStar|TestGenViewTableDefExpandedStarFromDerivedAggregateCanRebind' -count=1
  • go test ./pkg/sql/plan -count=1
  • BVT SQL/result sync check: 52 commands, 0 missing
  • git diff --check

The branch has also been merged with latest upstream/main (3af8be1e400d). Please re-review when you have time.

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

[P1] Preserve ordinary view wildcards when a different subtree contains SAMPLE(*).

On exact head 15af818, stableViewSQLWithExpandedStars returns the original SQL whenever viewSelectHasSampleStar(stmt) is true anywhere in the statement (pkg/sql/plan/build_ddl.go:289). That statement-wide guard prevents stabilization of unrelated ordinary wildcards.

I reproduced it with:

create view v_outer as select * from nation where exists (select sample(*, 100 percent) from region)

BuildPlan succeeds, but the persisted ViewData.Stmt still contains select * from nation. The nested SAMPLE expression does not define the outer output list, so adding a column to nation can still change the stored view shape, which is the bug this PR is intended to prevent.

Please keep SAMPLE() nodes intact while independently expanding ordinary wildcards in other select blocks, rather than disabling the whole rewrite. Add a create/alter/rebind regression combining an outer *, a nested SAMPLE(), and a base-table column addition. The latest JOIN ON and table-function traversal fixes are otherwise in the right direction.

@iamlinjunhong iamlinjunhong 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 exact head d296db0ce93e17fe326a372dcc356ae94e4412f0 against merge-base/origin main 1f9e501594509fb5d2e0284833faf8c3426e2285. Two P1 correctness gaps remain in the view-star stabilization closure: (1) a SELECT block mixing an ordinary wildcard with SAMPLE skips capture for the whole block; (2) ROLLUP/CUBE/grouping-set expansion returns before the original SELECT clause is captured. Both leave supported CREATE VIEW definitions with dynamic ordinary stars, so a later base-table column addition can change the view shape or make rebinding fail. No separate P2/P3 findings. Requesting changes.

Comment thread pkg/sql/plan/query_builder.go Resolved
Comment thread pkg/sql/plan/query_builder.go Resolved

@iamlinjunhong iamlinjunhong 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 exact head d4effd2bc95384e7bd95c8feca398a3e33b4bdfc against merge-base/origin main 1f9e501594509fb5d2e0284833faf8c3426e2285. The two P1s from my previous review—mixed ordinary-star/SAMPLE capture and the grouping-set early return—are fixed. One P1 correctness gap remains: a SAMPLE(*) output is still persisted as a wildcard and re-expands when the source schema changes, so the view's executable shape can diverge from its creation-time catalog shape. No separate P2/P3 findings. Requesting changes.

Comment thread pkg/sql/plan/build_ddl.go Outdated
}
expandedSelectList, ok := expandedSelectLists[selectStmt]
if ok {
if selectClauseHasSampleExpr(selectStmt) && !selectClauseHasOrdinaryStar(selectStmt) {

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.

[P1] Freeze the columns inside SAMPLE(*) instead of keeping this query block's source AST verbatim. For example, create t(a,b), then CREATE VIEW v AS SELECT SAMPLE(*, 100 PERCENT) FROM t, and add t.c. The persisted statement still contains SAMPLE(*); bindView reparses and binds that statement on every use (query_builder.go:10051,10114), so the sample projection grows from two columns to three while the view catalog still has the creation-time two columns. The mixed SELECT *, SAMPLE(*) path has the same problem because cloneViewSelectExprsForView puts the original sample wildcard back. The current BVT only executes count(*) after the ALTER, which cannot detect this output-shape drift. Please preserve the sampling operator but replace its star with the captured creation-time column list, then cover SELECT * FROM v and rejection of the newly added column after source DDL.

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

Re-review of exact head d4effd2bc95384e7bd95c8feca398a3e33b4bdfc. The previous outer-star/nested-SAMPLE issue is fixed, but one blocking traversal hole remains.

[P1] Stabilize subquery stars inside SAMPLE's column expressions.

SampleExpr.columns is unexported (pkg/sql/parsers/tree/expr.go:1850), and SampleExpr.Accept does not visit it (:1876-1881). Both reflective passes introduced here silently skip fields for which CanInterface() is false (pkg/sql/plan/build_ddl.go:529-533 and :1006-1011). Therefore a subquery nested in a SAMPLE column expression is neither detected nor rewritten.

I reproduced this with the exact-head service (and separately with a focused planner test):

CREATE TABLE one_col(id INT);
CREATE TABLE src(k INT);
CREATE VIEW v AS
  SELECT sample((SELECT * FROM one_col UNION ALL SELECT 1), 1 rows)
  FROM src;
SHOW CREATE VIEW v;
ALTER TABLE one_col ADD COLUMN extra INT;
EXPLAIN SELECT * FROM v;

SHOW CREATE VIEW still contains SELECT * FROM one_col; after the legal base-table change, rebinding fails with SQL parser error: SELECT statements have different number of columns. Thus an accepted view definition remains schema-dependent, contrary to this PR's invariant.

Please make SAMPLE participate in the normal exhaustive AST child traversal/cloning contract (or handle GetColumns() explicitly in both passes), rather than relying on reflection that silently ignores private children. Add a create/show-create/rebind regression for this shape, including the post-ALTER TABLE failure condition.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Addressed in commit 2e4228b9b921d6cafc5172bffdfc2a37b07085cf.

  • SAMPLE(*) is now frozen at view-creation time: the persisted view SQL keeps the SAMPLE operator but replaces * with the visible source-column list. Rebinding after adding a source column keeps the original view shape.
  • SampleExpr.Accept now visits its private columns children. The view star-detection and clone/rewrite passes also explicitly traverse GetColumns(), so stars inside subqueries used as SAMPLE arguments are expanded before persistence.
  • Mixed ordinary * plus SAMPLE(*) and the existing ROLLUP/CUBE/GROUPING SETS paths remain covered; the distributed view_star_nested_sample BVT now checks persisted SQL, post-DDL column shape, row output, and rejection of a newly added source column.

Validation passed:

  • go test ./pkg/sql/parsers/tree ./pkg/sql/plan -count=1
  • git diff --check

Please re-review the latest commit.

@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 exact green head 0a5809b. The earlier CTE, expression-subquery, JOIN ON, grouping-set, mixed-star, and SAMPLE(*) persistence gaps are closed. The current capture/rewrite path freezes creation-time columns while preserving SAMPLE semantics, and the rebinding tests cover the relevant public boundaries. No blocking findings.

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

Deep re-review of exact head 0a5809b. The latest SAMPLE fix closes the private-child traversal blocker: SampleExpr now participates in visitor traversal, view capture freezes SAMPLE wildcard columns at CREATE/ALTER time while preserving the sampling operator, and both detection and cloned rewrite paths explicitly handle its private columns. I re-audited set operations, CTEs, derived and expression subqueries, JOIN ON, table functions, grouping sets, and top-level expression carriers. Focused exact-head parser and planner regressions passed; public create/alter/rebind BVT coverage is green; git diff --check is clean; all current-head checks are terminal without failures.

This branch was previously deployed

1 inactive deployment
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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants