db_tools 0.1.2 → 0.2.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 326c65b22a64f78c54f46531150d1f3c83bf37e6a37ae5d2aeca513626acf46e
4
- data.tar.gz: ec4411bf59f70d88d115e4ce63fecf253f178fd1b03151c81b2da745e9b46818
3
+ metadata.gz: 155bf4aae2ada01b86665fd5e8fed52d34a939ec6f34ddb4f1dc7a74ec652637
4
+ data.tar.gz: 4fcf161a00c325da7967735445b12c550a059a2f56530bdefba4dec06896c2fd
5
5
  SHA512:
6
- metadata.gz: d3e455432fece050f0b0f9345e5026ff9bdd5136b8fea3a2747d22cf27a8bae25901d979c1900e93a5d2b4ce6a6ff2b0b25c1c1998e2cb1221caa783665a4c0c
7
- data.tar.gz: 9f14cd782f4bb211c913f6de11c3446d3394bb96368f0155571435e561ce29a644ceeff3147b79747821118d979add3bd03e2cba0f8c6e52e7da38b3af658084
6
+ metadata.gz: bd47418b3ca3fb7bf628092b7d9962d4eada1e68b1676c7765cfca0260a58bc206fad6c9fda0813dd53bf6a923acb36407d7560d007f57977188f5a360eeb375
7
+ data.tar.gz: 8b74248eccf89989af4c8d3681d8094bb58e69d96bb8a90c9093acf3cd8e90504f03759af280035305d7e3baf4d94aaa47ad5f205b711da1ce46c4ce9331a589
data/README.md CHANGED
@@ -21,6 +21,8 @@ end
21
21
  $ db s
22
22
  Usage: db snapshot <command> [name] (alias: db s)
23
23
 
24
+ status Show the database and whether it changed since the last snapshot
25
+ diff [name] Summarize what changed, per table, since the last snapshot (or name)
24
26
  list List snapshots of the development database
25
27
  create [name] Save a snapshot (name defaults to a timestamp)
26
28
  restore <name> Replace the development database with a snapshot
@@ -41,6 +43,30 @@ Saved current database as "auto-before-restore".
41
43
  Restored app_development from "good_state" (1.1s). The snapshot is kept.
42
44
  ```
43
45
 
46
+ `status` and `diff` compare the database with the snapshot most recently
47
+ created or restored (or the snapshot you name):
48
+
49
+ ```
50
+ $ db s status
51
+ Database: app_development
52
+ Tables: 79 (4,402,190 rows)
53
+ Last snapshot: good_state (2026-11-24 15:20)
54
+ Changed: yes, 2 tables. Run `db s diff` for a summary.
55
+
56
+ $ db s diff
57
+ Changes in app_development since snapshot "good_state" (2026-11-24 15:20):
58
+
59
+ TABLE BEFORE NOW CHANGE
60
+ orders 1,204 1,206 +2 rows
61
+ users 44,481 44,481 rows edited
62
+
63
+ 2 tables changed. BEFORE and NOW are row counts.
64
+ ```
65
+
66
+ The comparison uses a row count and checksum per table, so it says which
67
+ tables changed and by how many rows, not which rows. On MySQL, snapshots made
68
+ before db_tools 0.2.0 can't be compared.
69
+
44
70
  Restoring always saves the current database as `auto-before-restore` first, so
45
71
  `db s restore auto-before-restore` undoes a restore.
46
72
 
@@ -48,6 +74,8 @@ The same commands are available as Rails tasks:
48
74
 
49
75
  ```
50
76
  rails db:snapshot # help
77
+ rails db:snapshot:status
78
+ rails db:snapshot:diff[good_state]
51
79
  rails db:snapshot:list
52
80
  rails db:snapshot:create[good_state]
53
81
  rails db:snapshot:restore[good_state]
@@ -34,7 +34,7 @@ module DbTools
34
34
  private
35
35
 
36
36
  def directory
37
- File.join(root, "tmp", "db_snapshots", File.basename(database, ".*"))
37
+ DbTools.snapshot_directory(root, database)
38
38
  end
