Class: Yob::Database::Mysql

Inherits:
Base
  • Object
show all
Defined in:
lib/yob/database.rb

Instance Attribute Summary

Attributes inherited from Base

#configuration

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Mysql

Returns a new instance of Mysql.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/yob/database.rb', line 18

def initialize(configuration)
  super

  unless File.directory?(configuration.mysql_log_directory)
    raise Yob::Configuration::Error, "mysql_log_directory does not exist"
  end

  unless File.exists?(configuration.mysqldump_executable)
    raise Yob::Configuration::Error, "mysqldump_executable does not exist"
  end
end

Instance Method Details

#full_backupObject



30
31
32
33
34
35
36
37
38
39
# File 'lib/yob/database.rb', line 30

def full_backup
  writer = yield Time.now.strftime("%Y%m%d-%H%M%S#{random_filename_string}.sql.gpg"), nil
  begin
    puts "[Database::Mysql] dumping all databases to SQL..."
    system("#{configuration.mysqldump_executable} --all-databases --default-character-set=utf8 --skip-opt --create-options --add-drop-database --extended-insert --flush-logs --master-data --quick --single-transaction >&#{writer.fileno}")
    puts "[Database::Mysql] dump completed"
  ensure
    writer.close
  end
end

#partial_backupObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/yob/database.rb', line 41

def partial_backup
  require 'sqlite3'

  @db = SQLite3::Database.new(configuration.fetch("file_database", "#{File.dirname(__FILE__)}/yob.db"))
  @db.execute("CREATE TABLE IF NOT EXISTS files (id INTEGER PRIMARY KEY AUTOINCREMENT, filename varchar(255) unique not null, file_size integer not null, file_time datetime not null)")

  files = Dir["#{configuration.mysql_log_directory}/mysql-bin.*"]
  files.each do |filename|
    next if filename[-5..-1] == 'index'

    stats = File.stat(filename)
    file_time = stats.mtime.strftime("%Y-%m-%d %H:%M:%S")

    row = @db.get_first_row("SELECT id, file_size, file_time FROM files WHERE filename = ?", filename)
    if row && row[1].to_i == stats.size && row[2] == file_time
      puts "[Database::Mysql] skipping #{filename}" if @configuration["debug"]
    else
      File.open(filename, "r") do |logfile|
        yield "#{File.basename(filename)}#{random_filename_string}.gpg", logfile
      end

      if row
        @db.execute("UPDATE files SET file_size = ?, file_time = ? WHERE id = ?", stats.size, file_time, row[0])
      else
        stmt = @db.prepare("INSERT INTO files (filename, file_size, file_time) VALUES (?, ?, ?)")
        stmt.execute(filename, stats.size, file_time)
      end
    end
  end
end