jdbc-helper 0.7.6 → 0.7.7

Sign up to get free protection for your applications and to get access to all the features.
@@ -9,13 +9,13 @@ class CallableStatement < ParameterizedStatement
9
9
  # - IN parameter: value
10
10
  # - OUT parameter: class
11
11
  # - INOUT parameter: [value, class]
12
- # (Although class can be inferred from the value,
12
+ # (Although class can be inferred from the value,
13
13
  # we still need a way to figure out if it's INOUT parameter)
14
14
  def call *params
15
15
  check_closed
16
16
 
17
17
  out_params = set_params(params)
18
- measure_exec(:call) { @java_obj.execute }
18
+ @java_obj.execute
19
19
 
20
20
  result = {}
21
21
  out_params.each do |idx, jtype|
@@ -28,7 +28,7 @@ class CallableStatement < ParameterizedStatement
28
28
 
29
29
  private
30
30
  def set_params(params) # :nodoc:
31
- hash_params =
31
+ hash_params =
32
32
  if params.first.kind_of? Hash
33
33
  raise ArgumentError.new("More than one Hash given") if params.length > 1
34
34
  params.first
@@ -46,17 +46,17 @@ private
46
46
  case value
47
47
  # OUT parameter
48
48
  when Class
49
- jtype = JDBCHelper::Connection::RUBY_SQL_TYPE_MAP[value] || java.sql.Types::VARCHAR
49
+ jtype = JDBCHelper::Connection::RUBY_SQL_TYPE_MAP[value] || Java::java.sql.Types::VARCHAR
50
50
  @java_obj.registerOutParameter(idx_, jtype)
51
51
  out_params[idx] = jtype
52
52
 
53
53
  # INOUT parameter
54
54
  when Array
55
55
  set_param(idx_, value.first)
56
- jtype = JDBCHelper::Connection::RUBY_SQL_TYPE_MAP[value.last] || java.sql.Types::VARCHAR
56
+ jtype = JDBCHelper::Connection::RUBY_SQL_TYPE_MAP[value.last] || Java::java.sql.Types::VARCHAR
57
57
  @java_obj.registerOutParameter(idx_, jtype)
58
58
  out_params[idx] = jtype
59
-
59
+
60
60
  # IN parameter
61
61
  else
62
62
  set_param(idx_, value)
@@ -12,6 +12,7 @@ class ParameterizedStatement
12
12
 
13
13
  # Underlying Java object
14
14
  attr_reader :java_obj
15
+ alias java java_obj
15
16
 
16
17
  # @param [JDBCHelper::Connection] conn
17
18
  # @param [String] cstmt_str
@@ -36,16 +37,16 @@ class ParameterizedStatement
36
37
  when Float
37
38
  @java_obj.setDouble idx, param
38
39
  when Time
39
- @java_obj.setTimestamp idx, java.sql.Timestamp.new((param.to_f * 1000).to_i)
40
- when java.sql.Date
40
+ @java_obj.setTimestamp idx, Java::java.sql.Timestamp.new((param.to_f * 1000).to_i)
41
+ when Java::java.sql.Date
41
42
  @java_obj.setDate idx, param
42
- when java.sql.Time
43
+ when Java::java.sql.Time
43
44
  @java_obj.setTime idx, param
44
- when java.sql.Timestamp
45
+ when Java::java.sql.Timestamp
45
46
  @java_obj.setTimestamp idx, param
46
- when java.sql.Blob
47
+ when Java::java.sql.Blob
47
48
  @java_obj.setBinaryStream idx, param.getBinaryStream#, param.length
48
- when java.io.InputStream
49
+ when Java::java.io.InputStream
49
50
  @java_obj.setBinaryStream idx, param
50
51
  else
51
52
  @java_obj.setString idx, param.to_s
@@ -65,11 +66,7 @@ class ParameterizedStatement
65
66
 
66
67
  private
67
68
  def set_null idx, param
68
- @java_obj.setNull idx, java.sql.Types::NULL
69
- end
70
-
71
- def measure_exec(type, &blk) # :nodoc:
72
- @conn.send(:measure_exec, type, &blk)
69
+ @java_obj.setNull idx, Java::java.sql.Types::NULL
73
70
  end
74
71
 
75
72
  def check_closed