39
39
 
40
40
  def path(name)
@@ -1,9 +1,11 @@
1
+ require "json"
1
2
  require "shellwords"
2
3
 
3
4
  module DbTools
4
5
  module Adapters
5
6
  # MySQL can't copy a database server-side, so snapshots are gzipped
6
7
  # mysqldump files. Restoring recreates the database and loads the dump.
8
+ # A dump can't be queried, so each snapshot's fingerprint is saved beside it.
7
9
  class Mysql
8
10
  include FileSnapshots
9
11
 
@@ -22,10 +24,51 @@ module DbTools
22
24
  @env = config["password"] ? {"MYSQL_PWD" => config["password"].to_s} : {}
23
25
  end
24
26
 
27
+ def create(name)
28
+ super
29
+ File.write(fingerprint_path(name), JSON.generate(fingerprint))
30
+ end
31
+
32
+ def delete(name)
33
+ super
34
+ FileUtils.rm_f(fingerprint_path(name))
35
+ end
36
+
37
+ # Row count and CHECKSUM TABLE per table. For a snapshot, the one saved
38
+ # when it was created (nil for snapshots made before fingerprints existed).
39
+ def fingerprint(name = nil)
40
+ if name
41
+ path = fingerprint_path(name)
42
+ return File.exist?(path) ? JSON.parse(File.read(path)) : nil
43
+ end
44
+
45
+ tables = mysql("SELECT table_name FROM information_schema.tables " \
46
+ "WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'").lines.map(&:chomp)
47
+ return {} if tables.empty?
48
+
49
+ counts = mysql(tables.map { |t| "SELECT #{literal(t)}, count(*) FROM #{ident(t)}" }.join(" UNION ALL "))
50
+ .lines.to_h { |line| line.chomp.split("\t") }
51
+ checksums = mysql("CHECKSUM TABLE #{tables.map { |t| ident(t) }.join(", ")}")
52
+ .lines.to_h { |line| line.chomp.split("\t") }
53
+ tables.to_h { |t| [t, [counts.fetch(t).to_i, checksums.fetch("#{database}.#{t}")]] }
54
+ end
55
+
25
56
  private
26
57
 
27
58
  attr_reader :connection, :encoding, :env
28
59
 
60
+ def fingerprint_path(name)
61
+ path(name).delete_suffix(extension) + ".json"
62
+ end
63
+
64
+ def mysql(sql)
65
+ DbTools.run("mysql", *connection, "--batch", "--skip-column-names", database, "-e", sql, env: env)
66
+ end
67
+
68
+ def literal(value)
69
+ "'#{value.gsub("'", "''")}'"
70
+ end
71
+
29
72
  def extension
30
73
  ".sql.gz"
31
74
  end
@@ -8,9 +8,10 @@ module DbTools
8
8
  SEPARATOR = "__snap__"
9
9
  MAX_NAME_BYTES = 63
10
10
 
11
- attr_reader :database
11
+ attr_reader :root, :database
12
12
 
13
- def initialize(config, _root)
13
+ def initialize(config, root)
14
+ @root = root
14
15
  @database = config.fetch("database")
