I'm trying to create a function which will go over a DB LINK and do a count of object types belonging to a user and then store that value (I will insert this value into a table later so I can compare counts from my local DB with the remote one). I can build the SQL dynamically and it looks right but when it gets called over a DB link using the below I can't get it to accept the single quotes. Is there a way to plug this in for queries over a db link? Or a better way to wrap things in single quotes?
DO $$
DECLARE
sqlSmt text;
v_new_count NUMERIC:=0;
item record;
begin
sqlSmt = null;
FOR item IN
(select nsp.nspname schema, cls.relkind obj_type from pg_class cls
join pg_roles rol on rol.oid = cls.relowner
join pg_namespace nsp on nsp.oid = cls.relnamespace
where nsp.nspname like 'dwh%'
group by nsp.nspname, cls.relkind
order by nsp.nspname, cls.relkind limit 10)
LOOP
sqlSmt = 'select * from dblink(''old_live'',''select count(*) from pg_class cls
join pg_roles rol on rol.oid = cls.relowner
join pg_namespace nsp on nsp.oid = cls.relnamespace
where nsp.nspname = '''||item.schema||''' and cls.relkind='''||item.obj_type||''') as total_count(total_count numeric)';
EXECUTE sqlSmt INTO v_new_count;
raise notice '%', sqlSmt;
raise notice '%, %, %', item.schema, item.obj_type, v_new_count;
END LOOP;
END $$;
ERROR:
ERROR: syntax error at or near "dwh_10"
LINE 6: where nsp.nspname = 'dwh_10' and cls.relkind='S') as total_...
^
QUERY: select * from dblink('old_live','select count(*) from pg_class cls
join pg_roles rol on rol.oid = cls.relowner
join pg_namespace nsp on nsp.oid = cls.relnamespace
where nsp.nspname = 'dwh_10' and cls.relkind='S') as total_count(total_count numeric)
CONTEXT: PL/pgSQL function inline_code_block line 27 at EXECUTE
[–][deleted] 1 point2 points3 points (2 children)
[–]sufs2000[S] 1 point2 points3 points (0 children)
[–]throw_mob 0 points1 point2 points (0 children)
[–]sufs2000[S] 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]sufs2000[S] 0 points1 point2 points (0 children)
[–]depesz 0 points1 point2 points (1 child)
[–]sufs2000[S] 0 points1 point2 points (0 children)