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

Gleam使用sqlight查询SQLite todos表出现解码错误求助

问题原因

错误提示明确说明解码器期望字典(Dict),但实际收到的是3元素元组,核心问题是解码器与sqlight查询返回的数据结构不匹配:

  • 当前解码器使用decode.field,这是为键值对(字典)结构设计的,通过字段名提取数据;
  • 但sqlight的query函数默认返回位置元组,即每行数据按SELECT语句的字段顺序以元组形式返回,而非键值对字典。
解决方案

修改解码器,改用基于索引的解码方式,匹配元组的位置结构:

pub type Todo {
  Todo(id: Int, title: String, completed: Int)
}

// 修正函数名,符合解码器语义
fn todo_decoder() -> decode.Decoder(Todo) {
  let decoder = {
    use id <- decode.index(0, decode.int)
    use title <- decode.index(1, decode.string)
    use completed <- decode.index(2, decode.int)
    decode.success(Todo(id: id, title: title, completed: completed))
  }
  decoder
}

// db_directory、open_db_conn函数保持不变

pub fn get_todos() -> Result(List(Todo), sqlight.Error) {
  let assert Ok(conn) = open_db_conn()
  // 传入修改后的解码器
  let todos = sqlight.query("SELECT * FROM todos", conn, [], todo_decoder())

  case todos {
    Ok(results) -> {
      echo "Retrieved todos successfully."
      Ok(results)
    }
    Error(error) -> {
      echo "Error retrieving todos: " <> error.message
      Error(error)
    }
  }
}

额外优化建议

  1. 显式指定SQL字段:建议将SQL语句改为SELECT id, title, completed FROM todos,避免表结构变化导致索引对应错误;
  2. 语义规范:保持函数命名准确,避免编码器/解码器的概念混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:57:28