-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_connection.rb
executable file
·64 lines (50 loc) · 1.33 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
61
62
63
64
require 'sqlite3'
require 'singleton'
# set below = true for SQL queries to be printed to console
PRINT_QUERIES = false
class DBConnection < SQLite3::Database
include Singleton
SQL_FILE = File.join(File.dirname(__FILE__), 'import_db.sql')
DB_FILE = File.join(File.dirname(__FILE__), 'paintings.db')
# creates a connection to our database
def self.open
@db = SQLite3::Database.new(DB_FILE)
# inherited from the SQLite3 gem
@db.results_as_hash = true
@db.type_translation = true
end
def self.instance
reset! if @db.nil?
@db
end
def self.reset!
`#{"cat '#{SQL_FILE}' | sqlite3 '#{DB_FILE}'"}`
DBConnection.open
end
def self.execute(*args)
print_query(*args)
instance.execute(*args)
end
# unlike #execute, always returns the names of the columns first
def self.execute2(*args)
print_query(*args)
instance.execute2(*args)
end
def self.get_first_row(*args)
print_query(*args)
instance.get_first_row(*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