Created
April 18, 2014 15:24
-
-
Save diegoponciano/11049777 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
do $$ | |
declare | |
seq_name text; | |
tbl information_schema.tables%rowtype; | |
tables CURSOR FOR SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename; | |
begin | |
FOR table_record IN tables LOOP | |
seq_name = table_record.tablename || '_id_seq'; | |
-- tests if a sequence with this name already exists | |
IF EXISTS (SELECT 0 FROM pg_class where relname = seq_name) | |
THEN | |
raise warning '% already exists. Skipped.', seq_name; | |
ELSE | |
-- tests if id column exists for current table | |
IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name=table_record.tablename and column_name='id') | |
THEN | |
EXECUTE 'create sequence ' || seq_name; | |
EXECUTE 'alter sequence ' || seq_name || ' owned by ' || table_record.tablename || '.id'; | |
EXECUTE 'alter table ' || table_record.tablename || ' alter id set default nextval(''' || seq_name || ''')'; | |
raise info '% successfully created!', seq_name; | |
END IF; | |
END IF; | |
END LOOP; | |
end; | |
$$language plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment