patternsqlMinor
Set a default value for a jsonb property in PostgreSQL
Viewed 0 times
postgresqlvaluedefaultpropertyforjsonbset
Problem
Let's say that I have a
In some cases I also need to store the name of a picture that's uploaded to the server by the user in the JSON. Obviously I don't want clashes on the filenames so I wonder if it's possible to use
Is it possible or should I get the uuid in the application before inserting the data in the database?
Thanks beforehand.
jsonb column with documents like:{
"lead": "The lead",
"video": "An URL to the video"
}In some cases I also need to store the name of a picture that's uploaded to the server by the user in the JSON. Obviously I don't want clashes on the filenames so I wonder if it's possible to use
uuid_generate_v4() as default value:insert into document (title, content) values (
"The title of the document",
'{
"lead": "The lead",
"video": "An URL to the video",
"picture": ":?" -- Here I need the value returned by uuid_generate_v4()
}'
);Is it possible or should I get the uuid in the application before inserting the data in the database?
Thanks beforehand.
Solution
You can resort to
row_to_json for things like this.insert into document (title, content)
select 'The title of the document', row_to_json(n)
from (
select 'The lead' as lead,
'An URL to the video' as video,
uuid_generate_v4() as picture
) nCode Snippets
insert into document (title, content)
select 'The title of the document', row_to_json(n)
from (
select 'The lead' as lead,
'An URL to the video' as video,
uuid_generate_v4() as picture
) nContext
StackExchange Database Administrators Q#135355, answer score: 2
Revisions (0)
No revisions yet.