Class: SqliteRam

Inherits:
Object
  • Object
show all
Defined in:
lib/free_zipcode_data/sqlite_ram.rb

Overview

Open a SQlite DB, work with it in-memory and save back to disk

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sqlite_filename) ⇒ SqliteRam

Returns a new instance of SqliteRam.



10
11
12
13
14
15
# File 'lib/free_zipcode_data/sqlite_ram.rb', line 10

def initialize(sqlite_filename)
  @filename = sqlite_filename
  @ram_db   = SQLite3::Database.new(':memory:')
  @file_db  = SQLite3::Database.new(sqlite_filename)
  @conn     = @ram_db
end

Instance Attribute Details

#connObject (readonly)

Returns the value of attribute conn.



8
9
10
# File 'lib/free_zipcode_data/sqlite_ram.rb', line 8

def conn
  @conn
end

#filenameObject (readonly)

Returns the value of attribute filename.



8
9
10
# File 'lib/free_zipcode_data/sqlite_ram.rb', line 8

def filename
  @filename
end

Instance Method Details

#dump_tables(path) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/free_zipcode_data/sqlite_ram.rb', line 23

def dump_tables(path)
  tables = conn.execute('select name from sqlite_master where type = "table"')
  sql = nil
  tables.each do |table_array|
    table = table_array.first
    headers_sql = "pragma table_info('#{table}')"
    header = conn.execute(headers_sql).map { |e| e[1] }
    CSV.open(File.join(path, "#{table}.csv"), 'w') do |csv|
      csv << header
      sql = "select * from #{table}"
      conn.execute(sql).each do |row_array|
        csv << row_array
      end
    end
  end
end

#save_to_diskObject



17
18
19
20
21
# File 'lib/free_zipcode_data/sqlite_ram.rb', line 17

def save_to_disk
  backup = SQLite3::Backup.new(@file_db, 'main', @ram_db, 'main')
  backup.step(-1)
  backup.finish
end