Ik kan me eerlijk gezegd niet herinneren wanneer ik voor het laatst echt een expliciete cursor nodig had om in plpgsql te loopen. De impliciete cursor van een FOR-lus is veel netter:
DO $$ DECLARE rec record; nbrow bigint; BEGIN FOR rec IN SELECT * FROM pg_tables WHERE tablename NOT LIKE 'pg\_%' ORDER BY tablename LOOP EXECUTE 'SELECT count(*) FROM ' || quote_ident(rec.schemaname) || '.' || quote_ident(rec.tablename) INTO nbrow; -- Do something with nbrow END LOOP; END $$;Neem de schemanaam op, zodat dit over alle schema's werkt, ook schema's buiten je search_path.
Daarnaast heb je echt quote_ident() nodig, of format() met %I, of een regclass-variabele, om je tegen SQL-injection te beschermen — een tabelnaam kan binnen dubbele aanhalingstekens vrijwel alles zijn. Zie:
- Table name as a PostgreSQL function parameter
Een klein detail: escape de underscore (_) in het LIKE-patroon zodat die als letterlijke underscore telt: tablename NOT LIKE 'pg\_%'.
Hoe ik het zou schrijven
DO $$ DECLARE tbl regclass; nbrow bigint; BEGIN FOR tbl IN SELECT c.oid FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname NOT LIKE 'pg\_%' -- system schema(s) AND n.nspname <> 'information_schema' -- information schema ORDER BY n.nspname, c.relname LOOP EXECUTE 'SELECT count(*) FROM ' || tbl INTO nbrow; -- raise notice '%: % rows', tbl, nbrow; END LOOP; END $$;Bevraag pg_catalog.pg_class in plaats van tablename, want dat geeft je de OID van de tabel.
Het object-identifier-type regclass houdt alles netjes: tabelnamen worden automatisch dubbel aangehaald en waar nodig schema-kwalificerend, wat SQL-injection tevens blokkeert.
Deze query sluit daarnaast temp-tabellen uit (het temp-schema heet intern pg_temp%).
Om tabellen uit slechts één schema op te nemen:
AND n.nspname = 'public' -- schema name here, case-sensitive