15
16
  @env = {
16
17
  "PGHOST" => config["host"],
@@ -47,6 +48,29 @@ module DbTools
47
48
  psql("DROP DATABASE #{ident(prefix + name)} WITH (FORCE)")
48
49
  end
49
50
 
51
+ # Row count and a checksum per table, of the development database or of
52
+ # a snapshot. The checksum sums each row's xmin (the transaction that
53
+ # wrote it) rather than hashing contents: any insert, update or delete
54
+ # changes it, it reads ~10x faster, and copies made with TEMPLATE keep
55
+ # xmin, so a snapshot matches the database it was taken from.
56
+ def fingerprint(name = nil)
57
+ db = name ? prefix + name : database
58
+ tables = psql(<<~SQL, database: db).lines.map { |line| line.chomp.split("|", 2) }
59
+ SELECT CASE WHEN schemaname = 'public' THEN tablename ELSE schemaname || '.' || tablename END,
60
+ format('%I.%I', schemaname, tablename)
61
+ FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
62
+ SQL
63
+ return {} if tables.empty?
64
+
65
+ sql = tables.map do |table, qualified|
66
+ "SELECT count(*), coalesce(sum(xmin::text::bigint), 0), #{literal(table)} FROM #{qualified}"
67
+ end.join(" UNION ALL ")
68
+ psql(sql, database: db).lines.to_h do |line|
69
+ count, sum, table = line.chomp.split("|", 3)
70
+ [table, [count.to_i, sum]]
71
+ end
72
+ end
73
+
50
74
  private
51
75
 
52
76
  attr_reader :env
@@ -85,9 +109,9 @@ module DbTools
85
109
 
86
110
  # Each statement runs separately (CREATE/DROP DATABASE can't run in a
87
111
  # transaction) but in one session, so SET applies to what follows.
88
- def psql(*statements)
112
+ def psql(*statements, database: "postgres")
89
113
  DbTools.run(
90
- "psql", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-d", "postgres",
114
+ "psql", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-d", database,
91
115
  *statements.flat_map { |sql| ["-c", sql] },
92
116
  env: env
93
117
  )
@@ -13,8 +13,30 @@ module DbTools
13
13
  @database = config.fetch("database")
14
14
  end
15
15
 
16
+ # Row count and a SHA3 of the contents per table, of the development
17
+ # database or of a snapshot file. sha3_query is built into the sqlite3 shell.
18
+ def fingerprint(name = nil)
19
+ file = name ? path(name) : database_path
20
+ tables = DbTools.run("sqlite3", "-readonly", file,
21
+ "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").lines.map(&:chomp)
22
+ return {} if tables.empty?
23
+
24
+ sql = tables.map do |table|
25
+ ident = %("#{table.gsub('"', '""')}")
26
+ "SELECT (SELECT count(*) FROM #{ident}), hex(sha3_query(#{literal("SELECT * FROM #{ident}")})), #{literal(table)}"
27
+ end.join(" UNION ALL ")
28
+ DbTools.run("sqlite3", "-readonly", file, sql).lines.to_h do |line|
29
+ count, hash, table = line.chomp.split("|", 3)
30
+ [table, [count.to_i, hash]]
31
+ end
32
+ end
33
+
16
34
  private
17
35
 
36
+ def literal(value)
37
+ "'#{value.gsub("'", "''")}'"
38
+ end
39
+
18
40
  def extension
19
41
  ".sqlite3"
20
42
  end
@@ -8,6 +8,8 @@ module DbTools
8
8
  HELP = <<~TEXT
9
9
  Usage: db snapshot <command> [name] (alias: db s)
10
10
 
11
+ status Show the database and whether it changed since the last snapshot
12
+ diff [name] Summarize what changed, per table, since the last snapshot (or name)
11
13
  list List snapshots of the development database
12
14
  create [name] Save a snapshot (name defaults to a timestamp)
13
15
  restore <name> Replace the development database with a snapshot
@@ -25,6 +27,8 @@ module DbTools
25
27
  def run(args)
26
28
  command, name = args
27
29
  case command
30
+ when "status" then status
31
+ when "diff" then diff(name)
28
32
  when "list" then list
29
33
  when "create" then create(name)
30
34
  when "restore" then restore(name)
@@ -43,8 +47,7 @@ module DbTools
43
47
  width = [snapshots.map { |s| s[:name].length }.max, 4].max
44
48
  out.puts " #{"NAME".ljust(width)} #{"CREATED".ljust(16)} SIZE"
45
49
  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])}"
50
+ out.puts " #{s[:name].ljust(width)} #{created(s).ljust(16)} #{human_size(s[:size])}"
48
51
  end
49
52
  end
50
53
 
@@ -54,6 +57,7 @@ module DbTools
54
57
  raise Error, "A snapshot named \"#{name}\" already exists." if exists?(name)
