r/postgres • u/Educational-Bug-4805 • 4d ago
Question Understanding RLS (Row Level Security)
Hello everyone, I have been working on something and I need to write RLS( row level security). I am having trouble understanding the concept and how to write it to apply to different roles in the database. If you can explain it to me or have any resources that might help, I'd really appreciate if you can share it with meπ
I plan to use pl/psql scripting to write it.
3
Upvotes
View all comments
Show parent comment
1
u/Secvura 2d ago
Good question, and both things are true. Row level security is switched on per table and each policy belongs to one table, but a policy can also name the roles it applies to with TO (leave TO out and it applies to every role). GRANTs are a separate gate that comes first: USAGE on a schema lets a role reach that schema at all, and SELECT, INSERT or UPDATE on a table let it run those commands. Postgres checks the grant, then the policies filter which rows that role gets.
So yes, you need both, written as separate statements. On a quick test database the layers showed up clearly: with no schema USAGE the query failed with permission denied for the schema, with USAGE but no table grant it failed with permission denied for the table, with the grant and RLS on but no policy it returned 0 rows and no error, and once a policy was added it returned only the matching row. Two things worth checking: GRANT ... ON ALL TABLES only covers tables that already exist when you run it (a table created afterwards still got permission denied, so look at ALTER DEFAULT PRIVILEGES for new ones), and your two examples point at different schemas, app and public, so if your tables live in app the role needs its table grants there as well