patorashのブログ

方向性はまだない

コメントのないカラムを抽出してマイグレーション処理を生成する

データベースのカラムにコメントを追加していくシリーズ。

今までの経緯はこちら。

patorash.hatenablog.com

patorash.hatenablog.com

patorash.hatenablog.com

ここまでで、I18nを使ってデータを突っ込んだので、残りはそれらで漏れたテーブル・カラム群となります。

コメントのないカラムを抽出する

まずはbin/rails consoleでやっていきます。

tables = ApplicationRecord.connection.tables + ApplicationRecord.connection.views
table_with_columns = tables.each_with_object({}) { |table, hash| hash[table] = ApplicationRecord.connection.columns(table) }
table_with_columns = table_with_columns.select {|table_name, columns| columns.any?{ |column| column.comment.nil?} }
table_with_columns.transform_values! {|columns| columns.select {|column| column.comment.nil?}}

これで、table_with_columnsには、カラムにコメントのないテーブルとカラムのHashが出来上がります。

次に、このデータを元に、マイグレーション用のコードを書かせましょう。

table_with_columns.each { |table, columns| columns.each { |column| puts "change_column_comment(:#{table}, :#{column.name}, from: nil, to: '')" }}; nil

上記を実行すると、以下のような文字列が出力されます。(テーブル名、カラム名はダミーです)

change_column_comment(:posts, :id, from: nil, to: '')
change_column_comment(:posts, :title, from: nil, to: '')
change_column_comment(:posts, :content, from: nil, to: '')
change_column_comment(:tags, :id, from: nil, to: '')
change_column_comment(:tags, :name, from: nil, to: '')
# 以降、コメントのないカラムの数だけズラズラと…

出力された文字列をコピーしておきましょう。

マイグレーションファイルを作る

とりあえず生成。

bin/rails g migration AddColumnCommentsToEmptyColumn

書いていく

さきほどrails consoleで出力させたコードをペーストします。

class AddColumnCommentsToEmptyColumn < ActiveRecord::Migration[6.0]
  def change
    change_column_comment(:posts, :id, from: nil, to: '')
    change_column_comment(:posts, :title, from: nil, to: '')
    change_column_comment(:posts, :content, from: nil, to: '')
    change_column_comment(:tags, :id, from: nil, to: '')
    change_column_comment(:tags, :name, from: nil, to: '')
    # 以降、コメントのないカラムの数だけズラズラと…
  end
end

あとは、上記のコードのto: ''のところに、コメントを書いていくだけ!!👍

実行する

いざ、実験。

bin/rails db:migrate

どんどんコメントが追加されていきました。

確認するには、bin/rails dbconsolepsqlを起動します(PostgreSQLの場合)。そして、\d+ (テーブル名)を実行してみてください。例えば、\d+ posts等です。

f:id:patorash:20210303124346p:plain

バッチリ、コメントが追加されていました😀

まとめ

自力でコメントのないカラムを探してchange_column_commentを書いていくのは大変なので、コードにコードを書かせることで楽ができました。