8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/git_fit/db/rebuild.rb', line 8
def self.call(db, db_path, migrations_path)
backup = "#{db_path}.rebuild_bak"
FileUtils.cp(db_path, backup)
%w[-wal -shm].each do |ext|
src = "#{db_path}#{ext}"
FileUtils.cp(src, "#{backup}#{ext}") if File.exist?(src)
end
tables = db.tables
migration_tables = %i[schema_info schema_migrations]
data = {}
(tables - migration_tables).each { |t| data[t] = export_table(db, t) }
db.run("PRAGMA foreign_keys = OFF")
tables.each { |t| db.drop_table(t) }
Sequel.extension :migration
Sequel::Migrator.run(db, migrations_path)
new_tables = db.tables.to_set
data.each do |table, rows|
next unless new_tables.include?(table)
import_table(db, table, rows) if rows.any?
end
warn "Rebuilt #{db_path}: #{data.values.sum(&:size)} rows from #{data.size} tables"
rescue => e
if backup && File.exist?(backup)
FileUtils.cp(backup, db_path)
%w[-wal -shm].each do |ext|
src = "#{backup}#{ext}"
FileUtils.cp(src, "#{db_path}#{ext}") if File.exist?(src)
end
end
raise RebuildError, "Rebuild failed: #{e.message}"
ensure
[backup, "#{backup}-wal", "#{backup}-shm"].each do |f|
FileUtils.rm_f(f)
end
end
|