File tree Expand file tree Collapse file tree
packages/db/prisma/migrations/20250606154623_add_readonly_role Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ $$;
You can’t perform that action at this time.
0 commit comments