【问题标题】:Postgres stored procedure errs while parsing JSONB objectPostgres 存储过程在解析 JSONB 对象时出错
【发布时间】:2020-09-06 04:19:45
【问题描述】:

我正在尝试在 Postgres 中运行以下存储过程:

...
FOR showing IN SELECT * FROM json_to_recordset(to_json(event_times)) AS show(id INTEGER, 
    times JSONB, startDate DATE, endDate DATE) LOOP
  IF showing.id > 0 THEN
    UPDATE
      event_shows
    SET
      start_date = showing.startDate, end_date = showing.endDate, times = showing.times
    WHERE
      event_id = eid AND
      id = showing.id;
  ELSE
    INSERT INTO
      event_shows (event_id, start_date, end_date, times)
    VALUES
      (eid, showing.startDate, showing.endDate, showing.times);
  END IF;
END LOOP;

event_times 的值为[{"times":[{"end":"13:00","start":"12:00"}],"endDate":"2020-05-19T19:45:47.121Z","startDate":"2020-05-19T19:45:47.121Z"},{"startDate":"2020-05-20T19:55:15.000Z","endDate":"2020-05-20T19:55:15.000Z","times":[{"start":"12:00","end":"13:00"}]}]。

当我运行代码时,它会出错:

"SQL statement \"INSERT INTO\n          event_shows (event_id, start_date, end_date, times)\n        VALUES\n          (eid, showing.startDate, showing.endDate, showing.times)\"

消息是null value in column \"start_date\" violates not-null constraint。好像我的 JSONB 对象没有被正确解析。

我做错了什么?

表event_shows定义为:

CREATE TABLE event_shows (
  id SERIAL,
  event_id SERIAL NOT NULL REFERENCES event(id),
  start_date DATE NOT NULL,
  end_date DATE NOT NULL,
  times JSONB,
  PRIMARY KEY (id)
);

跑步:PostgreSQL 10.4 on x86_64-pc-linux-musl, compiled by gcc (Alpine 6.4.0) 6.4.0, 64-bit

【问题讨论】:

  • event_times 是什么类型?为什么你认为你需要打电话给to_json()呢?
  • 请始终公开您的 Postgres 版本。以及(最小)精确的CREATE TABLE event_shows ... 声明。还有“存储过程”是函数还是过程?典型的功能。始终发布完整的CREATE FUNCTION 声明以避免歧义(即使它不起作用)。
  • 如果/当我用showing.startDate 代替"2020-05-19T19:45:47.121Z" 进行调试时,INSERT 可以工作。因此,我相信在“解析”我的 event_times 时发生了一些奇怪的事情。

标签: postgresql plpgsql jsonb stored-functions


【解决方案1】:

基本上,Postgres 中的列名是敏感的,所以每当使用驼峰名称时,例如startDate,都应该用引号引起来。 Postgres 版本无关紧要。

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    相关资源
    最近更新 更多