schema_extractor 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 00af36b44554c23c33829b3c21cb5c392e2d15a9
4
+ data.tar.gz: 0c9aca168e4f9c53f8a95c20dc1bd44f8aea5182
5
+ SHA512:
6
+ metadata.gz: fa8e4f468f32f9ef901a8c1c7f6dddc1e1cdaa698eb2b4e03db30b9062fffe2737c64e3133771ad15369ea9c0f54429673723e3489bdc00082fdcef43d3db055
7
+ data.tar.gz: d73cb1ff9a7aebb3eb9fe4fe5b06994eb76f6388f864f37a29fd2636c1fc5eed788f370369d577ef69c01f893e08e5ff6f6590e222bed70efc55577fa9ccc528
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.1
5
+ before_install: gem install bundler -v 1.14.6
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in schema_extractor.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 nownabe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # SchemaExtractor
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/schema_extractor`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'schema_extractor'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install schema_extractor
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/schema_extractor.
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
41
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "schema_extractor"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ lib = File.expand_path("../../lib", __FILE__)
5
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
6
+
7
+ require "schema_extractor/runner"
8
+
9
+ SchemaExtractor::Runner.new(ARGV).run
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaExtractor
4
+ module Extractors
5
+ EXTRACTORS = {
6
+ mysql: "mysql",
7
+ }.freeze
8
+
9
+ class << self
10
+ def sources
11
+ EXTRACTORS.keys
12
+ end
13
+
14
+ def get_extractor(source, options)
15
+ underscored_name = EXTRACTORS[source.to_sym]
16
+ require "schema_extractor/#{underscored_name}/extractor"
17
+ klass = SchemaExtractor.const_get("#{underscored_name.capitalize}::Extractor")
18
+ klass.new(options)
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaExtractor
4
+ class Field
5
+ class InvalidFieldNameError < StandardError; end
6
+ class InvalidFieldTypeError < StandardError; end
7
+ class InvalidNullableValueError < StandardError; end
8
+
9
+ TYPES = %i[
10
+ date
11
+ datetime
12
+ decimal
13
+ float
14
+ integer
15
+ string
16
+ ].freeze
17
+ attr_reader :name
18
+ attr_reader :type
19
+ attr_reader :nullable
20
+ attr_reader :default
21
+
22
+ def initialize(name:, type:, nullable:, default: nil)
23
+ @name = validate_name!(name)
24
+ @type = validate_type!(type)
25
+ @nullable = validate_nullable!(nullable)
26
+ @default = validate_default!(default)
27
+ end
28
+
29
+ def nullable?
30
+ nullable
31
+ end
32
+
33
+ private
34
+
35
+ def validate_default!(default)
36
+ default
37
+ end
38
+
39
+ def validate_name!(name)
40
+ return name if name&.instance_of?(String) && !name.empty?
41
+ raise InvalidFieldNameError, "#{name} is invalid field name."
42
+ end
43
+
44
+ def validate_nullable!(nullable)
45
+ unless [true, false].include?(nullable)
46
+ raise(InvalidNullableValueError, "#{nullable} is invalid for nullable value.")
47
+ end
48
+ nullable
49
+ end
50
+
51
+ def validate_type!(type)
52
+ type = type&.to_sym
53
+ return type if type && TYPES.include?(type)
54
+ raise(InvalidFieldTypeError, "#{type} is invalid field type.")
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module SchemaExtractor
6
+ module Formatters
7
+ class Bigquery
8
+ class InvalidBigqueryFieldTypeError < StandardError; end
9
+
10
+ def format(schema)
11
+ JSON.pretty_generate(
12
+ schema.fields.map do |f|
13
+ {
14
+ name: f.name,
15
+ type: bq_type(f),
16
+ mode: bq_mode(f)
17
+ }
18
+ end
19
+ )
20
+ end
21
+
22
+ def extension
23
+ ".json"
24
+ end
25
+
26
+ private
27
+
28
+ def bq_mode(f)
29
+ f.nullable? && f.default.nil? ? "NULLABLE" : "REQUIRED"
30
+ end
31
+
32
+ def bq_type(f)
33
+ case f.type
34
+ when :decimal, :float
35
+ "FLOAT"
36
+ when :integer
37
+ "INTEGER"
38
+ when :string
39
+ "STRING"
40
+ when :date
41
+ "DATE"
42
+ when :datetime
43
+ "TIMESTAMP"
44
+ else
45
+ raise InvalidBigqueryFieldTypeError, "#{f.type} is invalid type for bigquery field."
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaExtractor
4
+ module Formatters
5
+ FORMATTERS = {
6
+ bq: "bigquery",
7
+ bigquery: "bigquery",
8
+ }.freeze
9
+
10
+ class << self
11
+ def formats
12
+ FORMATTERS.keys
13
+ end
14
+
15
+ def get_formatter(format)
16
+ underscored_name = FORMATTERS[format.to_sym]
17
+ require "schema_extractor/formatters/#{underscored_name}"
18
+ klass = SchemaExtractor::Formatters.const_get(underscored_name.capitalize)
19
+ klass.new
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "io/console"
4
+
5
+ require "mysql2"
6
+
7
+ require "schema_extractor/field"
8
+ require "schema_extractor/schema"
9
+
10
+ module SchemaExtractor
11
+ module Mysql
12
+ class UnknownFieldTypeError < StandardError; end
13
+
14
+ class Extractor
15
+ attr_reader :options
16
+
17
+ def initialize(options)
18
+ @options = options
19
+ end
20
+
21
+ def extract
22
+ tables.map { |t| get_schema(t) }
23
+ end
24
+
25
+ private
26
+
27
+ def ask_password
28
+ print "Password: "
29
+ STDIN.noecho(&:gets).chomp.tap { puts }
30
+ end
31
+
32
+ def build_field(row)
33
+ Field.new(
34
+ name: detect_name(row),
35
+ type: detect_type(row),
36
+ nullable: detect_nullable(row),
37
+ default: detect_default_value(row)
38
+ )
39
+ end
40
+
41
+ def client
42
+ @client ||= Mysql2::Client.new(
43
+ host: options.fetch(:host, "localhost"),
44
+ port: options.fetch(:port, "3306"),
45
+ username: options.fetch(:user, "root"),
46
+ password: options.fetch(:password) { ask_password },
47
+ database: options.fetch(:database)
48
+ )
49
+ end
50
+
51
+ def detect_default_value(row)
52
+ row["Default"]
53
+ end
54
+
55
+ def detect_name(row)
56
+ row["Field"]
57
+ end
58
+
59
+ def detect_nullable(row)
60
+ row["Null"] == "YES"
61
+ end
62
+
63
+ def detect_type(row)
64
+ case row["Type"]
65
+ when /^date/
66
+ :date
67
+ when /^datetime/
68
+ :datetime
69
+ when /^decimal/
70
+ :decimal
71
+ when /^float/
72
+ :float
73
+ when /^bigint/, /^int/, /^smallint/, /^tinyint/
74
+ :integer
75
+ when /^longtext/, /^text/, /^varchar/
76
+ :string
77
+ else
78
+ raise UnknownFieldTypeError, "#{row['Type']} is unknown type."
79
+ end
80
+ end
81
+
82
+ def get_schema(table)
83
+ schema = Schema.new(table)
84
+ client.query("describe #{table}").each { |r| schema.add(build_field(r)) }
85
+ schema
86
+ end
87
+
88
+ def tables
89
+ @tables ||= client.query("show tables").map { |row| row.values.first }
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "slop"
4
+
5
+ require "schema_extractor/extractors"
6
+ require "schema_extractor/formatters"
7
+
8
+ module SchemaExtractor
9
+ class OptionParser
10
+ def parse(args)
11
+ parser.parse(args)
12
+ end
13
+
14
+ private
15
+
16
+ def banner
17
+ "usage: schema_extractor [options]"
18
+ end
19
+
20
+ def formats
21
+ Formatters.formats.join(", ")
22
+ end
23
+
24
+ def options
25
+ Slop::Options.new do |o|
26
+ o.banner = banner
27
+
28
+ o.string(
29
+ "-s",
30
+ "--source",
31
+ "Source database type. Supported sources: #{sources}",
32
+ default: "mysql"
33
+ )
34
+ o.string(
35
+ "-f",
36
+ "--format",
37
+ "Output format. Supported formats: #{formats}",
38
+ default: "bigquery"
39
+ )
40
+ o.string(
41
+ "-o",
42
+ "--output",
43
+ "Output directory.",
44
+ default: "."
45
+ )
46
+
47
+ o.string "-h", "--host", "Host of database."
48
+ o.string "-u", "--user", "User of database."
49
+ o.string "-p", "--password", "Password of database."
50
+ o.string "-P", "--port", "Port of database."
51
+ o.string "-d", "--database", "Database name."
52
+
53
+ o.on "-v", "--version", "Show version." do
54
+ require "schema_extractor/version"
55
+ puts SchemaExtractor::VERSION
56
+ exit
57
+ end
58
+
59
+ o.on "--help", "Show this message." do
60
+ puts o
61
+ exit
62
+ end
63
+ end
64
+ end
65
+
66
+ def parser
67
+ Slop::Parser.new(options)
68
+ end
69
+
70
+ def sources
71
+ Extractors.sources.join(", ")
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "schema_extractor/extractors"
4
+ require "schema_extractor/formatters"
5
+ require "schema_extractor/option_parser"
6
+
7
+ module SchemaExtractor
8
+ class Runner
9
+ attr_reader :options
10
+
11
+ def initialize(args)
12
+ @options = OptionParser.new.parse(args)
13
+ end
14
+
15
+ def run
16
+ schemas = extractor.extract
17
+ schemas.each { |s| output(s) }
18
+ end
19
+
20
+ private
21
+
22
+ def extractor
23
+ SchemaExtractor::Extractors.get_extractor(options[:source], options.to_hash.compact)
24
+ end
25
+
26
+ def formatter
27
+ @formatter ||= SchemaExtractor::Formatters.get_formatter(options[:format])
28
+ end
29
+
30
+ def output(schema)
31
+ path = File.join(options[:output], "#{schema.name}#{formatter.extension}")
32
+ File.write(path, formatter.format(schema))
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaExtractor
4
+ class Schema
5
+ attr_reader :fields
6
+ attr_reader :name
7
+
8
+ def initialize(name)
9
+ @name = name
10
+ @fields = []
11
+ end
12
+
13
+ def add(field)
14
+ fields.push(field)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,3 @@
1
+ module SchemaExtractor
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,5 @@
1
+ require "schema_extractor/version"
2
+
3
+ module SchemaExtractor
4
+ # Your code goes here...
5
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path("../lib", __FILE__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require "schema_extractor/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "schema_extractor"
9
+ spec.version = SchemaExtractor::VERSION
10
+ spec.authors = ["nownabe"]
11
+ spec.email = ["nownabe@gmail.com"]
12
+
13
+ spec.summary = "Extract DB schema."
14
+ spec.homepage = "https://github.com/nownabe/schema_extractor"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.14"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "minitest", "~> 5.0"
27
+
28
+ spec.add_runtime_dependency "mysql2"
29
+ spec.add_runtime_dependency "slop"
30
+ end
metadata ADDED
@@ -0,0 +1,135 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: schema_extractor
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - nownabe
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-10-24 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.14'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.14'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: mysql2
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: slop
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ description:
84
+ email:
85
+ - nownabe@gmail.com
86
+ executables:
87
+ - schema_extractor
88
+ extensions: []
89
+ extra_rdoc_files: []
90
+ files:
91
+ - ".gitignore"
92
+ - ".travis.yml"
93
+ - Gemfile
94
+ - LICENSE.txt
95
+ - README.md
96
+ - Rakefile
97
+ - bin/console
98
+ - bin/setup
99
+ - exe/schema_extractor
100
+ - lib/schema_extractor.rb
101
+ - lib/schema_extractor/extractors.rb
102
+ - lib/schema_extractor/field.rb
103
+ - lib/schema_extractor/formatters.rb
104
+ - lib/schema_extractor/formatters/bigquery.rb
105
+ - lib/schema_extractor/mysql/extractor.rb
106
+ - lib/schema_extractor/option_parser.rb
107
+ - lib/schema_extractor/runner.rb
108
+ - lib/schema_extractor/schema.rb
109
+ - lib/schema_extractor/version.rb
110
+ - schema_extractor.gemspec
111
+ homepage: https://github.com/nownabe/schema_extractor
112
+ licenses:
113
+ - MIT
114
+ metadata: {}
115
+ post_install_message:
116
+ rdoc_options: []
117
+ require_paths:
118
+ - lib
119
+ required_ruby_version: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: '0'
124
+ required_rubygems_version: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - ">="
127
+ - !ruby/object:Gem::Version
128
+ version: '0'
129
+ requirements: []
130
+ rubyforge_project:
131
+ rubygems_version: 2.6.11
132
+ signing_key:
133
+ specification_version: 4
134
+ summary: Extract DB schema.
135
+ test_files: []