clickhouse-js-node-coding

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ClickHouse Node.js Client — Coding

ClickHouse Node.js 客户端编码开发

⚠️ Node.js runtime only. This skill covers the
@clickhouse/client
package running in a Node.js runtime exclusively — including Next.js Node runtime API routes, React Server Components, Server Actions, and standard Node.js processes. Do not apply this skill to browser client components, Web Workers, Next.js Edge runtime, Cloudflare Workers, or any usage of
@clickhouse/client-web
. For browser/edge environments, the correct package is
@clickhouse/client-web
.

⚠️ 仅适用于Node.js运行时。本技能仅涵盖在Node.js运行时中运行的
@clickhouse/client
包——包括Next.js Node运行时的API路由、React Server Components、Server Actions以及标准Node.js进程。请勿将此技能应用于浏览器客户端组件、Web Workers、Next.js Edge运行时、Cloudflare Workers或任何
@clickhouse/client-web
的使用场景。对于浏览器/边缘环境,应使用
@clickhouse/client-web
包。

How to Use This Skill

如何使用本技能

  1. Match the user's intent to a row in the Task Index below and read the corresponding reference file before writing code. After reading it, scan any Answer checklist in that reference and make sure the final answer covers each relevant item; those checklists capture details users usually need but are easy to omit in short answers.
  2. Always import from
    @clickhouse/client
    (never
    @clickhouse/client-web
    ) and create a client with
    createClient({ url })
    or rely on supported defaults when appropriate. Close it with
    await client.close()
    preferably when it's no longer needed or during graceful shutdown for global resources.
  3. Prefer
    JSONEachRow
    for typical row inserts/selects
    unless the user has already chosen another format or is streaming raw bytes (CSV / TSV / Parquet — see
    examples/node/performance/
    ). Note on
    clickhouse_settings
    :
    settings passed to
    createClient
    are defaults for every request; they can be overridden per-call by passing
    clickhouse_settings
    directly to
    insert()
    ,
    query()
    , or
    command()
    . Always mention this when the user configures settings at the client level.
  4. Always use
    query_params
    for user-supplied values
    — never template- literal-interpolate them into SQL. See
    reference/query-parameters.md
    . When answering a parameter-binding question, your response must explicitly name template-literal interpolation as a "SQL injection risk" — even when the user only asked about syntax and did not raise security. The literal phrase "SQL injection" needs to appear; this is the most common mistake from PostgreSQL/MySQL users and the security framing is part of the correct answer, not an optional aside.
  5. Pick the right method for the job:
    • client.insert()
      — write rows.
    • client.query()
      +
      resultSet.json()
      /
      .text()
      /
      .stream()
      — read rows that return data.
    • client.command()
      — DDL and other statements that don't return rows (
      CREATE
      ,
      DROP
      ,
      TRUNCATE
      ,
      ALTER
      ,
      SET
      in a session, etc.).
    • client.exec()
      — when you need the raw response stream of an arbitrary statement (rare in coding scenarios).
    • client.ping()
      — health check; returns
      { success, error? }
      , never throws on connection failure.
  6. Note version constraints when relevant. Examples:
    • pathname
      config option: client
      >= 1.0.0
      .
    • BigInt
      values in
      query_params
      : client
      >= 1.15.0
      .
    • TupleParam
      and JS
      Map
      in
      query_params
      : client
      >= 1.9.0
      .
    • Configurable
      json.parse
      /
      json.stringify
      : client
      >= 1.14.0
      .
    • Time
      /
      Time64
      data types: ClickHouse server
      >= 25.6
      .
    • Dynamic
      /
      Variant
      / new
      JSON
      types: ClickHouse server
      >= 24.1
      /
      24.5
      /
      24.8
      (no longer experimental since
      25.3
      ).

  1. 匹配用户意图与下方任务索引中的对应条目,编写代码前先阅读相关参考文档。阅读后,查看参考文档中的答案检查清单,确保最终回答涵盖所有相关项;这些清单包含了用户通常需要但在简短回答中容易遗漏的细节。
  2. 始终从
    @clickhouse/client
    导入
    (切勿使用
    @clickhouse/client-web
    ),使用
    createClient({ url })
    创建客户端,或在合适时依赖支持的默认配置。当客户端不再需要时,或在全局资源优雅关闭期间,最好使用
    await client.close()
    关闭客户端。
  3. 对于常规的行插入/查询,优先使用
    JSONEachRow
    格式
    ,除非用户已选择其他格式或正在流式传输原始字节(CSV/TSV/Parquet——详见
    examples/node/performance/
    )。 关于
    clickhouse_settings
    的说明
    :传递给
    createClient
    的设置是所有请求的默认配置;可以通过在
    insert()
    query()
    command()
    调用中直接传入
    clickhouse_settings
    来覆盖这些默认配置。当用户在客户端级别配置设置时,务必提及这一点。
  4. 用户提供的值务必使用
    query_params
    ——切勿通过模板字面量将其插入SQL中。详见
    reference/query-parameters.md
    回答参数绑定相关问题时,必须明确指出模板字面量插值存在"SQL injection"风险——即使用户仅询问语法而未提及安全问题。必须出现"SQL injection"这个短语;这是PostgreSQL/MySQL用户最常犯的错误,安全提示是正确回答的一部分,而非可选补充。
  5. 为任务选择合适的方法
    • client.insert()
      — 写入行数据。
    • client.query()
      +
      resultSet.json()
      /
      .text()
      /
      .stream()
      — 读取返回数据的行。
    • client.command()
      — 执行DDL和其他不返回行的语句(如会话中的
      CREATE
      DROP
      TRUNCATE
      ALTER
      SET
      等)。
    • client.exec()
      — 当你需要获取任意语句的原始响应流时使用(在编码场景中很少用到)。
    • client.ping()
      — 健康检查;返回
      { success, error? }
      ,连接失败时不会抛出异常。
  6. 相关时注意版本限制。示例:
    • pathname
      配置选项:客户端版本
      >= 1.0.0
    • query_params
      中的
      BigInt
      值:客户端版本
      >= 1.15.0
    • query_params
      中的
      TupleParam
      和JS
      Map
      :客户端版本
      >= 1.9.0
    • 可配置的
      json.parse
      /
      json.stringify
      :客户端版本
      >= 1.14.0
    • Time
      /
      Time64
      数据类型:ClickHouse服务器版本
      >= 25.6
    • Dynamic
      /
      Variant
      / 新
      JSON
      类型:ClickHouse服务器版本
      >= 24.1
      /
      24.5
      /
      24.8
      (自
      25.3
      版本起不再是实验性功能)。

