I have sql query part [code] but get error [code] I see redundant brackets. How to…
- User
I have sql query part
tbl_name RECORD; FOR tbl_name IN (SELECT table_name FROM information_schema.tables WHERE table_catalog = db_name and table_schema = current_schema_name) LOOP -- and table_type = 'BASE TABLE' | and table_type = 'VIEW' EXECUTE format('GRANT SELECT ON TABLE %I.%I TO %I;', current_schema_name, tbl_name, role_name); RAISE NOTICE 'Granted SELECT ON TABLE `%.%` to role `%`', current_schema_name, tbl_name, role_name; END LOOP;but get errorSQL Error [42P01]: ERROR: relation "access.(pbi_rls)" does not exist Where: SQL statement "GRANT SELECT ON TABLE access."(pbi_rls)" TO role_am_db_reader;"I see redundant brackets. How to remove them? Assistant
The error you're encountering is due to the way PostgreSQL is handling the
tbl_namevariable in yourEXECUTE formatstatement. When you use a record variable directly in the format string, PostgreSQL is treating the entire record as a string, including the parentheses.To fix this issue, you need to access the
table_namecolumn from thetbl_namerecord:DO $$ DECLARE tbl_name RECORD; db_name TEXT := 'your_database_name'; -- Replace with your database name current_schema_name TEXT := 'access'; -- Replace with your schema name role_name TEXT := 'role_am_db_reader'; -- Replace with your role name BEGIN FOR tbl_name IN (SELECT table_name FROM information_schema.tables WHERE table_catalog = db_name AND table_schema = current_schema_name) LOOP -- and table_type = 'BASE TABLE' | and table_type = 'VIEW' EXECUTE format('GRANT SELECT ON TABLE %I.%I TO %I;', current_schema_name, tbl_name.table_name, role_name); RAISE NOTICE 'Granted SELECT ON TABLE `%.%` to role `%`', current_schema_name, tbl_name.table_name, role_name; END LOOP; END $$;In this corrected version:
- The
tbl_namevariable is declared as aRECORDtype. - The
FORloop iterates over each row returned by theSELECTquery, assigning each row totbl_name. - Within the loop,
tbl_name.table_nameis used to access thetable_namecolumn from the current row. - The
EXECUTEstatement uses theformatfunction to safely construct theGRANT SELECTstatement, ensuring proper quoting of identifiers.
This should resolve the error and correctly grant
SELECTprivileges on the specified tables to therole_name. Make sure to replaceyour_database_name,access, androle_am_db_readerwith the actual values you intend to use.- The
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.