读懂Squirrel生成的Gleam代码:生成函数、Decoder与Row类型完全解析

原创2026-11-01 23:49:301,982 阅读

读懂Squirrel生成的Gleam代码:生成函数、Decoder与Row类型完全解析

快速上手:先让 Squirrel 生成一次代码

如果你刚接触 Squirrel(Type safe SQL in Gleam),最直观的学习方式就是亲手跑一次代码生成,然后逐行读懂它产出的文件。只需两步:

  1. 把 Squirrel 加为开发依赖:gleam add squirrel --dev
  2. 在 src/ 下任意目录建一个 sql 目录,放入 *.sql 文件,然后执行:
gleam run -m squirrel

运行后,src/$PATH/sql 目录旁边会生成一个 sql.gleam 模块,里面包含三个核心产物:

产物 作用
生成的查询函数 每条 SQL 对应一个同名的公开函数
*Row 类型 描述每一行查询结果长什么样
Decoder(解码器) 把 Postgres 返回值转换成 Gleam 值

下面用项目自带的经典例子拆解这三部分。假设你写了这样的查询文件 find_squirrel.sql:

select name, owned_acorns
from squirrel
where name = $1

一、拆解生成的函数:一条标准的 pog 流水线

生成出来的函数大致长这样:

pub fn find_squirrel(
  connection: pog.Connection,
  name: String,
) -> Result(pog.Returned(FindSquirrelRow), pog.QueryError) {
  let decoder = {
    use name <- decode.field(0, decode.string)
    use owned_acorns <- decode.field(1, decode.int)
    decode.success(FindSquirrelRow(name:, owned_acorns:))
  }

  "
  select name, owned_acorns
  from squirrel
  where name = $1
  "
  |> pog.query
  |> pog.parameter(pog.text(name))
  |> pog.returning(decoder)
  |> pog.execute(connection)
}

把它切成四段看:

1. 函数签名

  • 第一个参数 connection: pog.Connection 是数据库连接,Squirrel 会固定命名为 connection。如果你的 SQL 参数恰好也叫 connection,它会自动重命名为 connection_1 来避免遮蔽(见 renames_arguments_to_avoid_shadowing_connection.accepted)。
  • 参数命名很聪明:Squirrel 会分析 SQL 结构,尽量用有意义的名字。比如 where squirrel_id = $1 会生成参数 squirrel_id: Int;推断不出来时才退回 arg_1、arg_2 这样的通用名(见 query_with_many_arguments_returning_nil.accepted)。
  • 返回值 Result(pog.Returned(YourRow), pog.QueryError):Ok 分支里包着 pog.Returned,你可以从里面拿到行数和执行出的每一行 YourRow。

2. 参数编码:pog.parameter(...)

SQL 里的 $1、$2 占位符,会一一对应一个 pog.parameter(...) 调用。pog.text(name) 表示"把 name 编码为 Postgres 的文本"。数组参数则生成为 pog.array(fn(value) { pog.text(value) }, arg_2) 的形式——外层编码数组,内层编码每个元素。

3. 结果解码:pog.returning(decoder)

这就是下面要讲的 Decoder 登场的位置。

4. 执行:pog.execute(connection)

整条流水线的最后一步,真正执行查询。

💡 生成的代码依赖 pog 包运行,记得在项目里加上 pog 依赖。

二、Decoder 完全解析:从数据库到 Gleam 值

Decoder 使用 Gleam 的 gleam/dynamic/decode 构建,结构固定为:

let decoder = {
  use 列名 <- decode.field(索引, 类型解码器)
  decode.success(YourRow(列名:))
}

逐行理解:

  • decode.field(0, decode.string):从结果行的第 0 列(按 SELECT 列表顺序、从 0 开始计数)取一个字符串。索引 1 就是第二列,以此类推。
  • use x <- ...:把解码出的值绑定到变量 x,解码失败则整个 decoder 失败。
  • decode.success(YourRow(...)):全部列解完后,构造 Row 类型作为最终结果。

不同 Postgres 类型对应的解码器速查(编码方向同理):

Postgres 类型 生成的解码器 Gleam 类型
int2/int4/int8 decode.int Int
float4/float8/numeric decode.float Float
text/varchar/citext decode.string String
bool decode.bool Bool
date/time/timestamp pog.calendar_date_decoder() 等 calendar.Date 等
uuid 复用的 uuid_decoder() 辅助函数 uuid.Uuid
<类型>[] decode.list(元素解码器) List(<类型>)
用户自定义枚举 专用 <枚举名>_decoder() 自定义类型

几个值得记住的细节:

三、Enum 专属 Decoder:case 分支逐个匹配

当查询涉及数据库枚举类型时,Squirrel 会生成"类型 + 解码器"两件套,例如:

pub type SquirrelColour {
  LightBrown
  Grey
  Red
}

fn squirrel_colour_decoder() -> decode.Decoder(SquirrelColour) {
  use squirrel_colour <- decode.then(decode.string)
  case squirrel_colour {
    "light brown" -> decode.success(LightBrown)
    "grey" -> decode.success(Grey)
    "red" -> decode.success(Red)
    _ -> decode.failure(LightBrown, "SquirrelColour")
  }
}

逻辑很直白:先把枚举值解成字符串,再用 case 逐字面值匹配到对应的变体;匹配不上时 decode.failure(...) 给出第一个变体作为"期望值"和类型名,方便报错定位。完整的真实样例见 enum_decoding.accepted。

⚠️ 枚举名和变体会被转成 PascalCase。如果转换后仍是非法 Gleam 标识符(比如以数字开头),Squirrel 会直接报错提示你改名,而不是偷偷帮你改。

四、Row 类型:每行结果的数据契约

每个有返回列的查询都会生成一个公开类型,命名规则为查询名(或文件名)+ Row,字段名就是 SELECT 列表里的列名,顺序与 SELECT 一一对应:

pub type QueryRow {
  QueryRow(user_id: Int, roles: Option(String))
}

它回答了一个关键问题:这个查询的每一行结果在 Gleam 里长什么样? 拿到 pog.Returned(row_count, rows) 后,rows 就是一个 List(QueryRow),可以直接模式匹配、按字段访问。

两个特殊情况:

五、生成的文件里还有什么

  • 模块和每个函数/类型上方都有 🐿️ This ... was generated automatically 的文档注释,表明是自动生成的,请勿手改。
  • 查询按字母序排列;枚举/辅助函数统一放在模块末尾的"第二区",与查询代码用空行分隔。
  • 你的 SQL 文件头注释会被保留,成为生成函数的文档注释(见 query_with_comment.accepted)。

六、CI 里防止忘记重新生成

改过 .sql 后记得跑 gleam run -m squirrel。为了在流水线里兜底,还有一个校验命令:

gleam run -m squirrel check

它只验证生成代码是否与 SQL 查询保持一致,不通过则报错——非常适合放进 CI。

小结:生成代码的阅读路线图 🐿️

  1. 先看函数签名——参数怎么命名、返回什么 Row;
  2. 再看 decoder——每一列用什么类型解码、哪些列是 Option;
  3. 最后看流水线——pog.parameter 对应 $N,pog.execute 收尾。

更多生成样例都保存在 test/birdie_snapshots/ 目录下,测试逻辑在 test/squirrel_test.gleam;生成器的核心实现在 src/squirrel.gleam,类型推断细节在 src/squirrel/internal/query.gleam。照着这些真实样例读,很快你就能闭着眼睛看懂 Squirrel 生成的每一行代码。

登录后查看全文
squirrel