如何在 PostgreSQL 触发器中访问 Hasura session_variables

How to access Hasura session_variables in PostgreSQL triggers

我想限制个人用户(business)向 PostgreSQL table department 中的插入触发功能。每个 business 应该能够创建 最多 5 departments。我也在尝试访问 Hasura session_variables,其中包含用于识别 business 的标识符 x-hasura-business-id

console 显示关于 不存在的 postgres 函数 to 的错误,我不认为我正在使用。

我要创建的 SQL 函数的代码是

--- Create function to check business's department count
CREATE FUNCTION check_dpt_quota()
RETURNS trigger AS $$
    DECLARE department_count INTEGER;
    DECLARE session_variables JSON;
    
    BEGIN
        session_variables := current_setting('hasura.user', 't');
        
        SELECT count(*) INTO department_count FROM "public"."department"
            WHERE business_id = (session_variables ->> 'x-hasura-business-id')::uuid;
        
        IF department_count > 4 THEN
            RAISE EXCEPTION 'Error: Department Quota Exceeded';
        END IF;
        
        RETURN NEW;
    END;
$$ LANGUAGE plpgsql;

--- Create trigger to run function before INSERT
CREATE TRIGGER insert_department BEFORE INSERT ON "public"."department" FOR EACH ROW EXECUTE PROCEDURE check_dpt_quota();

我在通过 Hasura 控制台 创建 SQL 函数时遇到的错误是

[
    {
        "definition": {
            "schema": "public",
            "name": "to"
        },
        "reason": "in function \"to\": no such function exists in postgres : \"to\"",
        "type": "function"
    }
]

我不知道自己哪里做错了,而且错误消息的描述性不足以让我理解。有人可以帮我处理这段代码吗?

终于想通了!

我犯了两个错误。

  • 我检查了 Track this 选项,而 运行 SQL 查询

    触发函数不可跟踪

  • 在将值 current_setting('hasura.user', 't') 赋给 session_variables[= 之前​​,我没有将值 current_setting('hasura.user', 't') 转换为类型 json 14=]

代码的更正版本将是(只是修改的部分)

...
BEGIN
    session_variables := current_setting('hasura.user', 't')::JSON;
...