【问题标题】:Use now or current_timestamp inside a postgres function在 postgres 函数中使用 now 或 current_timestamp
【发布时间】:2020-04-05 02:06:34
【问题描述】:

尝试使用 || 更新表中的 JSONB 列运算符并使用 now 或 current_timestamp 插入当前时间,但不能。

我的 jsonb_column 结构是

{
  "status": "oldStatus",
  "statusUpdatedTimestamp": null //this field might be present or not, if it's present it has to be overwritten. if not, it has to be added
}
create or replace function update_jsonb() 
returns trigger language plpgsql 
as $function$ 
begin 
    if (TG_OP = 'UPDATE' and old.jsonb_column ->> 'status' <> new.jsonb_column ->> 'status') then 
        --need statusUpdatedTimestamp to have the current time
        new.jsonb_column = new.jsonb_column || '{"statusUpdatedTimestamp": ' now ' }';
    end if;

    return new;
end;
$function$ ;

我预期的 jsonb_column 输出是

{
  "status": "newStatus",
  "statusUpdatedTimestamp": '2019-12-11 10:10:35'
}

【问题讨论】:

    标签: json postgresql jsonb postgresql-9.6


    【解决方案1】:

    使用函数jsonb_build_object(),例如:

    select jsonb_build_object('statusUpdatedTimestamp', now()::text)
    
                         jsonb_build_object
    -------------------------------------------------------------
     {"statusUpdatedTimestamp": "2019-12-11 19:39:22.950725+01"}
    (1 row)
    

    select jsonb_build_object('statusUpdatedTimestamp', to_char(now(), 'YYYY-MM-DD HH24-MI-SS'))
    
                    jsonb_build_object
    ---------------------------------------------------
     {"statusUpdatedTimestamp": "2019-12-11 19:39:52"}
    (1 row)
    

    您的触发器函数的主体可能如下所示:

    if TG_OP = 'UPDATE' and old.jsonb_column ->> 'status' <> new.jsonb_column ->> 'status' then 
        new.jsonb_column = new.jsonb_column || jsonb_build_object('statusUpdatedTimestamp', to_char(now(), 'YYYY-MM-DD HH24-MI-SS'));
    end if;
    return new;
    

    【讨论】:

    • 能否请您帮忙说明一下功能说明?我是 postgres 的新手,很难将其适应函数
    猜你喜欢
    • 1970-01-01
    • 2011-02-28
    • 2020-03-08
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2011-02-13
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多