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

Postgraphile无法查询SQL函数:get_eligible_shifts不在Query类型中

问题:SQL函数get_eligible_shifts无法被Postgraphile查询

问题描述

存在SQL函数get_eligible_shifts,无法通过Postgraphile执行查询,报错提示:

Cannot query field "get_eligible_shifts" on type "Query".

同时该函数未在PostGraphiQL界面中显示。

Postgraphile 查询语句

{
  get_eligible_shifts(
    args: {workerId: 1}
  ) {
    id
    start
    end_time
    profession
    worker_name
    facility_id
    facility_name
    worker_document_id
    facility_requirement_id
  }
}

报错信息

{
  "errors": [
    {
      "message": "Cannot query field \"get_eligible_shifts\" on type \"Query\".",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ]
    }
  ]
}

可能的原因及解决方法

  • 权限配置缺失:Postgraphile使用的数据库用户对get_eligible_shifts函数没有EXECUTE权限,或对函数所在schema没有USAGE权限。执行以下SQL授权:

    GRANT EXECUTE ON FUNCTION get_eligible_shifts(workerId INT) TO postgraphile_user;
    GRANT USAGE ON SCHEMA 你的函数所属schema TO postgraphile_user;
    
  • 返回类型不兼容:Postgraphile无法识别函数的返回类型。如果函数返回多行记录,必须定义为TABLE(...)或SETOF 自定义类型,不能使用匿名行类型。示例写法:

    CREATE FUNCTION get_eligible_shifts(workerId INT)
    RETURNS TABLE(
      id INT,
      start TIMESTAMP,
      end_time TIMESTAMP,
      profession VARCHAR,
      worker_name VARCHAR
      -- 其他字段按需定义
    ) AS $$
    -- 函数逻辑代码
    $$ LANGUAGE sql STABLE;
    
  • 命名规则不匹配:Postgraphile默认会将SQL下划线命名转换为驼峰式,尝试用getEligibleShifts作为字段名查询,同时字段名也要同步转换:

    {
      getEligibleShifts(workerId: 1) {
        id
        start
        endTime
        profession
        workerName
        facilityId
        facilityName
        workerDocumentId
        facilityRequirementId
      }
    }
    
  • schema未被扫描:如果启动Postgraphile时指定了--schema参数,需确保函数所在的schema被包含在内。示例启动命令:

    postgraphile --schema public,你的函数所属schema
    
  • 函数稳定性标记问题:Postgraphile默认只暴露IMMUTABLE或STABLE类型的函数。如果你的函数是VOLATILE类型,需要在启动时添加--enable-unsafe-mutations参数,或修改函数为STABLE(符合业务逻辑前提下)。

  • 缓存未更新:修改函数定义后,Postgraphile可能缓存了旧的schema。重启Postgraphile服务,若使用了--cache参数则需清除缓存文件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:35:33