]> git.openstreetmap.org Git - rails.git/blob - db/migrate/20250212160355_backfill_note_descriptions.rb
Merge remote-tracking branch 'upstream/pull/5778'
[rails.git] / db / migrate / 20250212160355_backfill_note_descriptions.rb
1 class BackfillNoteDescriptions < ActiveRecord::Migration[7.2]
2   class Note < ApplicationRecord; end
3   class NoteComment < ApplicationRecord; end
4
5   disable_ddl_transaction!
6
7   def up
8     Note.in_batches(:of => 1000) do |notes|
9       note_ids = notes.pluck(:id)
10
11       sql_query = <<-SQL.squish
12         WITH first_comment AS(
13           SELECT DISTINCT ON (note_id) *
14           FROM note_comments
15           WHERE note_id BETWEEN #{note_ids.min} AND #{note_ids.max}
16           ORDER BY note_id, id
17         )
18         UPDATE notes
19         SET description = first_comment.body,
20             user_id = first_comment.author_id,
21             user_ip = first_comment.author_ip
22         FROM first_comment
23         WHERE first_comment.note_id = notes.id
24           AND first_comment.event = 'opened';
25       SQL
26
27       ActiveRecord::Base.connection.execute(sql_query)
28     end
29   end
30 end