Skip to content

to 3.0: update data branch: data branch create table and database - #23214

Merged
9 commits merged into
matrixorigin:3.0-devfrom
gouhongshen:branch_opt_to_3.0
Dec 4, 2025
Merged

9 commits merged into
matrixorigin:3.0-devfrom
gouhongshen:branch_opt_to_3.0

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Dec 4, 2025 •

Copy link
Copy Markdown
Contributor

User description

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue ##21979

What this PR does / why we need it:

  1. Change the minimal unit in single SQL size from batch to rows.
  2. Support validating the stage directory.
  3. data branch create table/database

PR Type

Enhancement, Tests


Description

  • Implement data branch create table/database operations with metadata tracking

  • Refactor clone handlers to return receipts for branch metadata updates

  • Enhance stage directory validation with improved object storage support

  • Update test cases to use new data branch create syntax


Diagram Walkthrough

flowchart LR
  A["Data Branch Operations"] --> B["Create Table Handler"]
  A --> C["Create Database Handler"]
  B --> D["Clone Receipt"]
  C --> D
  D --> E["Update Branch Metadata"]
  F["Directory Validation"] --> G["Enhanced Path Detection"]
  G --> H["Object Storage Support"]
Loading

File Walkthrough

Relevant files
Enhancement
5 files
clone.go
Refactor clone handlers to return receipts                             
+21/-23 
data_branch.go
Implement data branch create operations                                   
+459/-193
data_branch.go
Add sqlValuesAppender and batch row processing                     
+459/-193
data_branch.go
Improve stage directory validation logic                                 
+459/-193
self_handle.go
Update clone handlers to use receipts                                       
+2/-2     
Tests
18 files
data_branch_test.go
Remove obsolete buffer pool test                                                 
+0/-12   
dml_test.go
Update tests to use data branch create syntax                       
+4/-4     
diff_1.result
Update expected results for new syntax                                     
+7/-7     
diff_1.sql
Update test cases to data branch create                                   
+7/-7     
diff_2.result
Update expected results for new syntax                                     
+7/-7     
diff_2.sql
Update test cases to data branch create                                   
+7/-7     
diff_3.result
Update expected results for new syntax                                     
[link]   
diff_3.sql
Update test cases to data branch create                                   
+6/-6     
diff_4.result
Update expected results for new syntax                                     
+4/-4     
diff_4.sql
Update test cases to data branch create                                   
+4/-4     
diff_5.result
Update expected results for new syntax                                     
+4/-4     
diff_5.sql
Update test cases to data branch create                                   
+4/-4     
merge_1.result
Update expected results for new syntax                                     
+6/-6     
merge_1.sql
Update test cases to data branch create                                   
+125/-125
merge_2.result
Update expected results for new syntax                                     
+7/-7     
merge_2.sql
Update test cases to data branch create                                   
+7/-7     
merge_3.result
Update expected results for new syntax                                     
+2/-2     
merge_3.sql
Update test cases to data branch create                                   
+2/-2     

@qodo-code-review

qodo-code-review Bot commented Dec 4, 2025 •

Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
⚪
Insecure SQL parsing

Description: The code parses the original SQL using a permissive regular expression to extract
source/destination names for constructing a CREATE TABLE CLONE statement, which may allow
malformed or specially crafted inputs to bypass proper parser validation and lead to
executing unintended SQL targets.
data_branch.go [444-466]

Referred Code
//data branch create table xxx from yyy snap_opt to_account_op;
re := regexp.MustCompile(`(?i)^DATA\s+BRANCH\s+CREATE\s+TABLE\s+(\S+)\s+FROM\s+(.+?);?$`)
srcAndDst := re.FindStringSubmatch(execCtx.input.sql)
if srcAndDst == nil {
	return moerr.NewInternalErrorNoCtxf("cannot find src and dst table: %s", execCtx.input.sql)
}

sql := fmt.Sprintf("CREATE TABLE %s CLONE %s", srcAndDst[1], srcAndDst[2])

execCtx.reqCtx = context.WithValue(execCtx.reqCtx, tree.CloneLevelCtxKey{}, tree.NormalCloneLevelTable)

tempExecCtx = &ExecCtx{
	reqCtx: execCtx.reqCtx,
	input:  &UserInput{sql: sql},
}

if receipt, err = handleCloneTable(tempExecCtx, ses, cloneStmt, bh); err != nil {
	return
}

