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

如何在Supabase中检查指定列值行是否存在并解决OAuth场景异常

解决方案

问题根源

你遇到的核心问题是maybeSingle()在查询不到匹配行时会抛出错误,直接触发外层的catch块,导致后续的插入逻辑根本没机会执行——你以为的“预期错误”已经让代码跳转到异常处理分支,自然走不到插入步骤。

修复方案

方案1:捕获特定错误执行插入

把maybeSingle()换成single(),然后在catch里判断错误类型,确认是“无匹配行”的错误时再执行插入:

try {
  await Supabase.db
      .from('profiles')
      .select()
      .eq('email', user!.email.toString())
      .single();
  print('User exists in db');
} catch (e) {
  // 匹配Supabase无匹配行的错误码PGRST116
  if (e is PostgrestException && e.code == 'PGRST116') {
    await Supabase.db.from('profiles').insert({
      'uid': user.id,
      'email': user.email,
    });
  } else {
    print('Unexpected error: $e');
  }
}

方案2:统计匹配行数(更高效)

直接查询匹配的行数,不用返回整行数据,也不会触发异常:

final response = await Supabase.db
    .from('profiles')
    .select('count', const FetchOptions(count: CountOption.exact))
    .eq('email', user!.email.toString());

final count = int.parse(response.first['count'].toString());
if (count == 0) {
  await Supabase.db.from('profiles').insert({
    'uid': user.id,
    'email': user.email,
  });
} else {
  print('User exists in db');
}

关键注意点:行级安全配置

你的RLS规则只配置了读、删、更新权限,没有配置插入权限!这是很容易遗漏的点,必须给profiles表添加插入策略,比如允许用户插入自己的uid对应的行:

-- 如果uid是文本类型
CREATE POLICY "允许用户插入自己的 profile" ON profiles
FOR INSERT WITH CHECK (auth.uid()::text = uid);

-- 如果uid是UUID类型
CREATE POLICY "允许用户插入自己的 profile" ON profiles
FOR INSERT WITH CHECK (auth.uid() = uid);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:40:46