maintenance_cli.rb 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. # frozen_string_literal: true
  2. require 'tty-prompt'
  3. require_relative '../../config/boot'
  4. require_relative '../../config/environment'
  5. require_relative 'cli_helper'
  6. module Mastodon
  7. class MaintenanceCLI < Thor
  8. include CLIHelper
  9. def self.exit_on_failure?
  10. true
  11. end
  12. MIN_SUPPORTED_VERSION = 2019_10_01_213028 # rubocop:disable Style/NumericLiterals
  13. MAX_SUPPORTED_VERSION = 2022_11_04_133904 # rubocop:disable Style/NumericLiterals
  14. # Stubs to enjoy ActiveRecord queries while not depending on a particular
  15. # version of the code/database
  16. class Status < ApplicationRecord; end
  17. class StatusPin < ApplicationRecord; end
  18. class Poll < ApplicationRecord; end
  19. class Report < ApplicationRecord; end
  20. class Tombstone < ApplicationRecord; end
  21. class Favourite < ApplicationRecord; end
  22. class Follow < ApplicationRecord; end
  23. class FollowRequest < ApplicationRecord; end
  24. class Block < ApplicationRecord; end
  25. class Mute < ApplicationRecord; end
  26. class AccountIdentityProof < ApplicationRecord; end
  27. class AccountModerationNote < ApplicationRecord; end
  28. class AccountPin < ApplicationRecord; end
  29. class ListAccount < ApplicationRecord; end
  30. class PollVote < ApplicationRecord; end
  31. class Mention < ApplicationRecord; end
  32. class AccountDomainBlock < ApplicationRecord; end
  33. class AnnouncementReaction < ApplicationRecord; end
  34. class FeaturedTag < ApplicationRecord; end
  35. class CustomEmoji < ApplicationRecord; end
  36. class CustomEmojiCategory < ApplicationRecord; end
  37. class Bookmark < ApplicationRecord; end
  38. class WebauthnCredential < ApplicationRecord; end
  39. class FollowRecommendationSuppression < ApplicationRecord; end
  40. class CanonicalEmailBlock < ApplicationRecord; end
  41. class Appeal < ApplicationRecord; end
  42. class Webhook < ApplicationRecord; end
  43. class PreviewCard < ApplicationRecord
  44. self.inheritance_column = false
  45. end
  46. class MediaAttachment < ApplicationRecord
  47. self.inheritance_column = nil
  48. end
  49. class AccountStat < ApplicationRecord
  50. belongs_to :account, inverse_of: :account_stat
  51. end
  52. # Dummy class, to make migration possible across version changes
  53. class Account < ApplicationRecord
  54. has_one :user, inverse_of: :account
  55. has_one :account_stat, inverse_of: :account
  56. scope :local, -> { where(domain: nil) }
  57. def local?
  58. domain.nil?
  59. end
  60. def acct
  61. local? ? username : "#{username}@#{domain}"
  62. end
  63. # This is a duplicate of the AccountMerging concern because we need it to
  64. # be independent from code version.
  65. def merge_with!(other_account)
  66. # Since it's the same remote resource, the remote resource likely
  67. # already believes we are following/blocking, so it's safe to
  68. # re-attribute the relationships too. However, during the presence
  69. # of the index bug users could have *also* followed the reference
  70. # account already, therefore mass update will not work and we need
  71. # to check for (and skip past) uniqueness errors
  72. owned_classes = [
  73. Status, StatusPin, MediaAttachment, Poll, Report, Tombstone, Favourite,
  74. Follow, FollowRequest, Block, Mute,
  75. AccountModerationNote, AccountPin, AccountStat, ListAccount,
  76. PollVote, Mention
  77. ]
  78. owned_classes << AccountDeletionRequest if ActiveRecord::Base.connection.table_exists?(:account_deletion_requests)
  79. owned_classes << AccountNote if ActiveRecord::Base.connection.table_exists?(:account_notes)
  80. owned_classes << FollowRecommendationSuppression if ActiveRecord::Base.connection.table_exists?(:follow_recommendation_suppressions)
  81. owned_classes << AccountIdentityProof if ActiveRecord::Base.connection.table_exists?(:account_identity_proofs)
  82. owned_classes << Appeal if ActiveRecord::Base.connection.table_exists?(:appeals)
  83. owned_classes.each do |klass|
  84. klass.where(account_id: other_account.id).find_each do |record|
  85. begin
  86. record.update_attribute(:account_id, id)
  87. rescue ActiveRecord::RecordNotUnique
  88. next
  89. end
  90. end
  91. end
  92. target_classes = [Follow, FollowRequest, Block, Mute, AccountModerationNote, AccountPin]
  93. target_classes << AccountNote if ActiveRecord::Base.connection.table_exists?(:account_notes)
  94. target_classes.each do |klass|
  95. klass.where(target_account_id: other_account.id).find_each do |record|
  96. begin
  97. record.update_attribute(:target_account_id, id)
  98. rescue ActiveRecord::RecordNotUnique
  99. next
  100. end
  101. end
  102. end
  103. if ActiveRecord::Base.connection.table_exists?(:canonical_email_blocks)
  104. CanonicalEmailBlock.where(reference_account_id: other_account.id).find_each do |record|
  105. record.update_attribute(:reference_account_id, id)
  106. end
  107. end
  108. if ActiveRecord::Base.connection.table_exists?(:appeals)
  109. Appeal.where(account_warning_id: other_account.id).find_each do |record|
  110. record.update_attribute(:account_warning_id, id)
  111. end
  112. end
  113. end
  114. end
  115. class User < ApplicationRecord
  116. belongs_to :account, inverse_of: :user
  117. end
  118. desc 'fix-duplicates', 'Fix duplicates in database and rebuild indexes'
  119. long_desc <<~LONG_DESC
  120. Delete or merge duplicate accounts, statuses, emojis, etc. and rebuild indexes.
  121. This is useful if your database indexes are corrupted because of issues such as https://wiki.postgresql.org/wiki/Locale_data_changes
  122. Mastodon has to be stopped to run this task, which will take a long time and may be destructive.
  123. LONG_DESC
  124. def fix_duplicates
  125. @prompt = TTY::Prompt.new
  126. if ActiveRecord::Migrator.current_version < MIN_SUPPORTED_VERSION
  127. @prompt.error 'Your version of the database schema is too old and is not supported by this script.'
  128. @prompt.error 'Please update to at least Mastodon 3.0.0 before running this script.'
  129. exit(1)
  130. elsif ActiveRecord::Migrator.current_version > MAX_SUPPORTED_VERSION
  131. @prompt.warn 'Your version of the database schema is more recent than this script, this may cause unexpected errors.'
  132. exit(1) unless @prompt.yes?('Continue anyway? (Yes/No)')
  133. end
  134. if Sidekiq::ProcessSet.new.any?
  135. @prompt.error 'It seems Sidekiq is running. All Mastodon processes need to be stopped when using this script.'
  136. exit(1)
  137. end
  138. @prompt.warn 'This task will take a long time to run and is potentially destructive.'
  139. @prompt.warn 'Please make sure to stop Mastodon and have a backup.'
  140. exit(1) unless @prompt.yes?('Continue? (Yes/No)')
  141. deduplicate_users!
  142. deduplicate_account_domain_blocks!
  143. deduplicate_account_identity_proofs!
  144. deduplicate_announcement_reactions!
  145. deduplicate_conversations!
  146. deduplicate_custom_emojis!
  147. deduplicate_custom_emoji_categories!
  148. deduplicate_domain_allows!
  149. deduplicate_domain_blocks!
  150. deduplicate_unavailable_domains!
  151. deduplicate_email_domain_blocks!
  152. deduplicate_media_attachments!
  153. deduplicate_preview_cards!
  154. deduplicate_statuses!
  155. deduplicate_accounts!
  156. deduplicate_tags!
  157. deduplicate_webauthn_credentials!
  158. deduplicate_webhooks!
  159. Scenic.database.refresh_materialized_view('instances', concurrently: true, cascade: false) if ActiveRecord::Migrator.current_version >= 2020_12_06_004238
  160. Rails.cache.clear
  161. @prompt.say 'Finished!'
  162. end
  163. private
  164. def deduplicate_accounts!
  165. remove_index_if_exists!(:accounts, 'index_accounts_on_username_and_domain_lower')
  166. @prompt.say 'Deduplicating accounts… for local accounts, you will be asked to chose which account to keep unchanged.'
  167. find_duplicate_accounts.each do |row|
  168. accounts = Account.where(id: row['ids'].split(',')).to_a
  169. if accounts.first.local?
  170. deduplicate_local_accounts!(accounts)
  171. else
  172. deduplicate_remote_accounts!(accounts)
  173. end
  174. end
  175. @prompt.say 'Restoring index_accounts_on_username_and_domain_lower…'
  176. if ActiveRecord::Migrator.current_version < 20200620164023 # rubocop:disable Style/NumericLiterals
  177. ActiveRecord::Base.connection.add_index :accounts, 'lower (username), lower(domain)', name: 'index_accounts_on_username_and_domain_lower', unique: true
  178. else
  179. ActiveRecord::Base.connection.add_index :accounts, "lower (username), COALESCE(lower(domain), '')", name: 'index_accounts_on_username_and_domain_lower', unique: true
  180. end
  181. @prompt.say 'Reindexing textual indexes on accounts…'
  182. ActiveRecord::Base.connection.execute('REINDEX INDEX search_index;')
  183. ActiveRecord::Base.connection.execute('REINDEX INDEX index_accounts_on_uri;')
  184. ActiveRecord::Base.connection.execute('REINDEX INDEX index_accounts_on_url;')
  185. end
  186. def deduplicate_users!
  187. remove_index_if_exists!(:users, 'index_users_on_confirmation_token')
  188. remove_index_if_exists!(:users, 'index_users_on_email')
  189. remove_index_if_exists!(:users, 'index_users_on_remember_token')
  190. remove_index_if_exists!(:users, 'index_users_on_reset_password_token')
  191. @prompt.say 'Deduplicating user records…'
  192. # Deduplicating email
  193. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM users GROUP BY email HAVING count(*) > 1").each do |row|
  194. users = User.where(id: row['ids'].split(',')).sort_by(&:updated_at).reverse
  195. ref_user = users.shift
  196. @prompt.warn "Multiple users registered with e-mail address #{ref_user.email}."
  197. @prompt.warn "e-mail will be disabled for the following accounts: #{user.map(&:account).map(&:acct).join(', ')}"
  198. @prompt.warn 'Please reach out to them and set another address with `tootctl account modify` or delete them.'
  199. i = 0
  200. users.each do |user|
  201. user.update!(email: "#{i} " + user.email)
  202. end
  203. end
  204. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM users WHERE confirmation_token IS NOT NULL GROUP BY confirmation_token HAVING count(*) > 1").each do |row|
  205. users = User.where(id: row['ids'].split(',')).sort_by(&:created_at).reverse.drop(1)
  206. @prompt.warn "Unsetting confirmation token for those accounts: #{users.map(&:account).map(&:acct).join(', ')}"
  207. users.each do |user|
  208. user.update!(confirmation_token: nil)
  209. end
  210. end
  211. if ActiveRecord::Migrator.current_version < 20220118183010 # rubocop:disable Style/NumericLiterals
  212. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM users WHERE remember_token IS NOT NULL GROUP BY remember_token HAVING count(*) > 1").each do |row|
  213. users = User.where(id: row['ids'].split(',')).sort_by(&:updated_at).reverse.drop(1)
  214. @prompt.warn "Unsetting remember token for those accounts: #{users.map(&:account).map(&:acct).join(', ')}"
  215. users.each do |user|
  216. user.update!(remember_token: nil)
  217. end
  218. end
  219. end
  220. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM users WHERE reset_password_token IS NOT NULL GROUP BY reset_password_token HAVING count(*) > 1").each do |row|
  221. users = User.where(id: row['ids'].split(',')).sort_by(&:updated_at).reverse.drop(1)
  222. @prompt.warn "Unsetting password reset token for those accounts: #{users.map(&:account).map(&:acct).join(', ')}"
  223. users.each do |user|
  224. user.update!(reset_password_token: nil)
  225. end
  226. end
  227. @prompt.say 'Restoring users indexes…'
  228. ActiveRecord::Base.connection.add_index :users, ['confirmation_token'], name: 'index_users_on_confirmation_token', unique: true
  229. ActiveRecord::Base.connection.add_index :users, ['email'], name: 'index_users_on_email', unique: true
  230. ActiveRecord::Base.connection.add_index :users, ['remember_token'], name: 'index_users_on_remember_token', unique: true if ActiveRecord::Migrator.current_version < 20220118183010
  231. if ActiveRecord::Migrator.current_version < 20220310060641 # rubocop:disable Style/NumericLiterals
  232. ActiveRecord::Base.connection.add_index :users, ['reset_password_token'], name: 'index_users_on_reset_password_token', unique: true
  233. else
  234. ActiveRecord::Base.connection.add_index :users, ['reset_password_token'], name: 'index_users_on_reset_password_token', unique: true, where: 'reset_password_token IS NOT NULL', opclass: :text_pattern_ops
  235. end
  236. end
  237. def deduplicate_account_domain_blocks!
  238. remove_index_if_exists!(:account_domain_blocks, 'index_account_domain_blocks_on_account_id_and_domain')
  239. @prompt.say 'Removing duplicate account domain blocks…'
  240. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM account_domain_blocks GROUP BY account_id, domain HAVING count(*) > 1").each do |row|
  241. AccountDomainBlock.where(id: row['ids'].split(',').drop(1)).delete_all
  242. end
  243. @prompt.say 'Restoring account domain blocks indexes…'
  244. ActiveRecord::Base.connection.add_index :account_domain_blocks, ['account_id', 'domain'], name: 'index_account_domain_blocks_on_account_id_and_domain', unique: true
  245. end
  246. def deduplicate_account_identity_proofs!
  247. return unless ActiveRecord::Base.connection.table_exists?(:account_identity_proofs)
  248. remove_index_if_exists!(:account_identity_proofs, 'index_account_proofs_on_account_and_provider_and_username')
  249. @prompt.say 'Removing duplicate account identity proofs…'
  250. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM account_identity_proofs GROUP BY account_id, provider, provider_username HAVING count(*) > 1").each do |row|
  251. AccountIdentityProof.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  252. end
  253. @prompt.say 'Restoring account identity proofs indexes…'
  254. ActiveRecord::Base.connection.add_index :account_identity_proofs, ['account_id', 'provider', 'provider_username'], name: 'index_account_proofs_on_account_and_provider_and_username', unique: true
  255. end
  256. def deduplicate_announcement_reactions!
  257. return unless ActiveRecord::Base.connection.table_exists?(:announcement_reactions)
  258. remove_index_if_exists!(:announcement_reactions, 'index_announcement_reactions_on_account_id_and_announcement_id')
  259. @prompt.say 'Removing duplicate account identity proofs…'
  260. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM announcement_reactions GROUP BY account_id, announcement_id, name HAVING count(*) > 1").each do |row|
  261. AnnouncementReaction.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  262. end
  263. @prompt.say 'Restoring announcement_reactions indexes…'
  264. ActiveRecord::Base.connection.add_index :announcement_reactions, ['account_id', 'announcement_id', 'name'], name: 'index_announcement_reactions_on_account_id_and_announcement_id', unique: true
  265. end
  266. def deduplicate_conversations!
  267. remove_index_if_exists!(:conversations, 'index_conversations_on_uri')
  268. @prompt.say 'Deduplicating conversations…'
  269. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM conversations WHERE uri IS NOT NULL GROUP BY uri HAVING count(*) > 1").each do |row|
  270. conversations = Conversation.where(id: row['ids'].split(',')).sort_by(&:id).reverse
  271. ref_conversation = conversations.shift
  272. conversations.each do |other|
  273. merge_conversations!(ref_conversation, other)
  274. other.destroy
  275. end
  276. end
  277. @prompt.say 'Restoring conversations indexes…'
  278. if ActiveRecord::Migrator.current_version < 20220307083603 # rubocop:disable Style/NumericLiterals
  279. ActiveRecord::Base.connection.add_index :conversations, ['uri'], name: 'index_conversations_on_uri', unique: true
  280. else
  281. ActiveRecord::Base.connection.add_index :conversations, ['uri'], name: 'index_conversations_on_uri', unique: true, where: 'uri IS NOT NULL', opclass: :text_pattern_ops
  282. end
  283. end
  284. def deduplicate_custom_emojis!
  285. remove_index_if_exists!(:custom_emojis, 'index_custom_emojis_on_shortcode_and_domain')
  286. @prompt.say 'Deduplicating custom_emojis…'
  287. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM custom_emojis GROUP BY shortcode, domain HAVING count(*) > 1").each do |row|
  288. emojis = CustomEmoji.where(id: row['ids'].split(',')).sort_by(&:id).reverse
  289. ref_emoji = emojis.shift
  290. emojis.each do |other|
  291. merge_custom_emojis!(ref_emoji, other)
  292. other.destroy
  293. end
  294. end
  295. @prompt.say 'Restoring custom_emojis indexes…'
  296. ActiveRecord::Base.connection.add_index :custom_emojis, ['shortcode', 'domain'], name: 'index_custom_emojis_on_shortcode_and_domain', unique: true
  297. end
  298. def deduplicate_custom_emoji_categories!
  299. remove_index_if_exists!(:custom_emoji_categories, 'index_custom_emoji_categories_on_name')
  300. @prompt.say 'Deduplicating custom_emoji_categories…'
  301. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM custom_emoji_categories GROUP BY name HAVING count(*) > 1").each do |row|
  302. categories = CustomEmojiCategory.where(id: row['ids'].split(',')).sort_by(&:id).reverse
  303. ref_category = categories.shift
  304. categories.each do |other|
  305. merge_custom_emoji_categories!(ref_category, other)
  306. other.destroy
  307. end
  308. end
  309. @prompt.say 'Restoring custom_emoji_categories indexes…'
  310. ActiveRecord::Base.connection.add_index :custom_emoji_categories, ['name'], name: 'index_custom_emoji_categories_on_name', unique: true
  311. end
  312. def deduplicate_domain_allows!
  313. remove_index_if_exists!(:domain_allows, 'index_domain_allows_on_domain')
  314. @prompt.say 'Deduplicating domain_allows…'
  315. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM domain_allows GROUP BY domain HAVING count(*) > 1").each do |row|
  316. DomainAllow.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  317. end
  318. @prompt.say 'Restoring domain_allows indexes…'
  319. ActiveRecord::Base.connection.add_index :domain_allows, ['domain'], name: 'index_domain_allows_on_domain', unique: true
  320. end
  321. def deduplicate_domain_blocks!
  322. remove_index_if_exists!(:domain_blocks, 'index_domain_blocks_on_domain')
  323. @prompt.say 'Deduplicating domain_allows…'
  324. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM domain_blocks GROUP BY domain HAVING count(*) > 1").each do |row|
  325. domain_blocks = DomainBlock.where(id: row['ids'].split(',')).by_severity.reverse.to_a
  326. reject_media = domain_blocks.any?(&:reject_media?)
  327. reject_reports = domain_blocks.any?(&:reject_reports?)
  328. reference_block = domain_blocks.shift
  329. private_comment = domain_blocks.reduce(reference_block.private_comment.presence) { |a, b| a || b.private_comment.presence }
  330. public_comment = domain_blocks.reduce(reference_block.public_comment.presence) { |a, b| a || b.public_comment.presence }
  331. reference_block.update!(reject_media: reject_media, reject_reports: reject_reports, private_comment: private_comment, public_comment: public_comment)
  332. domain_blocks.each(&:destroy)
  333. end
  334. @prompt.say 'Restoring domain_blocks indexes…'
  335. ActiveRecord::Base.connection.add_index :domain_blocks, ['domain'], name: 'index_domain_blocks_on_domain', unique: true
  336. end
  337. def deduplicate_unavailable_domains!
  338. return unless ActiveRecord::Base.connection.table_exists?(:unavailable_domains)
  339. remove_index_if_exists!(:unavailable_domains, 'index_unavailable_domains_on_domain')
  340. @prompt.say 'Deduplicating unavailable_domains…'
  341. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM unavailable_domains GROUP BY domain HAVING count(*) > 1").each do |row|
  342. UnavailableDomain.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  343. end
  344. @prompt.say 'Restoring domain_allows indexes…'
  345. ActiveRecord::Base.connection.add_index :unavailable_domains, ['domain'], name: 'index_unavailable_domains_on_domain', unique: true
  346. end
  347. def deduplicate_email_domain_blocks!
  348. remove_index_if_exists!(:email_domain_blocks, 'index_email_domain_blocks_on_domain')
  349. @prompt.say 'Deduplicating email_domain_blocks…'
  350. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM email_domain_blocks GROUP BY domain HAVING count(*) > 1").each do |row|
  351. domain_blocks = EmailDomainBlock.where(id: row['ids'].split(',')).sort_by { |b| b.parent.nil? ? 1 : 0 }.to_a
  352. domain_blocks.drop(1).each(&:destroy)
  353. end
  354. @prompt.say 'Restoring email_domain_blocks indexes…'
  355. ActiveRecord::Base.connection.add_index :email_domain_blocks, ['domain'], name: 'index_email_domain_blocks_on_domain', unique: true
  356. end
  357. def deduplicate_media_attachments!
  358. remove_index_if_exists!(:media_attachments, 'index_media_attachments_on_shortcode')
  359. @prompt.say 'Deduplicating media_attachments…'
  360. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM media_attachments WHERE shortcode IS NOT NULL GROUP BY shortcode HAVING count(*) > 1").each do |row|
  361. MediaAttachment.where(id: row['ids'].split(',').drop(1)).update_all(shortcode: nil)
  362. end
  363. @prompt.say 'Restoring media_attachments indexes…'
  364. if ActiveRecord::Migrator.current_version < 20220310060626 # rubocop:disable Style/NumericLiterals
  365. ActiveRecord::Base.connection.add_index :media_attachments, ['shortcode'], name: 'index_media_attachments_on_shortcode', unique: true
  366. else
  367. ActiveRecord::Base.connection.add_index :media_attachments, ['shortcode'], name: 'index_media_attachments_on_shortcode', unique: true, where: 'shortcode IS NOT NULL', opclass: :text_pattern_ops
  368. end
  369. end
  370. def deduplicate_preview_cards!
  371. remove_index_if_exists!(:preview_cards, 'index_preview_cards_on_url')
  372. @prompt.say 'Deduplicating preview_cards…'
  373. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM preview_cards GROUP BY url HAVING count(*) > 1").each do |row|
  374. PreviewCard.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  375. end
  376. @prompt.say 'Restoring preview_cards indexes…'
  377. ActiveRecord::Base.connection.add_index :preview_cards, ['url'], name: 'index_preview_cards_on_url', unique: true
  378. end
  379. def deduplicate_statuses!
  380. remove_index_if_exists!(:statuses, 'index_statuses_on_uri')
  381. @prompt.say 'Deduplicating statuses…'
  382. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM statuses WHERE uri IS NOT NULL GROUP BY uri HAVING count(*) > 1").each do |row|
  383. statuses = Status.where(id: row['ids'].split(',')).sort_by(&:id)
  384. ref_status = statuses.shift
  385. statuses.each do |status|
  386. merge_statuses!(ref_status, status) if status.account_id == ref_status.account_id
  387. status.destroy
  388. end
  389. end
  390. @prompt.say 'Restoring statuses indexes…'
  391. if ActiveRecord::Migrator.current_version < 20220310060706 # rubocop:disable Style/NumericLiterals
  392. ActiveRecord::Base.connection.add_index :statuses, ['uri'], name: 'index_statuses_on_uri', unique: true
  393. else
  394. ActiveRecord::Base.connection.add_index :statuses, ['uri'], name: 'index_statuses_on_uri', unique: true, where: 'uri IS NOT NULL', opclass: :text_pattern_ops
  395. end
  396. end
  397. def deduplicate_tags!
  398. remove_index_if_exists!(:tags, 'index_tags_on_name_lower')
  399. remove_index_if_exists!(:tags, 'index_tags_on_lower_btree')
  400. @prompt.say 'Deduplicating tags…'
  401. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM tags GROUP BY lower((name)::text) HAVING count(*) > 1").each do |row|
  402. tags = Tag.where(id: row['ids'].split(',')).sort_by { |t| [t.usable?, t.trendable?, t.listable?].count(false) }
  403. ref_tag = tags.shift
  404. tags.each do |tag|
  405. merge_tags!(ref_tag, tag)
  406. tag.destroy
  407. end
  408. end
  409. @prompt.say 'Restoring tags indexes…'
  410. if ActiveRecord::Migrator.current_version < 20210421121431
  411. ActiveRecord::Base.connection.add_index :tags, 'lower((name)::text)', name: 'index_tags_on_name_lower', unique: true
  412. else
  413. ActiveRecord::Base.connection.execute 'CREATE UNIQUE INDEX CONCURRENTLY index_tags_on_name_lower_btree ON tags (lower(name) text_pattern_ops)'
  414. end
  415. end
  416. def deduplicate_webauthn_credentials!
  417. return unless ActiveRecord::Base.connection.table_exists?(:webauthn_credentials)
  418. remove_index_if_exists!(:webauthn_credentials, 'index_webauthn_credentials_on_external_id')
  419. @prompt.say 'Deduplicating webauthn_credentials…'
  420. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM webauthn_credentials GROUP BY external_id HAVING count(*) > 1").each do |row|
  421. WebauthnCredential.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  422. end
  423. @prompt.say 'Restoring webauthn_credentials indexes…'
  424. ActiveRecord::Base.connection.add_index :webauthn_credentials, ['external_id'], name: 'index_webauthn_credentials_on_external_id', unique: true
  425. end
  426. def deduplicate_webhooks!
  427. return unless ActiveRecord::Base.connection.table_exists?(:webhooks)
  428. remove_index_if_exists!(:webhooks, 'index_webhooks_on_url')
  429. @prompt.say 'Deduplicating webhooks…'
  430. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM webhooks GROUP BY url HAVING count(*) > 1").each do |row|
  431. Webhooks.where(id: row['ids'].split(',')).sort_by(&:id).reverse.drop(1).each(&:destroy)
  432. end
  433. @prompt.say 'Restoring webhooks indexes…'
  434. ActiveRecord::Base.connection.add_index :webhooks, ['url'], name: 'index_webhooks_on_url', unique: true
  435. end
  436. def deduplicate_local_accounts!(accounts)
  437. accounts = accounts.sort_by(&:id).reverse
  438. @prompt.warn "Multiple local accounts were found for username '#{accounts.first.username}'."
  439. @prompt.warn 'All those accounts are distinct accounts but only the most recently-created one is fully-functional.'
  440. accounts.each_with_index do |account, idx|
  441. @prompt.say '%2d. %s: created at: %s; updated at: %s; last logged in at: %s; statuses: %5d; last status at: %s' % [idx, account.username, account.created_at, account.updated_at, account.user&.last_sign_in_at&.to_s || 'N/A', account.account_stat&.statuses_count || 0, account.account_stat&.last_status_at || 'N/A']
  442. end
  443. @prompt.say 'Please chose the one to keep unchanged, other ones will be automatically renamed.'
  444. ref_id = @prompt.ask('Account to keep unchanged:') do |q|
  445. q.required true
  446. q.default 0
  447. q.convert :int
  448. end
  449. accounts.delete_at(ref_id)
  450. i = 0
  451. accounts.each do |account|
  452. i += 1
  453. username = account.username + "_#{i}"
  454. while Account.local.exists?(username: username)
  455. i += 1
  456. username = account.username + "_#{i}"
  457. end
  458. account.update!(username: username)
  459. end
  460. end
  461. def deduplicate_remote_accounts!(accounts)
  462. accounts = accounts.sort_by(&:updated_at).reverse
  463. reference_account = accounts.shift
  464. accounts.each do |other_account|
  465. if other_account.public_key == reference_account.public_key
  466. # The accounts definitely point to the same resource, so
  467. # it's safe to re-attribute content and relationships
  468. reference_account.merge_with!(other_account)
  469. end
  470. other_account.destroy
  471. end
  472. end
  473. def merge_conversations!(main_conv, duplicate_conv)
  474. owned_classes = [ConversationMute, AccountConversation]
  475. owned_classes.each do |klass|
  476. klass.where(conversation_id: duplicate_conv.id).find_each do |record|
  477. begin
  478. record.update_attribute(:account_id, main_conv.id)
  479. rescue ActiveRecord::RecordNotUnique
  480. next
  481. end
  482. end
  483. end
  484. end
  485. def merge_custom_emojis!(main_emoji, duplicate_emoji)
  486. owned_classes = [AnnouncementReaction]
  487. owned_classes.each do |klass|
  488. klass.where(custom_emoji_id: duplicate_emoji.id).update_all(custom_emoji_id: main_emoji.id)
  489. end
  490. end
  491. def merge_custom_emoji_categories!(main_category, duplicate_category)
  492. owned_classes = [CustomEmoji]
  493. owned_classes.each do |klass|
  494. klass.where(category_id: duplicate_category.id).update_all(category_id: main_category.id)
  495. end
  496. end
  497. def merge_statuses!(main_status, duplicate_status)
  498. owned_classes = [Favourite, Mention, Poll]
  499. owned_classes << Bookmark if ActiveRecord::Base.connection.table_exists?(:bookmarks)
  500. owned_classes.each do |klass|
  501. klass.where(status_id: duplicate_status.id).find_each do |record|
  502. begin
  503. record.update_attribute(:status_id, main_status.id)
  504. rescue ActiveRecord::RecordNotUnique
  505. next
  506. end
  507. end
  508. end
  509. StatusPin.where(account_id: main_status.account_id, status_id: duplicate_status.id).find_each do |record|
  510. begin
  511. record.update_attribute(:status_id, main_status.id)
  512. rescue ActiveRecord::RecordNotUnique
  513. next
  514. end
  515. end
  516. Status.where(in_reply_to_id: duplicate_status.id).find_each do |record|
  517. begin
  518. record.update_attribute(:in_reply_to_id, main_status.id)
  519. rescue ActiveRecord::RecordNotUnique
  520. next
  521. end
  522. end
  523. Status.where(reblog_of_id: duplicate_status.id).find_each do |record|
  524. begin
  525. record.update_attribute(:reblog_of_id, main_status.id)
  526. rescue ActiveRecord::RecordNotUnique
  527. next
  528. end
  529. end
  530. end
  531. def merge_tags!(main_tag, duplicate_tag)
  532. [FeaturedTag].each do |klass|
  533. klass.where(tag_id: duplicate_tag.id).find_each do |record|
  534. begin
  535. record.update_attribute(:tag_id, main_tag.id)
  536. rescue ActiveRecord::RecordNotUnique
  537. next
  538. end
  539. end
  540. end
  541. end
  542. def find_duplicate_accounts
  543. ActiveRecord::Base.connection.select_all("SELECT string_agg(id::text, ',') AS ids FROM accounts GROUP BY lower(username), COALESCE(lower(domain), '') HAVING count(*) > 1")
  544. end
  545. def remove_index_if_exists!(table, name)
  546. ActiveRecord::Base.connection.remove_index(table, name: name)
  547. rescue ArgumentError
  548. nil
  549. rescue ActiveRecord::StatementInvalid
  550. nil
  551. end
  552. end
  553. end