Skip to content

bug: extractNormalizedInsertQueryAndColumns does not remove backticks inside a dot-delimited column name #1401

Open

Description

@fidiego

Observed

extractNormalizedInsertQueryAndColumns cleans up leading and trailing backticks in columns such as "events.attributes" but leaves the internal backticks untouched leading to a block cannot be sorted error due to the mismatch.

This affects Nested type columns used via go-gorm.

Expected behaviour

Ideally, extractNormalizedInsertQueryAndColumns should handle this case.

Working `extractNormalizedInsertQueryColumns`

func extractNormalizedInsertQueryAndColumns(query string) (normalizedQuery string, tableName string, columns []string, err error) {
	query = truncateFormat.ReplaceAllString(query, "")
	query = truncateValues.ReplaceAllString(query, "")

	matches := normalizeInsertQueryMatch.FindStringSubmatch(query)
	if len(matches) == 0 {
		err = errors.Errorf("invalid INSERT query: %s", query)
		return
	}

	normalizedQuery = fmt.Sprintf("%s FORMAT Native", matches[1])
	tableName = strings.TrimSpace(matches[2])

	columns = make([]string, 0)
	matches = extractInsertColumnsMatch.FindStringSubmatch(matches[1])
	if len(matches) == 2 {
		columns = strings.Split(matches[1], ",")
		for i := range columns {
			// 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"`.
			col := columns[i]
			col = strings.TrimSpace(columns[i]) // trim lead/trail -in whitespace
			col = strings.Trim(col, "\"")       // trim lead/trail -ing double quote
			col = strings.Trim(col, "`")        // trim lead/trial -ing tilde
			// for columns like events.attributes that are otherwise represented like this: events`.`attributes
			col = strings.ReplaceAll(col, "`.`", ".") // replace internal tilde delimited periods w/ plain period
			columns[i] = col
		}
	}

	return
}

`show create traces`

SHOW CREATE TABLE ctl_api.otel_traces

Query id: 69b8f8cf-71c2-4967-8cba-d80945a4be78

   ┌─statement──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
