PostgreSQL anonymous functions

PostgreSQL provides the DO statement, which can be used to execute anonymous code blocks. The DO statement reduces the need to create shell scripts for administration purposes. However, one should note that all PostgreSQL functions are transactional, so if one would like to create indexes, for example, shell scripting is a better alternative. In the car portal schema, let's assume that we would like to have another user who can perform only select statements. One can create a role as follows:

 CREATE user select_only;

Now we need to grant select permission on each table for the newly created role. This can be done using dynamic SQL as follows:

DO $$
DECLARE r record;
BEGIN
FOR r IN SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema = 'car_portal_app' LOOP
EXECUTE 'GRANT SELECT ON ' || quote_ident(r.table_schema) || '.'|| quote_ident(r.table_name) || ' TO select_only';
END LOOP;
END$$;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset