Skip to content

Commit 1dfdd48

Browse files
authored
Merge pull request #812 from trycompai/claudio/comp-186-add-readonly-role
[dev] [claudfuen] claudio/comp-186-add-readonly-role
2 parents 9210311 + b7ba0f9 commit 1dfdd48

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

  • packages/db/prisma/migrations/20250606154623_add_readonly_role
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
-- This script creates a 'readonly' role with SELECT permissions on all tables
2+
-- in all non-system schemas, and ensures it gets access to future tables.
3+
4+
-- Create the new role
5+
DROP ROLE IF EXISTS readonly;
6+
CREATE ROLE readonly;
7+
8+
-- Grant USAGE on all existing schemas to the 'readonly' role
9+
DO
10+
$$
11+
DECLARE
12+
v_schema_name TEXT;
13+
BEGIN
14+
FOR v_schema_name IN
15+
SELECT schema_name
16+
FROM information_schema.schemata
17+
WHERE schema_name NOT IN ('pg_catalog', 'information_schema')
18+
LOOP
19+
EXECUTE format('GRANT USAGE ON SCHEMA %I TO readonly', v_schema_name);
20+
END LOOP;
21+
END
22+
$$;
23+
24+
-- Grant SELECT on all existing tables in all non-system schemas to the 'readonly' role
25+
DO
26+
$$
27+
DECLARE
28+
schema_name TEXT;
29+
table_name TEXT;
30+
BEGIN
31+
FOR schema_name, table_name IN
32+
SELECT t.table_schema, t.table_name
33+
FROM information_schema.tables t
34+
WHERE t.table_type = 'BASE TABLE'
35+
AND t.table_schema NOT IN ('pg_catalog', 'information_schema')
36+
LOOP
37+
EXECUTE format('GRANT SELECT ON TABLE %I.%I TO readonly', schema_name, table_name);
38+
END LOOP;
39+
END
40+
$$;
41+
42+
-- Grant SELECT on all future tables in all non-system schemas
43+
DO
44+
$$
45+
DECLARE
46+
v_schema_name TEXT;
47+
BEGIN
48+
FOR v_schema_name IN
49+
SELECT schema_name
50+
FROM information_schema.schemata
51+
WHERE schema_name NOT IN ('pg_catalog', 'information_schema')
52+
LOOP
53+
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT SELECT ON TABLES TO readonly',
54+
v_schema_name);
55+
END LOOP;
56+
END
57+
$$;

0 commit comments

Comments
 (0)