db_tools 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1a794fb33fcc06107733201ad198b0804e82b9b4ae81b824d89bc294457a576b
4
+ data.tar.gz: 25541b182fa3e9c8fdb063ee30aa47c2b246b1d3dab4ed200ff9f69f805ba7d3
5
+ SHA512:
6
+ metadata.gz: f46480ded35a0b168cd0e60c0117d74053d5c65afc8bedacd57c54787236646889f8c49689b6fd55b79a2b3a786e0ce58158332eb36d547205d8568daf5eea7e
7
+ data.tar.gz: c575fe57177204d03cccf39284c43e75378253605e1591bcad0134125bfd6934e3b69f48c0ca414e9628b6952657b7004cf34b9a6a248b1ee74f48cd3358eb20
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Seth Horsley
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,91 @@
1
+ # db_tools
2
+
3
+ Save, list and restore snapshots of your Rails app's **development** database.
4
+ Snapshot before a risky migration or data task, try it, and roll back in seconds.
5
+
6
+ Works with PostgreSQL, MySQL and SQLite. It only ever touches the `development`
7
+ database from `config/database.yml`.
8
+
9
+ ## Install
10
+
11
+ ```ruby
12
+ # Gemfile
13
+ group :development do
14
+ gem "db_tools"
15
+ end
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```
21
+ $ db s
22
+ Usage: db snapshot <command> [name] (alias: db s)
23
+
24
+ list List snapshots of the development database
25
+ create [name] Save a snapshot (name defaults to a timestamp)
26
+ restore <name> Replace the development database with a snapshot
27
+ (the current database is saved as "auto-before-restore" first)
28
+ delete <name> Delete a snapshot
29
+ ```
30
+
31
+ ```
32
+ $ db s create good_state
33
+ Snapshot "good_state" of app_development saved (2.1 GB, 1.2s).
34
+
35
+ $ db s list
36
+ NAME CREATED SIZE
37
+ good_state 2026-11-24 15:20 2.1 GB
38
+
39
+ $ db s restore good_state
40
+ Saved current database as "auto-before-restore".
41
+ Restored app_development from "good_state" (1.1s). The snapshot is kept.
42
+ ```
43
+
44
+ Restoring always saves the current database as `auto-before-restore` first, so
45
+ `db s restore auto-before-restore` undoes a restore.
46
+
47
+ The same commands are available as Rails tasks:
48
+
49
+ ```
50
+ rails db:snapshot # help
51
+ rails db:snapshot:list
52
+ rails db:snapshot:create[good_state]
53
+ rails db:snapshot:restore[good_state]
54
+ rails db:snapshot:delete[good_state]
55
+ ```
56
+
57
+ In zsh, quote the brackets: `rails "db:snapshot:create[good_state]"`.
58
+
59
+ ## How snapshots are stored
60
+
61
+ | Database | Snapshot | Tools needed |
62
+ |------------|-----------------------------------------------------------------|-----------------------|
63
+ | PostgreSQL | A database on the same server, `<db>__snap__<name>` | `psql` |
64
+ | MySQL | `tmp/db_snapshots/<db>/<name>.sql.gz` (mysqldump) | `mysql`, `mysqldump` |
65
+ | SQLite | `tmp/db_snapshots/<db>/<name>.sqlite3` (SQLite's backup API) | `sqlite3` |
66
+
67
+ **PostgreSQL** copies with `CREATE DATABASE ... TEMPLATE`. On PostgreSQL 18+ it
68
+ sets `file_copy_method = clone`, so on a copy-on-write filesystem (APFS, Btrfs,
69
+ XFS) a snapshot takes about a second and shares disk blocks with the original
70
+ until either changes. Elsewhere it's a regular full copy. Postgres can't copy a
71
+ database that's in use, so creating or restoring a snapshot **closes open
72
+ connections** to it (your server, console and job workers reconnect on their
73
+ next query).
74
+
75
+ **MySQL** snapshots take as long as `mysqldump` and a reload do, roughly a minute
76
+ per GB.
77
+
78
+ ## Development
79
+
80
+ ```
81
+ bundle install
82
+ bundle exec rake test
83
+ ```
84
+
85
+ The PostgreSQL and MySQL tests run against a real server when `psql` / `mysql`
86
+ can connect with default settings, and are skipped otherwise. They create and
87
+ drop their own scratch databases.
88
+
89
+ ## License
90
+
91
+ MIT
data/bin/db ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require_relative "../lib/db_tools"
4
+
5
+ exit DbTools::CLI.run(ARGV)
@@ -0,0 +1,45 @@
1
+ require "fileutils"
2
+
3
+ module DbTools
4
+ module Adapters
5
+ # Shared storage for adapters that keep snapshots as files in
6
+ # tmp/db_snapshots/<database>/. Includers define #extension, #dump(path)
7
+ # and #load(path).
8
+ module FileSnapshots
9
+ def list
10
+ Dir.glob(File.join(directory, "*#{extension}")).map do |path|
11
+ {name: File.basename(path, extension), created_at: File.mtime(path), size: File.size(path)}
12
+ end
13
+ end
14
+
15
+ # Dumps to a temporary file first so a failed dump never leaves a
16
+ # half-written snapshot behind.
17
+ def create(name)
18
+ FileUtils.mkdir_p(directory)
19
+ partial = "#{path(name)}.partial"
20
+ dump(partial)
21
+ File.rename(partial, path(name))
22
+ ensure
23
+ FileUtils.rm_f(partial) if partial
24
+ end
25
+
26
+ def restore(name)
27
+ load(path(name))
28
+ end
29
+
30
+ def delete(name)
31
+ File.delete(path(name))
32
+ end
33
+
34
+ private
35
+
36
+ def directory
37
+ File.join(root, "tmp", "db_snapshots", File.basename(database, ".*"))
38
+ end
39
+
40
+ def path(name)
41
+ File.join(directory, name + extension)
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,55 @@
1
+ require "shellwords"
2
+
3
+ module DbTools
4
+ module Adapters
5
+ # MySQL can't copy a database server-side, so snapshots are gzipped
6
+ # mysqldump files. Restoring recreates the database and loads the dump.
7
+ class Mysql
8
+ include FileSnapshots
9
+
10
+ attr_reader :root, :database
11
+
12
+ def initialize(config, root)
13
+ @root = root
14
+ @database = config.fetch("database")
15
+ @encoding = config["encoding"]
16
+ @connection = {
17
+ "--host" => config["host"],
18
+ "--port" => config["port"]&.to_s,
19
+ "--user" => config["username"],
20
+ "--socket" => config["socket"]
21
+ }.compact.map { |flag, value| "#{flag}=#{value}" }
22
+ @env = config["password"] ? {"MYSQL_PWD" => config["password"].to_s} : {}
23
+ end
24
+
25
+ private
26
+
27
+ attr_reader :connection, :encoding, :env
28
+
29
+ def extension
30
+ ".sql.gz"
31
+ end
32
+
33
+ def dump(path)
34
+ mysqldump = ["mysqldump", *connection, "--single-transaction", "--routines", "--triggers", "--events", database]
35
+ pipeline("#{mysqldump.shelljoin} | gzip > #{path.shellescape}")
36
+ end
37
+
38
+ def load(path)
39
+ create = "CREATE DATABASE #{ident(database)}"
40
+ create += " CHARACTER SET #{encoding}" if encoding
41
+ DbTools.run("mysql", *connection, "-e", "DROP DATABASE IF EXISTS #{ident(database)}; #{create}", env: env)
42
+ pipeline("gunzip -c #{path.shellescape} | #{["mysql", *connection, database].shelljoin}")
43
+ end
44
+
45
+ # pipefail so a failing mysqldump/mysql isn't hidden by gzip succeeding.
46
+ def pipeline(command)
47
+ DbTools.run("bash", "-o", "pipefail", "-c", command, env: env)
48
+ end
49
+
50
+ def ident(name)
51
+ "`#{name.gsub("`", "``")}`"
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,111 @@
1
+ module DbTools
2
+ module Adapters
3
+ # Snapshots are databases on the same server, copied with
4
+ # CREATE DATABASE ... TEMPLATE. On PostgreSQL 18+ the copy uses
5
+ # file_copy_method = clone, which is near-instant on copy-on-write
6
+ # filesystems (APFS, Btrfs, XFS); otherwise it is a regular file copy.
7
+ class Postgresql
8
+ SEPARATOR = "__snap__"
9
+ MAX_NAME_BYTES = 63
10
+
11
+ attr_reader :database
12
+
13
+ def initialize(config, _root)
14
+ @database = config.fetch("database")
15
+ @env = {
16
+ "PGHOST" => config["host"],
17
+ "PGPORT" => config["port"]&.to_s,
18
+ "PGUSER" => config["username"],
19
+ "PGPASSWORD" => config["password"]
20
+ }.compact
21
+ end
22
+
23
+ def list
24
+ rows = psql("SELECT datname, pg_database_size(oid), coalesce(shobj_description(oid, 'pg_database'), '') FROM pg_database")
25
+ rows.lines.filter_map do |line|
26
+ datname, size, comment = line.chomp.split("|", 3)
27
+ next unless datname.start_with?(prefix)
28
+ {name: datname.delete_prefix(prefix), created_at: parse_time(comment), size: size.to_i}
29
+ end
30
+ end
31
+
32
+ def create(name)
33
+ snapshot = prefix + name
34
+ if snapshot.bytesize > MAX_NAME_BYTES
35
+ raise Error, "Snapshot name too long: PostgreSQL database names are limited to #{MAX_NAME_BYTES} bytes."
36
+ end
37
+ copy(from: database, to: snapshot)
38
+ psql("COMMENT ON DATABASE #{ident(snapshot)} IS #{literal("db_tools snapshot #{Time.now.utc.iso8601}")}")
39
+ end
40
+
41
+ def restore(name)
42
+ psql("DROP DATABASE IF EXISTS #{ident(database)} WITH (FORCE)")
43
+ copy(from: prefix + name, to: database)
44
+ end
45
+
46
+ def delete(name)
47
+ psql("DROP DATABASE #{ident(prefix + name)} WITH (FORCE)")
48
+ end
49
+
50
+ private
51
+
52
+ attr_reader :env
53
+
54
+ def prefix
55
+ database + SEPARATOR
56
+ end
57
+
58
+ # Postgres refuses to copy a database with open connections, so block new
59
+ # ones (a running app reconnects immediately), close the rest, copy, and
60
+ # always reopen the source.
61
+ def copy(from:, to:)
62
+ psql("ALTER DATABASE #{ident(from)} ALLOW_CONNECTIONS false")
63
+ begin
64
+ psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity " \
65
+ "WHERE datname = #{literal(from)} AND pid <> pg_backend_pid()")
66
+ create_from_template(from, to)
67
+ ensure
68
+ psql("ALTER DATABASE #{ident(from)} ALLOW_CONNECTIONS true")
69
+ end
70
+ end
71
+
72
+ def create_from_template(from, to)
73
+ version = psql("SHOW server_version_num").to_i
74
+ create = "CREATE DATABASE #{ident(to)} TEMPLATE #{ident(from)}"
75
+ create += " STRATEGY = FILE_COPY" if version >= 150_000
76
+ return psql(create) if version < 180_000
77
+
78
+ begin
79
+ psql("SET file_copy_method = clone", create)
80
+ rescue Error
81
+ # The filesystem can't clone; fall back to a regular copy.
82
+ psql(create)
83
+ end
84
+ end
85
+
86
+ # Each statement runs separately (CREATE/DROP DATABASE can't run in a
87
+ # transaction) but in one session, so SET applies to what follows.
88
+ def psql(*statements)
89
+ DbTools.run(
90
+ "psql", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-d", "postgres",
91
+ *statements.flat_map { |sql| ["-c", sql] },
92
+ env: env
93
+ )
94
+ end
95
+
96
+ def ident(name)
97
+ %("#{name.gsub('"', '""')}")
98
+ end
99
+
100
+ def literal(value)
101
+ "'#{value.gsub("'", "''")}'"
102
+ end
103
+
104
+ def parse_time(comment)
105
+ Time.iso8601(comment.split.last.to_s)
106
+ rescue ArgumentError
107
+ nil
108
+ end
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,42 @@
1
+ module DbTools
2
+ module Adapters
3
+ # Snapshots are copies made with SQLite's online backup API (the sqlite3
4
+ # shell's .backup and .restore), which is safe while the app has the
5
+ # database open, including in WAL mode.
6
+ class Sqlite
7
+ include FileSnapshots
8
+
9
+ attr_reader :root, :database
10
+
11
+ def initialize(config, root)
12
+ @root = root
13
+ @database = config.fetch("database")
14
+ end
15
+
16
+ private
17
+
18
+ def extension
19
+ ".sqlite3"
20
+ end
21
+
22
+ def dump(path)
23
+ DbTools.run("sqlite3", database_path, ".backup #{quote(path)}")
24
+ end
25
+
26
+ def load(path)
27
+ DbTools.run("sqlite3", database_path, ".restore #{quote(path)}")
28
+ end
29
+
30
+ # Rails resolves relative SQLite paths against the app root.
31
+ def database_path
32
+ File.expand_path(database, root)
33
+ end
34
+
35
+ # The sqlite3 shell takes single-quoted arguments without escapes.
36
+ def quote(path)
37
+ raise Error, "Paths containing ' aren't supported: #{path}" if path.include?("'")
38
+ "'#{path}'"
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,31 @@
1
+ module DbTools
2
+ # Entry point for the `db` executable.
3
+ module CLI
4
+ HELP = <<~TEXT
5
+ Usage: db <command>
6
+
7
+ snapshot, s Save, list and restore snapshots of the development database
8
+
9
+ Run `db s` for snapshot commands.
10
+ TEXT
11
+
12
+ # @return [Integer] exit status
13
+ def self.run(args, root: Dir.pwd, out: $stdout, err: $stderr)
14
+ command, *rest = args
15
+ case command
16
+ when "snapshot", "s"
17
+ if rest.empty?
18
+ out.puts Snapshot::HELP
19
+ else
20
+ Snapshot.new(DbTools.adapter(root: root), out: out).run(rest)
21
+ end
22
+ else
23
+ out.puts HELP
24
+ end
25
+ 0
26
+ rescue Error => e
27
+ err.puts e.message
28
+ 1
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,7 @@
1
+ module DbTools
2
+ class Railtie < Rails::Railtie
3
+ rake_tasks do
4
+ load File.expand_path("../tasks/db_tools.rake", __dir__)
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,117 @@
1
+ module DbTools
2
+ # The snapshot commands, shared by the `db` executable and the Rails tasks.
3
+ # Storage is up to the adapter; this class handles names, safety and output.
4
+ class Snapshot
5
+ NAME_FORMAT = /\A[A-Za-z0-9_-]{1,40}\z/
6
+ AUTO_NAME = "auto-before-restore"
7
+
8
+ HELP = <<~TEXT
9
+ Usage: db snapshot <command> [name] (alias: db s)
10
+
11
+ list List snapshots of the development database
12
+ create [name] Save a snapshot (name defaults to a timestamp)
13
+ restore <name> Replace the development database with a snapshot
14
+ (the current database is saved as "#{AUTO_NAME}" first)
15
+ delete <name> Delete a snapshot
16
+
17
+ Names may use letters, numbers, - and _ (up to 40 characters).
18
+ TEXT
19
+
20
+ def initialize(adapter, out: $stdout)
21
+ @adapter = adapter
22
+ @out = out
23
+ end
24
+
25
+ def run(args)
26
+ command, name = args
27
+ case command
28
+ when "list" then list
29
+ when "create" then create(name)
30
+ when "restore" then restore(name)
31
+ when "delete" then delete(name)
32
+ else out.puts HELP
33
+ end
34
+ end
35
+
36
+ def list
37
+ snapshots = adapter.list.sort_by { |s| s[:created_at] || Time.at(0) }
38
+ if snapshots.empty?
39
+ out.puts "No snapshots of #{adapter.database} yet. Create one with `db s create [name]`."
40
+ return
41
+ end
42
+
43
+ width = [snapshots.map { |s| s[:name].length }.max, 4].max
44
+ out.puts " #{"NAME".ljust(width)} #{"CREATED".ljust(16)} SIZE"
45
+ snapshots.each do |s|
46
+ created = s[:created_at]&.strftime("%Y-%m-%d %H:%M") || "unknown"
47
+ out.puts " #{s[:name].ljust(width)} #{created.ljust(16)} #{human_size(s[:size])}"
48
+ end
49
+ end
50
+
51
+ def create(name = nil)
52
+ name ||= Time.now.strftime("%Y%m%d-%H%M%S")
53
+ validate_name!(name)
54
+ raise Error, "A snapshot named \"#{name}\" already exists." if exists?(name)
55
+
56
+ seconds = timed { adapter.create(name) }
57
+ out.puts "Snapshot \"#{name}\" of #{adapter.database} saved (#{human_size(size_of(name))}, #{seconds}s)."
58
+ end
59
+
60
+ def restore(name)
61
+ require_existing!(name, "restore")
62
+
63
+ # Keep the current state so a mistaken restore can be undone, unless
64
+ # we're restoring that very safety copy.
65
+ unless name == AUTO_NAME
66
+ adapter.delete(AUTO_NAME) if exists?(AUTO_NAME)
67
+ adapter.create(AUTO_NAME)
68
+ out.puts "Saved current database as \"#{AUTO_NAME}\"."
69
+ end
70
+
71
+ seconds = timed { adapter.restore(name) }
72
+ out.puts "Restored #{adapter.database} from \"#{name}\" (#{seconds}s). The snapshot is kept."
73
+ end
74
+
75
+ def delete(name)
76
+ require_existing!(name, "delete")
77
+ adapter.delete(name)
78
+ out.puts "Deleted snapshot \"#{name}\"."
79
+ end
80
+
81
+ private
82
+
83
+ attr_reader :adapter, :out
84
+
85
+ def validate_name!(name)
86
+ return if NAME_FORMAT.match?(name)
87
+ raise Error, "Invalid snapshot name \"#{name}\". Use letters, numbers, - and _ (up to 40 characters)."
88
+ end
89
+
90
+ def require_existing!(name, command)
91
+ raise Error, "Usage: db snapshot #{command} <name>" if name.nil?
92
+ return if exists?(name)
93
+ raise Error, "No snapshot named \"#{name}\". Run `db s list` to see them."
94
+ end
95
+
96
+ def exists?(name)
97
+ adapter.list.any? { |s| s[:name] == name }
98
+ end
99
+
100
+ def size_of(name)
101
+ adapter.list.find { |s| s[:name] == name }&.fetch(:size)
102
+ end
103
+
104
+ def timed
105
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
106
+ yield
107
+ (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).round(1)
108
+ end
109
+
110
+ def human_size(bytes)
111
+ return "unknown" unless bytes
112
+ units = %w[B KB MB GB TB]
113
+ exponent = bytes.zero? ? 0 : [(Math.log(bytes) / Math.log(1024)).floor, units.size - 1].min
114
+ format("%.1f %s", bytes.to_f / 1024**exponent, units[exponent]).sub(".0 B", " B")
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,3 @@
1
+ module DbTools
2
+ VERSION = "0.1.0"
3
+ end
data/lib/db_tools.rb ADDED
@@ -0,0 +1,65 @@
1
+ require "erb"
2
+ require "open3"
3
+ require "time"
4
+ require "yaml"
5
+
6
+ require_relative "db_tools/version"
7
+ require_relative "db_tools/adapters/file_snapshots"
8
+ require_relative "db_tools/adapters/postgresql"
9
+ require_relative "db_tools/adapters/mysql"
10
+ require_relative "db_tools/adapters/sqlite"
11
+ require_relative "db_tools/snapshot"
12
+ require_relative "db_tools/cli"
13
+ require_relative "db_tools/railtie" if defined?(Rails::Railtie)
14
+
15
+ module DbTools
16
+ class Error < StandardError; end
17
+
18
+ ADAPTERS = {
19
+ "postgresql" => Adapters::Postgresql,
20
+ "postgis" => Adapters::Postgresql,
21
+ "mysql2" => Adapters::Mysql,
22
+ "trilogy" => Adapters::Mysql,
23
+ "sqlite3" => Adapters::Sqlite
24
+ }.freeze
25
+
26
+ # Builds the adapter for the app's development database. Snapshots only
27
+ # ever target development, so no other environment is read.
28
+ def self.adapter(root: Dir.pwd)
29
+ config = development_config(root)
30
+ adapter_class = ADAPTERS.fetch(config["adapter"]) do
31
+ raise Error, "Unsupported database adapter #{config["adapter"].inspect}. " \
32
+ "Supported: #{ADAPTERS.keys.join(", ")}"
33
+ end
34
+ adapter_class.new(config, root)
35
+ end
36
+
37
+ def self.development_config(root)
38
+ path = File.join(root, "config", "database.yml")
39
+ raise Error, "No config/database.yml in #{root}" unless File.exist?(path)
40
+
41
+ config = YAML.safe_load(render_erb(path, root), aliases: true)&.fetch("development", nil)
42
+ raise Error, "config/database.yml has no development database" unless config.is_a?(Hash)
43
+
44
+ # Multi-database apps nest each database under a name; snapshot the primary one.
45
+ config = config["primary"] || config.values.first unless config.key?("adapter")
46
+ config
47
+ end
48
+
49
+ def self.render_erb(path, root)
50
+ ERB.new(File.read(path)).result
51
+ rescue NameError
52
+ # The YAML references the app (e.g. Rails credentials): boot it and try again.
53
+ require File.join(root, "config", "environment")
54
+ ERB.new(File.read(path)).result
55
+ end
56
+
57
+ # Runs a command without a shell and returns its stdout, raising on failure.
58
+ def self.run(*command, env: {})
59
+ stdout, stderr, status = Open3.capture3(env, *command)
60
+ raise Error, "#{command.first} failed: #{stderr.strip.empty? ? stdout.strip : stderr.strip}" unless status.success?
61
+ stdout
62
+ rescue Errno::ENOENT
63
+ raise Error, "#{command.first} not found. Is it installed and on your PATH?"
64
+ end
65
+ end
@@ -0,0 +1,24 @@
1
+ namespace :db do
2
+ desc "Show the db:snapshot commands"
3
+ task :snapshot do
4
+ puts DbTools::Snapshot::HELP.sub("db snapshot <command> [name] (alias: db s)", "rails db:snapshot:<command>[name]")
5
+ end
6
+
7
+ namespace :snapshot do
8
+ {
9
+ list: "List snapshots of the development database",
10
+ create: "Save a snapshot of the development database (optional name)",
11
+ restore: "Replace the development database with a snapshot",
12
+ delete: "Delete a snapshot"
13
+ }.each do |command, description|
14
+ desc description
15
+ task command, [:name] do |_task, args|
16
+ abort "db:snapshot only works in development (Rails.env is #{Rails.env})." unless Rails.env.development?
17
+
18
+ DbTools::Snapshot.new(DbTools.adapter(root: Rails.root.to_s)).run([command.to_s, args[:name]].compact)
19
+ rescue DbTools::Error => e
20
+ abort e.message
21
+ end
22
+ end
23
+ end
24
+ end
metadata ADDED
@@ -0,0 +1,55 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: db_tools
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Seth Horsley
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Save, list and restore snapshots of a Rails app's development database.
13
+ Supports PostgreSQL, MySQL and SQLite.
14
+ email:
15
+ - git-public.ch12j@seth4242.com
16
+ executables:
17
+ - db
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - LICENSE.txt
22
+ - README.md
23
+ - bin/db
24
+ - lib/db_tools.rb
25
+ - lib/db_tools/adapters/file_snapshots.rb
26
+ - lib/db_tools/adapters/mysql.rb
27
+ - lib/db_tools/adapters/postgresql.rb
28
+ - lib/db_tools/adapters/sqlite.rb
29
+ - lib/db_tools/cli.rb
30
+ - lib/db_tools/railtie.rb
31
+ - lib/db_tools/snapshot.rb
32
+ - lib/db_tools/version.rb
33
+ - lib/tasks/db_tools.rake
34
+ homepage: https://github.com/sethhorsley/db_tools
35
+ licenses:
36
+ - MIT
37
+ metadata: {}
38
+ rdoc_options: []
39
+ require_paths:
40
+ - lib
41
+ required_ruby_version: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - ">="
44
+ - !ruby/object:Gem::Version
45
+ version: '3.1'
46
+ required_rubygems_version: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ - - ">="
49
+ - !ruby/object:Gem::Version
50
+ version: '0'
51
+ requirements: []
52
+ rubygems_version: 4.0.20
53
+ specification_version: 4
54
+ summary: Snapshot and restore your local development database.
55
+ test_files: []