55
58
 
56
59
  seconds = timed { adapter.create(name) }
60
+ record_last(name)
57
61
  out.puts "Snapshot \"#{name}\" of #{adapter.database} saved (#{human_size(size_of(name))}, #{seconds}s)."
58
62
  end
59
63
 
@@ -69,6 +73,7 @@ module DbTools
69
73
  end
70
74
 
71
75
  seconds = timed { adapter.restore(name) }
76
+ record_last(name)
72
77
  out.puts "Restored #{adapter.database} from \"#{name}\" (#{seconds}s). The snapshot is kept."
73
78
  end
74
79
 
@@ -78,10 +83,107 @@ module DbTools
78
83
  out.puts "Deleted snapshot \"#{name}\"."
79
84
  end
80
85
 
86
+ def status
87
+ current = adapter.fingerprint
88
+ out.puts "Database: #{adapter.database}"
89
+ out.puts "Tables: #{current.size} (#{delimit(current.values.sum(&:first))} rows)"
90
+
91
+ snapshot = last_snapshot
92
+ unless snapshot
93
+ out.puts "Last snapshot: none. Create one with `db s create [name]`."
94
+ return
95
+ end
96
+ out.puts "Last snapshot: #{snapshot[:name]} (#{created(snapshot)})"
97
+
98
+ before = adapter.fingerprint(snapshot[:name])
99
+ changed = before && changes(before, current)
100
+ out.puts "Changed: " +
101
+ if changed.nil? then "unknown, \"#{snapshot[:name]}\" was saved before db_tools could compare snapshots"
102
+ elsif changed.empty? then "no"
103
+ else "yes, #{pluralize(changed.size, "table")}. Run `db s diff` for a summary."
104
+ end
105
+ end
106
+
107
+ def diff(name = nil)
108
+ snapshot = name ? find!(name, "diff") : last_snapshot
109
+ raise Error, "No snapshots of #{adapter.database} yet. Create one with `db s create [name]`." unless snapshot
110
+
111
+ before = adapter.fingerprint(snapshot[:name])
112
+ raise Error, "Can't diff against \"#{snapshot[:name]}\": it was saved before db_tools could compare snapshots." unless before
113
+
114
+ changed = changes(before, adapter.fingerprint)
115
+ since = "since snapshot \"#{snapshot[:name]}\" (#{created(snapshot)})"
116
+ if changed.empty?
117
+ out.puts "No changes in #{adapter.database} #{since}."
118
+ return
119
+ end
120
+
121
+ out.puts "Changes in #{adapter.database} #{since}:", ""
122
+ width = [changed.map { |table, *| table.length }.max, 5].max
123
+ out.puts " #{"TABLE".ljust(width)} #{"BEFORE".rjust(10)} #{"NOW".rjust(10)} CHANGE"
124
+ changed.each do |table, was, now|
125
+ out.puts " #{table.ljust(width)} #{rows_cell(was)} #{rows_cell(now)} #{change_label(was, now)}"
126
+ end
127
+ out.puts "", "#{pluralize(changed.size, "table")} changed. BEFORE and NOW are row counts."
128
+ end
129
+
81
130
  private
82
131
 
83
132
  attr_reader :adapter, :out
84
133
 
