Skip to content

Client::Insert concatenates the raw table name into SQL — table names needing backquotes cannot be used #560

Open

Description

@claude

Description

Client::Insert(const std::string& table_name, const Block& block) builds its INSERT statement by concatenating the raw table name:

https://github.com/ClickHouse/clickhouse-cpp/blob/master/clickhouse/client.cpp#L500

Query query("INSERT INTO " + table_name + " ( " + fields_section.str() + " ) VALUES", query_id);

The inconsistency is inside this one function: the column names a few lines above are quoted and escaped with NameToQueryString() (clickhouse/client.cpp:456, backquotes + ` → ``), but the table name is spliced in verbatim.

clickhouse/client.h:315 documents the parameter as a table name ("Intends for insert block of data into a table \p table_name"), so a caller reasonably passes the plain name. For any legal-but-needs-quoting name (my-table, user events, a name starting with a digit, …) the generated SQL fails to parse server-side even though the table exists — INSERT INTO my-table parses my minus table.

Callers can work around it by pre-quoting (client.Insert("\my-table`", block)), and qualified names (db.table) are also passed through this parameter today, so blind quoting would be a breaking change — hence this is as much a contract question as a bug: either quote/escape internally with pass-through for already-quoted input (JDBC's Statement.enquoteIdentifier` contract), or document that this parameter is a SQL fragment and the caller must quote it.

ClickHouse server version

26.8.1.2041 (official build), reached over HTTP at localhost:8123.

Reproduction

#include <clickhouse/client.h>
#include <iostream>

using namespace clickhouse;

int main() {
    ClientOptions opts;
    opts.SetHost("localhost").SetPort(9000).SetDefaultDatabase("default");
    Client client(opts);

    client.Execute("DROP TABLE IF EXISTS `my-table`");
    client.Execute("CREATE TABLE `my-table` (id Int64) ENGINE = Memory");

    Block block;
    auto col = std::make_shared<ColumnInt64>();
    col->Append(42);
    block.AppendColumn("id", col);

    try {
        client.Insert("my-table", block);          // plain table name, as the javadoc-style comment implies
        std::cout << "INSERT OK" << std::endl;
    } catch (const std::exception& e) {
        std::cout << "INSERT FAILED: " << e.what() << std::endl;
    }

    Client c2(opts);
    c2.Insert("`my-table`", block);                // pre-quoted workaround: succeeds
    return 0;
}

Expected: the insert succeeds, since `my-table` exists and the library already knows how to quote identifiers.

Actual: Client::Insert emits

INSERT INTO my-table ( `id` ) VALUES

and the server rejects it. Sending that exact generated statement against 26.8.1.2041 while the table exists:

$ curl -sS 'http://localhost:8123/' --data-binary 'CREATE TABLE IF NOT EXISTS `my-table` (id Int64) ENGINE = Memory'
$ curl -sS 'http://localhost:8123/' --data-binary 'INSERT INTO my-table ( `id` ) VALUES (42)'
Code: 62. DB::Exception: Syntax error: failed at position 15 (-): -table ( `id` ) VALUES (42).
Expected one of: token, Dot, OpeningRoundBracket, FROM INFILE, SETTINGS, VALUES, FORMAT, SELECT, WITH, FROM. (SYNTAX_ERROR)

$ curl -sS 'http://localhost:8123/' --data-binary 'INSERT INTO `my-table` ( `id` ) VALUES (42)'   # backquoted: succeeds, no output

Note on verification: the C++ program above compiles cleanly against the repo's static libs, but the sandbox used for this investigation does not permit executing built binaries, so the failure was confirmed by replaying the exact statement that Client::Impl::Insert constructs (verified by reading the string-building code) against a live server, as shown above. The client-side statement construction is deterministic — the table name is inserted with no quoting on any path.

Suggested fix

clickhouse/client.cpp:500 — run the table name through the same identifier-quoting path already used for column names, with an escape hatch for existing callers:

  • detect an already-quoted identifier (`...`) and pass it through unchanged;
  • handle the qualified database.table form by quoting each part separately, since a single NameToQueryString("db.table") would produce the wrong `db.table` ;
  • otherwise apply NameToQueryString().

Whatever is chosen, the contract for table_name should be spelled out in clickhouse/client.h:315-317 (raw identifier vs. SQL fragment) — the current ambiguity is what makes the two behaviours indistinguishable to callers.

Link

Same root cause as ClickHouse/clickhouse-java#3089 (client-v2 getTableSchema / insert(tableName, …)). Note this repo has no DESCRIBE TABLE-based schema introspection helper, so only the insert path is affected here.

Activity

  1. added theissue type on Sep 1, 2026
  2. slabko commented on Sep 2, 2026

    @slabko
    Contributor

    Note for future myself: Be aware of situations where the table name is nice.table. When calling client.insert("nice.table", data, settings);, you need to determine whether nice.table is the full table name or whether nice is the database name and table is the table name.
    For reference, ClickHouse always assumes that an unquoted, dot-separated table name consists of the database name and the table name. If we go that route, users will still need to quote table names that contain a dot.

  3. polyglotAI-bot commented on Nov 18, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — maintainer decision
    Decide the contract of table_name: document it as SQL text after INSERT INTO (no break, a fix in clickhouse/client.h:315), or quote it with the pass-through cases from the review of closed PR #573, behind a new CH_* option. No open PR covers this issue now.

    • Category: Bug
    • Classification: impact: none · area: Queries (table name quoting)
    • Status on master: Reproduced on master — 58453c2, ClickHouse 26.10.4.207, default 2.x build options: Insert("triage-560", …) fails with a server syntax error; pre-quoted, qualified, and double-quoted names work.
    • Breaking change: No — can be done without a break: document table_name as SQL text, or add the quoting behind a new CH_* option that CH_USE_3X_API enables. Quoting by default is a break: callers that pass db.table, double-quoted, or partly quoted names get different SQL.
    • Duplicates / related: Related: fix(client): quote table names in Insert queries #573 (closed PR: it quoted the name by default and broke pre-quoted names; the maintainer review lists the cases that a fix must keep). No other match found.

    Analysis: Client::Impl::Insert builds "INSERT INTO " + table_name + " ( " + … + " ) VALUES" (clickhouse/client.cpp:512). The column names go through NameToQueryString() (clickhouse/client.cpp:468, 506-508), but the table name does not. The header says only "insert block of data into a table table_name" (clickhouse/client.h:315), so it does not tell the caller that the parameter is SQL text. Callers depend on the pass-through: the README uses a qualified name (README.md:277), and ClientCase.ColEscapeNameTest passes a double-quoted name (ut/client_ut.cpp:1245). The maintainer review of #573 states that Insert() "has always accepted whatever is valid after INSERT INTO". Thus a plain name that needs quotes (my-table) fails on the server, and the workaround is to quote it before the call.

    Reproduction: complete program and output
    #include <clickhouse/client.h>
    
    #include <cstdlib>
    #include <iostream>
    #include <memory>
    #include <string>
    
    using namespace clickhouse;
    
    static ClientOptions Options() {
        const char* host = std::getenv("CLICKHOUSE_HOST");
        const char* port = std::getenv("CLICKHOUSE_PORT");
        return ClientOptions()
            .SetHost(host ? host : "localhost")
            .SetPort(port ? static_cast<uint16_t>(std::stoi(port)) : 9000);
    }
    
    static Block MakeBlock() {
        auto col = std::make_shared<ColumnInt64>();
        col->Append(42);
        Block block;
        block.AppendColumn("id", col);
        return block;
    }
    
    // A new Client for each case: a Client can stay unusable after an exception.
    static void Case(const std::string& table_name) {
        try {
            Client client(Options());
            client.Insert(table_name, MakeBlock());
            std::cout << "Insert(" << table_name << "): OK" << std::endl;
        } catch (const std::exception& e) {
            std::cout << "Insert(" << table_name << "): " << e.what() << std::endl;
        }
    }
    
    int main() {
        Client admin(Options());
        admin.Execute("DROP TABLE IF EXISTS `triage-560`");
        admin.Execute("CREATE TABLE `triage-560` (id Int64) ENGINE = Memory");
    
        Case("triage-560");               // plain table name
        Case("`triage-560`");             // pre-quoted name
        Case("default.`triage-560`");     // qualified, partly quoted
        Case("\"triage-560\"");           // double-quoted name
    
        admin.Select("SELECT count() FROM `triage-560`", [](const Block& b) {
            if (b.GetRowCount() > 0)
                std::cout << "rows in table: " << b[0]->As<ColumnUInt64>()->At(0) << std::endl;
        });
        admin.Execute("DROP TABLE IF EXISTS `triage-560`");
        return 0;
    }

    Output on master (58453c2), ClickHouse 26.10.4.207, default 2.x build options:

    Insert(triage-560): DB::Exception: Syntax error: failed at position 19 (-): -560 ( `id` ) VALUES. Expected one of: token, Dot, OpeningRoundBracket, FROM INFILE, SETTINGS, VALUES, FORMAT, SELECT, WITH, FROM
    Insert(`triage-560`): OK
    Insert(default.`triage-560`): OK
    Insert("triage-560"): OK
    rows in table: 3
    

    Automated triage by Polyglot AI. Classification added on 2026-11-19. A maintainer makes the final decision.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions