Skip to content

fix: preserve quoted object names in mo-dump exports - #56

Closed
ck89119 wants to merge 7 commits into
matrixorigin:mainfrom
ck89119:issue-30560-main
Closed

ck89119 wants to merge 7 commits into
matrixorigin:mainfrom
ck89119:issue-30560-main

Conversation

@ck89119

@ck89119 ck89119 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes matrixorigin/matrixone#30560.

Preserve database/table names containing apostrophes and backticks through catalog selection, SHOW CREATE, SELECT and generated restore statements. Bind catalog values as parameters; quote identifiers and CSV paths separately; propagate catalog iteration errors. Server-provided CREATE statements remain unchanged.

Also fix dependent views: a child referencing `zparent` `` could previously export successfully before its parent and fail during restore. Substring matching also mistook literals/comments for dependencies and could loop forever. Reuse the existing MatrixOne parser to collect relation references, then apply a finite dependency sort while moving each original DDL together with its catalog entry.

CTE scope, qualified names and identifier casing are explicit. Honor unused CTE prerequisites when jointly sortable for older eager binders; if those advisory references cycle, enforce the references reachable from the query. This allows newer MatrixOne's valid unused self/missing-reference CTEs without a server-version branch. Required cycles and unsupported SQL return contextual errors before relation output, with nonzero CLI exit and no success marker.

Express the existing unrestricted/empty-denylist depguard policy in the modern configuration syntax, keeping every configured linter enabled.

Validation

On macOS arm64, Go 1.23.0 and this worktree's CGo library:

  • Unfiltered normal UT (-count=1) and race (-race -count=1) for the owning cmd/mo-dump package: 207 test/subtest passes and only the two independently confirmed baseline CSV failures below in each run. The focused collector/sorter/dump regression set passes normally and under race (128 test/subtest events); no tests or assertions were weakened.
  • Configured incremental golangci-lint v1.61.0 against merge base 324c33dbdc7075cd5d7beaafd1e15c76709dd442, including depguard; go vet, gofmt, whitespace checks and standalone build: pass.
  • Real CLI export → MatrixOne restore → result queries: normal, schema-only, selected views with precreated base, independent literal-only views, unused self/missing CTEs, a mixed required/advisory cycle, and a used CTE chain: all pass. Every server-returned CREATE statement is preserved. The original PR executable still reports success but fails the escaped-parent restore on this same instance.
  • This view-order validation uses the existing isolated MatrixOne binary built from ca0343577d733dab775b5a361c3bdf12c558c7fd, not a fresh build of latest main. Earlier quoted ordinary-table and CSV LOCAL round trips from the original PR used MatrixOne 9dfe5c1be92e6ecc2cd32d1ee2deeb54233381c3 and remain historical evidence.

No row-processing path changes. View-bearing databases add one casing query, a complete token scan and an AST parse per view (VALUES additionally validates its header and source); dependency sorting uses at most two linear graph passes. This introduces bounded schema-processing work, not a claim of zero overhead or a measured throughput improvement.

Review follow-up: CTE context boundaries and VALUES views

