diff --git a/db/migrate/20250630040849_add_index_post_locale_post_id.rb b/db/migrate/20250630040849_add_index_post_locale_post_id.rb deleted file mode 100644 index becff14..0000000 --- a/db/migrate/20250630040849_add_index_post_locale_post_id.rb +++ /dev/null @@ -1,21 +0,0 @@ -# frozen_string_literal: true - -class AddIndexPostLocalePostId < ActiveRecord::Migration[7.2] - disable_ddl_transaction! - - def up - # clean up invalid index if index creation timeout - execute <<~SQL - DROP INDEX IF EXISTS index_discourse_translator_post_locales_on_post_id - SQL - - execute <<~SQL - CREATE UNIQUE INDEX CONCURRENTLY index_discourse_translator_post_locales_on_post_id - ON discourse_translator_post_locales (post_id) - SQL - end - - def down - raise ActiveRecord::IrreversibleMigration - end -end diff --git a/db/migrate/20250701042909_clear_dupes_add_index_to_post_locale.rb b/db/migrate/20250701042909_clear_dupes_add_index_to_post_locale.rb new file mode 100644 index 0000000..6f7beb1 --- /dev/null +++ b/db/migrate/20250701042909_clear_dupes_add_index_to_post_locale.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +class ClearDupesAddIndexToPostLocale < ActiveRecord::Migration[7.2] + disable_ddl_transaction! + + def up + execute <<~SQL + DELETE FROM discourse_translator_post_locales + WHERE id IN ( + SELECT id + FROM ( + SELECT id, + ROW_NUMBER() OVER ( + PARTITION BY post_id + ORDER BY created_at DESC, id DESC + ) AS rnum + FROM discourse_translator_post_locales + ) t + WHERE t.rnum > 1 + ) + SQL + + execute <<~SQL + DROP INDEX IF EXISTS index_discourse_translator_post_locales_on_post_id + SQL + + execute <<~SQL + CREATE UNIQUE INDEX CONCURRENTLY index_discourse_translator_post_locales_on_post_id + ON discourse_translator_post_locales (post_id) + SQL + end + + def down + raise ActiveRecord::IrreversibleMigration + end +end