-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_driver.rb
More file actions
79 lines (66 loc) · 1.71 KB
/
Copy pathdatabase_driver.rb
File metadata and controls
79 lines (66 loc) · 1.71 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class DatabaseDriver
def initialize(database, user, password)
@database = database
@user = user
@password = password
@connected = false
end
def self.open(database, user, password)
driver = self.new(database, user, password)
driver.connect
# if a block is not given it will return the object itself
return driver unless block_given?
begin
yield(driver)
# the method disconnet is ran always, even when an exception is raised
ensure
driver.disconnect
end
end
def connect
# connects to database
@connected = true
puts "Connected to #{@database} as #{@user}."
end
def disconnect
# disconnects from database
puts "Disconnected."
end
def begin_transaction
puts "Beginning transaction..."
end
def commit_transaction
puts "Committed transaction."
end
def rollback_transaction
puts "Rolled back transaction!"
end
def execute(sql)
raise "Not connected!" unless @connected
puts "Executing #{sql}..."
end
def transactionally
begin_transaction
yield
commit_transaction
rescue Exception => e
rollback_transaction
end
end
DatabaseDriver.open("my_database", "admin", "secret") do |driver|
# it runs the open class method
driver.transactionally do
driver.execute("UPDATE ORDERS SET status='completed'")
driver.execute("DELETE * FROM SHIPPING_QUEUE")
end
# not run in a transaction
driver.execute("SELECT * FROM ORddDERS")
driver.execute("SELECT * FROM USERS")
end
DatabaseDriver.open("my_database", "admin", "secret") do |driver|
driver.transactionally do
driver.execute("UPDATE ORDERS SET status='completed'")
raise "Boom!"
driver.execute("DELETE * FROM SHIPPING_QUEUE")
end
end