if err = updateBranchMetaTable(execCtx.reqCtx, ses, bh, receipt); err != nil {


 ... (clipped 2 lines)
Ticket Compliance
🟡
🎫 #21979
🟢 Add support for new data branching syntax to create tables from existing data sources.
Add support for new data branching syntax to create databases from existing data sources.
Ensure implementation integrates with branch metadata tracking and receipts.
Update tests and usage to the new data branch create syntax.
Validate stage/output directory paths robustly, including object storage backends.
⚪ Verify end-to-end metadata updates and receipts across multi-table database clone in real
deployment (beyond unit tests).
Validate new syntax behavior with cross-account operations and snapshots in production
environments.
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

⚪
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing Auditing: New critical operations like data branch table/database creation and branch metadata
updates are executed without any visible auditing/logging of actor identity, action, and
outcome in the added code.

Referred Code
func dataBranchCreateTable(
	execCtx *ExecCtx,
	ses *Session,
	stmt *tree.DataBranchCreateTable,
) (err error) {
	var (
		bh          BackgroundExec
		deferred    func(error) error
		receipt     cloneReceipt
		cloneStmt   *tree.CloneTable
		tempExecCtx *ExecCtx
	)

	if bh, deferred, err = getBackExecutor(execCtx.reqCtx, ses); err != nil {
		return
	}

	defer func() {
		if deferred != nil {
			err = deferred(err)
		}


 ... (clipped 74 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Error Context: Regex-based SQL parsing in dataBranchCreateTable returns internal errors with raw input
but lacks clear context about which part failed and may not handle malformed inputs or
absent matches beyond a generic internal error.

Referred Code
//data branch create table xxx from yyy snap_opt to_account_op;
re := regexp.MustCompile(`(?i)^DATA\s+BRANCH\s+CREATE\s+TABLE\s+(\S+)\s+FROM\s+(.+?);?$`)
srcAndDst := re.FindStringSubmatch(execCtx.input.sql)
if srcAndDst == nil {
	return moerr.NewInternalErrorNoCtxf("cannot find src and dst table: %s", execCtx.input.sql)
}

sql := fmt.Sprintf("CREATE TABLE %s CLONE %s", srcAndDst[1], srcAndDst[2])

execCtx.reqCtx = context.WithValue(execCtx.reqCtx, tree.CloneLevelCtxKey{}, tree.NormalCloneLevelTable)

tempExecCtx = &ExecCtx{
	reqCtx: execCtx.reqCtx,
	input:  &UserInput{sql: sql},
}

if receipt, err = handleCloneTable(tempExecCtx, ses, cloneStmt, bh); err != nil {
	return
}

if err = updateBranchMetaTable(execCtx.reqCtx, ses, bh, receipt); err != nil {


 ... (clipped 2 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status:
Internal Details: Errors like moerr.NewInternalErrorNoCtxf include the original SQL text in messages (e.g.,
regex parse failure), which might be user-facing and could leak internal processing
details.

Referred Code
if srcAndDst == nil {
	return moerr.NewInternalErrorNoCtxf("cannot find src and dst table: %s", execCtx.input.sql)
}

sql := fmt.Sprintf("CREATE TABLE %s CLONE %s", srcAndDst[1], srcAndDst[2])

execCtx.reqCtx = context.WithValue(execCtx.reqCtx, tree.CloneLevelCtxKey{}, tree.NormalCloneLevelTable)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Input Validation: The regex extraction of source/destination identifiers from execCtx.input.sql constructs a
CREATE TABLE CLONE statement without explicit sanitization beyond regex, which may require
validation/quoting to avoid injection or malformed identifiers.

Referred Code
re := regexp.MustCompile(`(?i)^DATA\s+BRANCH\s+CREATE\s+TABLE\s+(\S+)\s+FROM\s+(.+?);?$`)
srcAndDst := re.FindStringSubmatch(execCtx.input.sql)
if srcAndDst == nil {
	return moerr.NewInternalErrorNoCtxf("cannot find src and dst table: %s", execCtx.input.sql)
}

sql := fmt.Sprintf("CREATE TABLE %s CLONE %s", srcAndDst[1], srcAndDst[2])

execCtx.reqCtx = context.WithValue(execCtx.reqCtx, tree.CloneLevelCtxKey{}, tree.NormalCloneLevelTable)

tempExecCtx = &ExecCtx{
	reqCtx: execCtx.reqCtx,

Learn more about managing compliance generic rules or creating your own custom rules

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review

qodo-code-review Bot commented Dec 4, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Avoid redundant syntax and fragile regex

The DATA BRANCH CREATE syntax is redundant; it's better to extend the CLONE
command. Also, the implementation in dataBranchCreateTable should use the parsed
AST instead of a fragile regex to reconstruct SQL.

Examples:

pkg/frontend/data_branch.go [410-469]
func dataBranchCreateTable(
	execCtx *ExecCtx,
	ses *Session,
	stmt *tree.DataBranchCreateTable,
) (err error) {
	var (
		bh          BackgroundExec
		deferred    func(error) error
		receipt     cloneReceipt
		cloneStmt   *tree.CloneTable

 ... (clipped 50 lines)

Solution Walkthrough:

Before:

func dataBranchCreateTable(execCtx *ExecCtx, ses *Session, stmt *tree.DataBranchCreateTable) (err error) {
  // ...
  // Fragile: uses regex on the raw SQL string
  re := regexp.MustCompile(`(?i)^DATA\s+BRANCH\s+CREATE\s+TABLE\s+(\S+)\s+FROM\s+(.+?);?$`)
  srcAndDst := re.FindStringSubmatch(execCtx.input.sql)
  if srcAndDst == nil {
    return moerr.NewInternalErrorNoCtxf("cannot find src and dst table: %s", execCtx.input.sql)
  }
  
  // Reconstructs SQL from regex matches
  sql := fmt.Sprintf("CREATE TABLE %s CLONE %s", srcAndDst[1], srcAndDst[2])
  
  tempExecCtx := &ExecCtx{
    input:  &UserInput{sql: sql},
    // ...
  }
  
  // ... call handleCloneTable with reconstructed context
}

After:

func dataBranchCreateTable(execCtx *ExecCtx, ses *Session, stmt *tree.DataBranchCreateTable) (err error) {
  // ...
  // Robust: uses the parsed AST (`stmt`) to get table names and options
  dstTable := stmt.CreateTable.Table.String()
  srcTable := stmt.SrcTable.String()
  
  // Reconstructs SQL from the AST
  sql := fmt.Sprintf("CREATE TABLE %s CLONE %s", dstTable, srcTable)
  // Append snapshot options, etc., from the AST
  
  tempExecCtx := &ExecCtx{
    input:  &UserInput{sql: sql},
    // ...
  }
  
  // ... call handleCloneTable with robustly constructed context
}
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a significant implementation flaw where a fragile regex is used on raw SQL instead of the readily available AST, and also raises a valid, high-impact concern about the user-facing API design.

High
Possible issue
Correctly handle empty directory validation

Fix a bug in root directory validation where an error could be missed if the
directory is empty. Check the error returned from targetFS.List after the loop
to ensure the directory is valid.

pkg/frontend/data_branch.go [1420-1433]

 	if len(strings.Trim(targetPath, "/")) == 0 {
 		// service root: try listing to ensure the bucket/root is reachable
-		for _, err = range targetFS.List(ctx, targetPath) {
-			if err != nil {
-				if moerr.IsMoErrCode(err, moerr.ErrFileNotFound) {
-					return moerr.NewInvalidInputNoCtxf("output directory %s does not exist", inputDirPath)
-				}
-				return err
-			}
+		var firstEntry fileservice.DirEntry
+		for firstEntry, err = range targetFS.List(ctx, targetPath) {
 			// any entry means list works
 			break
 		}
+		if err != nil {
+			if moerr.IsMoErrCode(err, moerr.ErrFileNotFound) {
+				return moerr.NewInvalidInputNoCtxf("output directory %s does not exist", inputDirPath)
+			}
+			return err
+		}
+		// if err is nil, it means list succeeded, even if the directory is empty.
 		return nil
 	}
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a potential bug where an empty directory could cause an error from targetFS.List to be missed, and proposes a valid fix to ensure the error is checked.

Medium
  • Update

@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Dec 4, 2025
@gouhongshen

Copy link
Copy Markdown
Contributor Author

@mergify requeue

@mergify

mergify Bot commented Dec 4, 2025

Copy link
Copy Markdown
Contributor

requeue

✅ The queue state of this pull request has been cleaned. It can be re-embarked automatically

This pull request was closed.

This branch was previously deployed

1 inactive deployment
ci — 9e9ebce1 Deployed Dec 4, 2025 by ghost
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 kind/enhancement kind/feature Review effort 4/5 size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants