I am trying to insert into a table food with multiple not-null default columns, with commands like:
food_insertone('{"id": 1, "taste": "sweet"}'::JSON)food_insertone('{"id": 2}'::JSON)food_insertone('{"id": 3, "taste": null}'::JSON)
And the result should be like:
INSERTED 1, 'sweet'
INSERTED 2, ''
ERROR (null not allowed in taste)
The table food is defined as:
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;
And i am trying to insert as:
SELECT food_insertone('{"id": 1}'::JSON);
But this doesnt work and gives me an error:
null value in column "taste" violates not-null constraint
I understand that json_populate_record() creates NULL values for columns which are not mentioned in the JSON, which is causing NULL to be inserted, and thus this error. A plain insert would work, but this is a dynamic table.
INSERT INTO "food" (id) VALUES (1)for this particular case, but table has multiple such column.json_populate_record()with a row of default values of the table?