You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sqlc生成Go代码时遭遇'firstname'列不存在错误求助

解决sqlc生成Go代码时的"column 'firstname' does not exist"错误

问题原因

PostgreSQL默认会将未用双引号包裹的标识符转换为小写。你的表结构中通过双引号创建了驼峰格式的列名"firstName"和"lastName",但查询语句里的firstName、lastName未加双引号,sqlc解析时会将其转为小写的firstname、lastname,与表中实际列名不匹配,因此报错。

解决方案

有两种可行的解决方式:

方式1:给查询中的驼峰列名添加双引号

修改user.sql中的INSERT语句,为驼峰列名加上双引号,确保PostgreSQL能识别正确的列名:

-- name: CreateUser :one
INSERT INTO "user" (
  email, password, "firstName", "lastName"
) VALUES (
  $1, $2, $3, $4
)
RETURNING *;

方式2:改用蛇形命名法(推荐)

遵循PostgreSQL的常规命名规范,将列名改为蛇形(snake_case),避免大小写匹配问题:

  1. 修改表结构文件000001_init_schema.up.sql:
CREATE TABLE "user" (
  "id" BIGSERIAL PRIMARY KEY,
  "email" varchar(50) NOT NULL,
  "password" varchar(70) NOT NULL,
  "first_name" varchar(240) NOT NULL,
  "last_name" varchar(240) NOT NULL,
  "created_at" timestamptz NOT NULL DEFAULT 'now()',
  "created_by" bigint NOT NULL,
  "modified_at" timestamptz,
  "modified_by" bigint,
  "must_change_password" boolean NOT NULL DEFAULT 'true',
  "can_change_password" boolean NOT NULL DEFAULT 'false'
);
  1. 同步修改user.sql中的查询语句:
-- name: CreateUser :one
INSERT INTO "user" (
  email, password, first_name, last_name
) VALUES (
  $1, $2, $3, $4
)
RETURNING *;

这种方式下,sqlc的json_tags_case_style: "camel"配置会自动将蛇形列名转换为驼峰格式的JSON标签,生成的Go结构体完全满足JSON序列化需求。

内容的提问来源于stack exchange,提问作者Vladimer Grigalashvili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 22:09:24