Class: INat::DB

Inherits:
Object
  • Object
show all
Includes:
INat, App, App::Logger::DSL
Defined in:
lib/inat/data/db.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from App::Logger::DSL

#debug, debug, echo, #echo, error, #error, #info, info, log, #log, #warning, warning

Constructor Details

#initializeDB

Returns a new instance of DB.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/inat/data/db.rb', line 22

def initialize
  @mutex = Mutex::new
  @config = G.config
  @directory = @config[:data][:directory]
  FileUtils.mkpath @directory
  @data = SQLite3::Database::open "#{@directory}/inat-cache.db"
  @mutex.synchronize do
    @data.encoding = 'UTF-8'
    @data.auto_vacuum = 1
    @data.results_as_hash = true
    @data.foreign_keys = true
    @data.execute_batch Data::DDL.DDL
  end
  ObjectSpace.define_finalizer self, self.class.get_finalizer(@data)
end

Class Method Details

.execute(query, *args) ⇒ Object



78
79
80
# File 'lib/inat/data/db.rb', line 78

def execute query, *args
  instance.execute query, *args
end

.execute_batch(query) ⇒ Object



82
83
84
# File 'lib/inat/data/db.rb', line 82

def execute_batch query
  instance.execute_batch query
end

.instanceObject



73
74
75
76
# File 'lib/inat/data/db.rb', line 73

def instance
  @instance ||= new
  @instance
end

Instance Method Details

#execute(query, *args) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/inat/data/db.rb', line 38

def execute query, *args
  Status::status '[db]', '...'
  result = []
  @mutex.synchronize do
    last_time = Time::new
    info "DB: query = #{ query } args = #{ args.inspect }"
    result = @data.execute query, args
    time_diff = Time::new - last_time
    debug "DB OK: count = #{ Array === result && result.size || 'none' } time = #{ (time_diff * 1000000).to_i }ns"
  end
  Status::status '[db]', 'DONE'
  result
end

#execute_batch(query) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/inat/data/db.rb', line 52

def execute_batch query
  Status::status '[db]', '...'
  @mutex.synchronize do
    last_time = Time::new
    info "DB: batch = #{ query }"
    @data.execute_batch "BEGIN TRANSACTION;\n" + query + "\nCOMMIT;\n"
    time_diff = Time::new - last_time
    debug "DB OK: time = #{ (time_diff * 1000000).to_i }ns"
  end
  Status::status '[db]', 'DONE'
end