table_names=User.exec_sql("select table_name from information_schema.tables where table_schema = 'public'").mapdo|row|
row['table_name']
end
begin
# Move all tables to the backup schema:
User.exec_sql("DROP SCHEMA IF EXISTS #{backup_schema} CASCADE")
User.exec_sql("CREATE SCHEMA #{backup_schema}")
table_names.eachdo|table_name|
User.exec_sql("ALTER TABLE public.#{table_name} SET SCHEMA #{backup_schema}")
end
# Create a new empty db
Rake::Task["db:migrate"].invoke
# Fetch index definitions from the new db
index_definitions={}
table_names.eachdo|table_name|
index_definitions[table_name]=User.exec_sql("SELECT indexdef FROM pg_indexes WHERE tablename = '#{table_name}' and schemaname = 'public';").map{|x|x['indexdef']}
end
# Drop the new tables
table_names.eachdo|table_name|
User.exec_sql("DROP TABLE public.#{table_name}")
end
# Move the old tables back to the public schema
table_names.eachdo|table_name|
User.exec_sql("ALTER TABLE #{backup_schema}.#{table_name} SET SCHEMA public")
end
# Drop their indexes
index_names=User.exec_sql("SELECT indexname FROM pg_indexes WHERE schemaname = 'public' AND tablename IN ('#{table_names.join("', '")}')").map{|x|x['indexname']}