Correct the overly broad ancestor-mask scan introduced in 3fdcdaf. Resolve CTE names one context at a time: that context's active mask, then its visible bindings, then its parent. Ordinary nested queries inherit the active binding state; entering a different CTE definition uses that declaration's own state. A more distant mask must not hide a nearer binding. This preserves the earlier forward-shadow cases while keeping the real physical relation q required in the new nested-local-binding counterexample.

  • New collector and sorter regressions reproduce the previous wrong required/advisory classification, false dependency cycle, and loss of a required edge during advisory fallback. All earlier scope controls remain covered. Changed scope blocks have 100% statement coverage.
  • Fix the demonstrated CREATE VIEW ... AS VALUES ROW(1) export regression. The pinned parser already supports standalone VALUES; use its scanner to locate AS and the same parser to validate the view header and complete VALUES source. Collect references from the resulting AST, never token/substring guesses, and emit the original DDL unchanged. No dependency upgrade or second parser is introduced.
  • VALUES tests cover constant/multi-row/ordered sources, expression subquery dependencies, quoted names/column lists/comments, and rejection of malformed/non-view/multi-statement input. The scanner/adapter blocks changed in the latest fix have 100% statement coverage.
  • Against the exact prior 3fdcdaf CLI, the same task-owned MatrixOne instance reproduces all three failures: false-cycle export failure, successful export whose restore fails with ERROR 1146 (q missing), and VALUES export parse failure. The fixed CLI restores each case twice with exact values 2/2/1 and unchanged server-provided CREATE statements.
  • Re-ran all five earlier real-service scope controls after this correction: forward shadow (1), no forward mask (42), earlier local binding (7), deeper subquery mask (1), and directly inherited mask inside a nested WITH (1), all pass. Test databases were removed and the task-owned service stopped normally.
  • These latest checks use the existing local mo-service binary whose Go metadata reports 9dfe5c1be92e6ecc2cd32d1ee2deeb54233381c3, not a fresh latest-main build. Earlier ca034357 evidence above remains historical evidence. VALUES expression-subquery cases prove AST/reference handling only: the test server rejects executing those expressions, so they are not claimed as successful public-path round trips.

Review follow-up: scanner lifecycle isolation

Fix the 999ad23 regression where CREATE VIEW a_trigger /*! AS */ VALUES ROW(1) leaves pooled scanner state that makes the following VALUES ROW(' AS ) (') view fail export. The pinned scanner constructor does not reset CommentFlag; truncating the executable comment also passed an incomplete header to the parser, contaminating its separate scanner.

  • Fully scan the DDL before invoking the parser. Preserve the pinned scanner token stream in a private parsing copy, rather than treating consumed byte spans as token spelling. ASCII punctuation is emitted from its token ID; quoted payloads and context-sensitive BEGIN classification remain preserved. Executable-comment contents remain tokens; output continues to use the unchanged original server DDL.
  • Reset the owned scanner on acquisition and before returning it on every success/error path. Never feed an incomplete executable comment to the parser, even on the VALUES fallback path.
  • Added trigger/victim ordering, executable/versioned/ordinary comment, invalid-input-followed-by-valid-input, exact token spelling and unchanged-DDL regressions. All earlier CTE/VALUES cases still pass.
  • Real CLI: reproduced the exact prior executable's VALUES-to-VALUES export failure; the VALUES-to-SELECT and ordinary SELECT controls still succeed. The fixed CLI passes five variants in both full-database and selected-view mode, each restored twice with exact row values and original SHOW CREATE text. Test databases were removed and the task-owned service exited normally.

This adds a bounded token scan and private SQL text at the schema boundary, not the row-processing path. The service/toolchain and baseline-test limitations documented above still apply.

Review follow-up: lexer-token equivalence and executable-comment EOF

Fix both compatibility regressions verified at bc2322f:

  • A scanner's consumed interval is not necessarily one token's spelling. In the pinned lexer, * in an executable comment can consume the following character. Emit ASCII punctuation from its token ID instead of accidentally turning 0*34 into 0 *3 4. Preserve the actual lexer token stream for dependency analysis; do not change the server's existing arithmetic/lexical behavior or the original DDL emitted by the backup.
  • Do not reject a view solely because EOF retains CommentFlag=true. MatrixOne accepts executable comments ending at request EOF; pass the resulting tokens to the same grammar validator. Actual lexical errors, invalid expressions and multiple statements still fail, and pool-state reset remains intact.

Added independent original-input versus parsing-copy token type/value comparisons for 16 boundary cases. The review's separate 65-case lexer corpus also passes. This caught a context-sensitive BEGIN boundary as well: an inert ordinary-comment separator preserves SPBEGIN classification without executable-comment state. Latest changed production blocks have 100% statement coverage.