Task Index

任务索引

Identify the user's task and read the matching reference file.
TaskTriggers / symptomsReference file
Configure / connect the clientBuilding a
createClient
call, URL parameters,
clickhouse_settings
, default format, custom HTTP headers
reference/client-configuration.md
Ping the serverHealth checks, readiness probes, "is ClickHouse up?"
reference/ping.md
Choose an insert format"Which format should I use to insert?", JSON vs raw,
JSONEachRow
vs
JSON
vs
JSONObjectEachRow
reference/insert-formats.md
Insert into a subset of columns / different database
insert({ columns })
, excluding columns, ephemeral columns, cross-DB inserts
reference/insert-columns.md
Insert values, expressions, dates, decimals
INSERT … VALUES
with SQL functions,
Date
/
DateTime
from JS,
Decimal
precision,
INSERT … SELECT
reference/insert-values.md
Async inserts (server-side batching)
async_insert=1
, fire-and-forget vs wait-for-ack
reference/async-insert.md
Select and parse results
JSONEachRow
reads,
JSON
with metadata, picking a select format
reference/select-formats.md
Parameterize queriesBinding values, special characters / escaping, "SQL injection?",
{name: Type}
syntax
reference/query-parameters.md
Sessions & temporary tables
session_id
,
CREATE TEMPORARY TABLE
, per-session
SET
commands
reference/sessions.md
Modern data types
Dynamic
,
Variant
,
JSON
(object),
Time
,
Time64
reference/data-types.md
Custom JSON parse/stringifyPlug in
JSONBig
/
safe-stable-stringify
/ a
BigInt
-aware serializer
reference/custom-json.md

