class AddVersionNoToWikiPages < ActiveRecord::Migration[8.0]
  def up
    add_column :wiki_pages, :version_no, :integer

    execute <<~SQL
      UPDATE
        wiki_pages
      SET
        version_no = (
          SELECT
            MAX(version_no)
          FROM
            wiki_versions
          WHERE
            wiki_page_id = wiki_pages.id)
    SQL

    change_column_null :wiki_pages, :version_no, false

    add_check_constraint :wiki_pages, 'version_no > 0', name: 'chk_wiki_pages_version_no_positive'
  end

  def down
    remove_check_constraint :wiki_pages, name: 'chk_wiki_pages_version_no_positive'
    remove_column :wiki_pages, :version_no
  end
end
