db_vcs 1.0.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
+ SHA256:
3
+ metadata.gz: ad87a4ce6a39d924dfd4b7df99393d0379511b6034f38ef10be59e091b0bf847
4
+ data.tar.gz: 01d1173505e38a6abc7e9cceef3541fc13e338e4f90c0020e9b5f3ce35d452ea
5
+ SHA512:
6
+ metadata.gz: 6a90671b45f5d4c0069c01a37722f2224a0e655b3c3907a90cc255e2114f087e23d3c53a135b21fe6821ae188240f8f4cf9c52deb1416fb73c81dde74037ed39
7
+ data.tar.gz: 1952c97adeeb2134ed06b4ecde8036a3ed6adedee0634bf281e1e28a6fda120aa416e1707a3ddd8cd75a7d43fd4929e93290d8a19e6fdc267f9866209dd83c01
@@ -0,0 +1,9 @@
1
+ pg_config:
2
+ username: postgres
3
+ port: 5532
4
+ mongo_config:
5
+ mongo_uri: "mongodb://localhost:28017"
6
+ dbs_in_use:
7
+ <% DbVcs::Manager::ADAPTERS.keys.each do |adapter_name| %>
8
+ - <%= adapter_name %>
9
+ <% end %>
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format Fivemat
2
+ --require spec_helper
3
+ --require fivemat
data/.ruby-gemset ADDED
@@ -0,0 +1 @@
1
+ db_vcs
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ ruby-3.0.3
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ ## [Unreleased]
2
+
3
+ Nothing new yet
4
+
5
+ ## [1.0.0] - 2022-01-04
6
+
7
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at intale.a@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in db_vcs.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Ivan Dzyzenko
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,161 @@
1
+ # DbVcs
2
+
3
+ Makes it possible to version your local databases during development.
4
+
5
+ ## What is it for?
6
+
7
+ During the development, you need to handle several branches for several tickets at a time. This make the necessity to have correct database for each branch. For example, `branch1` add `table1.some_column` and `branch2` removes `table1.some_another_column`. When switching between `branch1` and `branch2` - you need to re-create databases, seed then, etc, to make your application work properly. This process may be annoying, especially for large projects with a ton of seeds.
8
+
9
+ ## How it works?
10
+
11
+ Integrating `db_vcs` helps you to have separated databases for each branch. It provides a tool to create a database for new branch with single command, based on a database you already have in main branch. No need to create/migrate/seed new database when switching between branches.
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application's Gemfile:
16
+
17
+ ```ruby
18
+ gem "db_vcs", require: "db_vcs/autoconfigure"
19
+ ```
20
+
21
+ And then execute:
22
+
23
+ $ bundle install
24
+
25
+ Or install it yourself as:
26
+
27
+ $ gem install db_vcs
28
+
29
+ `db_vcs` has its own command line tool - `db-vcs`. After installing a gem - you can run `db-vcs --help` in your terminal to see available options.
30
+
31
+ ## Configuration
32
+
33
+ `db_vcs` autoloads configuration from `.db_vcs.yml` file, placed under your project's root folder. The configuration loader supports ERB templating as well. Example:
34
+
35
+ ```yaml
36
+ environments: # The list of environments you want to use db_vcs gem for
37
+ - test
38
+ - development
39
+ db_basename: your_project_name # This name will be used as a prefix of all databases names, related to your project
40
+ dbs_in_use: # The list of databases you want to use db_vcs gem for
41
+ - mongo
42
+ - postgres
43
+ main_branch: main # The name of your main branch. When creating new database for new branch, this branch's database will be used as a source database
44
+ pg_config: # Configuration of PostgreSQL
45
+ host: localhost
46
+ port: '5432'
47
+ username: <%= ENV['PGUSER'] %>
48
+ password: postgres
49
+ mongo_config: # Configuration of Mongodb
50
+ mongodump_path: "/path/to/mongodump" # resolved automatically using which util. Override it otherwise
51
+ mongorestore_path: "/path/to/mongorestore" # resolved automatically using which util. Override it otherwise
52
+ mongo_uri: mongodb://localhost:27017
53
+ ```
54
+
55
+ Notices:
56
+
57
+ - to be able to use MongoDB - you need to have "mongo" gem installed
58
+ - to be able to use MongoDB - you need to have [MongoDB Database Tools](https://docs.mongodb.com/database-tools/) installed
59
+ - to be able to use PostgreSQL - you need to have "pg" gem installed
60
+
61
+ ## Usage
62
+
63
+ **WARNING!** This gem should be used **only** locally - its architecture isn't supposed the usage of it in production environment.
64
+
65
+ - Create configuration file `.db_vcs.yml` in your project's root folder.
66
+ - Edit your `database.yml`/`mongoid.yml`/any other config file and change database name to `DbVcs::Utils.db_name(env, DbVcs::Utils.current_branch)`. It will allow `db_vcs` gem correctly calculate database name for each branch/environment.
67
+
68
+ Example of `database.yml`:
69
+
70
+ ```yaml
71
+ development:
72
+ adapter: postgresql
73
+ prepared_statements: false
74
+ encoding: utf8
75
+ username: postgres
76
+ port: 5432
77
+ database: <%= DbVcs::Utils.db_name("development", DbVcs::Utils.current_branch) %>
78
+ test:
79
+ adapter: postgresql
80
+ prepared_statements: false
81
+ encoding: utf8
82
+ username: postgres
83
+ port: 5432
84
+ database: <%= DbVcs::Utils.db_name("test", DbVcs::Utils.current_branch) %>
85
+ ```
86
+
87
+ Example of `mongoid.yml`:
88
+
89
+ ```yaml
90
+ development:
91
+ clients:
92
+ default:
93
+ database: <%= DbVcs::Utils.db_name("development", DbVcs::Utils.current_branch) %>
94
+ hosts:
95
+ - localhost:27017
96
+ test:
97
+ clients:
98
+ default:
99
+ database: <%= DbVcs::Utils.db_name("test", DbVcs::Utils.current_branch) %>
100
+ hosts:
101
+ - localhost:27017
102
+ ```
103
+
104
+ - Create DbVcs-friendly databases. You can skip this step if you want to create databases in your own. Switch into you main branch, and run:
105
+
106
+ ```shell
107
+ bundle exec db-vcs init
108
+ ```
109
+
110
+ - Now, run commands to load your db structure and populate it with test data. In rails you would usually want to run `rails db:schema:load && rails db:seed`.
111
+
112
+ Done! The databases for your main branch are setup. Now, when switching into new branch, you can create the database for it just with a single command:
113
+
114
+ ```
115
+ bundle exec db-vcs create
116
+ ```
117
+
118
+ ## git-checkout integration
119
+
120
+ You may want to add git hook that, when switching between branches:
121
+
122
+ - will inform you about databases existence
123
+ - restart processes, such as puma server, to apply new database settings
124
+
125
+ To do so, create `.git/hooks/post-checkout` file(if you don't have it yet) and make it executable:
126
+
127
+ ```shell
128
+ touch .git/hooks/post-checkout
129
+ chmod +x .git/hooks/post-checkout
130
+ ```
131
+
132
+ Example of file's content:
133
+
134
+ ```shell
135
+ #!/bin/bash
136
+
137
+ # Comparison with third argument is needed to detect whether the checkout is related to the switching between branches. In this case third argument equals to 1.
138
+ if [ $3 -eq 1 ]
139
+ then
140
+ bundle exec db-vcs check
141
+ bundle exec pumactl -C config/puma.rb restart
142
+ fi
143
+ ```
144
+
145
+ ## Development
146
+
147
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment. Interactive console and tests require all, supported by DbVcs gem, databases to be installed and run. You can do it by running docker with `bin/start-docker` command.
148
+
149
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
150
+
151
+ ## Contributing
152
+
153
+ Bug reports and pull requests are welcome on GitHub at https://github.com/intale/db_vcs. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/intale/db_vcs/blob/master/CODE_OF_CONDUCT.md).
154
+
155
+ ## License
156
+
157
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
158
+
159
+ ## Code of Conduct
160
+
161
+ Everyone interacting in the DbVcs project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/intale/db_vcs/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ task default: %i[]
data/bin/console ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "db_vcs/autoconfigure"
6
+ require_relative "../spec/support/db_helper"
7
+
8
+ DbHelper.pre_create_all("development", DbVcs::Utils.current_branch)
9
+
10
+ require "irb"
11
+ 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
data/bin/start-docker ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "db_vcs/autoconfigure"
6
+
7
+ pg_user = DbVcs.config.pg_config.username
8
+ pg_port = DbVcs.config.pg_config.port
9
+ mongo_port = URI.parse(DbVcs.config.mongo_config.mongo_uri).port
10
+
11
+ pid = Kernel.spawn(
12
+ { "PGUSER" => pg_user.to_s, "PG_PORT" => pg_port.to_s, "MONGO_PORT" => mongo_port.to_s }, "docker-compose up 1>&2",
13
+ close_others: true
14
+ )
15
+ Process.waitpid(pid)
data/db_vcs.gemspec ADDED
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/db_vcs/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "db_vcs"
7
+ spec.version = DbVcs::VERSION
8
+ spec.authors = ["Ivan Dzyzenko"]
9
+ spec.email = ["ivan.dzyzenko@gmail.com"]
10
+
11
+ spec.summary = "Database versions control."
12
+ spec.description = "Have a separate database for each git branch!"
13
+ spec.homepage = "https://github.com/intale/db_vcs"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.4.0"
16
+
17
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/intale/vcs_db/tree/v#{spec.version}"
21
+ spec.metadata["changelog_uri"] = "https://github.com/intale/vcs_db/blob/v#{spec.version}/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
28
+ end
29
+ end
30
+ spec.bindir = "exe"
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+ spec.require_paths = ["lib"]
33
+
34
+ spec.add_development_dependency "pg", "~> 1.2"
35
+ spec.add_development_dependency "mongo", "~> 2.17"
36
+ spec.add_development_dependency "rspec", "~> 3.10"
37
+ spec.add_development_dependency "rspec-its", "~> 1.3"
38
+ spec.add_development_dependency "fivemat", "~> 1.3"
39
+ spec.add_development_dependency "rake", "~> 13.0"
40
+ spec.add_development_dependency "fakefs", "~> 1.4"
41
+ end
@@ -0,0 +1,23 @@
1
+ version: "3.9"
2
+
3
+ services:
4
+ db:
5
+ image: postgres:14
6
+ environment:
7
+ - PGUSER=${PGUSER}
8
+ - POSTGRES_HOST_AUTH_METHOD=trust
9
+ volumes:
10
+ - pg_db:/var/lib/postgresql/data
11
+ ports:
12
+ - ${PG_PORT}:5432
13
+
14
+ mongodb:
15
+ image: mongo:latest
16
+ volumes:
17
+ - mongo_db:/data/db
18
+ ports:
19
+ - ${MONGO_PORT}:27017
20
+
21
+ volumes:
22
+ mongo_db:
23
+ pg_db:
data/exe/db-vcs ADDED
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "db_vcs/autoconfigure"
5
+ require "optparse"
6
+
7
+ source_branch = DbVcs.config.main_branch
8
+ force = false
9
+
10
+ opt_parser = OptionParser.new do |parser|
11
+ parser.banner = <<~TEXT
12
+ Usage: db-vcs [command] [options]
13
+
14
+ Pre-create databases, suitable for usage with db_vcs gem. This will create empty databases:
15
+ db-vcs init
16
+ Checks databases existence and warns you if they miss
17
+ db-vcs check
18
+ Create databases for current branch, based on main branch:
19
+ db-vcs create
20
+ Create databases for current branch, based on a branch, defined by --source-branch option:
21
+ db-vcs create --source-branch=some_branch
22
+ Drop databases of current branch. By default you can not drop the databases of main branch (defined by config.main_branch):
23
+ db-vcs drop
24
+ Force drop databases of current branch:
25
+ db-vcs drop --force
26
+ Drop databases that don't have related branches.
27
+ db-vcs cleanup
28
+
29
+ TEXT
30
+
31
+ parser.on(
32
+ "-bBRANCH_NAME",
33
+ "--source-branch=BRANCH_NAME",
34
+ "Set the branch name to create databases from. Default value is a value of config.main_branch config option."
35
+ ) do |branch_name|
36
+ source_branch = branch_name
37
+ end
38
+
39
+ parser.on("-f", "--force", "Force the action. The effect depends on a command being executed.") do
40
+ force = true
41
+ end
42
+
43
+ parser.on("-h", "--help", "Prints this help") do
44
+ puts parser
45
+ exit
46
+ end
47
+ end
48
+
49
+ args = ARGV.dup
50
+ opt_parser.parse!(args)
51
+ command = args[0]
52
+
53
+ case command
54
+ when "create"
55
+ DbVcs::Manager.copy_for_all_envs(target: DbVcs::Utils.current_branch, source: source_branch)
56
+ when "drop"
57
+ if DbVcs::Utils.current_branch == DbVcs.config.main_branch && !force
58
+ puts "Databases of main branch(#{DbVcs.config.main_branch}) can't be dropped. Use --force option if you would like to do it."
59
+ else
60
+ DbVcs::Manager.drop_for_all_envs(DbVcs::Utils.current_branch)
61
+ end
62
+ when "cleanup"
63
+ databases_to_keep = DbVcs::Utils.git_branches.flat_map do |br|
64
+ DbVcs.config.environments.map do |env|
65
+ DbVcs::Utils.db_name(env, br)
66
+ end
67
+ end
68
+ DbVcs.config.dbs_in_use.each do |adapter_name|
69
+ manager = DbVcs::Manager.new(adapter_name)
70
+ manager.adapter.list_databases.each do |db_name|
71
+ next if databases_to_keep.include?(db_name)
72
+ next unless db_name.start_with?(DbVcs::Utils.normalize_db_part(DbVcs.config.db_basename))
73
+
74
+ manager.drop(db_name)
75
+ end
76
+ end
77
+ when "init"
78
+ DbVcs.config.dbs_in_use.each do |adapter_name|
79
+ inst = DbVcs::Manager.new(adapter_name)
80
+ DbVcs.config.environments.each do |env|
81
+ inst.create(DbVcs::Utils.db_name(env, DbVcs::Utils.current_branch))
82
+ end
83
+ end
84
+ when "check"
85
+ DbVcs.config.dbs_in_use.each do |adapter_name|
86
+ inst = DbVcs::Manager.new(adapter_name)
87
+ DbVcs.config.environments.each do |env|
88
+ db_name = DbVcs::Utils.db_name(env, DbVcs::Utils.current_branch)
89
+ unless inst.adapter.db_exists?(db_name)
90
+ inst.failure("#{db_name} does not exist! Run 'bundle exec db-vcs create' to create it.")
91
+ end
92
+ end
93
+ end
94
+ else
95
+ puts opt_parser.help
96
+ end
97
+
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DbVcs
4
+ module AdapterInterface
5
+ def config
6
+ raise NotImplementedError, "You have to implement this method in adapter's class"
7
+ end
8
+
9
+ def connection
10
+ raise NotImplementedError, "You have to implement this method in adapter's class"
11
+ end
12
+
13
+ def db_exists?(db_name)
14
+ raise NotImplementedError, "You have to implement this method in adapter's class"
15
+ end
16
+
17
+ def copy_database(to_db, from_db)
18
+ raise NotImplementedError, "You have to implement this method in adapter's class"
19
+ end
20
+
21
+ def create_database(db_name)
22
+ raise NotImplementedError, "You have to implement this method in adapter's class"
23
+ end
24
+
25
+ def list_databases
26
+ raise NotImplementedError, "You have to implement this method in adapter's class"
27
+ end
28
+
29
+ def drop_by_dbname(db_name)
30
+ raise NotImplementedError, "You have to implement this method in adapter's class"
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DbVcs
4
+ module Adapters
5
+ class Mongo
6
+ class Config
7
+ include DbVcs::ConfigAttributes
8
+
9
+ # Path to mongodump util. It is resolved automatically.
10
+ attr_accessor :mongodump_path
11
+ # Path to mongorestore util. It is resolved automatically.
12
+ attr_accessor :mongorestore_path
13
+ # Mongodb connection uri. Defaults to "mongodb://localhost:27017".
14
+ # See https://docs.mongodb.com/manual/reference/connection-string/ for more info.
15
+ attr_accessor :mongo_uri
16
+
17
+ def initialize
18
+ @mongodump_path = Utils.resolve_exec_path("mongodump")
19
+ @mongorestore_path = Utils.resolve_exec_path("mongorestore")
20
+ @mongo_uri = "mongodb://localhost:27017"
21
+ end
22
+ end
23
+
24
+ class << self
25
+ include DbVcs::AdapterInterface
26
+
27
+ # @return [DbVcs::Adapters::Mongo::Config]
28
+ def config
29
+ DbVcs.config.mongo_config
30
+ end
31
+
32
+ # @return [Mongo::Client]
33
+ def connection
34
+ @connection ||=
35
+ begin
36
+ require "mongo"
37
+ ::Mongo::Client.new(config.mongo_uri)
38
+ end
39
+ end
40
+
41
+ # @param db_name [String]
42
+ # @return [Boolean]
43
+ def db_exists?(db_name)
44
+ list_databases.include?(db_name)
45
+ end
46
+
47
+ # @param to_db [String]
48
+ # @param from_db [String]
49
+ # @return void
50
+ def copy_database(to_db, from_db)
51
+ command =
52
+ <<~SH
53
+ #{config.mongodump_path} #{config.mongo_uri} --db="#{from_db}" --archive --quiet \
54
+ | #{config.mongorestore_path} #{config.mongo_uri} --archive --quiet --nsFrom='#{from_db}.*' --nsTo='#{to_db}.*'
55
+ SH
56
+ `#{command}`
57
+ end
58
+
59
+ # @param db_name [String]
60
+ # @return void
61
+ def create_database(db_name)
62
+ # Mongodb databases should contain at least one collection
63
+ connection.use(db_name).database.collection("_db_vcs").insert_one(_db_vcs: 1)
64
+ end
65
+
66
+ # @return [Array<String>]
67
+ def list_databases
68
+ connection.database_names
69
+ end
70
+
71
+ # @param db_name [String]
72
+ # @return [void]
73
+ def drop_by_dbname(db_name)
74
+ connection.use(db_name).database.drop
75
+ end
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DbVcs
4
+ module Adapters
5
+ class Postgres
6
+ class Config
7
+ include DbVcs::ConfigAttributes
8
+
9
+ attr_accessor :host, :port, :username, :password
10
+
11
+ def initialize
12
+ @host = "localhost"
13
+ @port = "5432"
14
+ @username = "postgres"
15
+ @password = nil
16
+ end
17
+ end
18
+
19
+ class << self
20
+ include DbVcs::AdapterInterface
21
+
22
+ # @return [DbVcs::Adapters::Postgres::Config]
23
+ def config
24
+ DbVcs.config.pg_config
25
+ end
26
+
27
+ # @return [PG::Connection]
28
+ def connection
29
+ @connection ||=
30
+ begin
31
+ require "pg"
32
+ PG.connect(user: config.username, host: config.host, port: config.port, password: config.password)
33
+ end
34
+ end
35
+
36
+ # @param db_name [String]
37
+ # @return [Boolean]
38
+ def db_exists?(db_name)
39
+ !connection.exec("SELECT 1 AS one FROM pg_database WHERE datname='#{db_name}' LIMIT 1").first.nil?
40
+ end
41
+
42
+ # @param to_db [String]
43
+ # @param from_db [String]
44
+ # @return void
45
+ def copy_database(to_db, from_db)
46
+ connection.exec("CREATE DATABASE #{to_db} TEMPLATE #{from_db} OWNER #{config.username}")
47
+ end
48
+
49
+ # @param db_name [String]
50
+ # @return void
51
+ def create_database(db_name)
52
+ connection.exec("CREATE DATABASE #{db_name} OWNER #{config.username}")
53
+ end
54
+
55
+ # @return [Array<String>]
56
+ def list_databases
57
+ connection.exec("SELECT datname FROM pg_database WHERE datistemplate = false").to_a.flat_map(&:values)
58
+ end
59
+
60
+ # @param db_name [String]
61
+ # @return [void]
62
+ def drop_by_dbname(db_name)
63
+ connection.exec("DROP DATABASE IF EXISTS #{db_name}")
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,3 @@
1
+ require "db_vcs"
2
+
3
+ DbVcs.load_config
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DbVcs
4
+ class Config
5
+ include DbVcs::ConfigAttributes
6
+
7
+ # Environments you want to create database versions for. Default is ["development", "test"].
8
+ attr_accessor :environments
9
+ # This name will be used as a prefix to all your databases in a project.
10
+ attr_accessor :db_basename
11
+ # A list of databases you want to enable versioning for. See {DbVcs::Manager::ADAPTERS} keys for the list of
12
+ # available values. Defaults to empty array.
13
+ attr_accessor :dbs_in_use
14
+ # Configuration of dbs clients.
15
+ attr_reader :pg_config, :mongo_config
16
+ # A name of branch to be used as a default branch to copy databases from.
17
+ attr_accessor :main_branch
18
+
19
+ def initialize
20
+ @environments = %w(development test)
21
+ @dbs_in_use = []
22
+ @db_basename = Dir.pwd.split(File::SEPARATOR).last
23
+ @main_branch = "main"
24
+ @pg_config = DbVcs::Adapters::Postgres::Config.new
25
+ @mongo_config = DbVcs::Adapters::Mongo::Config.new
26
+ end
27
+
28
+ # @param hash [Hash]
29
+ # @return [void]
30
+ def pg_config=(hash)
31
+ pg_config.assign_attributes(hash)
32
+ end
33
+
34
+ # @param hash [Hash]
35
+ # @return [void]
36
+ def mongo_config=(hash)
37
+ mongo_config.assign_attributes(hash)
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DbVcs
4
+ module ConfigAttributes
5
+ # Assigns config attributes from hash.
6
+ # @param hash [Hash]
7
+ # Example:
8
+ # {
9
+ # environments: ["development"],
10
+ # pg_config: {
11
+ # port: 5433
12
+ # }
13
+ # }
14
+ # @return [void]
15
+ def assign_attributes(hash)
16
+ hash.each do |k, v|
17
+ if public_methods(false).include?(:"#{k}=")
18
+ public_send(:"#{k}=", v)
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DbVcs
4
+ class Manager
5
+ ADAPTERS = { "postgres" => DbVcs::Adapters::Postgres, "mongo" => DbVcs::Adapters::Mongo }.freeze
6
+
7
+ class << self
8
+ # @param adapter_name [String]
9
+ # @return [Class<DbVcs::Adapters::Postgres>, Class<DbVcs::Adapters::Mongo>]
10
+ # @raise [NotImplementedError] in case if no adapter is found
11
+ def get_adapter_by_name(adapter_name)
12
+ ADAPTERS[adapter_name] || raise(NotImplementedError, "No adapter for `#{adapter_name}' is implemented.")
13
+ end
14
+
15
+ # Creates databases for target branch from source branch for all setup environments for all setup databases
16
+ # @param :target [String] target branch name
17
+ # @param :source [String] a branch name to copy the db from
18
+ # @return [void]
19
+ def copy_for_all_envs(target:, source: DbVcs.config.main_branch)
20
+ DbVcs.config.dbs_in_use.each do |adapter_name|
21
+ inst = new(adapter_name)
22
+ DbVcs.config.environments.each do |env|
23
+ inst.copy(target: DbVcs::Utils.db_name(env, target), source: DbVcs::Utils.db_name(env, source))
24
+ end
25
+ end
26
+ end
27
+
28
+ # Drops databases of given branch name for all environments for all setup databases
29
+ # @param branch_name [String]
30
+ def drop_for_all_envs(branch_name)
31
+ DbVcs.config.dbs_in_use.each do |adapter_name|
32
+ inst = new(adapter_name)
33
+ DbVcs.config.environments.each do |env|
34
+ inst.drop(DbVcs::Utils.db_name(env, branch_name))
35
+ end
36
+ end
37
+ end
38
+ end
39
+
40
+ attr_reader :adapter, :adapter_name
41
+
42
+ # @param adapter_name [String]
43
+ def initialize(adapter_name)
44
+ @adapter_name = adapter_name
45
+ @adapter = self.class.get_adapter_by_name(adapter_name)
46
+ end
47
+
48
+ # @param :target [String] new database name
49
+ # @param :source [String] database name to create a new db from
50
+ # @return [void]
51
+ def copy(target:, source:)
52
+ unless adapter.db_exists?(source)
53
+ return failure "#{source}' doesn't exist"
54
+ end
55
+ if adapter.db_exists?(target)
56
+ return failure "#{target} already exists"
57
+ end
58
+ success "Copying #{source} -> #{target}"
59
+ adapter.copy_database(target, source)
60
+ end
61
+
62
+ # @param db_name [String]
63
+ # @return [void]
64
+ def drop(db_name)
65
+ unless adapter.db_exists?(db_name)
66
+ return failure "#{db_name}' doesn't exist"
67
+ end
68
+ adapter.drop_by_dbname(db_name)
69
+ success "Database #{db_name} was dropped successfully"
70
+ end
71
+
72
+ # @param db_name [String]
73
+ # @return [void]
74
+ def create(db_name)
75
+ if adapter.db_exists?(db_name)
76
+ return failure "#{db_name}' already exist"
77
+ end
78
+ adapter.create_database(db_name)
79
+ success "Database #{db_name} created successfully"
80
+ end
81
+
82
+ # @param text [String, nil]
83
+ # @return void
84
+ def message(text)
85
+ "#{adapter_name.capitalize} :: #{text}"
86
+ end
87
+
88
+ # @param text [String, nil]
89
+ # @return void
90
+ def success(text)
91
+ puts "\e[1m\e[32m#{message(text)}\e[0m\e[0m"
92
+ end
93
+
94
+ # @param text [String, nil]
95
+ # @return void
96
+ def failure(text)
97
+ puts "\e[1m\e[31m#{message(text)}\e[0m\e[0m"
98
+ end
99
+
100
+ # @param text [String, nil]
101
+ # @return void
102
+ def regular(text)
103
+ puts message(text)
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DbVcs
4
+ module Utils
5
+ class << self
6
+ # @return [String] current branch name
7
+ def current_branch
8
+ `git rev-parse --abbrev-ref HEAD`.chomp
9
+ end
10
+
11
+ # @return [Array<String>] array of local branches names
12
+ def git_branches
13
+ `git for-each-ref refs/heads --format='%(refname:short)'`.scan(/[[:graph:]]+/)
14
+ end
15
+
16
+ # Generate db name, based on branch name and environment.
17
+ # @param environment [String] application's environment name. E.g. "development", "test"
18
+ # @param branch [String]
19
+ # @return [String]
20
+ def db_name(environment, branch)
21
+ [DbVcs.config.db_basename, environment, branch].map do |str|
22
+ normalize_db_part(str)
23
+ end.join("_")
24
+ end
25
+
26
+ # Removes special characters from string that is used as a part of database name
27
+ # @param str [String]
28
+ # @return [String]
29
+ def normalize_db_part(str)
30
+ str.gsub(/[\W]/, "_")
31
+ end
32
+
33
+ # @param exec [String] a name of executable
34
+ # @param fallback_exec [String] a name of executable to fallback to if exec was not resolved
35
+ # @return [String] path to executable
36
+ def resolve_exec_path(exec, fallback_exec: nil)
37
+ path = `which #{exec}`.chomp
38
+ return resolve_exec_path(fallback_exec) if fallback_exec && path.empty?
39
+
40
+ path.empty? ? exec : path
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DbVcs
4
+ VERSION = "1.0.0"
5
+ end
data/lib/db_vcs.rb ADDED
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "yaml"
5
+ require "erb"
6
+ require_relative "db_vcs/config_attributes"
7
+ require_relative "db_vcs/config"
8
+ require_relative "db_vcs/adapter_interface"
9
+ require_relative "db_vcs/adapters/mongo"
10
+ require_relative "db_vcs/adapters/postgres"
11
+ require_relative "db_vcs/utils"
12
+ require_relative "db_vcs/manager"
13
+ require_relative "db_vcs/version"
14
+
15
+ module DbVcs
16
+ class Error < StandardError; end
17
+
18
+ class << self
19
+ # @return [DbVcs::Config]
20
+ def config
21
+ @config ||= DbVcs::Config.new
22
+ end
23
+
24
+ def configure
25
+ yield config
26
+ end
27
+
28
+ def load_config
29
+ config_path = File.join(Dir.pwd, ".db_vcs.yml")
30
+ if File.exists?(config_path)
31
+ config.assign_attributes(YAML.load(ERB.new(File.read(config_path)).result))
32
+ end
33
+ end
34
+ end
35
+ end
metadata ADDED
@@ -0,0 +1,172 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: db_vcs
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Ivan Dzyzenko
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-01-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: pg
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.2'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.2'
27
+ - !ruby/object:Gem::Dependency
28
+ name: mongo
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.17'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.17'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.10'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.10'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec-its
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.3'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.3'
69
+ - !ruby/object:Gem::Dependency
70
+ name: fivemat
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '1.3'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '1.3'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rake
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '13.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '13.0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: fakefs
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '1.4'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '1.4'
111
+ description: Have a separate database for each git branch!
112
+ email:
113
+ - ivan.dzyzenko@gmail.com
114
+ executables:
115
+ - db-vcs
116
+ extensions: []
117
+ extra_rdoc_files: []
118
+ files:
119
+ - ".db_vcs.yml.sample"
120
+ - ".rspec"
121
+ - ".ruby-gemset"
122
+ - ".ruby-version"
123
+ - CHANGELOG.md
124
+ - CODE_OF_CONDUCT.md
125
+ - Gemfile
126
+ - LICENSE.txt
127
+ - README.md
128
+ - Rakefile
129
+ - bin/console
130
+ - bin/setup
131
+ - bin/start-docker
132
+ - db_vcs.gemspec
133
+ - docker-compose.yml
134
+ - exe/db-vcs
135
+ - lib/db_vcs.rb
136
+ - lib/db_vcs/adapter_interface.rb
137
+ - lib/db_vcs/adapters/mongo.rb
138
+ - lib/db_vcs/adapters/postgres.rb
139
+ - lib/db_vcs/autoconfigure.rb
140
+ - lib/db_vcs/config.rb
141
+ - lib/db_vcs/config_attributes.rb
142
+ - lib/db_vcs/manager.rb
143
+ - lib/db_vcs/utils.rb
144
+ - lib/db_vcs/version.rb
145
+ homepage: https://github.com/intale/db_vcs
146
+ licenses:
147
+ - MIT
148
+ metadata:
149
+ allowed_push_host: https://rubygems.org
150
+ homepage_uri: https://github.com/intale/db_vcs
151
+ source_code_uri: https://github.com/intale/vcs_db/tree/v1.0.0
152
+ changelog_uri: https://github.com/intale/vcs_db/blob/v1.0.0/CHANGELOG.md
153
+ post_install_message:
154
+ rdoc_options: []
155
+ require_paths:
156
+ - lib
157
+ required_ruby_version: !ruby/object:Gem::Requirement
158
+ requirements:
159
+ - - ">="
160
+ - !ruby/object:Gem::Version
161
+ version: 2.4.0
162
+ required_rubygems_version: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ requirements: []
168
+ rubygems_version: 3.3.5
169
+ signing_key:
170
+ specification_version: 4
171
+ summary: Database versions control.
172
+ test_files: []