You're absolutely right — the error:
ERROR: relation "access.(pbi_rls)" does not exist
is caused by incorrect quoting or formatting of the table name, likely due to how tbl_name is being used in the EXECUTE format(...) call.
The issue comes from this line:
EXECUTE format('GRANT SELECT ON TABLE %I.%I TO %I;', current_schema_name, tbl_name, role_name);
🔍 Root Cause
✅ Fix: Access the correct field from the RECORD
Since your loop is:
FOR tbl_name IN (SELECT table_name FROM ...)
you should reference the actual column inside the loop using:
tbl_name.table_name
Here’s the corrected version:
DO $$
DECLARE
db_name TEXT := current_database();
current_schema_name TEXT := 'access';
role_name TEXT := 'role_am_db_reader';
tbl_name RECORD;
BEGIN
FOR tbl_name IN
SELECT table_name
FROM information_schema.tables
WHERE table_catalog = db_name
AND table_schema = current_schema_name
AND table_type = 'BASE TABLE' -- optional filter
LOOP
EXECUTE format('GRANT SELECT ON TABLE %I.%I TO %I;',
current_schema_name,
tbl_name.table_name, -- <-- here we use the field from the record
role_name);
RAISE NOTICE 'Granted SELECT ON TABLE %.% to role %',
current_schema_name,
tbl_name.table_name,
role_name;
END LOOP;
END $$;
🧠 Summary
| Problem | Fix |
|---|
Using tbl_name directly as %I | Use tbl_name.table_name instead |
Incorrect formatting causing "(...)" | |
Looping over RECORD without accessing the field | |
✅ Bonus Tip – Avoid RECORD if possible
If you only need one field (table_name), consider using a scalar loop:
DO $$
DECLARE
current_table_name TEXT;
current_schema_name TEXT := 'access';
role_name TEXT := 'role_am_db_reader';
BEGIN
FOR current_table_name IN
SELECT table_name
FROM information_schema.tables
WHERE table_schema = current_schema_name
AND table_catalog = current_database()
AND table_type = 'BASE TABLE'
LOOP
EXECUTE format('GRANT SELECT ON TABLE %I.%I TO %I;',
current_schema_name,
current_table_name,
role_name);
RAISE NOTICE 'Granted SELECT ON TABLE %.% to role %',
current_schema_name,
current_table_name,
role_name;
END LOOP;
END $$;
This avoids ambiguity and makes the code cleaner.