1. │ CREATE TABLE ctl_api.otel_traces
(
    `id` String,
    `created_by_id` String,
    `created_at` DateTime64(3),
    `updated_at` DateTime64(3),
    `deleted_at` UInt64,
    `runner_id` String,
    `runner_job_id` String,
    `runner_job_execution_id` String,
    `timestamp` DateTime64(9) CODEC(Delta(8), ZSTD(1)),
    `timestamp_date` Date DEFAULT toDate(timestamp),
    `timestamp_time` DateTime DEFAULT toDateTime(timestamp),
    `resource_attributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)),
    `resource_schema_url` LowCardinality(String) CODEC(ZSTD(1)),
    `scope_name` String CODEC(ZSTD(1)),
    `scope_version` LowCardinality(String) CODEC(ZSTD(1)),
    `scope_attributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)),
    `scope_dropped_attr_count` Int64,
    `scope_schema_url` LowCardinality(String) CODEC(ZSTD(1)),
    `trace_id` String CODEC(ZSTD(1)),
    `span_id` String CODEC(ZSTD(1)),
    `parent_span_id` String CODEC(ZSTD(1)),
    `trace_state` String CODEC(ZSTD(1)),
    `span_name` LowCardinality(String) CODEC(ZSTD(1)),
    `span_kind` LowCardinality(String) CODEC(ZSTD(1)),
    `service_name` LowCardinality(String) CODEC(ZSTD(1)),
    `span_attributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)),
    `duration` Int64 CODEC(ZSTD(1)),
    `status_code` LowCardinality(String) CODEC(ZSTD(1)),
    `status_message` String CODEC(ZSTD(1)),
    `events.timestamp` Array(DateTime64(9)),
    `events.name` Array(LowCardinality(String)),
    `events.attributes` Array(Map(LowCardinality(String), String)),
    `links.trace_id` Array(String),
    `links.span_id` Array(String),
    `links.span_state` Array(String),
    `links.attributes` Array(Map(LowCardinality(String), String)),
    INDEX idx_trace_id trace_id TYPE bloom_filter(0.001) GRANULARITY 1,
    INDEX idx_span_attr_key mapKeys(resource_attributes) TYPE bloom_filter(0.1) GRANULARITY 1,
    INDEX idx_span_attr_value mapKeys(resource_attributes) TYPE bloom_filter(0.1) GRANULARITY 1,
    INDEX idx_res_attr_key mapKeys(resource_attributes) TYPE bloom_filter(0.1) GRANULARITY 1,
    INDEX idx_res_attr_value mapKeys(resource_attributes) TYPE bloom_filter(0.1) GRANULARITY 1,
    INDEX idx_scope_attr_key mapKeys(resource_attributes) TYPE bloom_filter(0.1) GRANULARITY 1,
    INDEX idx_scope_attr_value mapKeys(resource_attributes) TYPE bloom_filter(0.1) GRANULARITY 1
)
ENGINE = MergeTree
PARTITION BY toDate(timestamp)
ORDER BY (service_name, span_name, toUnixTimestamp(timestamp), trace_id)
TTL toDateTime(timestamp) + toIntervalDay(180)
SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1 │
   └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

1 row in set. Elapsed: 0.004 sec.

Code example

package code

// given an auto-migrated struct like this

type Trace struct {
	Events         []OtelTraceEvent  `gorm:"type:Nested(timestamp DateTime64(9), name LowCardinality(String), attributes Map(LowCardinality(String), String));"` // order matters, dont't touch nested def
	Links          []OtelTraceLink   `gorm:"type:Nested(trace_id String, span_id String, span_state String, attributes Map(LowCardinality(String), String));"`   // order matters, dont't touch nested def
}

// and a non-migrated struct like this
type TraceIngestion struct {
	EventsTimestamp  []time.Time         `gorm:"type:DateTime64(9);column:events.timestamp"`
	EventsName       []string            `gorm:"type:LowCardinality(String);column:events.name"`
	EventsAttributes []map[string]string `gorm:"type:Map(LowCardinality(String), String);column:events.attributes"`
	LinksTraceID     []string            `gorm:"type:LowCardinality(String);column:links.trace_id"`
	LinksSpanID      []string            `gorm:"type:LowCardinality(String);column:links.span_id"`
	LinksState       []string            `gorm:"type:LowCardinality(String);column:links.span_state"`
	LinksAttributes  []map[string]string `gorm:"type:Map(LowCardinality(String), String);column:links.attributes"`
}

Error log

block cannot be sorted - missing columns in requested order: [events.timestamp events.name events.attributes]"

Details

Environment

  • clickhouse-go version: 2.28.2
  • Interface: go-gorm/clickhouse
  • Go version: 1.22.0
  • Operating system: OS X
  • ClickHouse version: 24.9.1.628
  • Is it a ClickHouse Cloud? No
  • ClickHouse Server non-default settings, if any: -
  • CREATE TABLE statements for tables involved:
  • Sample data for all these tables, use clickhouse-obfuscator if necessary

Activity

  1. jkaflik commented on Sep 12, 2024

    @jkaflik
    Member

    @fidiego thanks for reporting this. Could you (if possible) post an INSERT statement generated by go-gorm?

  2. self-assigned this
    on Sep 12, 2024
  3. fidiego commented on Sep 12, 2024

    @fidiego
    Author

    sure thing @jkaflik.

    INSERT SQL

    INSERT INTO
        `otel_traces` (
            `id`,
            `created_by_id`,
            `created_at`,
            `updated_at`,
            `deleted_at`,
            `runner_id`,
            `runner_job_id`,
            `runner_job_execution_id`,
            `timestamp`,
            `timestamp_date`,
            `timestamp_time`,
            `resource_attributes`,
            `resource_schema_url`,
            `scope_name`,
            `scope_version`,
            `scope_attributes`,
            `scope_dropped_attr_count`,
            `scope_schema_url`,
            `trace_id`,
            `span_id`,
            `parent_span_id`,
            `trace_state`,
            `span_name`,
            `span_kind`,
            `service_name`,
            `span_attributes`,
            `duration`,
            `status_code`,
            `status_message`,
            `events`.`timestamp`,
            `events`.`name`,
            `events`.`attributes`
        )
    VALUES
        (
            '',
            '',
            '2024-09-09 18:49:12.765',
            '2024-09-09 18:49:12.765',
            0,
            'runccccccccccccccccccccccc',
            '',
            '',
            '2018-12-13 08:51:00',
            '0000-00-00 00:00:00',
            '0000-00-00 00:00:00',
            { 'job.id' :'jobidentfier',
            'service.name': 'runner-runxxxxxxxxxxxxxxxxxxxxxxxxxxx' },
            '',
            'my.library',
            '1.0.0',
            {'my.scope.attribute':'some scope attribute'},
            0,
            '',
            '5bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            'eee19b7ec3c1b174',
            'eee19b7ec3c1b173',
            '',
            'I''m a server span',
            'Server',
            'runner-runxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            {'my.span.attr':'some value'},
            1,
            'Unset',
            '',
            (
                '2018-12-13 14:51:01',
                '2020-02-11 20:26:13',
                '2020-02-11 20:26:13'
            ),
            ('ebento1', 'event-with-attr', 'event'),
            (
                [],
                { 'span-event-attr' :'span-event-attr-val' } ',
                []
            )
        )
    

  4. fidiego commented on Sep 20, 2024

    @fidiego
    Author

    hi @jkaflik, following up on this. if it is useful, i can set up a reproduction.

  5. jkaflik commented on Sep 27, 2024

    @jkaflik
    Member

    @fidiego sorry for delayed response. Yes, please.

  6. fidiego commented on Oct 1, 2024

    @fidiego
    Author

    @jkaflik no worries.

    I've set up a PoC here. https://github.com/fidiego/ch-go-poc

    In my actual code I define a struct for the migration w/ gorm:"type:Nested(...) (like exemplars in the poc) and a second struct for reading with explicit columns (like events.* in the poc). Because it's simpler than writing scanner/value code. Read works great, but creating/migrating w/ the dot-delimited columns raises an error.

    The dot-delimited fields work as event.column but not as events.column.

  7. fidiego commented on Oct 9, 2024

    @fidiego
    Author

    hi @jkaflik, i hope all is well. i wanted to ask if there was anything you needed from my end or if there were any updates on this issue.

  8. jkaflik commented on Oct 15, 2024

    @jkaflik
    Member

    @fidiego, thanks for submitting a reproduction DDL. I will take a look this week. Apologies, my focus was shift on another project.

  9. fidiego commented on Dec 11, 2024

    @fidiego
    Author

    hi @jkaflik and @SpencerTorres, i just wanted to circle back on this. there is no urgency on my end but i am curious as to whether or not this is something that can be addressed in clickhouse-go.

  10. SpencerTorres commented on Mar 4, 2025

    @SpencerTorres
    Member

    Hey @fidiego!

    I wonder if this can be fixed on the go-gorm side? Based on the SHOW CREATE TABLE syntax, the preferred snytax is

    `events.timestamp`
    

    Is there any way to make dialect-specific changes for this one node in the AST?

    I've seen this issue before with this function where it is unable to determine the columns within the INSERT. Another solution we can consider is adding a context key where you can specifically provide the column names you want to insert. This way you're not blocked by what the regex parses. I understand this may not be what you want if you're using an ORM though.

    If it doesn't break backwards compatibility we could also just merge your proposed change. What are your thoughts?

  11. SpencerTorres commented on Mar 8, 2025

    @SpencerTorres
    Member

    I've seen this issue before

    Here's the related issue I was thinking of #1485 (comment) (see Further Actions section)

    Further examples of potential fix in #1485 (comment)

  12. git-hulk commented on Apr 23, 2025

    @git-hulk

    @SpencerTorres I'm not sure if it sounds good to introduce clickhouse-sql-parser to parse the query instead of using regex. I would be happy to submit a PR if this sounds good to you.

  13. SpencerTorres commented on May 5, 2025

    @SpencerTorres
    Member

    @git-hulk I'm concerned about the memory usage and latency this would add just to extract the column names. I'm also cautious about adding new dependencies.

    I think we have some other fixes in mind that I would like to try first before going that route. Thanks for the suggestion though, I might re-use that module for something else

  14. git-hulk commented on May 6, 2025

    @git-hulk

    @git-hulk I'm concerned about the memory usage and latency this would add just to extract the column names. I'm also cautious about adding new dependencies.

    I think we have some other fixes in mind that I would like to try first before going that route. Thanks for the suggestion though, I might re-use that module for something else

    @SpencerTorres Thanks for your reply.

  15. moong-dal commented on Jun 3, 2025

    @moong-dal

    I was facing a problem with quoted column names containing a space followed by an opening parenthesis, which was preventing me from doing an ETL job.
    A sample query that could not be correctly parsed via the current regex implementation: INSERT INTO db.table (`ITEM`, `QTY (MT)`)
    I have written a simple parser here .
    The readme shows an example that identifies columns correctly.
    The tests also have many examples.
    It is 20% faster than the current regex based solution. Let me know if you want me to create a PR which adds it to the clickhouse-go codebase.

  16. added theissue type on Jul 29, 2025
  17. polyglotAI-bot commented on Nov 15, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Close — already fixed
    PR #1614 (commit 60f96c09) fixed the reported defect in v2.38.0. Before you close, track the second defect of the 2025-06-03 comment (`QTY (MT)`) separately: it still fails on main, and open PR #2031 fixes it in our run.

    Analysis: On main, extractInsertQueryComponents removes every backtick from each column name (batch.go:115), so `events`.`timestamp` matches the block column; before PR #1614 the code removed only the first and last backtick. The `QTY (MT)` case is a different defect: the greedy pattern extractInsertColumnsMatch (batch.go:13) takes the last ( in the statement, which is inside the quoted name, so the column list becomes one name.

    Reproduction: complete program and output
    package main
    
    import (
    	"context"
    	"fmt"
    	"os"
    	"time"
    
    	"github.com/ClickHouse/clickhouse-go/v2"
    )
    
    func main() {
    	addr := os.Getenv("CLICKHOUSE_ADDR")
    	if addr == "" {
    		addr = "localhost:9000"
    	}
    	ctx := context.Background()
    	conn, err := clickhouse.Open(&clickhouse.Options{Addr: []string{addr}})
    	if err != nil {
    		fmt.Println("open:", err)
    		return
    	}
    	defer conn.Close()
    
    	for _, q := range []string{
    		"DROP TABLE IF EXISTS issue_1401",
    		"CREATE TABLE issue_1401 (id UInt32, events Nested(timestamp DateTime64(9), name String), `QTY (MT)` Float64) ENGINE = MergeTree ORDER BY id",
    	} {
    		if err := conn.Exec(ctx, q); err != nil {
    			fmt.Println("setup:", err)
    			return
    		}
    	}
    	defer conn.Exec(ctx, "DROP TABLE issue_1401")
    
    	ts := time.Date(2018, 12, 13, 8, 51, 0, 0, time.UTC)
    	cases := []struct {
    		name  string
    		query string
    		row   []any
    	}{
    		{"nested, backticks per part (go-gorm)", "INSERT INTO `issue_1401` (`id`, `events`.`timestamp`, `events`.`name`)", []any{uint32(1), []time.Time{ts}, []string{"a"}}},
    		{"nested, one backtick pair", "INSERT INTO `issue_1401` (`id`, `events.timestamp`, `events.name`)", []any{uint32(2), []time.Time{ts}, []string{"b"}}},
    		{"quoted column with ' ('", "INSERT INTO issue_1401 (`id`, `QTY (MT)`)", []any{uint32(3), 1.5}},
    	}
    	for _, c := range cases {
    		batch, err := conn.PrepareBatch(ctx, c.query)
    		if err == nil {
    			err = batch.Append(c.row...)
    		}
    		if err == nil {
    			err = batch.Send()
    		}
    		if err != nil {
    			fmt.Printf("%s: ERROR %v\n", c.name, err)
    			continue
    		}
    		fmt.Printf("%s: OK\n", c.name)
    	}
    
    	rows, err := conn.Query(ctx, "SELECT id, events.name, `QTY (MT)` FROM issue_1401 ORDER BY id")
    	if err != nil {
    		fmt.Println("select:", err)
    		return
    	}
    	defer rows.Close()
    	for rows.Next() {
    		var (
    			id    uint32
    			names []string
    			qty   float64
    		)
    		if err := rows.Scan(&id, &names, &qty); err != nil {
    			fmt.Println("scan:", err)
    			return
    		}
    		fmt.Printf("row: id=%d events.name=%v qty=%v\n", id, names, qty)
    	}
    }

    Output on main (d124d2b0), ClickHouse 26.9.1.1629 (v2.38.0 gives the same output):

    nested, backticks per part (go-gorm): OK
    nested, one backtick pair: OK
    quoted column with ' (': ERROR requested column order is incorrect length to sort block - expected 2, got 1
    row: id=1 events.name=[a] qty=0
    row: id=2 events.name=[b] qty=0
    

    Output on v2.28.2, ClickHouse 26.9.1.1629 (v2.37.2 gives the same output):

    nested, backticks per part (go-gorm): ERROR block cannot be sorted - missing columns in requested order: [events.timestamp events.name]
    nested, one backtick pair: OK
    quoted column with ' (': ERROR requested column order is incorrect length to sort block - expected 2, got 1
    row: id=2 events.name=[b] qty=0
    

    Output on main with the diff of PR #2031 applied:

    nested, backticks per part (go-gorm): OK
    nested, one backtick pair: OK
    quoted column with ' (': OK
    row: id=1 events.name=[a] qty=0
    row: id=2 events.name=[b] qty=0
    row: id=3 events.name=[] qty=1.5
    

    Automated triage by Polyglot AI. A maintainer makes the final decision. Shortened on 2026-11-20: the edit history has the first version.

  18. added
    queries
    on Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugqueries

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions