DO $$
	DECLARE row record; str text;
	BEGIN
		FOR row IN
			SELECT *
			FROM (
				SELECT t.schemaname sch, t.tablename tab, c.column_name col, pg_get_serial_sequence( quote_ident(c.table_schema)||'.'||quote_ident(c.table_name), c.column_name ) seq, t.tableowner own, c.column_default def
				FROM pg_tables t
				JOIN information_schema.columns c ON c.column_default LIKE '%nextval%' AND c.table_schema = t.schemaname AND c.table_name = t.tablename
			) sub
			WHERE def NOT LIKE 'nextval('''||replace(quote_ident(sch)||'.', 'public.', '')||quote_ident(tab||'_'||col||'_seq')||'''::regclass)'
			ORDER BY sch, tab
		LOOP
			str := quote_ident(row.sch)||'.'||quote_ident(row.tab||'_'||row.col||'_seq');
			IF NOT row.seq = str THEN
				RAISE NOTICE 'CREATE SEQUENCE: %', str;
				EXECUTE 'CREATE SEQUENCE '||str||';';
				EXECUTE 'SELECT setval( '''||str||''', last_value ) FROM '||row.seq||';';
				EXECUTE 'ALTER SEQUENCE '||str||' OWNER TO '||quote_ident(row.own)||';';
			END IF;
			IF NOT row.def = 'nextval('''||str||'''::regclass)' THEN
				RAISE NOTICE 'SET DEFAULT: %.%.%', row.sch, row.tab, row.col;
				EXECUTE 'ALTER TABLE '||quote_ident(row.sch)||'.'||quote_ident(row.tab)||' ALTER COLUMN '||quote_ident(row.col)||' SET DEFAULT nextval('''||str||'''::regclass)';
			END IF;
			IF NOT row.seq = str THEN
				EXECUTE 'DROP SEQUENCE '||row.seq||';';
				EXECUTE 'ALTER SEQUENCE '||str||' OWNED BY '||quote_ident(row.sch)||'.'||quote_ident(row.tab)||'.'||quote_ident(row.col)||';';
			END IF;
		END LOOP;
	END
$$;