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



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
# 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)

  tables = db.tables - [:schema_migrations]
  data = {}
  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)
  end
  raise RebuildError, "Rebuild failed: #{e.message}"
end

.export_table(db, table) ⇒ Object



36
37
38
# File 'lib/git_fit/db/rebuild.rb', line 36

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

.import_table(db, table, rows) ⇒ Object



40
41
42
43
44
45
# File 'lib/git_fit/db/rebuild.rb', line 40

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