-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_connection.rb
60 lines (47 loc) · 1.25 KB
/
db_connection.rb
1
2
3
4
5
6
7
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
require 'sqlite3'
PRINT_QUERIES = ENV['PRINT_QUERIES'] == 'true'
# https://tomafro.net/2010/01/tip-relative-paths-with-file-expand-path
ROOT_FOLDER = File.join(File.dirname(__FILE__), '..')
FAMILY_SQL_FILE = File.join(ROOT_FOLDER, 'family.sql')
FAMILY_DB_FILE = File.join(ROOT_FOLDER, 'family.db')
class DBConnection
def self.open(db_file_name)
@db = SQLite3::Database.new(db_file_name)
@db.results_as_hash = true
@db.type_translation = true
@db
end
def self.reset
commands = [
"rm '#{FAMILY_DB_FILE}'",
"cat '#{FAMILY_SQL_FILE}' | sqlite3 '#{FAMILY_DB_FILE}'"
]
commands.each { |command| `#{command}` }
DBConnection.open(FAMILY_DB_FILE)
end
def self.instance
reset if @db.nil?
@db
end
def self.execute(*args)
print_query(*args)
instance.execute(*args)
end
def self.execute2(*args)
print_query(*args)
instance.execute2(*args)
end
def self.last_insert_row_id
instance.last_insert_row_id
end
private
def self.print_query(query, *interpolation_args)
return unless PRINT_QUERIES
puts '--------------------'
puts query
unless interpolation_args.empty?
puts "interpolate: #{interpolation_args.inspect}"
end
puts '--------------------'
end
end