Using a driver to submit the original DDL requests unchanged, the exact prior executable reproduces adjacent-numeric/column multiplication failures and three EOF-comment failures. The fixed CLI passes seven shapes in both full-database and selected-view mode, each restored twice, with unchanged SHOW CREATE text and exact source/restored results (0/6/68/68/1/1/1). The earlier trigger-to-victim scanner-leak case also passes both modes and two restores. Test databases were removed and the task-owned service stopped normally. The same prebuilt-service/latest-main limitations noted above apply.

Review follow-up: ANSI_QUOTES-authored view sources

Stored SHOW CREATE text carries no creation-time sql_mode, and the dump connection's mode is not necessarily the mode that authored the view. Parsing defaults unchanged, then only on failure retry through the same scanner/lexer pipeline with double-quoted strings converted to identifiers from their cleaned values (ANSI_QUOTES semantics). No session-mode guessing, second parser, or DDL rewriting; the emitted backup keeps the original server text.

  • Default mode never reaches the fallback: strings in select/alias contexts stay literals, and all 65 lexer-equivalence cases plus earlier token/CTE/VALUES tests pass with identical results.
  • Fallback coverage includes qualified names, doubled internal quotes and harmless unknown references; a two-view mocked dump places an ANSI-quoted parent before its child.
  • Added a real-service ANSI_QUOTES control on the available prebuilt MatrixOne 9dfe5c1: create and query child through a double-quoted parent, then export and restore with base, 056e72b and the fix. This server normalizes that identifier to backticks in SHOW CREATE, so it cannot reproduce the review's verbatim double-quoted preservation; the verbatim shape is proven by the collect + mocked-dump regression above. Latest changed production blocks have 96.8% statement coverage.

The advisory-dependency handling requested by earlier reviews, and use of current main's dependency metadata (which does not persist sql_mode) as a future ownership change, remain open coordination items with PR #55 and the reviewers; this PR keeps the single existing sorted path and documents the limitation rather than silently removing validated fallback behavior during review.

Limits

Test_toCsvFields and Test_toCsvLine fail identically on clean base 324c33d with the same toolchain. CSV row encoding and those assertions are unchanged; the latest normal/race package runs were unfiltered and report these two failures explicitly.

The concrete VALUES source regression is handled by the adapter above. The pinned parser may still reject other syntax introduced by newer servers; the dump fails with view context rather than falling back to substring matching. Restoring newer unused-CTE definitions on older eager servers is not guaranteed: an older binder may reject the original SQL independently of ordering. Selected dumps still require omitted/external prerequisites. Output is streaming, so callers must check the exit status and success marker before accepting a backup.

@ck89119
ck89119 marked this pull request as ready for review October 19, 2026 08:50
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T08:55:16.348114Z 17b7f37 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@mergify

mergify Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@XuPeng-SH
XuPeng-SH self-requested a review October 19, 2026 10:50

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

Reviewed base 324c33dbdc7075cd5d7beaafd1e15c76709dd442 -> head 17b7f37488ef72127c2f2d96f600e08899c0e074.

The catalog parameterization, separation of identifier/string quoting, and small implementation scope are sound. Row streaming and buffer ownership are unchanged; the added work is at metadata/file boundaries, not per exported row. There are no earlier reviewer findings or discussion threads to resolve.

Requesting changes for one verified export/restore gap: escaped view names are now accepted, but existing view dependency ordering still matches raw names and can emit a successful, unrestorable backup. Details and the concrete counterexample are inline.

Validation: exact-head CLI build and go vet passed with Go 1.23.0 and this checkout's CGo library. Package run: 81 tests/subtests passed; Test_toCsvFields and Test_toCsvLine failed identically on head and clean base, confirming the disclosed pre-existing failures. The ordering counterexample was verified against the real adjustViewOrder implementation and exact-head CLI output; restoring that output failed on an isolated MatrixOne 0928 release (f1857c3822) and MySQL 8.4.8. The author's newer-server happy-path evidence is retained; this review does not claim a latest-main kernel validation. No production code was modified.

Comment thread cmd/mo-dump/main.go Resolved

