class Sequel::JDBC::Database
Attributes
Map of JDBC
type ids to callable objects that return appropriate ruby or java values.
Whether to convert some Java types to ruby types when retrieving rows. True by default, can be set to false to roughly double performance when fetching rows.
The Java database driver we are using (should be a Java class)
The fetch size to use for JDBC
Statement objects created by this database. By default, this is nil so a fetch size is not set explicitly.
Map of JDBC
type ids to callable objects that return appropriate ruby values.
Public Instance Methods
Execute the given stored procedure with the give name. If a block is given, the stored procedure should return rows.
# File lib/sequel/adapters/jdbc.rb 187 def call_sproc(name, opts = OPTS) 188 args = opts[:args] || [] 189 sql = "{call #{name}(#{args.map{'?'}.join(',')})}" 190 synchronize(opts[:server]) do |conn| 191 begin 192 cps = conn.prepareCall(sql) 193 194 i = 0 195 args.each{|arg| set_ps_arg(cps, arg, i+=1)} 196 197 if defined?(yield) 198 yield log_connection_yield(sql, conn){cps.executeQuery} 199 else 200 log_connection_yield(sql, conn){cps.executeUpdate} 201 if opts[:type] == :insert 202 last_insert_id(conn, opts) 203 end 204 end 205 rescue *DATABASE_ERROR_CLASSES => e 206 raise_error(e) 207 ensure 208 cps.close if cps 209 end 210 end 211 end
Connect to the database using JavaSQL::DriverManager.getConnection, and falling back to driver.new.connect if the driver is known.
# File lib/sequel/adapters/jdbc.rb 215 def connect(server) 216 opts = server_opts(server) 217 conn = if jndi? 218 get_connection_from_jndi 219 else 220 args = [uri(opts)] 221 args.concat([opts[:user], opts[:password]]) if opts[:user] && opts[:password] 222 begin 223 JavaSQL::DriverManager.setLoginTimeout(opts[:login_timeout]) if opts[:login_timeout] 224 raise StandardError, "skipping regular connection" if opts[:jdbc_properties] 225 JavaSQL::DriverManager.getConnection(*args) 226 rescue StandardError, *DATABASE_ERROR_CLASSES => e 227 raise e unless driver 228 # If the DriverManager can't get the connection - use the connect 229 # method of the driver. (This happens under Tomcat for instance) 230 props = java.util.Properties.new 231 if opts && opts[:user] && opts[:password] 232 props.setProperty("user", opts[:user]) 233 props.setProperty("password", opts[:password]) 234 end 235 opts[:jdbc_properties].each{|k,v| props.setProperty(k.to_s, v)} if opts[:jdbc_properties] 236 begin 237 c = driver.new.connect(args[0], props) 238 raise(Sequel::DatabaseError, 'driver.new.connect returned nil: probably bad JDBC connection string') unless c 239 c 240 rescue StandardError, *DATABASE_ERROR_CLASSES => e2 241 if e2.respond_to?(:message=) && e2.message != e.message 242 e2.message = "#{e2.message}\n#{e.class.name}: #{e.message}" 243 end 244 raise e2 245 end 246 end 247 end 248 setup_connection_with_opts(conn, opts) 249 end
Close given adapter connections, and delete any related prepared statements.
# File lib/sequel/adapters/jdbc.rb 252 def disconnect_connection(c) 253 @connection_prepared_statements_mutex.synchronize{@connection_prepared_statements.delete(c)} 254 c.close 255 end
# File lib/sequel/adapters/jdbc.rb 257 def execute(sql, opts=OPTS, &block) 258 return call_sproc(sql, opts, &block) if opts[:sproc] 259 return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)} 260 synchronize(opts[:server]) do |conn| 261 statement(conn) do |stmt| 262 if block 263 if size = fetch_size 264 stmt.setFetchSize(size) 265 end 266 yield log_connection_yield(sql, conn){stmt.executeQuery(sql)} 267 else 268 case opts[:type] 269 when :ddl 270 log_connection_yield(sql, conn){stmt.execute(sql)} 271 when :insert 272 log_connection_yield(sql, conn){execute_statement_insert(stmt, sql)} 273 opts = Hash[opts] 274 opts[:stmt] = stmt 275 last_insert_id(conn, opts) 276 else 277 log_connection_yield(sql, conn){stmt.executeUpdate(sql)} 278 end 279 end 280 end 281 end 282 end
# File lib/sequel/adapters/jdbc.rb 285 def execute_ddl(sql, opts=OPTS) 286 opts = Hash[opts] 287 opts[:type] = :ddl 288 execute(sql, opts) 289 end
# File lib/sequel/adapters/jdbc.rb 291 def execute_insert(sql, opts=OPTS) 292 opts = Hash[opts] 293 opts[:type] = :insert 294 execute(sql, opts) 295 end
Use the JDBC
metadata to get a list of foreign keys for the table.
# File lib/sequel/adapters/jdbc.rb 304 def foreign_key_list(table, opts=OPTS) 305 m = output_identifier_meth 306 schema, table = metadata_schema_and_table(table, opts) 307 foreign_keys = {} 308 metadata(:getImportedKeys, nil, schema, table) do |r| 309 if fk = foreign_keys[r[:fk_name]] 310 fk[:columns] << [r[:key_seq], m.call(r[:fkcolumn_name])] 311 fk[:key] << [r[:key_seq], m.call(r[:pkcolumn_name])] 312 elsif r[:fk_name] 313 foreign_keys[r[:fk_name]] = {:name=>m.call(r[:fk_name]), :columns=>[[r[:key_seq], m.call(r[:fkcolumn_name])]], :table=>m.call(r[:pktable_name]), :key=>[[r[:key_seq], m.call(r[:pkcolumn_name])]]} 314 end 315 end 316 foreign_keys.values.each do |fk| 317 [:columns, :key].each do |k| 318 fk[k] = fk[k].sort.map{|_, v| v} 319 end 320 end 321 end
Sequel::Database#freeze
# File lib/sequel/adapters/jdbc.rb 297 def freeze 298 @type_convertor_map.freeze 299 @basic_type_convertor_map.freeze 300 super 301 end
Use the JDBC
metadata to get the index information for the table.
# File lib/sequel/adapters/jdbc.rb 324 def indexes(table, opts=OPTS) 325 m = output_identifier_meth 326 schema, table = metadata_schema_and_table(table, opts) 327 indexes = {} 328 metadata(:getIndexInfo, nil, schema, table, false, true) do |r| 329 next unless name = r[:column_name] 330 next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re 331 i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>[false, 0].include?(r[:non_unique])} 332 i[:columns] << m.call(name) 333 end 334 indexes 335 end
Whether or not JNDI is being used for this connection.
# File lib/sequel/adapters/jdbc.rb 338 def jndi? 339 !!(uri =~ JNDI_URI_REGEXP) 340 end
All tables in this database
# File lib/sequel/adapters/jdbc.rb 343 def tables(opts=OPTS) 344 get_tables('TABLE', opts) 345 end
The uri for this connection. You can specify the uri using the :uri, :url, or :database options. You don't need to worry about this if you use Sequel.connect with the JDBC
connectrion strings.
# File lib/sequel/adapters/jdbc.rb 351 def uri(opts=OPTS) 352 opts = @opts.merge(opts) 353 ur = opts[:uri] || opts[:url] || opts[:database] 354 ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}" 355 end
All views in this database
# File lib/sequel/adapters/jdbc.rb 358 def views(opts=OPTS) 359 get_tables('VIEW', opts) 360 end
Private Instance Methods
Call the DATABASE_SETUP proc directly after initialization, so the object always uses sub adapter specific code. Also, raise an error immediately if the connection doesn't have a uri, since JDBC
requires one.
# File lib/sequel/adapters/jdbc.rb 368 def adapter_initialize 369 @connection_prepared_statements = {} 370 @connection_prepared_statements_mutex = Mutex.new 371 @fetch_size = @opts[:fetch_size] ? typecast_value_integer(@opts[:fetch_size]) : default_fetch_size 372 @convert_types = typecast_value_boolean(@opts.fetch(:convert_types, true)) 373 raise(Error, "No connection string specified") unless uri 374 375 resolved_uri = jndi? ? get_uri_from_jndi : uri 376 setup_type_convertor_map_early 377 378 @driver = if (match = /\Ajdbc:([^:]+)/.match(resolved_uri)) && (prok = Sequel::Database.load_adapter(match[1].to_sym, :map=>DATABASE_SETUP, :subdir=>'jdbc')) 379 prok.call(self) 380 else 381 @opts[:driver] 382 end 383 384 setup_type_convertor_map 385 end
Yield the native prepared statements hash for the given connection to the block in a thread-safe manner.
# File lib/sequel/adapters/jdbc.rb 389 def cps_sync(conn, &block) 390 @connection_prepared_statements_mutex.synchronize{yield(@connection_prepared_statements[conn] ||= {})} 391 end
# File lib/sequel/adapters/jdbc.rb 393 def database_error_classes 394 DATABASE_ERROR_CLASSES 395 end
# File lib/sequel/adapters/jdbc.rb 397 def database_exception_sqlstate(exception, opts) 398 if database_exception_use_sqlstates? 399 while exception.respond_to?(:cause) 400 exception = exception.cause 401 return exception.getSQLState if exception.respond_to?(:getSQLState) 402 end 403 end 404 nil 405 end
# File lib/sequel/adapters/jdbc.rb 412 def dataset_class_default 413 Dataset 414 end
The default fetch size to use for statements. Nil by default, so that the default for the JDBC
driver is used.
# File lib/sequel/adapters/jdbc.rb 498 def default_fetch_size 499 nil 500 end
Raise a disconnect error if the SQL
state of the cause of the exception indicates so.
Sequel::Database#disconnect_error?
# File lib/sequel/adapters/jdbc.rb 417 def disconnect_error?(exception, opts) 418 cause = exception.respond_to?(:cause) ? exception.cause : exception 419 super || (cause.respond_to?(:getSQLState) && cause.getSQLState =~ /^08/) 420 end
Execute the prepared statement. If the provided name is a dataset, use that as the prepared statement, otherwise use it as a key to look it up in the prepared_statements hash. If the connection we are using has already prepared an identical statement, use that statement instead of creating another. Otherwise, prepare a new statement for the connection, bind the variables, and execute it.
# File lib/sequel/adapters/jdbc.rb 429 def execute_prepared_statement(name, opts=OPTS) 430 args = opts[:arguments] 431 if name.is_a?(Dataset) 432 ps = name 433 name = ps.prepared_statement_name 434 else 435 ps = prepared_statement(name) 436 end 437 sql = ps.prepared_sql 438 synchronize(opts[:server]) do |conn| 439 if name and cps = cps_sync(conn){|cpsh| cpsh[name]} and cps[0] == sql 440 cps = cps[1] 441 else 442 log_connection_yield("CLOSE #{name}", conn){cps[1].close} if cps 443 if name 444 opts = Hash[opts] 445 opts[:name] = name 446 end 447 cps = log_connection_yield("PREPARE#{" #{name}:" if name} #{sql}", conn){prepare_jdbc_statement(conn, sql, opts)} 448 if size = fetch_size 449 cps.setFetchSize(size) 450 end 451 cps_sync(conn){|cpsh| cpsh[name] = [sql, cps]} if name 452 end 453 i = 0 454 args.each{|arg| set_ps_arg(cps, arg, i+=1)} 455 msg = "EXECUTE#{" #{name}" if name}" 456 if ps.log_sql 457 msg += " (" 458 msg << sql 459 msg << ")" 460 end 461 begin 462 if defined?(yield) 463 yield log_connection_yield(msg, conn, args){cps.executeQuery} 464 else 465 case opts[:type] 466 when :ddl 467 log_connection_yield(msg, conn, args){cps.execute} 468 when :insert 469 log_connection_yield(msg, conn, args){execute_prepared_statement_insert(cps)} 470 opts = Hash[opts] 471 opts[:prepared] = true 472 opts[:stmt] = cps 473 last_insert_id(conn, opts) 474 else 475 log_connection_yield(msg, conn, args){cps.executeUpdate} 476 end 477 end 478 rescue *DATABASE_ERROR_CLASSES => e 479 raise_error(e) 480 ensure 481 cps.close unless name 482 end 483 end 484 end
Execute the prepared insert statement
# File lib/sequel/adapters/jdbc.rb 487 def execute_prepared_statement_insert(stmt) 488 stmt.executeUpdate 489 end
Execute the insert SQL
using the statement
# File lib/sequel/adapters/jdbc.rb 492 def execute_statement_insert(stmt, sql) 493 stmt.executeUpdate(sql) 494 end
Gets the connection from JNDI.
# File lib/sequel/adapters/jdbc.rb 503 def get_connection_from_jndi 504 jndi_name = JNDI_URI_REGEXP.match(uri)[1] 505 javax.naming.InitialContext.new.lookup(jndi_name).connection 506 end
Backbone of the tables and views support.
# File lib/sequel/adapters/jdbc.rb 517 def get_tables(type, opts) 518 ts = [] 519 m = output_identifier_meth 520 if schema = opts[:schema] 521 schema = schema.to_s 522 end 523 metadata(:getTables, nil, schema, nil, [type].to_java(:string)){|h| ts << m.call(h[:table_name])} 524 ts 525 end
Gets the JDBC
connection uri from the JNDI resource.
# File lib/sequel/adapters/jdbc.rb 509 def get_uri_from_jndi 510 conn = get_connection_from_jndi 511 conn.meta_data.url 512 ensure 513 conn.close if conn 514 end
Support Date objects used in bound variables
# File lib/sequel/adapters/jdbc.rb 528 def java_sql_date(date) 529 java.sql.Date.new(Time.local(date.year, date.month, date.day).to_i * 1000) 530 end
Support DateTime objects used in bound variables
# File lib/sequel/adapters/jdbc.rb 533 def java_sql_datetime(datetime) 534 ts = java.sql.Timestamp.new(Time.local(datetime.year, datetime.month, datetime.day, datetime.hour, datetime.min, datetime.sec).to_i * 1000) 535 ts.setNanos((datetime.sec_fraction * 1000000000).to_i) 536 ts 537 end
Support fractional seconds for Time objects used in bound variables
# File lib/sequel/adapters/jdbc.rb 540 def java_sql_timestamp(time) 541 ts = java.sql.Timestamp.new(time.to_i * 1000) 542 ts.setNanos(time.nsec) 543 ts 544 end
By default, there is no support for determining the last inserted id, so return nil. This method should be overridden in subadapters.
# File lib/sequel/adapters/jdbc.rb 553 def last_insert_id(conn, opts) 554 nil 555 end
# File lib/sequel/adapters/jdbc.rb 546 def log_connection_execute(conn, sql) 547 statement(conn){|s| log_connection_yield(sql, conn){s.execute(sql)}} 548 end
Yield the metadata for this database
# File lib/sequel/adapters/jdbc.rb 558 def metadata(*args, &block) 559 synchronize do |c| 560 result = c.getMetaData.public_send(*args) 561 begin 562 metadata_dataset.send(:process_result_set, result, &block) 563 ensure 564 result.close 565 end 566 end 567 end
Return the schema and table suitable for use with metadata queries.
# File lib/sequel/adapters/jdbc.rb 570 def metadata_schema_and_table(table, opts) 571 im = input_identifier_meth(opts[:dataset]) 572 schema, table = schema_and_table(table) 573 schema ||= opts[:schema] 574 schema = im.call(schema) if schema 575 table = im.call(table) 576 [schema, table] 577 end
# File lib/sequel/adapters/jdbc.rb 632 def schema_column_set_db_type(schema) 633 case schema[:type] 634 when :string 635 if schema[:db_type] =~ /\A(character( varying)?|n?(var)?char2?)\z/io && schema[:column_size] > 0 636 schema[:db_type] += "(#{schema[:column_size]})" 637 end 638 when :decimal 639 if schema[:db_type] =~ /\A(decimal|numeric)\z/io && schema[:column_size] > 0 && schema[:scale] >= 0 640 schema[:db_type] += "(#{schema[:column_size]}, #{schema[:scale]})" 641 end 642 end 643 end
# File lib/sequel/adapters/jdbc.rb 645 def schema_parse_table(table, opts=OPTS) 646 m = output_identifier_meth(opts[:dataset]) 647 schema, table = metadata_schema_and_table(table, opts) 648 pks, ts = [], [] 649 metadata(:getPrimaryKeys, nil, schema, table) do |h| 650 next if schema_parse_table_skip?(h, schema) 651 pks << h[:column_name] 652 end 653 schemas = [] 654 metadata(:getColumns, nil, schema, table, nil) do |h| 655 next if schema_parse_table_skip?(h, schema) 656 s = { 657 :type=>schema_column_type(h[:type_name]), 658 :db_type=>h[:type_name], 659 :default=>(h[:column_def] == '' ? nil : h[:column_def]), 660 :allow_null=>(h[:nullable] != 0), 661 :primary_key=>pks.include?(h[:column_name]), 662 :column_size=>h[:column_size], 663 :scale=>h[:decimal_digits], 664 :remarks=>h[:remarks] 665 } 666 if s[:primary_key] 667 s[:auto_increment] = h[:is_autoincrement] == "YES" 668 end 669 s[:max_length] = s[:column_size] if s[:type] == :string 670 if s[:db_type] =~ /number|numeric|decimal/i && s[:scale] == 0 671 s[:type] = :integer 672 end 673 schema_column_set_db_type(s) 674 schemas << h[:table_schem] unless schemas.include?(h[:table_schem]) 675 ts << [m.call(h[:column_name]), s] 676 end 677 if schemas.length > 1 678 raise Error, 'Schema parsing in the jdbc adapter resulted in columns being returned for a table with the same name in multiple schemas. Please explicitly qualify your table with a schema.' 679 end 680 ts 681 end
Skip tables in the INFORMATION_SCHEMA when parsing columns.
# File lib/sequel/adapters/jdbc.rb 684 def schema_parse_table_skip?(h, schema) 685 h[:table_schem] == 'INFORMATION_SCHEMA' 686 end
Java being java, you need to specify the type of each argument for the prepared statement, and bind it individually. This guesses which JDBC
method to use, and hopefully JRuby will convert things properly for us.
# File lib/sequel/adapters/jdbc.rb 588 def set_ps_arg(cps, arg, i) 589 case arg 590 when Integer 591 cps.setLong(i, arg) 592 when Sequel::SQL::Blob 593 cps.setBytes(i, arg.to_java_bytes) 594 when String 595 cps.setString(i, arg) 596 when Float 597 cps.setDouble(i, arg) 598 when TrueClass, FalseClass 599 cps.setBoolean(i, arg) 600 when NilClass 601 set_ps_arg_nil(cps, i) 602 when DateTime 603 cps.setTimestamp(i, java_sql_datetime(arg)) 604 when Date 605 cps.setDate(i, java_sql_date(arg)) 606 when Time 607 cps.setTimestamp(i, java_sql_timestamp(arg)) 608 when Java::JavaSql::Timestamp 609 cps.setTimestamp(i, arg) 610 when Java::JavaSql::Date 611 cps.setDate(i, arg) 612 else 613 cps.setObject(i, arg) 614 end 615 end
Use setString with a nil value by default, but this doesn't work on all subadapters.
# File lib/sequel/adapters/jdbc.rb 618 def set_ps_arg_nil(cps, i) 619 cps.setString(i, nil) 620 end
Return the connection. Can be overridden in subadapters for database specific setup.
# File lib/sequel/adapters/jdbc.rb 623 def setup_connection(conn) 624 conn 625 end
Setup the connection using the given connection options. Return the connection. Can be overridden in subadapters for database specific setup.
# File lib/sequel/adapters/jdbc.rb 628 def setup_connection_with_opts(conn, opts) 629 setup_connection(conn) 630 end
Called after loading subadapter-specific code, overridable by subadapters.
# File lib/sequel/adapters/jdbc.rb 689 def setup_type_convertor_map 690 end
Called before loading subadapter-specific code, necessary so that subadapter initialization code that runs queries works correctly. This cannot be overridden in subadapters.
# File lib/sequel/adapters/jdbc.rb 694 def setup_type_convertor_map_early 695 @type_convertor_map = TypeConvertor::MAP.merge(Java::JavaSQL::Types::TIMESTAMP=>method(:timestamp_convert)) 696 @basic_type_convertor_map = TypeConvertor::BASIC_MAP.dup 697 end
Yield a new statement object, and ensure that it is closed before returning.
# File lib/sequel/adapters/jdbc.rb 700 def statement(conn) 701 stmt = conn.createStatement 702 yield stmt 703 rescue *DATABASE_ERROR_CLASSES => e 704 raise_error(e) 705 ensure 706 stmt.close if stmt 707 end
A conversion method for timestamp columns. This is used to make sure timestamps are converted using the correct timezone.
# File lib/sequel/adapters/jdbc.rb 711 def timestamp_convert(r, i) 712 if v = r.getTimestamp(i) 713 to_application_timestamp([v.getYear + 1900, v.getMonth + 1, v.getDate, v.getHours, v.getMinutes, v.getSeconds, v.getNanos]) 714 end 715 end