如何使用json插入非空列的表?
我试图用多个非空的默认列插入到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)
餐桌被定义为:
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中未提及的列创buildNULL值,这会导致插入NULL,从而导致此错误。 一个简单的插入将工作,但这是一个dynamic表。
使用默认值简单的情况下:
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)