如何使用json插入非空列的表?

时间:2017-09-25 12:34:56

标签: json postgresql plpgsql postgresql-9.6 node-postgres

我正在尝试使用多个非空默认列插入表food,其命令如下:

  • food_insertone('{"id": 1, "taste": "sweet"}'::JSON)
  • food_insertone('{"id": 2}'::JSON)
  • food_insertone('{"id": 3, "taste": null}'::JSON)

结果应该是:

INSERTED 1, 'sweet'
INSERTED 2, ''
ERROR (null not allowed in taste)

food定义为:

CREATE TABLE "food" (
  "id"    INT,
  "taste" TEXT NOT NULL DEFAULT '',
  ...
);

CREATE OR REPLACE FUNCTION "food_insertone" (JSON)
RETURNS VOID AS $$
  INSERT INTO "food" SELECT * FROM json_populate_record(NULL::"food", $1);
$$ LANGUAGE SQL;

我试图插入:

SELECT food_insertone('{"id": 1}'::JSON);

但这不起作用并给我一个错误:

null value in column "taste" violates not-null constraint

我理解json_populate_record()为JSON中未提及的列创建NULL值,这会导致插入NULL,从而导致此错误。普通插入可以工作,但这是一个动态表。

1 个答案:

答案 0 :(得分:1)

使用默认值simple case:

t=# create table food(id int, t text not null default 'some');
CREATE TABLE
t=# insert into food(id) SELECT id FROM json_populate_record(NULL::"food", '{"id":0}');
INSERT 0 1
t=# select * from food ;
 id |  t
----+------
  0 | some
(1 row)

使用coalesce和另一个值:

t=# insert into food(id,t) 
SELECT id,coalesce(t,'some simple other value') 
FROM json_populate_record(NULL::"food", '{"id":0}');   

当然你可以用一些怪异的方法来获得实际的默认值:

t=# insert into food(id,t) SELECT id,coalesce(t,rtrim) FROM json_populate_record(NULL::"food", '{"id":0}') join (select rtrim(ltrim(split_part(column_default,'::',1),$$'$$),$$'$$) from information_schema.columns where table_name = 'food' and column_name = 't') dflt on true;
INSERT 0 1
t=# select * from food ;
 id |            t
----+-------------------------
  0 | some simple other value
  0 | some
(2 rows)