@@ -32,8 +32,8 @@ class PreparedStatement < ParameterizedStatement
32
32
  check_closed
33
33
 
34
34
  set_params(params)
35
- if measure_exec(:p_execute) { @java_obj.execute }
36
- ResultSetEnumerator.new(measure_exec(:p_query) { @java_obj.getResultSet })
35
+ if @java_obj.execute
36
+ ResultSetEnumerator.new(@java_obj.getResultSet)
37
37
  else
38
38
  @java_obj.getUpdateCount
39
39
  end
@@ -44,7 +44,7 @@ class PreparedStatement < ParameterizedStatement
44
44
  check_closed
45
45
 
46
46
  set_params(params)
47
- measure_exec(:p_update) { @java_obj.execute_update }
47
+ @java_obj.execute_update
48
48
  end
49
49
 
50
50
  # @return [Array] Returns an Array if block is not given
@@ -53,8 +53,7 @@ class PreparedStatement < ParameterizedStatement
53
53
 
54
54
  set_params(params)
55
55
  # sorry, ignoring privacy
56
- @conn.send(:process_and_close_rset,
57
- measure_exec(:p_query) { @java_obj.execute_query }, &blk)
56
+ @conn.send(:process_and_close_rset, @java_obj.execute_query, &blk)
58
57
  end
59
58
 
60
59
  # @return [JDBCHelper::Connection::ResultSetEnumerator]
@@ -64,7 +63,7 @@ class PreparedStatement < ParameterizedStatement
64
63
  return query(*params, &blk) if block_given?
65
64
 
66
65
  set_params(params)
67
- ResultSetEnumerator.new(measure_exec(:p_query) { @java_obj.execute_query })
66
+ ResultSetEnumerator.new(@java_obj.execute_query)
68
67
  end
69
68
 
70
69
  # Adds to the batch
@@ -75,14 +74,15 @@ class PreparedStatement < ParameterizedStatement
75
74
  set_params(params)
76
75
  @java_obj.add_batch
77
76
  end
77
+
78
78
  # Executes the batch
79
+ # @return [Fixnum] Sum of all successful update counts
79
80
  def execute_batch
80
81
  check_closed
81
82
 
82
- measure_exec(:p_execute_batch) {
83
- @java_obj.executeBatch
84
- }
83
+ @java_obj.executeBatch.select { |e| e > 0 }.inject(:+) || 0
85
84
  end
85
+
86
86
  # Clears the batch
87
87
  # @return [NilClass]
88
88
  def clear_batch
@@ -113,7 +113,7 @@ private
113
113
  end
114
114
 
115
115
  def set_null idx, param
116
- @java_obj.setNull idx, @types ? @types[idx - 1] : java.sql.Types::NULL
116
+ @java_obj.setNull idx, @types ? @types[idx - 1] : Java::java.sql.Types::NULL
117
117
  end
118
118
 
119
119
  def initialize(*args)
@@ -123,7 +123,7 @@ private
123
123
  @pmd = @java_obj.getParameterMetaData
124
124
  @types = @pmd.getParameterCount.times.map { |idx|
125
125
  # Oracle does not support getParameterType
126
- @pmd.getParameterType(idx + 1) rescue java.sql.Types::NULL
126
+ @pmd.getParameterType(idx + 1) rescue Java::java.sql.Types::NULL
127
127
  }
128
128
  rescue Exception => e
129
129
  Logger.new($stderr).warn e.to_s
@@ -113,8 +113,9 @@ private
113
113
  JDBCHelper::Connection::GETTER_MAP.fetch(type, :get_string)
114
114
  end
115
115
 
116
- @col_labels << @rsmd.get_column_label(i)
117
- @col_labels_d << @col_labels.last.downcase
116
+ label = @rsmd.get_column_label(i)
117
+ @col_labels << label
118
+ @col_labels_d << label.downcase
118
119
 
119
120
  end
120
121
 
@@ -97,6 +97,11 @@ class Row
97
97
  @labels.zip(@values).sort.hash
98
98
  end
99
99
 
100
+ # @return [Hash]
101
+ def to_h
102
+ Hash[ @labels.zip(@values) ]
103
+ end
104
+
100
105
  alias :== :eql?
101
106
 
102
107
  private
@@ -29,7 +29,7 @@ SqlServer = MSSQL
29
29
  module SqlServerConnector