@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-reviewed the complete change at 19737d5. The escaped-name ordering defect and literal-induced hang are resolved using the existing parser and bounded dependency sorting. Required/advisory CTE handling also passes the concrete newer-MatrixOne unused-CTE counterexamples.

Normal and race owning-package checks each pass 138 test/subtest events, excluding only the two independently confirmed pre-existing CSV encoding failures documented in the PR. Full configured incremental SCA, vet, formatting and build pass; seven real CLI export/MatrixOne restore/query cases pass with unchanged DDL on source ca034357. gpt-6.1-sol/xhigh final overall review found no unresolved material blocker.

This approves the reviewed code; it does not claim latest-main compatibility, an unfiltered green suite, remote CI success, or measured zero overhead. See the updated PR validation and limits.

@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-reviewed the full base324c33d -> head19737d5 change, all six files, current discussion threads, and validation artifacts. No subagents used; no production/test files modified.

Requesting changes for one newly verified regression in CTE binding/dependency discovery (inline). This supersedes my previous approval at the same head: the new nested forward-shadow counterexample was not covered by the prior acceptance set. The prior escaped-identifier finding is correctly resolved, but the added scope resolver still differs from actual MatrixOne binding and can emit an unrestorable backup with a success marker.

Existing normal/race evidence (138 passing test/subtest events each), configured incremental SCA/vet/build, and seven CLI round trips remain valid for their covered cases: every delivery file matches their recorded fingerprint. New proof: an isolated exact-head CLI export/restore fails the nested CTE case; the source view queries correctly; original17b7f37 restores the same fixture; a focused overlay UT fails the required parent-first assertion. Real-service source ca034357, not latest-main claimed. Local reproduction services/databases are task-owned and cleaned up.

Design: reuse of the parser and bounded sorting remains justified, and the one required/advisory graph path has a concrete compatibility purpose. The issue is an incomplete reimplementation of binding scope; fix it in that resolver rather than adding per-SQL exceptions or another parser. No additional confirmed blocker found in quoting/catalog error ownership, original DDL/pair preservation, normal/error output, test fixture economy, or row-path performance. Production delta +318/-66 lines, tests +561/-29, lint config +8; no tracked documentation delta. These were reviewed separately.

The two unchanged, independently confirmed baseline CSV failures and pinned-parser forward-syntax limitation remain explicitly documented; neither is reported as a newly introduced failure. No zero-overhead/throughput claim is made.

Comment thread cmd/mo-dump/view_order.go Resolved

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

REQUEST_CHANGES at 056e72b (base 324c33d).

The two historical escaped-name/forward-mask review findings are resolved and have regression coverage. However, a new independent ANSI_QUOTES case fails export at this head; the exact clean baseline exports and restores the same fixture (inline).

The requested no-compatibility constraint is also not met: view_order.go explicitly retains advisory prerequisites for older eager binders and retries the graph with required-only edges. Remove that compatibility policy and its advisory traversal/state, retaining one supported dependency contract. Coordinate with #55: both replace the same view-order owner, but with different CTE resolution and SQL handling. Their current merge has conflicts and must not retain duplicate parsers/sorters. Current MatrixOne main has authoritative binder-owned dependency metadata; assess that owner and readiness/generation semantics before expanding the client's scope resolver again.

Independent validation: unfiltered normal and race owning-package runs each have 201 passing test/subtest events and only the two independently clean-base-confirmed CSV failures; incremental configured lint, vet, standalone build, gofmt and diff checks pass. An additional 1,312-case lexer-token equivalence corpus passes, so the ANSI failure is a missing parser-environment contract rather than evidence that the latest token fixes are broken. Scanner/AST cleanup, finite sorting, original DDL/catalog pairing, error propagation and metadata-only performance costs were reviewed. No tracked documentation delta. Prebuilt real-service evidence is not latest-main validation. No subagents or source edits.

Comment thread cmd/mo-dump/view_source.go Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: mo-dump cannot export ordinary tables whose names contain apostrophes or backticks

2 participants