class AddVersionNoToPosts < ActiveRecord::Migration[8.0]
  def up
    add_column :posts, :version_no, :integer

    execute <<~SQL
      UPDATE
        posts
      SET
        version_no = (
          SELECT
            MAX(version_no)
          FROM
            post_versions
          WHERE
            post_id = posts.id)
    SQL

    change_column_null :posts, :version_no, false

    add_check_constraint :posts, 'version_no > 0', name: 'chk_posts_version_no_positive'
  end

  def down
    remove_check_constraint :posts, name: 'chk_posts_version_no_positive'
    remove_column :posts, :version_no
  end
end
