Setting default value for a json column

女生的网名这么多〃 提交于 2019-12-11 09:35:09

问题


I am looking at using Postgres's feature of setting json into a column via activerecords json handling features I am wondering how I would give it a default value upon table creation of something like {name: '', other_name: ''} and so on ...

I am also looking to understand how if I create a default json value for a column, like the example above and then later on I fill in the values, but then at a some other time reset it back to "default" how that would look.


回答1:


It's just like any other default, once you fix up the json syntax:

CREATE TABLE mytable (
    someothercol integer,
    somecol json DEFAULT '{"name": "", "other_name": ""}'
);

If you set to DEFAULT, it does just that:

regress=> INSERT INTO mytable(someothercol, somecol) VALUES (42, '{"nondefault": 1}');
INSERT 0 1
regress=> SELECT * FROM mytable;
 someothercol |      somecol      
--------------+-------------------
           42 | {"nondefault": 1}
(1 row)

regress=> UPDATE mytable SET somecol = DEFAULT WHERE someothercol = 42;
UPDATE 1
regress=> SELECT * FROM mytable;
 someothercol |            somecol             
--------------+--------------------------------
           42 | {"name": "", "other_name": ""}
(1 row)


来源:https://stackoverflow.com/questions/26518078/setting-default-value-for-a-json-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!