0. これはなに
mysqlworkbenchで作成する SQL script(create table)から、テーブル一覧をcsvとして抽出する方法についてメモ。
1. ながれ
- SQL script をexport する
- 抽出スクリプト(ruby)
- 抽出する
2. SQL script を exportする
メニュー > File > Export > Forward Engineer を開く

Output SQL Script File: を指定し、あとは基本、デフォルトでOK。
3. 抽出スクリプト(ruby)
extract.rb
# frozen_string_literal: true
require 'csv'
input_file = ARGV[0] || 'schema.sql'
output_file = ARGV[1] || 'output.csv'
tables = []
current_table = nil
table_comment = nil
# 正規表現
TABLE_START_REGEX = /CREATE TABLE IF NOT EXISTS `[^`]+`\.`([^`]+)`/i
COLUMN_DEF_REGEX = /^\s*`([^`]+)`\s+[^,]+/ # バッククォートで始まるカラム
COLUMN_COMMENT_REGEX = /COMMENT\s+'([^']*)'/
TABLE_COMMENT_REGEX = /COMMENT\s*=\s*'([^']*)'/
File.readlines(input_file).each do |line|
line.rstrip!
# --- テーブル開始 ---
if (m = line.match(TABLE_START_REGEX))
current_table = m[1]
table_comment = nil
tables << { name: current_table, comment: nil, columns: [] }
next
end
# --- テーブルコメント ---
if current_table && (m = line.match(TABLE_COMMENT_REGEX))
table_comment = m[1]
tables.last[:comment] = table_comment.gsub("\\n", "\n")
next
end
# --- カラム定義 ---
if current_table && (m = line.match(COLUMN_DEF_REGEX))
column_name = m[1]
# カラムコメント
comment = nil
if (cm = line.match(COLUMN_COMMENT_REGEX))
comment = cm[1].gsub("\\n", "\n")
end
tables.last[:columns] << { name: column_name, comment: comment }
end
end
# --- CSV 出力 ---
id = 1
before_table_name = ""
CSV.open(output_file, 'w', force_quotes: true) do |csv|
csv << %w[id table_name table_comment column_name column_comment]
tables.each do |table|
table_name = table[:name]
table_comment = table[:comment]
table[:columns].each do |col|
csv << [
id,
(table_name == before_table_name) ? "" : table_name,
(table_name == before_table_name) ? "" : table_comment,
col[:name],
col[:comment]
]
id += 1
before_table_name = table_name
end
end
end
puts "CSV created: #{output_file}"
4. 抽出する
# ruby extract.rb <sql script filename>
これで、output.csv に抽出される。