Class: JDBCHelper::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/jdbc-helper/connection.rb,
lib/jdbc-helper/connection/row.rb,
lib/jdbc-helper/connection/type_map.rb,
lib/jdbc-helper/connection/statement_pool.rb,
lib/jdbc-helper/connection/callable_statement.rb,
lib/jdbc-helper/connection/prepared_statement.rb,
lib/jdbc-helper/connection/result_set_enumerator.rb,
lib/jdbc-helper/connection/parameterized_statement.rb

Overview

p_upd.close

Defined Under Namespace

Classes: CallableStatement, ParameterizedStatement, PreparedStatement, ResultSetEnumerator, Row, Stat, StatementPool, Transaction

Constant Summary collapse

RUBY_SQL_TYPE_MAP =
{
  Fixnum => java.sql.Types::INTEGER,
  Bignum => java.sql.Types::BIGINT,
  String => java.sql.Types::VARCHAR,
  Float  => java.sql.Types::DOUBLE,
  Time   => java.sql.Types::TIMESTAMP
}
GETTER_MAP =
{
  java.sql.Types::TINYINT                   => :getInt,
  java.sql.Types::SMALLINT                  => :getInt,
  java.sql.Types::INTEGER                   => :getInt,
  java.sql.Types::BIGINT                    => :getLong,

  java.sql.Types::CHAR                      => :getString,
  java.sql.Types::VARCHAR                   => :getString,
  java.sql.Types::LONGVARCHAR               => :getString,
  (java.sql.Types::NCHAR        rescue nil) => :getString,
  (java.sql.Types::NVARCHAR     rescue nil) => :getString,
  (java.sql.Types::LONGNVARCHAR rescue nil) => :getString,

  # !! MySQL function returns VARBINARY type
  java.sql.Types::BINARY             => :getBinaryStream,
  java.sql.Types::VARBINARY          => :getBinaryStream,
  java.sql.Types::LONGVARBINARY      => :getBinaryStream,

  java.sql.Types::REAL               => :getDouble,
  java.sql.Types::FLOAT              => :getFloat,
  java.sql.Types::DOUBLE             => :getDouble,

  java.sql.Types::DATE               => :getDate,
  java.sql.Types::TIME               => :getTime,
  java.sql.Types::TIMESTAMP          => :getTimestamp,

  java.sql.Types::BLOB               => :getBlob,
  java.sql.Types::CLOB               => :getString,
  (java.sql.Types::NCLOB rescue nil) => :getString,

  java.sql.Types::BOOLEAN            => :getBoolean
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Connection

Creates a database connection.

  • ‘args` hash must include :driver (or “driver”) and :url (or “url”)

  • and takes optional :user and :password tuples (or “user”, “password”)

  • You can also specify :timeout (or “timeout”) to override the default connection timeout (60 seconds)

Must be closed explicitly if not used. If a block is given, the connection is automatically closed after executing the block.

Parameters:

  • args (Hash) (defaults to: {})

Raises:

  • (ArgumentError)


147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/jdbc-helper/connection.rb', line 147

def initialize(args = {})
  # Subsequent deletes should not affect the input
  @args = Marshal.load(Marshal.dump(args))
  args = InsensitiveHash[ @args ]

  raise ArgumentError.new("driver not given") unless args.has_key? :driver
  raise ArgumentError.new("url not given") unless args.has_key? :url

  @driver = args.delete :driver
  @url = args.delete :url

  # NameError will be thrown for invalid drivers
  Java::JavaClass.for_name @driver

  timeout = args.has_key?(:timeout) ? args.delete(:timeout) : Constants::DEFAULT_LOGIN_TIMEOUT
  if timeout
    if timeout.is_a?(Fixnum) == false || timeout <= 0
      raise ArgumentError.new("Timeout must be a positive integer")
    end
    java.sql.DriverManager.setLoginTimeout timeout
  end

  props = java.util.Properties.new
  args.each do |k, v|
    props.setProperty(k.to_s, v.to_s) if v
  end
  
  @conn = java.sql.DriverManager.get_connection(@url, props)
  @spool = StatementPool.send :new, self
  @bstmt = nil

  @stats = Hash.new { | h, k | h[k] = Stat.new(k, 0, 0, 0) }
  @prev_stat = Stat.new(nil, 0, 0, 0)

  @pstmts = []
  
  @table_wrappers = {}

  if block_given?
    begin
      yield self
    ensure
      close rescue nil
    end
  end
end

Instance Attribute Details

#driverString (readonly)

JDBC driver of the connection

Returns:

  • (String)


130
131
132
# File 'lib/jdbc-helper/connection.rb', line 130

def driver
  @driver
end

#fetch_sizeFixnum

Returns the fetch size of the connection. If not set, nil is returned.

Returns:

  • (Fixnum)


400
401
402
# File 'lib/jdbc-helper/connection.rb', line 400

def fetch_size
  @fetch_size
end

#statsHash (readonly)

Returns the accumulated statistics of each operation

Returns:

  • (Hash)

    Accumulated statistics of each type of operation



122
123
124
# File 'lib/jdbc-helper/connection.rb', line 122

def stats
  @stats
end

#urlString (readonly)

JDBC URL of the connection

Returns:

  • (String)


126
127
128
# File 'lib/jdbc-helper/connection.rb', line 126

def url
  @url
end

Instance Method Details

#add_batch(qstr) ⇒ NilClass

Adds a statement to be executed in batch Adds to the batch

Parameters:

  • qstr (String)

Returns:

  • (NilClass)


347
348
349
350
351
352
# File 'lib/jdbc-helper/connection.rb', line 347

def add_batch(qstr)
  check_closed

  @bstmt ||= @spool.take
  @bstmt.add_batch qstr
end

#clear_batchNilClass

Clears the batched statements including prepared statements.

Returns:

  • (NilClass)


372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/jdbc-helper/connection.rb', line 372

def clear_batch
  check_closed

  if @bstmt
    @bstmt.clear_batch
    @spool.give @bstmt
    @bstmt = nil
  end

  @pstmts.each do |stmt|
    measure_exec(:execute_batch) { stmt.clear_batch }
  end
end

#cloneJDBCHelper::Connection

Creates another connection with the same parameters as this Connection.



196
197
198
199
200
# File 'lib/jdbc-helper/connection.rb', line 196

def clone
  nc = JDBCHelper::Connection.new @args
  nc.fetch_size = @fetch_size if @fetch_size
  nc
end

#closeNilClass

Closes the connection

Returns:

  • (NilClass)


404
405
406
407
408
409
# File 'lib/jdbc-helper/connection.rb', line 404

def close
  return if closed?
  @spool.close
  @conn.close
  @conn = @spool = nil
end

#closed?Boolean

Returns if this connection is closed or not

Returns:

  • (Boolean)


413
414
415
# File 'lib/jdbc-helper/connection.rb', line 413

def closed?
  @conn.nil?
end

#enumerate(qstr) {|JDBCHelper::Connection::Row| ... } ⇒ JDBCHelper::Connection::ResultSetEnumerator

Returns an enumerable object of the query result. “enumerate” method is preferable when dealing with a large result set, since it doesn’t have to build a large array.

The returned enumerator is automatically closed after enumeration.

conn.enumerate('SELECT * FROM T').each_slice(10) do | slice |
    slice.each { | row | print row }
    puts
end

Parameters:

  • qstr (String)

    SQL string

Yields:

Returns:



328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/jdbc-helper/connection.rb', line 328

def enumerate(qstr, &blk)
  check_closed

  return query(qstr, &blk) if block_given?

  stmt = @spool.take
  begin
    rset = measure_exec(:query) { stmt.execute_query(qstr) }
    return ResultSetEnumerator.send(:new, rset) { @spool.give stmt }
  rescue Exception
    @spool.give stmt
    raise
  end
end

#execute(qstr) ⇒ Fixnum|ResultSetEnumerator

Executes an SQL and returns the count of the update rows or a ResultSetEnumerator object depending on the type of the given statement. If a ResultSetEnumerator is returned, it must be enumerated or closed.

Parameters:

  • qstr (String)

    SQL string

Returns:



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/jdbc-helper/connection.rb', line 260

def execute(qstr)
  check_closed

  stmt = @spool.take
  begin
    if measure_exec(:execute) { stmt.execute(qstr) }
      ResultSetEnumerator.send(:new, stmt.getResultSet) { @spool.give stmt }
    else
      rset = stmt.getUpdateCount
      @spool.give stmt
      rset
    end
  rescue Exception => e
    @spool.give stmt
    raise
  end
end

#execute_batchNilClass

Executes batched statements including prepared statements. No effect when no statment is added

Returns:

  • (NilClass)


356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/jdbc-helper/connection.rb', line 356

def execute_batch
  check_closed

  if @bstmt
    measure_exec(:execute_batch) { @bstmt.execute_batch }
    @spool.give @bstmt
    @bstmt = nil
  end

  @pstmts.each do |stmt|
    measure_exec(:execute_batch) { stmt.execute_batch }
  end
end

#function(func_name) ⇒ JDBCHelper::FunctionWrapper

Returns a function wrapper for the given function name

Parameters:

  • func_name (String/Symbol)

    Name of the function to be wrapped

Returns:

Since:

  • 0.2.2



437
438
439
# File 'lib/jdbc-helper/connection.rb', line 437

def function func_name
  JDBCHelper::FunctionWrapper.new self, func_name
end

#inspectObject



449
450
451
452
453
# File 'lib/jdbc-helper/connection.rb', line 449

def inspect
  InsensitiveHash[@args].merge({ :closed? => closed? }).tap { |c|
    c.delete(:password)
  }.inspect
end

#jdbc_connObject Also known as: java_obj

Returns the underlying JDBC Connection object. Only use this when you really need to access it directly.



134
135
136
# File 'lib/jdbc-helper/connection.rb', line 134

def jdbc_conn
  @conn
end

#prepare(qstr) ⇒ Object

Creates a prepared statement, which is also an encapsulation of Java PreparedStatement object

Parameters:

  • qstr (String)

    SQL string



204
205
206
207
208
209
210
211
# File 'lib/jdbc-helper/connection.rb', line 204

def prepare(qstr)
  check_closed

  pstmt = PreparedStatement.send(:new, self, qstr,
      measure_exec(:prepare) { @conn.prepare_statement(qstr) })
  @pstmts << pstmt
  pstmt
end

#prepare_call(qstr) ⇒ Object

Creates a callable statement.

Parameters:

  • qstr (String)

    SQL string



220
221
222
223
224
225
# File 'lib/jdbc-helper/connection.rb', line 220

def prepare_call(qstr)
  check_closed

  CallableStatement.send(:new, self, qstr,
      measure_exec(:prepare_call) { @conn.prepare_call qstr })
end

#prepared_statementsArray

Returns Prepared statements currently opened for this connection.

Returns:

  • (Array)

    Prepared statements currently opened for this connection



214
215
216
# File 'lib/jdbc-helper/connection.rb', line 214

def prepared_statements
  @pstmts
end

#prev_statJDBCHelper::Connection::Stat

Returns the statistics of the previous operation

Returns:



116
117
118
# File 'lib/jdbc-helper/connection.rb', line 116

def prev_stat
  @prev_stat.dup
end

#procedure(proc_name) ⇒ JDBCHelper::ProcedureWrapper

Returns a procedure wrapper for the given procedure name

Parameters:

  • proc_name (String/Symbol)

    Name of the procedure to be wrapped

Returns:

Since:

  • 0.3.0



445
446
447
# File 'lib/jdbc-helper/connection.rb', line 445

def procedure proc_name
  JDBCHelper::ProcedureWrapper.new self, proc_name
end

#query(qstr) {|JDBCHelper::Connection::Row| ... } ⇒ Array

Executes a select query. When a code block is given, each row of the result is passed to the block one by one. If a code block not given, this method will return the array of the entire result rows. (which can be pretty inefficient when the result set is large. In such cases, use enumerate instead.)

The concept of statement object of JDBC is encapsulated, so there’s no need to do additional task, when you nest select queries, for example.

conn.query("SELECT a FROM T") do | trow |
    conn.query("SELECT * FROM U_#{trow.a}") do | urow |
        # ... and so on ...
    end
end

Parameters:

  • qstr (String)

    SQL string

Yields:

Returns:

  • (Array)


305
306
307
308
309
310
311
312
# File 'lib/jdbc-helper/connection.rb', line 305

def query(qstr, &blk)
  check_closed

  @spool.with do | stmt |
    rset = measure_exec(:query) { stmt.execute_query(qstr) }
    process_and_close_rset(rset, &blk)
  end
end

#sequence(sequence_name) ⇒ JDBCHelper::SequenceWrapper

Returns a sequence wrapper for the given name

Parameters:

  • sequence_name (String/Symbol)

    Name of the sequence to be wrapped

Returns:

Since:

  • 0.4.2



429
430
431
# File 'lib/jdbc-helper/connection.rb', line 429

def sequence sequence_name
  JDBCHelper::SequenceWrapper.new self, sequence_name
end

#set_fetch_size(fsz) ⇒ NilClass Also known as: fetch_size=

Gives the JDBC driver a hint of the number of rows to fetch from the database by a single interaction. This is only a hint. It may have no effect at all.

Parameters:

  • fsz (Fixnum)

Returns:

  • (NilClass)


390
391
392
393
394
395
# File 'lib/jdbc-helper/connection.rb', line 390

def set_fetch_size(fsz)
  check_closed

  @fetch_size = fsz
  @spool.each { | stmt | stmt.set_fetch_size @fetch_size }
end

#table(table_name) ⇒ JDBCHelper::TableWrapper

Returns a table wrapper for the given table name

Parameters:

  • table_name (String/Symbol)

    Name of the table to be wrapped

Returns:

Since:

  • 0.2.0



421
422
423
# File 'lib/jdbc-helper/connection.rb', line 421

def table table_name
  @table_wrappers[table_name] ||= JDBCHelper::TableWrapper.new self, table_name
end

#transaction {|JDBCHelper::Connection::Transaction| ... } ⇒ Boolean

Executes the given code block as a transaction. Returns true if the transaction is committed. A transaction object is passed to the block, which only has commit and rollback methods. The execution breaks out of the code block when either of the methods is called.

Yields:

Returns:

  • (Boolean)

    True if committed

Raises:

  • (ArgumentError)


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/jdbc-helper/connection.rb', line 232

def transaction
  check_closed

  raise ArgumentError.new("Transaction block not given") unless block_given?
  tx = Transaction.send :new, @conn
  ac = @conn.get_auto_commit
  status = :unknown
  begin
    @conn.set_auto_commit false
    yield tx
    @conn.commit
    status = :committed
  rescue Transaction::Commit
    status = :committed
  rescue Transaction::Rollback
    status = :rolledback
  ensure
    @conn.rollback if status == :unknown && @conn.get_auto_commit == false
    @conn.set_auto_commit ac
  end
  status == :committed
end

#update(qstr) ⇒ Fixnum

Executes an update and returns the count of the updated rows.

Parameters:

  • qstr (String)

    SQL string

Returns:

  • (Fixnum)

    Count of affected records



281
282
283
284
285
286
287
# File 'lib/jdbc-helper/connection.rb', line 281

def update(qstr)
  check_closed

  @spool.with do | stmt |
    ret = measure_exec(:update) { stmt.execute_update(qstr) }
  end
end