class SchemaExtractor::Mysql::Extractor
Attributes
options[R]
Public Class Methods
new(options)
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 17 def initialize(options) @options = options end
Public Instance Methods
extract()
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 21 def extract tables.map { |t| get_schema(t) } end
Private Instance Methods
ask_password()
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 27 def ask_password print "Password: " STDIN.noecho(&:gets).chomp.tap { puts } end
build_field(row)
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 32 def build_field(row) Field.new( name: detect_name(row), type: detect_type(row), nullable: detect_nullable(row), default: detect_default_value(row) ) end
client()
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 41 def client @client ||= Mysql2::Client.new( host: options.fetch(:host, "localhost"), port: options.fetch(:port, "3306"), username: options.fetch(:user, "root"), password: options.fetch(:password) { ask_password }, database: options.fetch(:database) ) end
detect_default_value(row)
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 51 def detect_default_value(row) if !row["Default"].nil? && detect_type(row) == :boolean return row["Default"] == 0 ? false : true end row["Default"] end
detect_name(row)
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 58 def detect_name(row) row["Field"] end
detect_nullable(row)
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 62 def detect_nullable(row) row["Null"] == "YES" end
detect_type(row)
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 66 def detect_type(row) case row["Type"] when /^tinyint\(1\)$/ :boolean when /^date$/ :date when /^datetime$/ :datetime when /^decimal\(\d+,\d+\)$/ :decimal when /^float$/ :float when /^bigint\(\d+\)$/, /^int\(\d+\)$/, /^smallint\(\d+\)$/, /^tinyint\(\d+\)$/ :integer when /^longtext$/, /^text$/, /^varchar\(\d+\)$/ :string else raise UnknownFieldTypeError, "#{row['Type']} is unknown type." end end
get_schema(table)
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 87 def get_schema(table) schema = Schema.new(table) client.query("describe #{table}").each { |r| schema.add(build_field(r)) } schema end
tables()
click to toggle source
# File lib/schema_extractor/mysql/extractor.rb, line 93 def tables @tables ||= client.query("show tables").map { |row| row.values.first } end