Skip to content

fix(batch): parse table and column names with quote awareness - #2031

Open
Tyagiquamar wants to merge 4 commits into
ClickHouse:mainfrom
Tyagiquamar:fix/quote-aware-prepare-batch
Open

Tyagiquamar wants to merge 4 commits into
ClickHouse:mainfrom
Tyagiquamar:fix/quote-aware-prepare-batch

Conversation

@Tyagiquamar

@Tyagiquamar Tyagiquamar commented Sep 18, 2026 •

Copy link
Copy Markdown

Summary

Fixes #2012

When parsing `INSERT INTO` queries in `extractInsertQueryComponents`, the parser previously used regular expressions that had edge cases with identifier formatting:

  1. Queries where the column list immediately followed the table name without a space (e.g. `INSERT INTO table(col1, col2) VALUES (...)`) failed `extractInsertColumnsMatch` because it required `\s(`.
  2. Table identifiers that contained parentheses inside backticks or double quotes (e.g. `INSERT INTO my_table(1) (col1, col2)`) were prematurely cut off by `([^(]+)`.

This PR replaces regex-based table and column decomposition with `parseInsertTableAndColumns`, which:

  • Scans identifiers with quote awareness for backticks and double quotes.
  • Identifies the unquoted column list boundary regardless of intervening whitespace.
  • Adds test cases covering unspaced column lists and parenthesized table names.

Checklist

  • Unit tests covering the scenarios were added

Note

Medium Risk
Touches core batch INSERT parsing used by PrepareBatch on all transports; behavior change is broad but heavily regression-tested.

Overview
Fixes PrepareBatch / extractInsertQueryComponents when INSERT INTO uses awkward but valid ClickHouse syntax. Regex-based table/column extraction is replaced with parseInsertTableAndColumns, backed by quote-aware scanBalancedParens and findUnquotedParen, so parsing no longer breaks on missing space before (col1, col2), parentheses inside quoted table names, or INSERT INTO function ... targets.

extractInsertQueryComponents now builds the normalized statement from the full sanitized query and parses table/columns through the new scanner; duplicate INSERT regex in conn_batch.go is removed in favor of the shared helper.

Unit cases and TestIssue2012_PrepareBatch_WithoutSpaceBeforeColumns cover native/HTTP and database/sql for the reported regression.

Reviewed by Cursor Bugbot for commit 54d8ff6. Bugbot is set up for automated code reviews on this repo. Configure here.

@Tyagiquamar

Copy link
Copy Markdown
Author

Hi team, following up to check if anyone has time to review this PR when convenient. Tests and checks are passing. Thanks!

@Tyagiquamar

Copy link
Copy Markdown
Author

Hi team, following up to check if anyone has time to review this PR when convenient. Thanks!

Comment thread batch.go Resolved
Comment thread batch.go Resolved
@github-actions

github-actions Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Claude review

Replaces the regex-based INSERT INTO table/column extraction with a quote-aware scanner (parseInsertTableAndColumns) so INSERT INTO t(a, b) and quoted table names containing parentheses parse correctly, and adds unit cases plus an integration regression test for #2012. The parser change itself is sound, but the database/sql half of the regression test cannot pass, so changes are requested.

Parser: traced the new scanner against the existing batch_test.go matrix (comments, SETTINGS, VALUES/FORMAT keywords as identifiers, nested/quoted column names, trailing ;) and the three new cases; all behave as before or better. Keeping the whole sanitized statement as insertStmt (instead of the regex capture) only changes behavior for malformed input, where the server now reports the error instead of the driver silently dropping text. Removing the dead insertMatch/columnMatch regexes from conn_batch.go is correct — nothing referenced them.

Key concern driving the verdict:

  • The database/sql subtest prepares and executes outside a transaction, so the batch is never sent and the follow-up SELECT returns no rows (see inline on tests/issues/issue_2012_test.go). This is consistent with every integration job on the PR head being red.

Blind spots:

  • Could not read the failing CI logs from the review sandbox; the std-path trace explains at least one failure, but there may be others.
  • No live server available to confirm that table names containing parentheses ("issue_2012(native)") are accepted by every CI server version and by the Replicated database on ClickHouse Cloud.

Verdict: ⚠️ Request changes

General findings

  • ⚠️ Should fix — CI integration jobs are red on the PR head
    All eight test (go, clickhouse) matrix jobs failed for commit acfdd9b. The review sandbox could not fetch the logs, so only the database/sql subtest failure (inline finding) is confirmed by code trace. Please check the job output for any additional failures — in particular whether CREATE TABLE "issue_2012(native)" / `issue_2012_bt(native)` is accepted on every server version in the matrix — before re-requesting review.

Inline comments are attached to the relevant lines. This summary updates in place on re-review.

@Tyagiquamar

Copy link
Copy Markdown
Author

Update on the automated review findings (all addressed in b3d9f49, verified locally): gofmt clean on batch.go/conn_batch.go/tests/issues/issue_2012_test.go; INSERT/INTO matching now uses the boundary-aware isKeyword helper; parseInsertTableAndColumns has a doc comment; stale insertMatch/columnMatch regexes removed from conn_batch.go; regression test tests/issues/issue_2012_test.go added (native + HTTP paths, wider-table scenario and quoted table name with paren). Unit suite TestExtractNormalizedInsertQueryAndColumns passes; go vet clean on changed packages. Ready for human review.

Comment thread tests/issues/issue_2012_test.go Outdated
require.NoError(t, err)
t.Cleanup(func() { db.ExecContext(ctx, "DROP TABLE IF EXISTS "+tableName) })

stmt, err := db.PrepareContext(ctx, "INSERT INTO "+tableName+"(col1, col2)")

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.

❌ Must fix — database/sql subtest never sends the batch, so the SELECT finds no row

A statement prepared via db.PrepareContext is a batch whose Send is only invoked by tx.Commit() (stdDriver.PrepareContext stores batch.Send in std.commit; stdBatch.Close is a no-op). Without a transaction the row appended at line 111 is never written, so the QueryRowContext(...).Scan at line 119 fails with sql: no rows in result set on both protocols — which matches the red integration jobs on this PR.

  • Use the pattern from issue_2067_test.go: BeginTx → tx.PrepareContext → Exec → tx.Commit().
  • Consider also exercising one quoted-with-parentheses table name on the std path so this surface covers the second half of the fix.
-			stmt, err := db.PrepareContext(ctx, "INSERT INTO "+tableName+"(col1, col2)")
+			tx, err := db.BeginTx(ctx, nil)
+			require.NoError(t, err)
+			stmt, err := tx.PrepareContext(ctx, "INSERT INTO "+tableName+"(col1, col2)")
 			require.NoError(t, err)
 			defer stmt.Close()
 
 			_, err = stmt.ExecContext(ctx, uint32(5), "std_sql")
 			require.NoError(t, err)
+			require.NoError(t, tx.Commit())

@Tyagiquamar
Tyagiquamar requested review from a team and polyglotAI-bot as code owners November 27, 2026 09:52
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.

PrepareBatch: FORMAT/VALUES stripping is not quote-aware — column list silently dropped, quoted values corrupted, or query made invalid

3 participants