30
30
  extend Connector
31
31
  def self.connect(host, user, password, db,
32
- timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
32
+ timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
33
33
  extra_params = {}, &block)
34
34
  check_params extra_params
35
35
  MSSQL.connect(host, user, password, db,
@@ -25,7 +25,7 @@ end#MySQLConnector
25
25
  module MySQLConnector
26
26
  extend Connector
27
27
  def self.connect(host, user, password, db,
28
- timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
28
+ timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
29
29
  extra_params = {}, &block)
30
30
  check_params extra_params
31
31
  MySQL.connect(host, user, password, db,
@@ -39,7 +39,7 @@ end#OracleConnector
39
39
  module OracleConnector
40
40
  extend Connector
41
41
  def self.connect(host, user, password, service_name,
42
- timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
42
+ timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
43
43
  extra_params = {}, &block)
44
44
  check_params extra_params
45
45
  Oracle.connect(host, user, password, service_name,
@@ -47,7 +47,7 @@ module OracleConnector
47
47
  end
48
48
 
49
49
  def self.connect_by_sid(host, user, password, sid,
50
- timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
50
+ timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
51
51
  extra_params = {}, &block)
52
52
  check_params extra_params
53
53
  Oracle.connect_by_sid(host, user, password, sid,
@@ -29,7 +29,7 @@ Postgres = PostgreSQL
29
29
  module PostgresConnector
30
30
  extend Connector
31
31
  def self.connect(host, user, password, db,
32
- timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
32
+ timeout = Constants::DEFAULT_LOGIN_TIMEOUT,
33
33
  extra_params = {}, &block)
34
34
  check_params extra_params
35
35
  PostgreSQL.connect(host, user, password, db,
@@ -82,7 +82,7 @@ module SQL
82
82
  def == other
83
83
  self.to_s == other.to_s
84
84
  end
85
-
85
+
86
86
  def eql? other
87
87
  self.class == other.class && self.to_s == other.to_s
88
88
  end
@@ -112,7 +112,7 @@ module SQL
112
112
  def self.singleton
113
113
  @@singleton ||= NotNullExpression.new
114
114
  end
115
-
115
+
116
116
  def initialize
117
117
  end
118
118
 
@@ -55,7 +55,7 @@ module SQL
55
55
 
56
56
  # SQL Helpers
57
57
  # ===========
58
-
58
+
59
59
  # Generates insert SQL with hash
60
60
  def self.insert table, data_hash
61
61
  insert_internal 'insert', table, data_hash
@@ -83,7 +83,7 @@ module SQL
83
83
  def self.select table, opts = {}
84
84
  opts = opts.reject { |k, v| v.nil? }
85
85
  check [
86
- "select #{opts.fetch(:select, ['*']).join(', ')} from #{table}",
86
+ "select #{opts.fetch(:select, ['*']).join(', ')} from #{table}",
87
87
  where_internal(opts.fetch(:where, {})),
88
88
  order(opts.fetch(:order, []).join(', '))
89
89
  ].reject(&:empty?).join(' ')
@@ -162,7 +162,7 @@ protected
162
162
  params = conds[1..-1] || []
163
163
  '(' +
164
164
  base.gsub('?') {
165
- param = params.shift
165
+ param = params.shift
166
166
  param ? value(param) : '?'
167
167
  } + ')'
168
168
  end
@@ -52,7 +52,7 @@ module SQLPrepared
52
52
  opts = opts.reject { |k, v| v.nil? }
53
53
  w_c, w_b = where_internal(opts.fetch(:where, {}))
54
54
  sql = [
55
- "select #{opts.fetch(:select, ['*']).join(', ')} from #{table}",
55
+ "select #{opts.fetch(:select, ['*']).join(', ')} from #{table}",
56
56
  w_c.to_s,
57
57
  SQL.order(opts.fetch(:order, []).join(', '))
58
58
  ].reject(&:empty?).join(' ')
@@ -80,8 +80,8 @@ module SQLPrepared
80
80
  conds = [conds] unless conds.is_a? Array
81
81
  binds = []
82
82
  clauses = []
83
- conds.compact.each do |cond|
84
- c, b = where_unit cond
83
+ conds.compact.each do |cond|
84
+ c, b = where_unit cond
85
85
  next if c.empty?
86
86
 
87
87
  binds += b
@@ -129,14 +129,7 @@ module SQLPrepared
129
129
  binds << v.begin << v.end
130
130
  ">= ? and #{k} <#{'=' unless v.exclude_end?} ?"
131
131
  when Array
132
- "in (" +
133
- v.map { |e|
134
- case e
135
- when String
136
- SQL.value e
137
- else
138
- e.to_s
139
- end }.join(', ') + ")"
132
+ "in (" + v.map { |ie| SQL.value ie }.join(', ') + ")"
140
133
  else
141
134
  binds << v
142
135
  "= ?"
@@ -147,7 +140,7 @@ module SQLPrepared
147
140
  ''
148
141
  else
149
142
  binds += conds[1..-1] if conds.length > 1
150
- "(#{conds.first})"
143
+ "(#{conds.first})"
151
144
  end
152
145
  else
153
146
  raise NotImplementedError.new("Parameter to where must be either Hash or String")
@@ -1,3 +1,3 @@
1
1
  module JDBCHelper
2
- VERSION = '0.7.6'
2
+ VERSION = '0.7.7'
3
3
  end
@@ -14,7 +14,7 @@ class FunctionWrapper < ObjectWrapper
14
14
  def initialize conn, name
15
15
  super conn, name
16
16
 
17
- @suffix =
17
+ @suffix =
18
18
  case conn.driver
19
19
  when /oracle/
20
20
  " from dual"
@@ -11,6 +11,11 @@ class ProcedureWrapper < ObjectWrapper
11
11
  # @return [String]
12
12
  alias to_s name
13
13
 
14
+ def initialize conn, name
15
+ super conn, name
16
+ @cols = nil
17
+ end
18
+
14
19
  # Executes the procedure and returns the values of INOUT & OUT parameters in Hash
15
20
  # @return [Hash]
16
21
  def call(*args)
@@ -41,7 +46,7 @@ private
41
46
 
42
47
  # Alas, metadata lookup can be case-sensitive. e.g. Oracle
43
48
  dbmd = @connection.java_obj.get_meta_data
44
- lookups =
49
+ lookups =
45
50
  if schema
46
51
  [ lambda { dbmd.getProcedureColumns(package, schema, procedure, nil) },
47
52
  lambda { dbmd.getProcedureColumns(package_u, schema_u, procedure_u, nil) } ]
@@ -124,7 +129,7 @@ private
124
129
 
125
130
  final = {}
126
131
  result.each do |idx, ret|
127
- key = input.keys.find { |key| key.to_s.upcase == @cols[idx - 1] }
132
+ key = input.keys.find { |k| k.to_s.upcase == @cols[idx - 1] }
128
133
  final[key] = ret
129
134
  end
130
135
  final
@@ -79,6 +79,7 @@ class TableWrapper < ObjectWrapper
79
79
  def insert_ignore data_hash = {}
80
80
  sql, binds = JDBCHelper::SQLPrepared.insert_ignore(name, @query_default.merge(data_hash))
81
81
  pstmt = prepare :insert, sql
82
+ pstmt.set_fetch_size @fetch_size if @fetch_size
82
83
  pstmt.send @update_method, *binds
83
84
  end
84
85
 
@@ -124,7 +125,7 @@ class TableWrapper < ObjectWrapper
124
125
  self
125
126
  end
126
127
  alias truncate_table! truncate!
127
-
128
+
128
129
  # Drops the table.
129
130
  # @note This operation cannot be undone
130
131
  # @return [JDBCHelper::TableWrapper] Self.
@@ -181,12 +182,23 @@ class TableWrapper < ObjectWrapper
181
182
  # @param [Hash] data_hash Default values
182
183
  # @return [JDBCHelper::TableWrapper]
183
184
  # @since 0.4.5
184
- def default data_hash
185
+ def default data_hash, &block
185
186
  raise ArgumentError.new("Hash required") unless data_hash.kind_of? Hash
186
187
 
187
188
  obj = self.dup
188
189
  obj.instance_variable_set :@query_default, @query_default.merge(data_hash)
189
- obj
190
+ ret obj, &block
191
+ end
192
+
193
+ # Returns a new TableWrapper object with the given fetch size.
194
+ # If a block is given, executes the select statement and yields each row to the block.
195
+ # @param [Fixnum] fsz Fetch size
196
+ # @return [JDBCHelper::TableWrapper]
197
+ # @since 0.7.7
198
+ def fetch_size fsz, &block
199
+ obj = self.dup
200
+ obj.instance_variable_set :@fetch_size, fsz
201
+ ret obj, &block
190
202
  end
191
203
 
192
204
  # Executes a select SQL for the table and returns an Enumerable object,
@@ -195,12 +207,12 @@ class TableWrapper < ObjectWrapper
195
207
  # @since 0.4.0
196
208
  def each &block
197
209
  sql, binds = JDBCHelper::SQLPrepared.select(
198
- name,
199
- :select => @query_select,
210
+ name,
211
+ :select => @query_select,
200
212
  :where => @query_where,
201
213
  :order => @query_order)
202
214
  pstmt = prepare :select, sql
203
- pstmt.enumerate *binds, &block
215
+ pstmt.enumerate(*binds, &block)
204
216
  end
205
217
 
206
218
  # Returns a new TableWrapper object whose subsequent inserts, updates,
@@ -227,13 +239,46 @@ class TableWrapper < ObjectWrapper
227
239
  @update_method == :add_batch
228
240
  end
229
241
 
242
+ # Clear batched operations.
243
+ # @param [*Symbol] types Types of batched operations to clear.
244
+ # If not given, :insert, :update and :delete.
245
+ # @return [nil]
246
+ def clear_batch *types
247
+ types = [:insert, :update, :delete] if types.empty?
248
+ types.each do |type|
249
+ raise ArgumentError.new("Invalid type: #{type}") unless @pstmts.has_key?(type)
250
+ @pstmts[type].values.each(&:clear_batch)
251
+ end
252
+ nil
253
+ end
254
+
255
+ # Execute batched operations.
256
+ # TableWrapper uses multiple PreparedStatements and each of them may have its own homogeneous batched commands.
257
+ # It is thus not possible for TableWrapper to precisely serialize all the commands when interleaved.
258
+ # What you can do here is to specify the types of commands (:insert, :update, and :delete) in the order of execution.
259
+ # The default is to execute deletes first, then updates, and finally inserts.
260
+ # You can also execute a subset of the three types.
261
+ # @param [*Symbol] types Types of batched operations to execute in order.
262
+ # If not given, :delete, :insert and :update.
263
+ # @return [Hash] Sum of all update counts indexed by operation type
264
+ def execute_batch *types
265
+ types = [:delete, :insert, :update] if types.empty?
266
+
267
+ Hash.new { 0 }.tap { |cnts|
268
+ types.each do |type|
269
+ raise ArgumentError.new("Invalid type: #{type}") unless @pstmts.has_key?(type)
270
+ cnts[type] += @pstmts[type].values.map(&:execute_batch).select { |e| e > 0 }.inject(:+) || 0
271
+ end
272
+ }
273
+ end
274
+
230
275
  # Returns the select SQL for this wrapper object
231
276
  # @return [String] Select SQL
232
277
  # @since 0.4.0
233
278
  def sql
234
279
  JDBCHelper::SQL.select(
235
- name,
236
- :select => @query_select,
280
+ name,
281
+ :select => @query_select,
237
282
  :where => @query_where,
238
283
  :order => @query_order)
239
284
  end
@@ -243,6 +288,8 @@ class TableWrapper < ObjectWrapper
243
288
  @update_method = :update
244
289
  @query_default = {}
245
290
  @query_where = []
291
+ @query_order = nil
292
+ @query_select = nil
246
293
  @pstmts = {
247
294
  :select => {},
248
295
  :insert => {},
@@ -250,8 +297,9 @@ class TableWrapper < ObjectWrapper
250
297
  :count => {},
251
298
  :update => {}
252
299
  }
300
+ @fetch_size = nil
253
301
  end
254
-
302
+
255
303
  # Closes the prepared statements
256
304
  # @since 0.5.0
257
305
  def close
@@ -291,7 +339,7 @@ private
291
339
 
292
340
  def ret obj, &block
293
341
  if block_given?
294
- obj.each &block
342
+ obj.each(&block)
295
343
  else
296
344
  obj
297
345
  end