Created
March 11, 2016 00:42
-
-
Save d-tasaki/d9c5f20ad93900440f3a to your computer and use it in GitHub Desktop.
MySQLのダンプファイルをテーブル毎に分割するスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# これはなに?: | |
# MySQLのダンプファイルをテーブル毎に分割します。 | |
# カレントディレクトリ配下に「<データベース名>/<テーブル名>.dump」という構成でファイル分割します。 | |
# | |
# 使い方: | |
# gunzip -c XXXXdb.dump.gz | ruby dump_splitter.rb | |
require 'fileutils' | |
class DumpSplitter | |
attr_accessor :input_stream, :output_stream | |
attr_accessor :database, :table | |
def initialize(input_stream) | |
self.input_stream = input_stream | |
end | |
def parse | |
while line = self.input_stream.gets | |
begin | |
if line =~ /^-- Host: .* Database: ([^`\n\r]+)/ | |
# -- Host: localhost Database: XXXXdb | |
# ↑ここ | |
self.database = $1.chomp | |
make_folder | |
puts "Database is #{self.database}" | |
elsif line =~ /^-- Current Database: `([^`]+)`/ | |
# -- Current Database: `XXXXdb` | |
# ↑ここ | |
self.database = $1.chomp | |
make_folder | |
puts "Database is #{self.database}" | |
elsif line =~ /^-- Table structure for table `([^`]+)`/ | |
# -- Table structure for table `users` | |
# ↑ここ | |
self.table = $1.chomp | |
open_output_stream | |
puts "Table is #{self.table}" | |
end | |
rescue ArgumentError | |
# UTF-8として不正なバイト文字があった場合「invalid byte sequence in UTF-8 (ArgumentError)」が発生する。 | |
# 無視します。 | |
end | |
self.output_stream << line unless self.output_stream.nil? | |
end | |
ensure | |
close_output_stream | |
end | |
private | |
def make_folder | |
path = self.database | |
FileUtils.mkdir_p(path) unless FileTest.exist?(path) | |
end | |
def open_output_stream | |
close_output_stream unless self.output_stream.nil? | |
path = "#{self.database}/#{self.table}.dump" | |
self.output_stream = open(path, "w") | |
end | |
def close_output_stream | |
self.output_stream.close unless self.output_stream.nil? | |
self.output_stream = nil | |
end | |
end | |
DumpSplitter.new(STDIN).parse |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment