diff --git a/batch.go b/batch.go index fa29d9773a..097ae3daf3 100644 --- a/batch.go +++ b/batch.go @@ -6,12 +6,6 @@ import ( "strings" ) -// normalizeInsertQueryMatch captures the INSERT statement and its table name. It runs on -// a query sanitizeInsertQuery has already stripped of comments, so it does not have to -// skip them itself. -var normalizeInsertQueryMatch = regexp.MustCompile(`(?i)(INSERT\s+INTO\s+([^(]+)(?:\s*\([^()]*(?:\([^()]*\)[^()]*)*\))?)(?:\s*VALUES)?`) -var extractInsertColumnsMatch = regexp.MustCompile(`(?si)INSERT INTO .+\s\((?P.+)\)$`) - // extractInsertSettingsMatch captures a trailing SETTINGS clause. The `\w+\s*=` // after the SETTINGS keyword requires an actual `name = value` assignment so a table // or column merely named "settings" is not mistaken for a settings clause. The `s` flag @@ -74,6 +68,130 @@ func extractNormalizedInsertQueryAndColumns(query string) (normalizedQuery strin return fmt.Sprintf("%s FORMAT Native", insertStmt), tableName, columns, nil } +// scanBalancedParens starts at openIdx (which must point to '(') and returns the +// index of its matching ')', respecting single-quoted, double-quoted, and +// backtick-quoted segments. Returns -1 if parentheses are unbalanced. +func scanBalancedParens(s string, openIdx int) int { + depth := 1 + var quote byte + for i := openIdx + 1; i < len(s); i++ { + c := s[i] + if quote != 0 { + if c == '\\' && i+1 < len(s) { + i++ + continue + } + if c == quote { + quote = 0 + } + continue + } + + if c == '\'' || c == '"' || c == '`' { + quote = c + continue + } + + if c == '(' { + depth++ + } else if c == ')' { + depth-- + if depth == 0 { + return i + } + } + } + return -1 +} + +// findUnquotedParen returns the index of the first '(' in s outside of backtick- or +// double-quoted identifiers, or -1 if none is found. +func findUnquotedParen(s string) int { + var quote byte + for i := 0; i < len(s); i++ { + c := s[i] + if quote != 0 { + if c == '\\' && i+1 < len(s) { + i++ + continue + } + if c == quote { + quote = 0 + } + continue + } + + if c == '`' || c == '"' { + quote = c + continue + } + + if c == '(' { + return i + } + } + return -1 +} + +// parseInsertTableAndColumns extracts the table name and optional column list from a +// sanitized INSERT statement. It scans with quote awareness so parentheses inside +// quoted table identifiers (e.g. `table(1)`) or table function arguments +// (e.g. `INSERT INTO function null('x UInt64')`) are not mistaken for the column list. +func parseInsertTableAndColumns(sanitized string) (tableName string, columnsPart string, ok bool) { + s := strings.TrimSpace(sanitized) + if !isKeyword(s, nil, insertKeyword) { + return "", "", false + } + s = strings.TrimSpace(s[len(insertKeyword):]) + if !isKeyword(s, nil, intoKeyword) { + return "", "", false + } + s = strings.TrimSpace(s[len(intoKeyword):]) + if s == "" { + return "", "", false + } + + if isKeyword(s, nil, tableKeyword) { + if rest := strings.TrimSpace(s[len(tableKeyword):]); rest != "" && rest[0] != '(' { + s = rest + } + } + + if isKeyword(s, nil, functionKeyword) { + if rest := strings.TrimSpace(s[len(functionKeyword):]); rest != "" && rest[0] != '(' { + funcOpen := findUnquotedParen(s) + if funcOpen == -1 { + return strings.TrimSpace(s), "", true + } + funcClose := scanBalancedParens(s, funcOpen) + if funcClose == -1 { + return strings.TrimSpace(s), "", true + } + tableName = strings.TrimSpace(s[:funcClose+1]) + afterFunc := strings.TrimSpace(s[funcClose+1:]) + if afterFunc != "" && afterFunc[0] == '(' { + if colClose := scanBalancedParens(afterFunc, 0); colClose != -1 { + columnsPart = afterFunc[1:colClose] + } + } + return tableName, columnsPart, true + } + } + + tableEnd := findUnquotedParen(s) + if tableEnd == -1 { + tableName = strings.TrimSpace(s) + return tableName, "", true + } + + tableName = strings.TrimSpace(s[:tableEnd]) + if colEnd := scanBalancedParens(s, tableEnd); colEnd != -1 { + columnsPart = s[tableEnd+1 : colEnd] + } + + return tableName, columnsPart, true +} + // extractInsertQueryComponents strips any FORMAT clause or VALUES suffix from // an INSERT query and returns the bare statement, so the caller can append the // FORMAT of its choosing. @@ -91,24 +209,23 @@ func extractInsertQueryComponents(query string) (insertStmt string, tableName st sanitized = sanitized[:loc[0]] } - matches := normalizeInsertQueryMatch.FindStringSubmatch(sanitized) - if len(matches) == 0 { + parsedTable, parsedColumnsPart, ok := parseInsertTableAndColumns(sanitized) + if !ok || parsedTable == "" { // The query as given by the caller is reported, not the sanitized one, so the // error still shows what was passed in. err = fmt.Errorf("invalid INSERT query: %s", query) return } - insertStmt = matches[1] + insertStmt = strings.TrimSpace(sanitized) if settingsClause != "" { insertStmt += " " + settingsClause } - tableName = strings.TrimSpace(matches[2]) + tableName = parsedTable columns = make([]string, 0) - matches = extractInsertColumnsMatch.FindStringSubmatch(matches[1]) - if len(matches) == 2 { - rawColumns := splitColumnsRespectingQuotes(matches[1]) + if parsedColumnsPart != "" { + rawColumns := splitColumnsRespectingQuotes(parsedColumnsPart) // refers to https://clickhouse.com/docs/en/sql-reference/syntax#identifiers // we can use identifiers with double quotes or backticks, for example: "id", `id`, but not both, like `"id"`. for _, col := range rawColumns { @@ -254,6 +371,10 @@ func appendCommentSeparator(out []byte, rest string) []byte { } const ( + insertKeyword = "INSERT" + intoKeyword = "INTO" + tableKeyword = "TABLE" + functionKeyword = "FUNCTION" valuesKeyword = "VALUES" formatKeyword = "FORMAT" settingsKeyword = "SETTINGS" diff --git a/batch_test.go b/batch_test.go index 72839a9bf5..f3140b5e21 100644 --- a/batch_test.go +++ b/batch_test.go @@ -282,6 +282,30 @@ INSERT INTO ` + "`_test_1345# $.ДБ`.`2. Таблица №2`" + ` (col1, col2) expectedColumns: []string{"col1", "col2"}, expectedError: false, }, + { + name: "Insert without space before column list", + query: "INSERT INTO table_name(col1, col2) VALUES (1, 2)", + expectedNormalizedQuery: "INSERT INTO table_name(col1, col2) FORMAT Native", + expectedTableName: "table_name", + expectedColumns: []string{"col1", "col2"}, + expectedError: false, + }, + { + name: "Insert with parentheses inside backtick-quoted table name", + query: "INSERT INTO `my_table(1)` (col1, col2) VALUES (1, 2)", + expectedNormalizedQuery: "INSERT INTO `my_table(1)` (col1, col2) FORMAT Native", + expectedTableName: "`my_table(1)`", + expectedColumns: []string{"col1", "col2"}, + expectedError: false, + }, + { + name: "Insert with parentheses inside double-quoted table name and no space before columns", + query: "INSERT INTO \"my_table(1)\"(col1, col2) VALUES (1, 2)", + expectedNormalizedQuery: "INSERT INTO \"my_table(1)\"(col1, col2) FORMAT Native", + expectedTableName: "\"my_table(1)\"", + expectedColumns: []string{"col1", "col2"}, + expectedError: false, + }, { name: "Insert with #! comment without space", query: "#!comment\nINSERT INTO table_name (col1, col2) VALUES (1, 2)", @@ -1016,6 +1040,30 @@ INSERT INTO ` + "`_test_1345# $.ДБ`.`2. Таблица №2`" + ` (col1, col2) expectedColumns: []string{"col1", "my_weird,col2", "col3"}, expectedError: false, }, + { + name: "Insert into table function without explicit columns", + query: "INSERT INTO function null('x FixedString(16)') VALUES ('a')", + expectedNormalizedQuery: "INSERT INTO function null('x FixedString(16)') FORMAT Native", + expectedTableName: "function null('x FixedString(16)')", + expectedColumns: []string{}, + expectedError: false, + }, + { + name: "Insert into table function with explicit columns", + query: "INSERT INTO function null('x UInt64, y String') (y, x)", + expectedNormalizedQuery: "INSERT INTO function null('x UInt64, y String') (y, x) FORMAT Native", + expectedTableName: "function null('x UInt64, y String')", + expectedColumns: []string{"y", "x"}, + expectedError: false, + }, + { + name: "Insert into table named function with columns", + query: "INSERT INTO function (col1, col2) VALUES (1, 2)", + expectedNormalizedQuery: "INSERT INTO function (col1, col2) FORMAT Native", + expectedTableName: "function", + expectedColumns: []string{"col1", "col2"}, + expectedError: false, + }, } for _, tc := range testCases { diff --git a/conn_batch.go b/conn_batch.go index bbe815c1bc..671178614f 100644 --- a/conn_batch.go +++ b/conn_batch.go @@ -6,7 +6,6 @@ import ( "fmt" "log/slog" "os" - "regexp" "slices" "syscall" "time" @@ -16,9 +15,6 @@ import ( "github.com/ClickHouse/clickhouse-go/v2/lib/proto" ) -var insertMatch = regexp.MustCompile(`(?i)(?:(?:--[^\n]*|#![^\n]*|#\s[^\n]*)\n\s*)*(INSERT\s+INTO\s+[^( ]+(?:\s*\([^()]*(?:\([^()]*\)[^()]*)*\))?)(?:\s*VALUES)?`) -var columnMatch = regexp.MustCompile(`INSERT INTO .+\s\((?P.+)\)$`) - func (c *connect) prepareBatch(ctx context.Context, release nativeTransportRelease, acquire nativeTransportAcquire, query string, opts driver.PrepareBatchOptions) (driver.Batch, error) { query, _, queryColumns, verr := extractNormalizedInsertQueryAndColumns(query) if verr != nil { diff --git a/tests/issues/issue_2012_test.go b/tests/issues/issue_2012_test.go new file mode 100644 index 0000000000..792a262917 --- /dev/null +++ b/tests/issues/issue_2012_test.go @@ -0,0 +1,129 @@ +package issues + +import ( + "context" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/ClickHouse/clickhouse-go/v2" + clickhouse_tests "github.com/ClickHouse/clickhouse-go/v2/tests" + clickhouse_std_tests "github.com/ClickHouse/clickhouse-go/v2/tests/std" +) + +// TestIssue2012_PrepareBatch_WithoutSpaceBeforeColumns is a regression test for +// https://github.com/ClickHouse/clickhouse-go/issues/2012: +// PrepareBatch("INSERT INTO t(a, b)") without a space between the table name and the +// opening parenthesis must extract the specified columns instead of failing to parse +// and falling back to all columns from DESCRIBE TABLE (which failed on HTTP transport). +// It also tests quoted table names containing parentheses. +func TestIssue2012_PrepareBatch_WithoutSpaceBeforeColumns(t *testing.T) { + ctx := context.Background() + protocols := []clickhouse.Protocol{clickhouse.Native, clickhouse.HTTP} + + t.Run("native and http driver", func(t *testing.T) { + for _, protocol := range protocols { + t.Run(protocol.String(), func(t *testing.T) { + conn, err := clickhouse_tests.GetConnection("issues", t, protocol, nil, nil, nil) + require.NoError(t, err) + t.Cleanup(func() { conn.Close() }) + + // Case 1: Standard table name with no space before columns on a table with an extra default column + tableName := "issue_2012_" + protocol.String() + require.NoError(t, conn.Exec(ctx, "DROP TABLE IF EXISTS "+tableName)) + require.NoError(t, conn.Exec(ctx, "CREATE TABLE "+tableName+" (col1 UInt32, col2 String, col3 UInt32 DEFAULT 42) ENGINE MergeTree ORDER BY col1")) + t.Cleanup(func() { conn.Exec(ctx, "DROP TABLE IF EXISTS "+tableName) }) + + batch, err := conn.PrepareBatch(ctx, "INSERT INTO "+tableName+"(col1, col2)") + require.NoError(t, err) + require.NoError(t, batch.Append(uint32(1), "hello")) + require.NoError(t, batch.Append(uint32(2), "world")) + require.NoError(t, batch.Send()) + + var ( + col1 uint32 + col2 string + col3 uint32 + ) + require.NoError(t, conn.QueryRow(ctx, "SELECT col1, col2, col3 FROM "+tableName+" WHERE col1 = 1").Scan(&col1, &col2, &col3)) + assert.Equal(t, uint32(1), col1) + assert.Equal(t, "hello", col2) + assert.Equal(t, uint32(42), col3) + + // Case 2: Double-quoted table name containing parentheses + quotedTable := "\"issue_2012(" + protocol.String() + ")\"" + require.NoError(t, conn.Exec(ctx, "DROP TABLE IF EXISTS "+quotedTable)) + require.NoError(t, conn.Exec(ctx, "CREATE TABLE "+quotedTable+" (col1 UInt32, col2 String, col3 UInt32 DEFAULT 99) ENGINE MergeTree ORDER BY col1")) + t.Cleanup(func() { conn.Exec(ctx, "DROP TABLE IF EXISTS "+quotedTable) }) + + batchQuoted, err := conn.PrepareBatch(ctx, "INSERT INTO "+quotedTable+"(col1, col2)") + require.NoError(t, err) + require.NoError(t, batchQuoted.Append(uint32(10), "quoted")) + require.NoError(t, batchQuoted.Send()) + + require.NoError(t, conn.QueryRow(ctx, "SELECT col1, col2, col3 FROM "+quotedTable+" WHERE col1 = 10").Scan(&col1, &col2, &col3)) + assert.Equal(t, uint32(10), col1) + assert.Equal(t, "quoted", col2) + assert.Equal(t, uint32(99), col3) + + // Case 3: Backtick-quoted table name containing parentheses + backtickTable := "`issue_2012_bt(" + protocol.String() + ")`" + require.NoError(t, conn.Exec(ctx, "DROP TABLE IF EXISTS "+backtickTable)) + require.NoError(t, conn.Exec(ctx, "CREATE TABLE "+backtickTable+" (col1 UInt32, col2 String, col3 UInt32 DEFAULT 100) ENGINE MergeTree ORDER BY col1")) + t.Cleanup(func() { conn.Exec(ctx, "DROP TABLE IF EXISTS "+backtickTable) }) + + batchBT, err := conn.PrepareBatch(ctx, "INSERT INTO "+backtickTable+"(col1, col2)") + require.NoError(t, err) + require.NoError(t, batchBT.Append(uint32(20), "backtick")) + require.NoError(t, batchBT.Send()) + + require.NoError(t, conn.QueryRow(ctx, "SELECT col1, col2, col3 FROM "+backtickTable+" WHERE col1 = 20").Scan(&col1, &col2, &col3)) + assert.Equal(t, uint32(20), col1) + assert.Equal(t, "backtick", col2) + assert.Equal(t, uint32(100), col3) + }) + } + }) + + t.Run("database/sql", func(t *testing.T) { + useSSL, err := strconv.ParseBool(clickhouse_tests.GetEnv("CLICKHOUSE_USE_SSL", "false")) + require.NoError(t, err) + + for _, protocol := range protocols { + t.Run(protocol.String(), func(t *testing.T) { + db, err := clickhouse_std_tests.GetDSNConnection("issues", protocol, useSSL, nil) + require.NoError(t, err) + t.Cleanup(func() { db.Close() }) + + tableName := "issue_2012_sql_" + protocol.String() + _, err = db.ExecContext(ctx, "DROP TABLE IF EXISTS "+tableName) + require.NoError(t, err) + _, err = db.ExecContext(ctx, "CREATE TABLE "+tableName+" (col1 UInt32, col2 String, col3 UInt32 DEFAULT 77) ENGINE MergeTree ORDER BY col1") + require.NoError(t, err) + t.Cleanup(func() { db.ExecContext(ctx, "DROP TABLE IF EXISTS "+tableName) }) + + 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()) + + var ( + col1 uint32 + col2 string + col3 uint32 + ) + require.NoError(t, db.QueryRowContext(ctx, "SELECT col1, col2, col3 FROM "+tableName+" WHERE col1 = 5").Scan(&col1, &col2, &col3)) + assert.Equal(t, uint32(5), col1) + assert.Equal(t, "std_sql", col2) + assert.Equal(t, uint32(77), col3) + }) + } + }) +}