1 class BackfillNoteDescriptions < ActiveRecord::Migration[7.2]
 
   2   class Note < ApplicationRecord; end
 
   3   class NoteComment < ApplicationRecord; end
 
   5   disable_ddl_transaction!
 
   8     Note.in_batches(:of => 1000) do |notes|
 
   9       note_ids = notes.pluck(:id)
 
  11       sql_query = <<-SQL.squish
 
  12         WITH first_comment AS(
 
  13           SELECT DISTINCT ON (note_id) *
 
  15           WHERE note_id BETWEEN #{note_ids.min} AND #{note_ids.max}
 
  19         SET description = first_comment.body,
 
  20             user_id = first_comment.author_id,
 
  21             user_ip = first_comment.author_ip
 
  23         WHERE first_comment.note_id = notes.id
 
  24           AND first_comment.event = 'opened';
 
  27       ActiveRecord::Base.connection.execute(sql_query)