AI Hints
Home›PostgreSQL Tutorial›Roles, Privileges and Row-Level Security
PostgreSQL · Lesson 81 of 120

Practice: Shop Staff Access

Tenants and settings.

⏱ 2 min read▶ Video at 1:12:51🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Apps usually connect as one database user, not one per shop. So instead of role names, the app sets a value for each request, like the current shop, and the policy reads it.

  • One app user
  • Set shop per request
  • Policy reads it

Policies with a setting

The policy compares shop with current setting app dot shop. The app role can read and insert. Set local app dot shop to toronto. Run it. Toronto sees its own orders, and can't insert a Dublin order.

query.sqlsql
CREATE TABLE shop_orders (id int, shop text, total numeric);
INSERT INTO shop_orders VALUES (1, 'toronto', 40), (2, 'dublin', 25);
ALTER TABLE shop_orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY by_shop ON shop_orders
  USING (shop = current_setting('app.shop'))
  WITH CHECK (shop = current_setting('app.shop'));
CREATE ROLE app; GRANT SELECT, INSERT ON shop_orders TO app;

BEGIN; SET ROLE app; SET LOCAL app.shop = 'toronto';
SELECT * FROM shop_orders;
INSERT INTO shop_orders VALUES (3, 'dublin', 99);
Output
CREATE TABLE
INSERT 0 2
ALTER TABLE
CREATE POLICY
CREATE ROLE
GRANT
BEGIN
SET
SET
 id |  shop   | total
----+---------+-------
  1 | toronto |    40
(1 row)

ERROR:  new row violates row-level security policy for table "shop_orders"

Multi-tenant pattern

Every table has a tenant column. Every request sets the tenant inside a transaction. Policies filter by it. And with check stops writing into another tenant's data. Mistakes in app code can't leak data.

keyvalue
tenant columnon every table
SET LOCALper request
USINGfilter reads
WITH CHECKguard writes

Summary

Settings plus row level security give safe multi tenant apps from one database user. Next, Postgres from Python.

Key takeaways
  • current_setting
  • SET LOCAL
  • WITH CHECK
Next up: psycopg Basics — Postgres from Python