DO $$
	DECLARE row record;
	BEGIN
		FOR row IN
			SELECT c.table_schema sch, c.table_name tab, c.column_name col, t.tableowner own, regexp_replace( regexp_replace( regexp_replace( replace( c.column_default, '"', '' ), '^[^'']*''', '' ), '''.*', '' ), '.*[.]', '' ) seq
			FROM information_schema.columns c
			JOIN pg_tables t ON c.table_schema = t.schemaname AND c.table_name = t.tablename
			WHERE c.column_default LIKE '%nextval%' AND pg_get_serial_sequence( quote_ident(c.table_schema)||'.'||quote_ident(c.table_name), c.column_name ) IS NULL
			ORDER BY c.table_schema, c.table_name
		LOOP
			RAISE NOTICE '%(%) -> %.%.%', quote_ident(row.seq), row.own, row.sch, row.tab, row.col;
			EXECUTE 'ALTER SEQUENCE '||quote_ident(row.sch)||'.'||quote_ident(row.seq)||' OWNER TO '||quote_ident(row.own)||';';
			EXECUTE 'ALTER SEQUENCE '||quote_ident(row.sch)||'.'||quote_ident(row.seq)||' OWNED BY '||quote_ident(row.sch)||'.'||quote_ident(row.tab)||'.'||quote_ident(row.col)||';';
		END LOOP;
		FOR row IN
			SELECT c.table_schema sch, c.table_name tab, c.column_name col
			FROM information_schema.columns c
			WHERE c.column_default LIKE '%nextval%' AND pg_get_serial_sequence( quote_ident(c.table_schema)||'.'||quote_ident(c.table_name), c.column_name ) IS NULL
			ORDER BY c.table_schema, c.table_name
		LOOP
			RAISE NOTICE 'ERROR IN %.%.%', row.sch, row.tab, row.col;
		END LOOP;
	END
$$;