ddg 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 257cc02abe88b39d7d8da6fa3cb5785c343d0a85
4
+ data.tar.gz: 1e3a4b9b20acd5b7ab46576da2f9ab23737ad189
5
+ SHA512:
6
+ metadata.gz: d7d324f7b7f638b087722d78d598f1b597287228e1f4837817a3431fcc9e02c2d3a0ef16c00d44390f43685379d508bf68419c1f0f7910e9e4849fee714b67d5
7
+ data.tar.gz: 22179796a45419fc49ac42652856acb3b17e1ffe67e1711c5b61489ed5066b23e776b6647b26988ab2a2f005f1c16712db80cd7b025dceb4323f731f55f149e5
@@ -0,0 +1,7 @@
1
+ .byebug_history
2
+ .rbenv-vars
3
+ .rspec_status
4
+ coverage
5
+ *.dot
6
+ *.png
7
+ tmp*
@@ -0,0 +1,17 @@
1
+ AllCops:
2
+ Exclude:
3
+ - '*.gemspec'
4
+ - 'Rakefile'
5
+ - 'bin/ddg.rb'
6
+ - 'spec/*/**'
7
+ - 'vendor/*'
8
+ - 'vendor/*/**'
9
+
10
+ Metrics/BlockLength:
11
+ Exclude:
12
+ - 'spec/**/*'
13
+
14
+ # This allows classes without a top-level
15
+ # documentation comment
16
+ Style/Documentation:
17
+ Enabled: false
@@ -0,0 +1 @@
1
+ 2.3.3
@@ -0,0 +1 @@
1
+ language: ruby
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2018-07-20
10
+ ### Added
11
+ - Korean translation from @pierceh89.
12
+
13
+ ### Changed
14
+ - Fix phrasing and spelling in German translation.
15
+
16
+ ### Removed
17
+ - Section about "changelog" vs "CHANGELOG".
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
6
+
7
+ gem 'simplecov', require: false, group: :test
@@ -0,0 +1,73 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ ddg (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.0)
10
+ byebug (10.0.2)
11
+ diff-lcs (1.3)
12
+ docile (1.3.0)
13
+ jaro_winkler (1.5.1)
14
+ json (2.1.0)
15
+ lazy_priority_queue (0.1.1)
16
+ mysql2 (0.5.2)
17
+ parallel (1.12.1)
18
+ parser (2.5.1.2)
19
+ ast (~> 2.4.0)
20
+ pg (1.0.0)
21
+ powerpack (0.1.2)
22
+ rainbow (3.0.0)
23
+ rake (10.5.0)
24
+ rgl (0.5.3)
25
+ lazy_priority_queue (~> 0.1.0)
26
+ stream (~> 0.5.0)
27
+ rspec (3.7.0)
28
+ rspec-core (~> 3.7.0)
29
+ rspec-expectations (~> 3.7.0)
30
+ rspec-mocks (~> 3.7.0)
31
+ rspec-core (3.7.1)
32
+ rspec-support (~> 3.7.0)
33
+ rspec-expectations (3.7.0)
34
+ diff-lcs (>= 1.2.0, < 2.0)
35
+ rspec-support (~> 3.7.0)
36
+ rspec-mocks (3.7.0)
37
+ diff-lcs (>= 1.2.0, < 2.0)
38
+ rspec-support (~> 3.7.0)
39
+ rspec-support (3.7.1)
40
+ rubocop (0.58.1)
41
+ jaro_winkler (~> 1.5.1)
42
+ parallel (~> 1.10)
43
+ parser (>= 2.5, != 2.5.1.1)
44
+ powerpack (~> 0.1)
45
+ rainbow (>= 2.2.2, < 4.0)
46
+ ruby-progressbar (~> 1.7)
47
+ unicode-display_width (~> 1.0, >= 1.0.1)
48
+ ruby-progressbar (1.9.0)
49
+ simplecov (0.16.1)
50
+ docile (~> 1.1)
51
+ json (>= 1.8, < 3)
52
+ simplecov-html (~> 0.10.0)
53
+ simplecov-html (0.10.2)
54
+ stream (0.5)
55
+ unicode-display_width (1.4.0)
56
+
57
+ PLATFORMS
58
+ ruby
59
+
60
+ DEPENDENCIES
61
+ bundler (~> 1.16)
62
+ byebug
63
+ ddg!
64
+ mysql2
65
+ pg
66
+ rake (~> 10.0)
67
+ rgl
68
+ rspec (~> 3.0)
69
+ rubocop
70
+ simplecov
71
+
72
+ BUNDLED WITH
73
+ 1.16.2
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Brandon Powers
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.
@@ -0,0 +1,190 @@
1
+ # Database Dependency Graph (DDG)
2
+
3
+ ![build-status](https://travis-ci.com/brandon-powers/ddg.svg?token=K9gDMpa56TyPTDdHanqY&branch=master)
4
+
5
+ **ddg** is a tool for building and manipulating database dependency graphs. Hence, the origin of the abbreviation.
6
+
7
+ The database dependency graph is defined as follows: a directed, acyclic graph (DAG) where nodes represent tables and edges represent dependencies based on foreign key constraint(s). It currently supports two behaviors:
8
+ 1. Determining the evaluation order and optionally performing a task on each node in the evaluation order.
9
+ 2. Generating an image file containing a graph diagram of the database dependency graph.
10
+
11
+ The data stores that **ddg** supports are the following:
12
+ - MySQL
13
+ - PostgreSQL
14
+ - Redshift
15
+
16
+ ## Installation
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem 'ddg'
22
+ ```
23
+
24
+ And then execute:
25
+
26
+ $ bundle install
27
+
28
+ Or install it yourself as:
29
+
30
+ $ gem install ddg
31
+
32
+ ## Usage
33
+
34
+ **To initialize a dependency graph**:
35
+
36
+ ```ruby
37
+ require 'dependency_graph'
38
+
39
+ graph = DependencyGraph.new(
40
+ adapter: :postgresql,
41
+ database: 'database',
42
+ user: 'user',
43
+ password: 'password',
44
+ port: 12345,
45
+ host: 'www.example.com'
46
+ )
47
+ ```
48
+
49
+ **To print the evaluation order**:
50
+
51
+ ```ruby
52
+ puts(graph.evaluation_order)
53
+
54
+ # >> [users, reports, user_reports]
55
+ ```
56
+
57
+ **To perform an action on each node, in the evaluation order**:
58
+
59
+ ```ruby
60
+ graph.evaluation_order do |node|
61
+ ETL.incremental_load(node)
62
+ end
63
+ ```
64
+
65
+ **To generate a graph.png image of the dependency graph**:
66
+
67
+ ```ruby
68
+ graph.visualize
69
+ ```
70
+
71
+ **To use the dependency graph with a CLI**:
72
+
73
+ ```sh
74
+ $ ddg -a postgresql -d dev -u dev_ro -x password123 -p 16379 -h dev.com --evaluation-order
75
+ # >> [users, reports, user_reports]
76
+ ```
77
+
78
+ **To use the dependency graph with a Rake command**:
79
+
80
+ ```sh
81
+ $ bundle exec rake ddg:evaluation_order
82
+ # >> [users, reports, user_reports]
83
+ ```
84
+
85
+ ## More on Adapters
86
+
87
+ In theory, any data store that supports the information schema (ANSI-standard) is supported by the existing SQL used to extract table to foreign key mappings. However, if a data store is not currently supported, an adapter can be written rather easily by creating a new class inheriting from `DDG::Adapter::Base`.
88
+
89
+ To add an adapter that supports the information schema:
90
+
91
+ ```ruby
92
+ # frozen_string_literal: true
93
+
94
+ require 'ddg/adapter/base'
95
+
96
+ module DDG
97
+ module Adapter
98
+ class DataStore < Base
99
+ # TODO: Implement the constructor by assigning a client to @db.
100
+ def initialize(config)
101
+ @db = DataStoreClient.new(
102
+ host: config[:host],
103
+ port: config[:port],
104
+ username: config[:user],
105
+ password: config[:password],
106
+ database: config[:database]
107
+ )
108
+ end
109
+
110
+ # TODO: Implement the select function, which executes
111
+ # the SQL contained in the `sql` parameter and
112
+ # returns an Array of Hashes, representing named rows.
113
+ def select(sql)
114
+ [{}]
115
+ end
116
+ end
117
+ end
118
+ end
119
+ ```
120
+
121
+ To add an adapter that does NOT support the information schema:
122
+
123
+ ```ruby
124
+ # frozen_string_literal: true
125
+
126
+ require 'ddg/adapter/base'
127
+
128
+ module DDG
129
+ module Adapter
130
+ class DataStore < Base
131
+ # TODO: Implement the constructor by assigning a client to @db.
132
+ def initialize(config)
133
+ @db = DataStoreClient.new
134
+ end
135
+
136
+ # TODO: Implement the following instance method.
137
+ #
138
+ # Retrieves a mapping from table to a
139
+ # set of its foreign key constraints.
140
+ #
141
+ # Example:
142
+ # {
143
+ # user_reports: [
144
+ # :users,
145
+ # :reports,
146
+ # ...
147
+ # ],
148
+ # ...
149
+ # }
150
+ #
151
+ # @return [Hash]
152
+ def tables_with_foreign_keys; end
153
+ end
154
+ end
155
+ end
156
+ ```
157
+
158
+ From the PostgreSQL documentation on information schema querying: "Only those constraints are shown for which the current user has write access to the referencing table (by way of being the owner or having some privilege other than SELECT)."
159
+
160
+ The SQL to extract the foreign keys of each table was heavily influenced, barring minor changes, from this article: https://msdn.microsoft.com/en-us/library/aa175805(SQL.80).aspx.
161
+
162
+ ## Contributing
163
+
164
+ Make sure to copy the `hooks/` directory into your local `.git/hooks/` directory to ensure the git hooks for this project run. Most notably, there exists a pre-commit hook that runs tests and a linter over the code, failing the commit if the tests or linter fails.
165
+
166
+ Bug reports and pull requests are welcome on GitHub at https://github.com/brandon-powers/ddg.
167
+
168
+ ## License
169
+
170
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
171
+
172
+ ## TODO
173
+ - Fix integration with Travis-CI.
174
+ - Write documentation on DDG in this README.
175
+ - Create a GIF at the top-level of the README to demonstrate basic usage and grab attention.
176
+ - Clearly define external development and testing dependencies.
177
+ - Tag gem at 0.1.0 and publish it to RubyGems.
178
+ - Write an example application that uses this gem, and highlight or link it in the documentation here.
179
+ - Write a blog post on DDG for Medium.
180
+ - Share blog post and GitHub project on HackerNews, LinkedIn, Twitter, Instagram?, Facebook, Personal Website?.
181
+
182
+ ## Architecture and Design Goals
183
+ - Duck-typing over abstract class hierarchy
184
+ - Adapter interface that is extensible
185
+ - Adapter Factory uses Factory OO pattern
186
+ - Both data warehouses/dimensional models and general-purpose usage, in any relational database
187
+ - Measured performance and benchmark testing
188
+ - CI/CD integration with Travis-CI
189
+ - Example application that uses this gem/functionality
190
+ - SemVer, CHANGELOG-compliant
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+ require 'rubocop/rake_task'
6
+ require 'ddg'
7
+ require 'pg'
8
+ require 'mysql2'
9
+
10
+ RSpec::Core::RakeTask.new(:spec) do |t|
11
+ t.verbose = false
12
+ t.rspec_opts = '--format documentation'
13
+ end
14
+
15
+ RuboCop::RakeTask.new(:rubocop) do |t|
16
+ t.options = ['--display-cop-names']
17
+ t.options = ['-c', '.rubocop.yml']
18
+ end
19
+
20
+ task(default: %i[spec rubocop])
21
+
22
+ namespace :ddg do
23
+ desc 'Print the evaluation order of the database specified by the environment'
24
+ task :evaluation_order do
25
+ ddg = DDG::DependencyGraph.new(
26
+ ENV['ADAPTER'].to_sym,
27
+ host: ENV['HOST'],
28
+ port: ENV['PORT'],
29
+ database: ENV['DATABASE'],
30
+ user: ENV['USER'],
31
+ password: ENV['PASSWORD']
32
+ )
33
+ puts(ddg.evaluation_order)
34
+ end
35
+ end
36
+
37
+ namespace :db do
38
+ namespace :setup do
39
+ desc 'Creates a PostgreSQL database with tables ' \
40
+ 'that have referential constraints on each other'
41
+ task :postgresql do
42
+ conn = PG.connect(
43
+ user: ENV['TEST_USER'],
44
+ host: ENV['TEST_HOST'],
45
+ port: ENV['TEST_PORT'],
46
+ dbname: ENV['TEST_DATABASE'],
47
+ password: ENV['TEST_PASSWORD']
48
+ )
49
+ postgresql_schema = File.read('db/schemata/postgresql.sql')
50
+ conn.exec(postgresql_schema)
51
+ end
52
+
53
+ desc 'Creates a MySQL database with tables ' \
54
+ 'that have referential constraints on each other'
55
+ task :mysql do
56
+ conn = Mysql2::Client.new(
57
+ username: ENV['TEST_USER'],
58
+ host: ENV['TEST_HOST'],
59
+ port: ENV['TEST_PORT'],
60
+ database: ENV['TEST_DATABASE'],
61
+ password: ENV['TEST_PASSWORD']
62
+ )
63
+ mysql_schema = File.read('db/schemata/mysql.sql')
64
+
65
+ mysql_schema.strip.split(';').each do |query|
66
+ conn.query(query)
67
+ end
68
+ end
69
+ end
70
+
71
+ namespace :teardown do
72
+ desc 'Deletes the PostgreSQL database created with db:setup:postgresql'
73
+ task :postgresql do
74
+ conn = PG.connect(
75
+ user: ENV['TEST_USER'],
76
+ host: ENV['TEST_HOST'],
77
+ port: ENV['TEST_PORT'],
78
+ dbname: ENV['TEST_DATABASE'],
79
+ password: ENV['TEST_PASSWORD']
80
+ )
81
+
82
+ conn.exec('DROP TABLE IF EXISTS user_reports CASCADE;')
83
+ conn.exec('DROP TABLE IF EXISTS users CASCADE;')
84
+ conn.exec('DROP TABLE IF EXISTS reports CASCADE;')
85
+ conn.close
86
+
87
+ drop_database_sql = "DROP DATABASE #{ENV['TEST_DATABASE']};"
88
+ drop_user_sql = "DROP USER #{ENV['TEST_USER']};"
89
+
90
+ system("sudo -u postgres psql -c \"#{drop_database_sql}\" 1>/dev/null 2>&1")
91
+ system("sudo -u postgres psql -c \"#{drop_user_sql}\" 1>/dev/null 2>&1")
92
+ end
93
+
94
+ desc 'Deletes the MySQL database created with db:setup:mysql'
95
+ task :mysql do
96
+ conn = Mysql2::Client.new(
97
+ username: ENV['TEST_USER'],
98
+ host: ENV['TEST_HOST'],
99
+ port: ENV['TEST_PORT'],
100
+ database: ENV['TEST_DATABASE'],
101
+ password: ENV['TEST_PASSWORD']
102
+ )
103
+
104
+ conn.query('DROP TABLE IF EXISTS user_reports CASCADE;')
105
+ conn.query('DROP TABLE IF EXISTS users CASCADE;')
106
+ conn.query('DROP TABLE IF EXISTS reports CASCADE;')
107
+ conn.close
108
+
109
+ drop_database_sql = "DROP DATABASE #{ENV['TEST_DATABASE']};"
110
+ drop_user_sql = "DROP USER '#{ENV['TEST_USER']}'@'#{ENV['TEST_HOST']}';"
111
+
112
+ system("sudo mysql -u root -p -e \"#{drop_database_sql}\" 1>/dev/null 2>&1")
113
+ system("sudo mysql -u root -p -e \"#{drop_user_sql}\" 1>/dev/null 2>&1")
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # frozen_string_literal: true
4
+
5
+ BASE_DIR = File.expand_path('lib', __dir__)
6
+ $LOAD_PATH.unshift(BASE_DIR) unless $LOAD_PATH.include?(BASE_DIR)
7
+
8
+ require 'ddg'
9
+ require 'optparse'
10
+
11
+ class CLI
12
+ def initialize
13
+ @config = {}
14
+ @actions = { evaluation_order: false }
15
+ @adapter = nil
16
+ @opts = option_parser
17
+ end
18
+
19
+ def option_parser
20
+ OptionParser.new do |o|
21
+ o.on('--help', 'Display this message') do
22
+ STDERR.puts(o)
23
+ exit 0
24
+ end
25
+
26
+ o.on('-a', '--adapter ADAPTER', String, 'Adapter') do |adapter|
27
+ @adapter = adapter.to_sym
28
+ end
29
+
30
+ o.on('-u', '--user USER', String, 'User') do |user|
31
+ @config[:user] = user.to_s
32
+ end
33
+
34
+ o.on('-W', '--password PASSWORD', String, 'Password') do |password|
35
+ @config[:password] = password.to_s
36
+ end
37
+
38
+ o.on('-p', '--port PORT', String, 'Port') do |port|
39
+ @config[:port] = port.to_s
40
+ end
41
+
42
+ o.on('-h', '--host HOST', String, 'Host') do |host|
43
+ @config[:host] = host.to_s
44
+ end
45
+
46
+ o.on('-d', '--database DATABASE', String, 'Database') do |database|
47
+ @config[:database] = database.to_s
48
+ end
49
+
50
+ evaluation_order_str = 'Print the evaluation order of the database ' \
51
+ 'dependency graph specified by the environment'
52
+
53
+ o.on('-e', '--evaluation-order', evaluation_order_str) do |evaluation_order|
54
+ @actions[:evaluation_order] = evaluation_order
55
+ end
56
+
57
+ o.on('-v', '--visualize FORMAT, FILENAME', Array, 'Generate a <filename>.<format> image file') do |visualize|
58
+ @config[:format] = visualize[0]
59
+ @config[:filename] = visualize[1]
60
+ end
61
+ end
62
+ end
63
+
64
+ def parse!(args)
65
+ @opts.parse!(args)
66
+
67
+ # TODO: These defaults should move to #initialize.
68
+ #
69
+ # Default to using environment variables,
70
+ # typically via .rbenv-vars.
71
+ @config[:host] = ENV['HOST']
72
+ @config[:port] = ENV['PORT']
73
+ @config[:user] = ENV['USER']
74
+ @config[:password] = ENV['PASSWORD']
75
+ @config[:database] = ENV['DATABASE']
76
+ @adapter = ENV['ADAPTER'].to_sym
77
+
78
+ graph = DDG::DependencyGraph.new(@adapter, @config)
79
+
80
+ puts(graph.evaluation_order) if @actions[:evaluation_order]
81
+ graph.visualize(@config[:format], @config[:filename]) if @config[:format] && @config[:filename]
82
+ end
83
+ end
84
+
85
+ cli = CLI.new
86
+ cli.parse!(ARGV)
@@ -0,0 +1,33 @@
1
+ CREATE TABLE IF NOT EXISTS `users` (
2
+ `id` INTEGER AUTO_INCREMENT,
3
+ `name` VARCHAR(150) NOT NULL,
4
+ `created_at` DATE,
5
+ `updated_at` DATE,
6
+
7
+ PRIMARY KEY (`id`)
8
+ )
9
+ ENGINE = InnoDB;
10
+
11
+ CREATE TABLE IF NOT EXISTS `reports` (
12
+ `id` INTEGER AUTO_INCREMENT,
13
+ `name` VARCHAR(150) NOT NULL,
14
+ `created_at` DATE,
15
+ `updated_at` DATE,
16
+
17
+ PRIMARY KEY (`id`)
18
+ )
19
+ ENGINE = InnoDB;
20
+
21
+ CREATE TABLE IF NOT EXISTS `user_reports` (
22
+ `id` INTEGER AUTO_INCREMENT,
23
+ `user_id` INTEGER,
24
+ `report_id` INTEGER,
25
+ `name` VARCHAR(150) NOT NULL,
26
+ `created_at` DATE,
27
+ `updated_at` DATE,
28
+
29
+ PRIMARY KEY (`id`),
30
+ FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
31
+ FOREIGN KEY (`report_id`) REFERENCES `reports` (`id`)
32
+ )
33
+ ENGINE = InnoDB;
@@ -0,0 +1,29 @@
1
+ CREATE TABLE users (
2
+ id INTEGER NOT NULL,
3
+ name VARCHAR,
4
+ created_at TIMESTAMP,
5
+ updated_at TIMESTAMP,
6
+
7
+ PRIMARY KEY(id)
8
+ );
9
+
10
+ CREATE TABLE reports (
11
+ id INTEGER NOT NULL,
12
+ name VARCHAR,
13
+ created_at TIMESTAMP,
14
+ updated_at TIMESTAMP,
15
+
16
+ PRIMARY KEY(id)
17
+ );
18
+
19
+ CREATE TABLE user_reports (
20
+ id INTEGER NOT NULL,
21
+ user_id INTEGER NOT NULL,
22
+ report_id INTEGER NOT NULL,
23
+ created_at TIMESTAMP,
24
+ updated_at TIMESTAMP,
25
+
26
+ PRIMARY KEY(id),
27
+ FOREIGN KEY (user_id) REFERENCES users(id),
28
+ FOREIGN KEY (report_id) REFERENCES reports(id)
29
+ );
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'ddg/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'ddg'
9
+ spec.version = DDG::VERSION
10
+ spec.authors = ['Brandon Powers']
11
+ spec.email = ['brandonkpowers@gmail.com']
12
+
13
+ spec.summary = 'DDG is a tool for building and ' \
14
+ 'manipulating database dependency graphs (DDG).'
15
+ spec.description = ''
16
+ spec.homepage = 'https://github.com/brandon-powers/ddg'
17
+ spec.license = 'MIT'
18
+
19
+ spec.files = `git ls-files`.split("\n")
20
+ spec.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
21
+ spec.require_paths = ['lib']
22
+
23
+ spec.bindir = 'bin'
24
+
25
+ spec.add_development_dependency 'bundler', '~> 1.16'
26
+ spec.add_development_dependency 'rake', '~> 10.0'
27
+
28
+ spec.add_development_dependency 'rgl'
29
+ spec.add_development_dependency 'pg'
30
+ spec.add_development_dependency 'mysql2'
31
+
32
+ spec.add_development_dependency 'rspec', '~> 3.0'
33
+ spec.add_development_dependency 'rubocop'
34
+ spec.add_development_dependency 'byebug'
35
+ end
@@ -0,0 +1,11 @@
1
+ ADAPTER=postgresql
2
+ USER=user
3
+ PASSWORD=password
4
+ DATABASE=database
5
+ HOST=host
6
+ PORT=port
7
+ TEST_USER=ddg_test_user
8
+ TEST_PASSWORD=ddg_test_password
9
+ TEST_DATABASE=ddg_test_db
10
+ TEST_HOST=localhost
11
+ TEST_PORT=5432
@@ -0,0 +1,3 @@
1
+ #!/bin/bash
2
+
3
+ bundle exec rake
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ddg/dependency_graph'
4
+ require 'ddg/version'
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DDG
4
+ module Adapter
5
+ class Base
6
+ # Retrieves a mapping from table to a
7
+ # set of its foreign key constraints.
8
+ #
9
+ # This query is supported by any relational
10
+ # database that supports the ANSI information
11
+ # schema standard.
12
+ #
13
+ # Example:
14
+ # {
15
+ # user_reports: [
16
+ # :users,
17
+ # :reports,
18
+ # ...
19
+ # ],
20
+ # ...
21
+ # }
22
+ #
23
+ # @return [Hash]
24
+ def tables_with_foreign_keys
25
+ records = select(foreign_key_sql)
26
+
27
+ records.each_with_object({}) do |record, table_to_fk|
28
+ table_name = record[:table_name].to_sym
29
+ referenced_table_name = record[:referenced_table_name].to_sym
30
+
31
+ table_to_fk[table_name] = [] unless table_to_fk.key?(table_name)
32
+
33
+ if !table_to_fk[table_name].include?(referenced_table_name) &&
34
+ table_name != referenced_table_name
35
+ table_to_fk[table_name] << referenced_table_name
36
+ end
37
+ end
38
+ end
39
+
40
+ private
41
+
42
+ def foreign_key_sql
43
+ <<~SQL
44
+ SELECT
45
+ kcu1.table_name AS table_name,
46
+ kcu2.table_name AS referenced_table_name
47
+ FROM information_schema.referential_constraints AS rc
48
+ INNER JOIN information_schema.key_column_usage AS kcu1
49
+ ON kcu1.constraint_catalog = rc.constraint_catalog
50
+ AND kcu1.constraint_schema = rc.constraint_schema
51
+ AND kcu1.constraint_name = rc.constraint_name
52
+ INNER JOIN information_schema.key_column_usage AS kcu2
53
+ ON kcu2.constraint_catalog = rc.unique_constraint_catalog
54
+ AND kcu2.constraint_schema = rc.unique_constraint_schema
55
+ AND kcu2.constraint_name = rc.unique_constraint_name
56
+ AND kcu2.ordinal_position = kcu1.ordinal_position
57
+ ;
58
+ SQL
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ddg/adapter/base'
4
+ require 'mysql2'
5
+ require 'json'
6
+
7
+ module DDG
8
+ module Adapter
9
+ class MySQL < Base
10
+ def initialize(config)
11
+ @db = Mysql2::Client.new(
12
+ host: config[:host],
13
+ port: config[:port],
14
+ username: config[:user],
15
+ password: config[:password],
16
+ database: config[:database]
17
+ )
18
+ end
19
+
20
+ def select(sql)
21
+ @db.query(sql).to_a.map do |row|
22
+ JSON.parse(row.to_json, symbolize_names: true)
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ddg/adapter/base'
4
+ require 'pg'
5
+ require 'json'
6
+
7
+ module DDG
8
+ module Adapter
9
+ class PostgreSQL < Base
10
+ def initialize(config)
11
+ @db = PG::Connection.open(
12
+ host: config[:host],
13
+ port: config[:port],
14
+ user: config[:user],
15
+ password: config[:password],
16
+ dbname: config[:database]
17
+ )
18
+ end
19
+
20
+ def select(sql)
21
+ @db.exec(sql).to_a.map do |row|
22
+ JSON.parse(row.to_json, symbolize_names: true)
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ddg/adapter/postgresql'
4
+ require 'ddg/adapter/mysql'
5
+
6
+ module DDG
7
+ class AdapterFactory
8
+ class << self
9
+ def adapter(adapter, config)
10
+ case adapter
11
+ when :postgresql, :redshift
12
+ Adapter::PostgreSQL.new(config)
13
+ when :mysql
14
+ Adapter::MySQL.new(config)
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ddg/adapter_factory'
4
+ require 'rgl/adjacency'
5
+ require 'rgl/topsort'
6
+ require 'rgl/dot'
7
+
8
+ module DDG
9
+ class DependencyGraph
10
+ attr_reader(
11
+ :adapter,
12
+ :graph
13
+ )
14
+
15
+ def initialize(adapter, config)
16
+ @adapter = AdapterFactory.adapter(adapter, config)
17
+ @graph = RGL::DirectedAdjacencyGraph.new
18
+ @evaluation_order = []
19
+ end
20
+
21
+ def evaluation_order
22
+ return @evaluation_order unless @evaluation_order.empty?
23
+ build_graph unless graph_built?
24
+
25
+ @evaluation_order = @graph.topsort_iterator.to_a.reverse
26
+ @evaluation_order.each { |table| yield(table) } if block_given?
27
+ @evaluation_order
28
+ end
29
+
30
+ def visualize(format, filename)
31
+ build_graph unless graph_built?
32
+ @graph.write_to_graphic_file(fmt = format, dotfile = filename)
33
+ end
34
+
35
+ def build_graph
36
+ @adapter.tables_with_foreign_keys.each do |table, foreign_keys|
37
+ foreign_keys.each do |foreign_key|
38
+ @graph.add_edge(table, foreign_key)
39
+ end
40
+ end
41
+ end
42
+
43
+ private
44
+
45
+ def graph_built?
46
+ !@graph.edges.empty? && !@graph.vertices.empty?
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DDG
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'ddg/adapter/mysql'
5
+
6
+ RSpec.describe DDG::Adapter::MySQL do
7
+ before(:all) do
8
+ system('bundle exec rake db:setup:mysql')
9
+ end
10
+
11
+ after(:all) do
12
+ system('bundle exec rake db:teardown:mysql')
13
+ end
14
+
15
+ let(:config) do
16
+ {
17
+ database: ENV['TEST_DATABASE'],
18
+ user: ENV['TEST_USER'],
19
+ host: ENV['TEST_HOST'],
20
+ port: ENV['TEST_PORT'],
21
+ password: ENV['TEST_PASSWORD']
22
+ }
23
+ end
24
+
25
+ describe '#tables_with_foreign_keys' do
26
+ context 'when there are tables with foreign keys in the database' do
27
+ let(:expected_table_to_fks) do
28
+ {
29
+ user_reports: %i[
30
+ reports
31
+ users
32
+ ]
33
+ }
34
+ end
35
+
36
+ it 'returns a mapping from table to an array of foreign keys' do
37
+ adapter = DDG::Adapter::MySQL.new(config)
38
+ table_to_fks = adapter.tables_with_foreign_keys
39
+ expect(table_to_fks).to eq(expected_table_to_fks)
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'ddg/adapter/postgresql'
5
+
6
+ RSpec.describe DDG::Adapter::PostgreSQL do
7
+ before(:all) do
8
+ system('bundle exec rake db:setup:postgresql')
9
+ end
10
+
11
+ after(:all) do
12
+ system('bundle exec rake db:teardown:postgresql')
13
+ end
14
+
15
+ let(:config) do
16
+ {
17
+ database: ENV['TEST_DATABASE'],
18
+ user: ENV['TEST_USER'],
19
+ host: ENV['TEST_HOST'],
20
+ port: ENV['TEST_PORT'],
21
+ password: ENV['TEST_PASSWORD']
22
+ }
23
+ end
24
+
25
+ describe '#tables_with_foreign_keys' do
26
+ context 'when there are tables with foreign keys in the database' do
27
+ let(:expected_table_to_fks) do
28
+ {
29
+ user_reports: %i[
30
+ users
31
+ reports
32
+ ]
33
+ }
34
+ end
35
+
36
+ it 'returns a mapping from table to an array of foreign keys' do
37
+ adapter = DDG::Adapter::PostgreSQL.new(config)
38
+ table_to_fks = adapter.tables_with_foreign_keys
39
+ expect(table_to_fks).to eq(expected_table_to_fks)
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'ddg/adapter_factory'
5
+
6
+ RSpec.describe DDG::AdapterFactory do
7
+ before(:all) do
8
+ system('bundle exec rake db:setup:postgresql')
9
+ system('bundle exec rake db:setup:mysql')
10
+ end
11
+
12
+ after(:all) do
13
+ system('bundle exec rake db:teardown:postgresql')
14
+ system('bundle exec rake db:teardown:mysql')
15
+ end
16
+
17
+ let(:config) do
18
+ {
19
+ database: ENV['TEST_DATABASE'],
20
+ user: ENV['TEST_USER'],
21
+ host: ENV['TEST_HOST'],
22
+ port: ENV['TEST_PORT'],
23
+ password: ENV['TEST_PASSWORD']
24
+ }
25
+ end
26
+
27
+ describe '::adapter' do
28
+ context 'when PostgreSQL is passed with valid configuration' do
29
+ it 'returns an instance of DDG::Adapter::PostgreSQL' do
30
+ adapter = DDG::AdapterFactory.adapter(:postgresql, config)
31
+ expect(adapter).to be_a(DDG::Adapter::PostgreSQL)
32
+ end
33
+ end
34
+
35
+ context 'when Redshift is passed with valid configuration' do
36
+ it 'returns an instance of DDG::Adapter::PostgreSQL' do
37
+ adapter = DDG::AdapterFactory.adapter(:redshift, config)
38
+ expect(adapter).to be_a(DDG::Adapter::PostgreSQL)
39
+ end
40
+ end
41
+
42
+ context 'when MySQL is passed with valid configuration' do
43
+ it 'returns an instance of DDG::Adapter::MySQL' do
44
+ adapter = DDG::AdapterFactory.adapter(:mysql, config)
45
+ expect(adapter).to be_a(DDG::Adapter::MySQL)
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'ddg/dependency_graph'
5
+
6
+ RSpec.describe DDG::DependencyGraph do
7
+ before(:all) do
8
+ system('bundle exec rake db:setup:postgresql')
9
+ system('bundle exec rake db:setup:mysql')
10
+ end
11
+
12
+ after(:all) do
13
+ system('bundle exec rake db:teardown:postgresql')
14
+ system('bundle exec rake db:teardown:mysql')
15
+ end
16
+
17
+ let(:adapter) { :postgresql }
18
+ let(:config) do
19
+ {
20
+ database: ENV['TEST_DATABASE'],
21
+ user: ENV['TEST_USER'],
22
+ host: ENV['TEST_HOST'],
23
+ port: ENV['TEST_PORT'],
24
+ password: ENV['TEST_PASSWORD']
25
+ }
26
+ end
27
+
28
+ describe '#initialize' do
29
+ context 'when given valid configuration' do
30
+ it 'initializes an instance of DependencyGraph' do
31
+ graph = DDG::DependencyGraph.new(adapter, config)
32
+ expect(graph).to be_a(DDG::DependencyGraph)
33
+ expect(graph.adapter).to be_a(DDG::Adapter::Base)
34
+ expect(graph.graph).to_not be_nil
35
+ end
36
+ end
37
+ end
38
+
39
+ describe '#evaluation_order' do
40
+ context 'when users, reports, and user_reports exist in a PostgreSQL database' do
41
+ it 'returns the correct evaluation order given referential constraints' do
42
+ graph = DDG::DependencyGraph.new(adapter, config)
43
+ expect(graph.evaluation_order).to eq(%i[users reports user_reports])
44
+ end
45
+ end
46
+
47
+ context 'when users, reports, and user_reports exist in a MySQL database' do
48
+ let(:adapter) { :mysql }
49
+
50
+ it 'returns the correct evaluation order given referential constraints' do
51
+ graph = DDG::DependencyGraph.new(adapter, config)
52
+ expect(graph.evaluation_order).to eq(%i[reports users user_reports])
53
+ end
54
+ end
55
+ end
56
+
57
+ describe '#build_graph' do
58
+ it 'builds the dependency graph' do
59
+ graph = DDG::DependencyGraph.new(adapter, config)
60
+ graph.build_graph
61
+ expect(graph.graph).to_not be_nil
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ RSpec.describe DDG do
6
+ it 'has a version number' do
7
+ expect(DDG::VERSION).not_to be nil
8
+ end
9
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'simplecov'
4
+ SimpleCov.start
5
+
6
+ require 'bundler/setup'
7
+ require 'ddg'
8
+
9
+ RSpec.configure do |config|
10
+ # Enable flags like --only-failures and --next-failure
11
+ config.example_status_persistence_file_path = '.rspec_status'
12
+
13
+ # Disable RSpec exposing methods globally on `Module` and `main`
14
+ config.disable_monkey_patching!
15
+
16
+ config.expect_with :rspec do |c|
17
+ c.syntax = :expect
18
+ end
19
+ end
metadata ADDED
@@ -0,0 +1,186 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ddg
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Brandon Powers
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-08-08 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.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
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: rgl
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pg
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
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: mysql2
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rubocop
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: byebug
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ description: ''
126
+ email:
127
+ - brandonkpowers@gmail.com
128
+ executables:
129
+ - ddg.rb
130
+ extensions: []
131
+ extra_rdoc_files: []
132
+ files:
133
+ - ".gitignore"
134
+ - ".rubocop.yml"
135
+ - ".ruby-version"
136
+ - ".travis.yml"
137
+ - CHANGELOG.md
138
+ - Gemfile
139
+ - Gemfile.lock
140
+ - LICENSE.txt
141
+ - README.md
142
+ - Rakefile
143
+ - bin/ddg.rb
144
+ - db/schemata/mysql.sql
145
+ - db/schemata/postgresql.sql
146
+ - ddg.gemspec
147
+ - dot-rbenv-vars
148
+ - hooks/pre-commit
149
+ - lib/ddg.rb
150
+ - lib/ddg/adapter/base.rb
151
+ - lib/ddg/adapter/mysql.rb
152
+ - lib/ddg/adapter/postgresql.rb
153
+ - lib/ddg/adapter_factory.rb
154
+ - lib/ddg/dependency_graph.rb
155
+ - lib/ddg/version.rb
156
+ - spec/ddg/adapter/mysql_spec.rb
157
+ - spec/ddg/adapter/postgresql_spec.rb
158
+ - spec/ddg/adapter_factory_spec.rb
159
+ - spec/ddg/dependency_graph_spec.rb
160
+ - spec/ddg_spec.rb
161
+ - spec/spec_helper.rb
162
+ homepage: https://github.com/brandon-powers/ddg
163
+ licenses:
164
+ - MIT
165
+ metadata: {}
166
+ post_install_message:
167
+ rdoc_options: []
168
+ require_paths:
169
+ - lib
170
+ required_ruby_version: !ruby/object:Gem::Requirement
171
+ requirements:
172
+ - - ">="
173
+ - !ruby/object:Gem::Version
174
+ version: '0'
175
+ required_rubygems_version: !ruby/object:Gem::Requirement
176
+ requirements:
177
+ - - ">="
178
+ - !ruby/object:Gem::Version
179
+ version: '0'
180
+ requirements: []
181
+ rubyforge_project:
182
+ rubygems_version: 2.6.14.1
183
+ signing_key:
184
+ specification_version: 4
185
+ summary: DDG is a tool for building and manipulating database dependency graphs (DDG).
186
+ test_files: []