Kannan Goundan
Kannan Goundan

Reputation: 5222

Postgres: auto-populating an `INSERT` field based on session variable

I have a web app backed by Postgres.

I occasionally have bugs where I forget to add user_id = ? to the WHERE clause of an SQL request. To protect against this problem in a general way, I'm looking into Postgres row-level security (article):

This allows me to completely ignore user_id when writing SELECT and UPDATE requests.

My remaining problem is INSERTs. Is there a way to avoid having to provide user_id on INSERTs?

Upvotes: 3

Views: 264

Answers (1)

Edouard
Edouard

Reputation: 7065

Just having a look at the manual :

Existing table rows are checked against the expression specified in USING, while new rows that would be created via INSERT or UPDATE are checked against the expression specified in WITH CHECK

it seems that you just have to add a WITH CHECK clause to your policy in addition of the USING clause, and which will apply to the INSERT and UPDATE statements.

Upvotes: 1

Related Questions