activerecord-dbsnapshot 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
+ SHA256:
3
+ metadata.gz: 54a0b9a73c7af8b2c2f02e7b6a15b476ce11544309d3e293f4078fdbf468bdc6
4
+ data.tar.gz: 4854a6d9eff890a5f9bd01f0d67422eba4620fc027bb8bd9bb9a0373dddc9115
5
+ SHA512:
6
+ metadata.gz: 74857122ff508b761901ea8020826c1bd5831f8e4247a61d4d4bdc091d52ab45838116dc6b4666043a0869f3c0a7fca027f0823943d802b6542c6a1749719a90
7
+ data.tar.gz: 79d48c80d7880338520575b9dda121b9a21c1a6974c689fb3c9f73cacfcb739d43e20711533897582e39f4e7463713351cac3bef982c362256e1f284ac7919a5
data/.idea/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
@@ -0,0 +1,22 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="RUBY_MODULE" version="4">
3
+ <component name="ModuleRunConfigurationManager">
4
+ <shared />
5
+ </component>
6
+ <component name="NewModuleRootManager">
7
+ <content url="file://$MODULE_DIR$">
8
+ <sourceFolder url="file://$MODULE_DIR$/features" isTestSource="true" />
9
+ <sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
10
+ <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
11
+ </content>
12
+ <orderEntry type="inheritedJdk" />
13
+ <orderEntry type="sourceFolder" forTests="false" />
14
+ <orderEntry type="library" scope="PROVIDED" name="bundler (v2.3.26, RVM: ruby-3.1.4 [global]) [gem]" level="application" />
15
+ <orderEntry type="library" scope="PROVIDED" name="rake (v13.0.6, RVM: ruby-3.1.4 [global]) [gem]" level="application" />
16
+ </component>
17
+ <component name="RakeTasksCache">
18
+ <option name="myRootTask">
19
+ <RakeTaskImpl id="rake" />
20
+ </option>
21
+ </component>
22
+ </module>
data/.idea/misc.xml ADDED
@@ -0,0 +1,4 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectRootManager" version="2" project-jdk-name="RVM: ruby-3.1.4 [global]" project-jdk-type="RUBY_SDK" />
4
+ </project>
data/.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/activerecord-dbsnapshot.iml" filepath="$PROJECT_DIR$/.idea/activerecord-dbsnapshot.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
data/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 TODO: Write your name
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,35 @@
1
+ # Activerecord::Dbsnapshot
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ 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/activerecord/dbsnapshot`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ 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).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/activerecord-dbsnapshot.
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/activerecord/dbsnapshot/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "activerecord-dbsnapshot"
7
+ spec.version = Activerecord::Dbsnapshot::VERSION
8
+ spec.authors = ["Ryan Mammina"]
9
+ spec.email = ["ryan@avamia.com"]
10
+
11
+ spec.summary = "Dump and Restore database snapshots."
12
+ spec.homepage = "https://github.com/avamia/activerecord-dbsnapshot"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = ">= 3.0.0"
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = "https://github.com/avamia/activerecord-dbsnapshot"
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(__dir__) do
22
+ `git ls-files -z`.split("\x0").reject do |f|
23
+ (File.expand_path(f) == __FILE__) ||
24
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git appveyor Gemfile])
25
+ end
26
+ end
27
+ spec.require_paths = ["lib"]
28
+
29
+ # spec.add_dependency "example-gem", "~> 1.0"
30
+ end
@@ -0,0 +1,17 @@
1
+ require 'activerecord/dbsnapshot'
2
+ require 'rails'
3
+
4
+ module ActiveRecord
5
+ class DbSnapshot
6
+ class Railtie < Rails::Railtie
7
+ # Auto-load the generator when Rails starts
8
+ generators do
9
+ require 'generators/snapshot/snapshot_generator'
10
+ end
11
+
12
+ rake_tasks do
13
+ load 'tasks/snapshot_tasks.rake'
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Activerecord
4
+ module Dbsnapshot
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
@@ -0,0 +1,77 @@
1
+ require_relative "dbsnapshot/version"
2
+
3
+ module ActiveRecord
4
+ class DbSnapshot
5
+ class << self
6
+ attr_accessor :snapshot_name, :excluded_tables
7
+
8
+ def name(value)
9
+ formatted_name = value.to_s.gsub('-', '_').underscore.to_sym
10
+ @snapshot_name = formatted_name
11
+ end
12
+
13
+ # Stores an array of tables to be excluded from the snapshot.
14
+ def exclude(tables)
15
+ @excluded_tables = tables.map(&:to_s)
16
+ end
17
+
18
+ # Finds the latest snapshot configuration
19
+ def latest_configuration
20
+ config_files = Dir.glob(Rails.root.join('db', 'snapshots', "*.rb"))
21
+ return nil if config_files.empty?
22
+
23
+ latest_config_file = config_files.max_by { |file| extract_timestamp(file) }
24
+ return nil unless latest_config_file
25
+
26
+ require latest_config_file
27
+
28
+ klass_name = File.basename(latest_config_file, '.rb').gsub(/^[^_]+_/, '').camelize
29
+ klass = klass_name.constantize
30
+
31
+ puts klass.snapshot_name, klass.excluded_tables.inspect
32
+ klass
33
+ end
34
+
35
+ # Finds snapshot configuration by name
36
+ def find_configuration(name)
37
+ config_file = Dir.glob(Rails.root.join('db', 'snapshots', "*_#{name}.rb")).first
38
+ unless config_file
39
+ puts "Snapshot configuration not found: #{name}"
40
+ return nil
41
+ end
42
+
43
+ load config_file
44
+ ActiveRecord::DbSnapshot.new
45
+ end
46
+
47
+ # Builds the dump command based on configuration
48
+ def build_dump_command(config, db_config, output_file)
49
+ pg_dump_cmd = "pg_dump"
50
+ pg_dump_cmd << " -U #{db_config[:username]}"
51
+ pg_dump_cmd << " -h #{db_config[:host]}"
52
+ pg_dump_cmd << " #{db_config[:database]}"
53
+
54
+ excluded_tables = config.excluded_tables.map(&:to_s).join(" ")
55
+ if excluded_tables.empty?
56
+ return "#{pg_dump_cmd} > #{output_file}"
57
+ else
58
+ excluded_tables_option = "--exclude-table=" + excluded_tables
59
+ return "#{pg_dump_cmd} #{excluded_tables_option} > #{output_file}"
60
+ end
61
+ end
62
+
63
+ # Executes the dump command
64
+ def execute_dump_command(dump_command)
65
+ system(dump_command)
66
+ end
67
+
68
+ private
69
+ def extract_timestamp(file)
70
+ timestamp = File.basename(file, ".rb").split('_').first.to_i
71
+ Time.at(timestamp)
72
+ end
73
+ end
74
+ end
75
+ end
76
+
77
+ require 'activerecord/dbsnapshot/railtie' if defined?(Rails)
@@ -0,0 +1,22 @@
1
+ Description:
2
+ Generates a configuration class for database snapshots.
3
+
4
+ Example:
5
+ rails generate snapshot NAME [options]
6
+
7
+ This will create:
8
+ - A new snapshot configuration file at db/snapshots/YYYYMMDDHHMMSS_NAME.rb
9
+
10
+ Options:
11
+ --exclude_tables=one two three
12
+ This option allows you to specify tables that should be excluded from the snapshot.
13
+ You can list multiple tables by separating them with a space.
14
+
15
+ Example:
16
+ rails generate snapshot MySnapshot --exclude_tables=users sessions logs
17
+
18
+ This will generate a configuration file that excludes the 'users', 'sessions', and 'logs' tables.
19
+
20
+ More Information:
21
+ The generated configuration file is a Ruby class that extends ActiveRecord::DbSnapshot.
22
+ You can edit this class to further customize the behavior of your database snapshot.
@@ -0,0 +1,18 @@
1
+ require 'rails/generators'
2
+
3
+ class SnapshotGenerator < Rails::Generators::NamedBase
4
+ source_root File.expand_path('templates', __dir__)
5
+
6
+ class_option :exclude_tables, type: :array, default: [], desc: "List of tables to exclude from the snapshot"
7
+
8
+ def create_snapshot_config
9
+ @exclude_tables = options[:exclude_tables] || []
10
+
11
+ @class_name = file_name.gsub('-', '_').camelize
12
+ @symbol_name = file_name.gsub('-', '_').underscore
13
+
14
+ timestamp = Time.now.strftime('%Y%m%d%H%M%S')
15
+ filename_with_timestamp = "#{timestamp}_#{@symbol_name}"
16
+ template "snapshot_config.rb.erb", File.join("db/snapshots", "#{filename_with_timestamp}.rb")
17
+ end
18
+ end
@@ -0,0 +1,4 @@
1
+ class <%= @class_name %> < ActiveRecord::DbSnapshot
2
+ name :<%= @symbol_name %>
3
+ exclude <%= @exclude_tables.inspect %>
4
+ end
@@ -0,0 +1,67 @@
1
+ # lib/tasks/snapshot_tasks.rake
2
+
3
+ namespace :db do
4
+ namespace :snapshot do
5
+ desc "Dump database based on snapshot configuration"
6
+ task :dump, [:name] => :environment do |t, args|
7
+ unless `which pg_dump`.present?
8
+ puts "Error: pg_dump not found. Ensure PostgreSQL client tools are installed."
9
+ next
10
+ end
11
+
12
+ unless Rails.env.development?
13
+ puts "You are about to dump the database. This action is not recommended in non-development environments."
14
+ puts "Proceed? (yes/no)"
15
+ response = STDIN.gets.chomp.downcase
16
+ unless response == 'yes'
17
+ puts "Dump canceled."
18
+ next
19
+ end
20
+ end
21
+
22
+ config = args[:name] ? ActiveRecord::DbSnapshot.find_configuration(args[:name]) : ActiveRecord::DbSnapshot.latest_configuration
23
+ unless config
24
+ puts "No snapshot configuration found."
25
+ next
26
+ end
27
+
28
+ db_config = ActiveRecord::Base.connection_config
29
+ output_file = Rails.root.join('db', 'snapshots', "#{config.snapshot_name}.sql")
30
+
31
+ puts output_file
32
+
33
+
34
+ dump_command = ActiveRecord::DbSnapshot.build_dump_command(config, db_config, output_file)
35
+ ActiveRecord::DbSnapshot.execute_dump_command(dump_command)
36
+
37
+ puts "Database dump completed: #{output_file}"
38
+ end
39
+
40
+ desc "Restore a snapshot SQL file into the database"
41
+ task :restore, [:name] => :environment do |_, args|
42
+ name = args[:name]
43
+ filename = "db/snapshots/#{name}.sql"
44
+
45
+ unless File.exist?(filename)
46
+ puts "Snapshot file not found: #{filename}"
47
+ next
48
+ end
49
+
50
+ unless Rails.env.development?
51
+ puts "You are about to restore a database snapshot. This action is not recommended in non-development environments."
52
+ puts "Proceed? (yes/no)"
53
+ response = STDIN.gets.chomp.downcase
54
+ unless response == 'yes'
55
+ puts "Snapshot restoration canceled."
56
+ next
57
+ end
58
+ end
59
+
60
+ # Restore the SQL file into the database
61
+ sql = File.read(filename)
62
+ ActiveRecord::Base.connection.execute(sql)
63
+
64
+ puts "Snapshot '#{name}' restored successfully."
65
+ end
66
+ end
67
+ end
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: activerecord-dbsnapshot
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ryan Mammina
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-03-06 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description:
14
+ email:
15
+ - ryan@avamia.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".idea/.gitignore"
21
+ - ".idea/activerecord-dbsnapshot.iml"
22
+ - ".idea/misc.xml"
23
+ - ".idea/modules.xml"
24
+ - ".idea/vcs.xml"
25
+ - ".rspec"
26
+ - ".rubocop.yml"
27
+ - LICENSE.txt
28
+ - README.md
29
+ - Rakefile
30
+ - activerecord-dbsnapshot.gemspec
31
+ - lib/activerecord/dbsnapshot.rb
32
+ - lib/activerecord/dbsnapshot/railtie.rb
33
+ - lib/activerecord/dbsnapshot/version.rb
34
+ - lib/generators/snapshot/USAGE
35
+ - lib/generators/snapshot/snapshot_generator.rb
36
+ - lib/generators/snapshot/templates/snapshot_config.rb.erb
37
+ - lib/tasks/snapshot_tasks.rake
38
+ homepage: https://github.com/avamia/activerecord-dbsnapshot
39
+ licenses:
40
+ - MIT
41
+ metadata:
42
+ homepage_uri: https://github.com/avamia/activerecord-dbsnapshot
43
+ source_code_uri: https://github.com/avamia/activerecord-dbsnapshot
44
+ post_install_message:
45
+ rdoc_options: []
46
+ require_paths:
47
+ - lib
48
+ required_ruby_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: 3.0.0
53
+ required_rubygems_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: '0'
58
+ requirements: []
59
+ rubygems_version: 3.2.3
60
+ signing_key:
61
+ specification_version: 4
62
+ summary: Dump and Restore database snapshots.
63
+ test_files: []