识别用户的任务并阅读对应的参考文档。
任务触发场景/症状参考文档
配置/连接客户端编写
createClient
调用、URL参数、
clickhouse_settings
、默认格式、自定义HTTP请求头
reference/client-configuration.md
Ping服务器健康检查、就绪探针、"ClickHouse是否正常运行?"
reference/ping.md
选择插入格式"我应该使用哪种格式插入数据?"、JSON与原始格式对比、
JSONEachRow
vs
JSON
vs
JSONObjectEachRow
reference/insert-formats.md
插入到部分列/不同数据库使用
insert({ columns })
、排除列、临时列、跨数据库插入
reference/insert-columns.md
插入值、表达式、日期、小数带SQL函数的
INSERT … VALUES
、从JS传入
Date
/
DateTime
Decimal
精度、
INSERT … SELECT
reference/insert-values.md
异步插入(服务器端批量处理)设置
async_insert=1
、即发即弃 vs 等待确认
reference/async-insert.md
查询并解析结果读取
JSONEachRow
格式数据、带元数据的
JSON
格式、选择查询格式
reference/select-formats.md
参数化查询值绑定、特殊字符/转义、"SQL injection风险?"、
{name: Type}
语法
reference/query-parameters.md
会话与临时表
session_id
CREATE TEMPORARY TABLE
、会话级
SET
命令
reference/sessions.md
现代数据类型
Dynamic
Variant
JSON
(对象)、
Time
Time64
reference/data-types.md
自定义JSON解析/序列化接入
JSONBig
/
safe-stable-stringify
/ 支持
BigInt
的序列化器
reference/custom-json.md

Conventions used in answers

回答中的约定

  • Always show
    import { createClient } from '@clickhouse/client'
    (Node, never Web).
  • Always
    await client.close()
    at the end of self-contained snippets; in long-running services, close on graceful shutdown.
  • For inserts, prefer
    format: 'JSONEachRow'
    and
    values: [...]
    unless the user's scenario requires otherwise.
  • For selects, prefer
    await (await client.query({...})).json<RowType>()
    for small / medium result sets; for bigger results suggest streaming.
  • When showing parameter binding, use ClickHouse's native
    {name: Type}
    syntax — never
    $1
    ,
    ?
    , or
    :name
    .
  • For DDL inside a cluster or behind a load balancer, set
    clickhouse_settings: { wait_end_of_query: 1 }
    on the
    command()
    call so the server only acknowledges after the change is applied. See https://clickhouse.com/docs/en/interfaces/http/#response-buffering.

  • 始终展示
    import { createClient } from '@clickhouse/client'
    (Node环境,切勿使用Web版本)。
  • 在独立代码片段末尾始终添加
    await client.close()
    ;在长期运行的服务中,在优雅关闭时关闭客户端。
  • 插入数据时,优先使用
    format: 'JSONEachRow'
    values: [...]
    ,除非用户场景有特殊要求。
  • 查询数据时,对于中小型结果集,优先使用
    await (await client.query({...})).json<RowType>()
    ;对于大型结果集,建议使用流式处理。
  • 展示参数绑定时,使用ClickHouse原生的
    {name: Type}
    语法——切勿使用
    $1
    ?
    :name
  • 在集群内或负载均衡器后的环境中执行DDL时,在
    command()
    调用中设置
    clickhouse_settings: { wait_end_of_query: 1 }
    ,以便服务器在变更生效后再返回确认。详见https://clickhouse.com/docs/en/interfaces/http/#response-buffering。

Out of scope

超出范围的内容

This skill covers day-to-day coding against
@clickhouse/client
(Node). The following topics are intentionally not covered here:
  • Errors, hangs, type mismatches, proxy pathname surprises, log silence, socket hang-ups,
    ECONNRESET
    → use the
    clickhouse-js-node-troubleshooting
    skill.
  • Streaming, Parquet, file streams, server-side bulk moves, progress streaming, async-insert throughput tuning — see
    examples/node/performance/
    .
  • TLS, RBAC / read-only users, deeper SQL-injection guidance — see
    examples/node/security/
    .
  • CREATE TABLE
    patterns, deployment-shaped connection strings, replication / sharding choices
    — see
    examples/node/schema-and-deployments/
    .
  • Browser, Web Worker, Next.js Edge, Cloudflare Workers — use
    @clickhouse/client-web
    and see
    examples/web/
    .

本技能涵盖基于
@clickhouse/client
(Node环境)的日常编码内容。以下主题在本技能的覆盖范围内:
  • 错误、挂起、类型不匹配、代理路径异常、日志无输出、套接字挂起、
    ECONNRESET
    → 使用
    clickhouse-js-node-troubleshooting
    技能。
  • 流式处理、Parquet、文件流、服务器端批量迁移、进度流式传输、异步插入吞吐量调优——详见
    examples/node/performance/
  • TLS、RBAC/只读用户、深入的SQL注入指导——详见
    examples/node/security/
  • CREATE TABLE
    模式、部署相关的连接字符串、复制/分片选择
    ——详见
    examples/node/schema-and-deployments/
  • 浏览器、Web Worker、Next.js Edge、Cloudflare Workers——使用
    @clickhouse/client-web
    并详见
    examples/web/

Still Stuck?

仍有疑问?