-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
jdbc.rb
108 lines (94 loc) · 2.54 KB
/
jdbc.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
require 'java'
module Sequel
module JDBC
module JavaLang; include_package 'java.lang'; end
module JavaSQL; include_package 'java.sql'; end
def self.load_driver(driver)
JavaLang::Class.forName(driver)
# "com.mysql.jdbc.Driver"
end
class Database < Sequel::Database
set_adapter_scheme :jdbc
def connect
unless conn_string = @opts[:uri] || @opts[:url] || @opts[:database]
raise Error, "No connection string specified"
end
unless conn_string =~ /^jdbc:/
conn_string = "jdbc:#{conn_string}"
end
JavaSQL::DriverManager.getConnection(
conn_string,
@opts[:user],
@opts[:password]
)
# "jdbc:mysql://127.0.0.1:3306/ruby?user=root"
# "mysql://127.0.0.1:3306/ruby?user=root"
end
def disconnect
@pool.disconnect {|c| c.close}
end
def dataset(opts = nil)
JDBC::Dataset.new(self, opts)
end
def execute_and_forget(sql)
@logger.info(sql) if @logger
@pool.hold do |conn|
stmt = conn.createStatement
begin
stmt.executeQuery(sql)
ensure
stmt.close
end
end
end
def execute(sql)
@logger.info(sql) if @logger
@pool.hold do |conn|
stmt = conn.createStatement
begin
yield stmt.executeQuery(sql)
ensure
stmt.close
end
end
end
end
class Dataset < Sequel::Dataset
def literal(v)
case v
when Time
literal(v.iso8601)
else
super
end
end
def fetch_rows(sql, &block)
@db.synchronize do
@db.execute(sql) do |result|
# get column names
meta = result.getMetaData
column_count = meta.getColumnCount
@columns = []
column_count.times {|i| @columns << meta.getColumnName(i).to_sym}
# get rows
while result.next
row = {}
@columns.each_with_index {|v, i| row[v] = result.getObject(i)}
yield row
end
end
end
self
end
def insert(*values)
@db.execute_and_forget insert_sql(*values)
end
def update(*args, &block)
@db.execute_and_forget update_sql(*args, &block)
end
def delete(opts = nil)
@db.execute_and_forget delete_sql(opts)
end
end
end
end