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

Postgrest Kotlin函数报错:execute与set引用未解析求助

解决Postgrest Kotlin客户端Delete/Update方法报错问题

问题1:删除分类时execute()未解析引用

你的删除代码写法不符合Supabase Postgrest Kotlin客户端的API规范,修复后的代码如下:

override suspend fun deleteCategory(id: Int) {
    postgrest["category"]
        .delete()
        .eq("id", id)
        .execute()
}

错误原因说明

  • 原代码中.delete { eq("id", id) }的lambda写法不正确,正确流程是先调用delete()获取查询构建器,再通过eq()添加过滤条件。
  • 无需手动指定Dispatchers.IO:Postgrest客户端的suspend方法已默认在后台线程执行,额外添加线程切换属于冗余操作。

问题2:更新分类时set()未解析引用

你的更新代码存在两个问题:API写法错误,且缺少分类ID过滤(会导致更新全表数据),修复后的代码如下:

override suspend fun updateCategory(id: Int, name: String) {
    postgrest["category"]
        .update {
            set("name", name)
        }
        .eq("id", id)
        .execute()
}

错误原因说明

  • 原代码中.update().set("name", name)的链式调用不符合API要求,set()方法需要放在update()的lambda参数中执行。
  • 必须添加eq("id", id)过滤条件:否则会更新表中所有分类的名称,造成数据混乱。

更优实现建议

1. 类型安全操作(推荐)

定义实体类,使用强类型API替代字符串表名和字段名,避免拼写错误:

import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.exceptions.PostgrestException

// 定义实体类
data class Category(
    val id: Int,
    val name: String,
    val items: List<Item>? = null
)

data class Item(
    val id: Int,
    val name: String,
    val price: Double,
    val categoryId: Int,
    val organizationId: Int
)

// 类型安全的删除方法
override suspend fun deleteCategory(id: Int) {
    try {
        postgrest.from<Category>()
            .delete()
            .eq(Category::id, id)
            .execute()
    } catch (e: PostgrestException) {
        // 处理数据库/网络异常,比如日志记录、抛出业务异常
        e.printStackTrace()
    }
}

// 类型安全的更新方法
override suspend fun updateCategory(id: Int, name: String) {
    try {
        postgrest.from<Category>()
            .update {
                set(Category::name, name)
            }
            .eq(Category::id, id)
            .execute()
    } catch (e: PostgrestException) {
        e.printStackTrace()
    }
}

2. 异常处理

添加try-catch捕获PostgrestException,处理网络请求失败、数据库约束违规等异常场景,保证程序稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:54:55