Module: GitFit::DB::Rebuild

Defined in:
lib/git_fit/db/rebuild.rb

Class Method Summary collapse

Class Method Details

.call(db, db_path, migrations_path) ⇒ Object



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
48
49
# File 'lib/git_fit/db/rebuild.rb', line 10

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 StandardError => 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

.export_table(db, table) ⇒ Object



51
52
53
# File 'lib/git_fit/db/rebuild.rb', line 51

def self.export_table(db, table)
  db[table].all.map { |r| r.except(:id) }
end

.import_table(db, table, rows) ⇒ Object



55
56
57
58
59
60
# File 'lib/git_fit/db/rebuild.rb', line 55

def self.import_table(db, table, rows)
  return if rows.empty?
  target = db[table].columns - [:id]
  filtered = rows.map { |r| r.select { |k, _| target.include?(k) } }
  db[table].multi_insert(filtered)
end