134
+ # Tables whose row count or checksum differ, as [table, [rows, checksum] or nil, same].
135
+ def changes(before, after)
136
+ (before.keys | after.keys).sort.filter_map do |table|
137
+ [table, before[table], after[table]] unless before[table] == after[table]
138
+ end
139
+ end
140
+
141
+ def change_label(was, now)
142
+ return "table added" unless was
143
+ return "table removed" unless now
144
+ delta = now.first - was.first
145
+ return "rows edited" if delta.zero?
146
+ format("%+d %s", delta, (delta.abs == 1) ? "row" : "rows")
147
+ end
148
+
149
+ def rows_cell(fingerprint)
150
+ (fingerprint ? delimit(fingerprint.first) : "-").rjust(10)
151
+ end
152
+
153
+ # The snapshot most recently created or restored here, falling back to the
154
+ # newest one (e.g. snapshots made before this was recorded).
155
+ def last_snapshot
156
+ snapshots = adapter.list
157
+ recorded = File.read(last_path).strip if File.exist?(last_path)
158
+ snapshots.find { |s| s[:name] == recorded } || snapshots.max_by { |s| s[:created_at] || Time.at(0) }
159
+ end
160
+
161
+ def record_last(name)
162
+ FileUtils.mkdir_p(File.dirname(last_path))
163
+ File.write(last_path, name)
164
+ end
165
+
166
+ def last_path
167
+ File.join(DbTools.snapshot_directory(adapter.root, adapter.database), ".last")
168
+ end
169
+
170
+ def find!(name, command)
171
+ require_existing!(name, command)
172
+ adapter.list.find { |s| s[:name] == name }
173
+ end
174
+
175
+ def created(snapshot)
176
+ snapshot[:created_at]&.strftime("%Y-%m-%d %H:%M") || "unknown"
177
+ end
178
+
179
+ def delimit(number)
180
+ number.to_s.reverse.scan(/\d{1,3}/).join(",").reverse
181
+ end
182
+
183
+ def pluralize(count, word)
184
+ "#{count} #{word}#{"s" unless count == 1}"
185
+ end
186
+
85
187
  def validate_name!(name)
86
188
  return if NAME_FORMAT.match?(name)
87
189
  raise Error, "Invalid snapshot name \"#{name}\". Use letters, numbers, - and _ (up to 40 characters)."
@@ -1,3 +1,3 @@
1
1
  module DbTools
2
- VERSION = "0.1.2"
2
+ VERSION = "0.2.0"
3
3
  end
data/lib/db_tools.rb CHANGED
@@ -40,7 +40,7 @@ module DbTools
40
40
 
41
41
  source = File.read(path)
42
42
  config = begin
43
- development_section(ERB.new(source).result(Stubs.module_eval("binding")))
43
+ development_section(ERB.new(source).result(Stubs.module_eval("binding", __FILE__, __LINE__)))
44
44
  rescue NameError
45
45
  UNRESOLVED
46
46
  end
@@ -67,9 +67,15 @@ module DbTools
67
67
  module Stubs
68
68
  Rails = BasicObject.new
69
69
  def Rails.method_missing(*) = self
70
+ def Rails.respond_to_missing?(*) = true
70
71
  def Rails.to_s = UNRESOLVED
71
72
  end
72
73
 
74
+ # Where snapshot files and bookkeeping live: tmp/, so Rails ignores them.
75
+ def self.snapshot_directory(root, database)
76
+ File.join(root, "tmp", "db_snapshots", File.basename(database, ".*"))
77
+ end
78
+
73
79
  # Runs a command without a shell and returns its stdout, raising on failure.
74
80
  def self.run(*command, env: {})
75
81
  stdout, stderr, status = Open3.capture3(env, *command)
@@ -6,13 +6,15 @@ namespace :db do
6
6
 
7
7
  namespace :snapshot do
8
8
  {
9
+ status: "Show whether the development database changed since the last snapshot",
10
+ diff: "Summarize what changed since the last snapshot (optional name)",
9
11
  list: "List snapshots of the development database",
10
12
  create: "Save a snapshot of the development database (optional name)",
11
13
  restore: "Replace the development database with a snapshot",
12
14
  delete: "Delete a snapshot"
13
15
  }.each do |command, description|
14
16
  desc description
15
- task command, (command == :list) ? [] : [:name] do |_task, args|
17
+ task command, %i[status list].include?(command) ? [] : [:name] do |_task, args|
16
18
  abort "db:snapshot only works in development (Rails.env is #{Rails.env})." unless Rails.env.development?
17
19
 
18
20
  DbTools::Snapshot.new(DbTools.adapter(root: Rails.root.to_s)).run([command.to_s, args[:name]].compact)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: db_tools
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.2
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Seth Horsley