From 4a6459000f2c208bcd66f9158a8d13c1e707d490 Mon Sep 17 00:00:00 2001 From: Miha Mencin Date: Thu, 17 Jan 2019 17:54:15 +0100 Subject: [PATCH] SCI-2936 added migration --- ...55006_change_indices_from_int_to_bigint.rb | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 db/migrate/20190117155006_change_indices_from_int_to_bigint.rb diff --git a/db/migrate/20190117155006_change_indices_from_int_to_bigint.rb b/db/migrate/20190117155006_change_indices_from_int_to_bigint.rb new file mode 100644 index 000000000..d1646ff18 --- /dev/null +++ b/db/migrate/20190117155006_change_indices_from_int_to_bigint.rb @@ -0,0 +1,41 @@ +class ChangeIndicesFromIntToBigint < ActiveRecord::Migration[5.1] + def up + # find primary and foreign keys of type integer throughout the database + sql = <<-EOM + select tc.table_schema, tc.table_name, kc.column_name, ic.data_type + from information_schema.table_constraints tc + join information_schema.key_column_usage kc + on kc.table_name = tc.table_name and kc.table_schema = tc.table_schema and kc.constraint_name = tc.constraint_name + join information_schema.columns ic + on ic.table_schema = tc.table_schema and ic.table_name=tc.table_name and ic.column_name = kc.column_name + where (tc.constraint_type = 'PRIMARY KEY' OR tc.constraint_type = 'FOREIGN KEY') + and kc.ordinal_position is not null + and ic.data_type = 'integer' + order by tc.table_schema, + tc.table_name, + kc.position_in_unique_constraint; + EOM + + # get all user defined views + user_viewes = ActiveRecord::Base.connection.execute( + "select * from pg_views where schemaname = any (current_schemas(false))" + ) + + # drop all existing views + user_viewes.each do |user_view| + ActiveRecord::Base.connection.execute("drop view #{user_view['viewname']}") + end + + keys = ActiveRecord::Base.connection.execute(sql) + + # change all keys + keys.each do |key| + change_column key['table_name'], key['column_name'], :bigint + end + + # recreate user defined views + user_viewes.each do |user_view| + ActiveRecord::Base.connection.execute("create view #{user_view['viewname']} as #{user_view['definition']}") + end + end +end