0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

mysqlworkbenchのSQLscriptからテーブル一覧を抽出する方法

0
Posted at

0. これはなに

mysqlworkbenchで作成する SQL script(create table)から、テーブル一覧をcsvとして抽出する方法についてメモ。

1. ながれ

  • SQL script をexport する
  • 抽出スクリプト(ruby)
  • 抽出する

2. SQL script を exportする

メニュー > File > Export > Forward Engineer を開く
スクリーンショット 2026-03-25 15.00.25.png

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 に抽出される。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?