class ActiveRecord::ConnectionAdapters::JdbcAdapter

Built on top of `ActiveRecord::ConnectionAdapters::AbstractAdapter` which provides the abstract interface for database-specific functionality, this class serves 2 purposes in AR-JDBC :

Historically this class is mostly been used standalone and that's still a valid use-case esp. since (with it's `arjdbc.jdbc.RubyJdbcConnectionClass`) JDBC provides a unified interface for all databases in Java it tries to do it's best implementing all `ActiveRecord` functionality on top of that. This might no be perfect that's why it checks for a `config` module (or tries to resolve one from the JDBC driver's meta-data) and if the database has “extended” AR-JDBC support mixes in the given module for each adapter instance. This is sufficient for most database specific specs we support, but for compatibility with native (MRI) adapters it's perfectly fine to sub-class the adapter and override some of its API methods.

Constants

ADAPTER_NAME

Attributes

prepared_statements[R]

Public Class Methods

arel2_visitors(config) click to toggle source

@deprecated re-implemented - no longer used @return [Hash] the AREL visitor to use If there's a `self.arel2_visitors(config)` method on the adapter spec than it is preferred and will be used instead of this one.

# File lib/arjdbc/jdbc/adapter.rb, line 165
def self.arel2_visitors(config)
  { 'jdbc' => ::Arel::Visitors::ToSql }
end
configure_arel2_visitors(config) click to toggle source

@deprecated re-implemented - no longer used @see arel2_visitors

# File lib/arjdbc/jdbc/adapter.rb, line 171
def self.configure_arel2_visitors(config)
  visitors = ::Arel::Visitors::VISITORS
  klass = config[:adapter_spec]
  klass = self unless klass.respond_to?(:arel2_visitors)
  visitor = nil
  klass.arel2_visitors(config).each do |name, arel|
    visitors[name] = ( visitor = arel )
  end
  if visitor && config[:adapter] =~ /^(jdbc|jndi)$/
    visitors[ config[:adapter] ] = visitor
  end
  visitor
end
new(connection, logger = nil, pool = nil) click to toggle source
Calls superclass method ArJdbc::Abstract::Core::new
# File lib/arjdbc/jdbc/adapter.rb, line 48
def self.new(connection, logger = nil, pool = nil)
  adapter = super
  Jdbc::JndiConnectionPoolCallbacks.prepare(adapter, adapter.instance_variable_get(:@connection))
  adapter
end
new(connection, logger = nil, config = nil) click to toggle source

Initializes the (JDBC connection) adapter instance. The passed configuration Hash's keys are symbolized, thus changes to the original `config` keys won't be reflected in the adapter. If the adapter's sub-class or the spec module that this instance will extend in responds to `configure_connection` than it will be called. @param connection an (optional) connection instance @param logger the `ActiveRecord::Base.logger` to use (or nil) @param config the database configuration @note `initialize(logger, config)` with 2 arguments is supported as well

Calls superclass method ArJdbc::Abstract::Core::new
# File lib/arjdbc/jdbc/adapter.rb, line 63
def initialize(connection, logger = nil, config = nil)
  @config = config.respond_to?(:symbolize_keys) ? config.symbolize_keys : config
  # FIXME: Rails 5 defaults to prepared statements on and we do not seem
  # to work yet.  So default to off unless it is requested until that is
  # fixed.
  @config[:prepared_statements] = false if !@config[:prepared_statements]

  # NOTE: JDBC 4.0 drivers support checking if connection isValid
  # thus no need to @config[:connection_alive_sql] ||= 'SELECT 1'
  #
  # NOTE: setup to retry 5-times previously - maybe do not set at all ?
  @config[:retry_count] ||= 1

  @config[:adapter_spec] = adapter_spec(@config) unless @config.key?(:adapter_spec)
  spec = @config[:adapter_spec]

  super(connection, logger, @config)

  # kind of like `extend ArJdbc::MyDB if self.class == JdbcAdapter` :
  klass = @config[:adapter_class]
  extend spec if spec && ( ! klass || klass == JdbcAdapter)
end

Protected Class Methods

insert?(sql) click to toggle source

@return whether the given SQL string is an 'INSERT' query

# File lib/arjdbc/jdbc/adapter.rb, line 596
def self.insert?(sql)
  JdbcConnection::insert?(sql)
end
prepared_statements?(config) click to toggle source
Allows changing the prepared statements setting for this connection.
@see #prepared_statements?

def prepared_statements=(statements)

@prepared_statements = statements

end

# File lib/arjdbc/jdbc/adapter.rb, line 542
def self.prepared_statements?(config)
  config.key?(:prepared_statements) ?
    type_cast_config_to_boolean(config.fetch(:prepared_statements)) :
      false # off by default - NOTE: on AR 4.x it's on by default !?
end
select?(sql) click to toggle source

@return whether the given SQL string is a 'SELECT' like query (returning a result set)

# File lib/arjdbc/jdbc/adapter.rb, line 591
def self.select?(sql)
  JdbcConnection::select?(sql)
end
suble_binds=(flag) click to toggle source
# File lib/arjdbc/jdbc/adapter.rb, line 554
def self.suble_binds=(flag); @@suble_binds = flag; end
suble_binds?() click to toggle source
# File lib/arjdbc/jdbc/adapter.rb, line 553
def self.suble_binds?; @@suble_binds; end
type_cast_config_to_boolean(config) click to toggle source

@private

# File lib/arjdbc/jdbc/adapter.rb, line 615
def self.type_cast_config_to_boolean(config)
  config == 'false' ? false : (config == 'true' ? true : config)
end
type_cast_config_to_integer(config) click to toggle source

@private

# File lib/arjdbc/jdbc/adapter.rb, line 608
def self.type_cast_config_to_integer(config)
  config =~ /\A\d+\z/ ? config.to_i : config
end
update?(sql) click to toggle source

@return whether the given SQL string is an 'UPDATE' (or 'DELETE') query

# File lib/arjdbc/jdbc/adapter.rb, line 601
def self.update?(sql)
  ! select?(sql) && ! insert?(sql)
end

Public Instance Methods

_string_to_date(value) click to toggle source

@note Used by Java API to convert dates from (custom) SELECTs (might get refactored). @private

# File lib/arjdbc/jdbc/adapter.rb, line 623
def _string_to_date(value); jdbc_column_class.string_to_date(value) end
_string_to_time(value) click to toggle source

@note Used by Java API to convert times from (custom) SELECTs (might get refactored). @private

# File lib/arjdbc/jdbc/adapter.rb, line 627
def _string_to_time(value); jdbc_column_class.string_to_dummy_time(value) end
_string_to_timestamp(value) click to toggle source

@note Used by Java API to convert times from (custom) SELECTs (might get refactored). @private

# File lib/arjdbc/jdbc/adapter.rb, line 631
def _string_to_timestamp(value); jdbc_column_class.string_to_time(value) end
adapter_name() click to toggle source

@return [String] the 'JDBC' adapter name.

# File lib/arjdbc/jdbc/adapter.rb, line 140
def adapter_name
  ADAPTER_NAME
end
adapter_spec(config) click to toggle source

Locate the specialized (database specific) adapter specification module if one exists based on provided configuration data. This module will than extend an instance of the adapter (unless an `:adapter_class` provided).

This method is called during {#initialize} unless an explicit `config` is set. @param config the configuration to check for `:adapter_spec` @return [Module] the database specific module

# File lib/arjdbc/jdbc/adapter.rb, line 110
def adapter_spec(config)
  dialect = (config[:dialect] || config[:driver]).to_s
  ::ArJdbc.modules.each do |constant| # e.g. ArJdbc::MySQL
    if constant.respond_to?(:adapter_matcher)
      spec = constant.adapter_matcher(dialect, config)
      return spec if spec
    end
  end

  if (config[:jndi] || config[:data_source]) && ! config[:dialect]
    begin
      data_source = config[:data_source] ||
        Java::JavaxNaming::InitialContext.new.lookup(config[:jndi])
      connection = data_source.getConnection
      config[:dialect] = connection.getMetaData.getDatabaseProductName
    rescue Java::JavaSql::SQLException => e
      warn "failed to set database :dialect from connection meda-data (#{e})"
    else
      return adapter_spec(config) # re-try matching a spec with set config[:dialect]
    ensure
      connection.close if connection  # return to the pool
    end
  end

  nil
end
columns(table_name, name = nil) click to toggle source
# File lib/arjdbc/jdbc/adapter.rb, line 264
def columns(table_name, name = nil)
  @connection.columns(table_name.to_s)
end
data_source_exists?(name) click to toggle source

@override

# File lib/arjdbc/jdbc/adapter.rb, line 360
def data_source_exists?(name)
  table_exists?(name)
end
data_sources() click to toggle source

@override

# File lib/arjdbc/jdbc/adapter.rb, line 355
def data_sources
  tables
end
database_name() click to toggle source

Returns the underlying database name. @override

# File lib/arjdbc/jdbc/adapter.rb, line 224
def database_name
  @connection.database_name
end
exec_query_raw(sql, name = 'SQL', binds = [], &block) click to toggle source

Similar to {#exec_query} except it returns “raw” results in an array where each rows is a hash with keys as columns (just like Rails used to do up until 3.0) instead of wrapping them in a {#ActiveRecord::Result}. @param sql the query string (or AREL object) @param name logging marker for the executed SQL statement log entry @param binds the bind parameters @yield [v1, v2] depending on the row values returned from the query In case a block is given it will yield each row from the result set instead of returning mapped query results in an array. @return [Array] unless a block is given

# File lib/arjdbc/jdbc/adapter.rb, line 283
def exec_query_raw(sql, name = 'SQL', binds = [], &block)
  if sql.respond_to?(:to_sql)
    sql = to_sql(sql, binds); to_sql = true
  end
  if prepared_statements?
    log(sql, name, binds) { @connection.execute_query_raw(sql, binds, &block) }
  else
    sql = suble_binds(sql, binds) unless to_sql # deprecated behavior
    log(sql, name) { @connection.execute_query_raw(sql, &block) }
  end
end
execute(sql, name = nil, binds = nil) click to toggle source

Executes the SQL statement in the context of this connection. The return value from this method depends on the SQL type (whether it's a SELECT, INSERT etc.). For INSERTs a generated id might get returned while for UPDATE statements the affected row count. Please note that this method returns “raw” results (in an array) for statements that return a result set, while {#exec_query} is expected to return a `ActiveRecord::Result` (since AR 3.1). @note This method does not use prepared statements. @note The method does not emulate various “native” `execute` results on MRI. @see exec_query @see exec_insert @see exec_update

# File lib/arjdbc/jdbc/adapter.rb, line 313
def execute(sql, name = nil, binds = nil)
  sql = suble_binds to_sql(sql, binds), binds if binds
  if name == :skip_logging
    _execute(sql, name)
  else
    log(sql, name) { _execute(sql, name) }
  end
end
execute_quietly(sql, name = 'SQL') click to toggle source

Kind of `execute(sql) rescue nil` but logging failures at debug level only.

# File lib/arjdbc/jdbc/adapter.rb, line 333
def execute_quietly(sql, name = 'SQL')
  log(sql, name) do
    begin
      _execute(sql)
    rescue => e
      logger.debug("#{e.class}: #{e.message}: #{sql}")
    end
  end
end
foreign_keys(table_name) click to toggle source

@override

# File lib/arjdbc/jdbc/adapter.rb, line 380
def foreign_keys(table_name)
  @connection.foreign_keys(table_name)
end
indexes(table_name, name = nil, schema_name = nil) click to toggle source

@override

# File lib/arjdbc/jdbc/adapter.rb, line 365
def indexes(table_name, name = nil, schema_name = nil)
  @connection.indexes(table_name, name, schema_name)
end
is_a?(klass) click to toggle source

@override Will return true even when native adapter classes passed in e.g. `jdbc_adapter.is_a? ConnectionAdapter::PostgresqlAdapter`

This is only necessary (for built-in adapters) when `config` is forced to `nil` and the `:adapter_spec` module is used to extend the `JdbcAdapter`, otherwise we replace the class constants for built-in adapters (MySQL, PostgreSQL and SQLite3).

Calls superclass method
# File lib/arjdbc/jdbc/adapter.rb, line 152
def is_a?(klass)
  # This is to fake out current_adapter? conditional logic in AR tests
  if klass.is_a?(Class) && klass.name =~ /#{adapter_name}Adapter$/i
    true
  else
    super
  end
end
jdbc_column_class() click to toggle source

Returns the (JDBC) `ActiveRecord` column class for this adapter. This is used by (database specific) spec modules to override the class. @see ActiveRecord::ConnectionAdapters::JdbcColumn

# File lib/arjdbc/jdbc/adapter.rb, line 98
def jdbc_column_class
  ::ActiveRecord::ConnectionAdapters::JdbcColumn
end
jdbc_connection_class(spec) click to toggle source

Returns the (JDBC) connection class to be used for this adapter. This is used by (database specific) spec modules to override the class used assuming some of the available methods have been re-defined. @see ActiveRecord::ConnectionAdapters::JdbcConnection

# File lib/arjdbc/jdbc/adapter.rb, line 90
def jdbc_connection_class(spec)
  connection_class = spec.jdbc_connection_class if spec && spec.respond_to?(:jdbc_connection_class)
  connection_class ? connection_class : ::ActiveRecord::ConnectionAdapters::JdbcConnection
end
modify_types(types) click to toggle source

Allows for modification of the detected native types. @param types the resolved native database types @see native_database_types

# File lib/arjdbc/jdbc/adapter.rb, line 205
def modify_types(types)
  types
end
native_database_types() click to toggle source

DB specific types are detected but adapter specs (or extenders) are expected to hand tune these types for concrete databases. @return [Hash] the native database types @override

# File lib/arjdbc/jdbc/adapter.rb, line 189
def native_database_types
  @native_database_types ||= begin
    types = @connection.native_database_types
    modify_types(types)
    types
  end
end
native_sql_to_type(type) click to toggle source

@private

# File lib/arjdbc/jdbc/adapter.rb, line 229
def native_sql_to_type(type)
  if /^(.*?)\(([0-9]+)\)/ =~ type
    tname, limit = $1, $2.to_i
    ntypes = native_database_types
    if ntypes[:primary_key] == type
      return :primary_key, nil
    else
      ntypes.each do |name, val|
        if name == :primary_key
          next
        end
        if val[:name].downcase == tname.downcase &&
            ( val[:limit].nil? || val[:limit].to_i == limit )
          return name, limit
        end
      end
    end
  elsif /^(.*?)/ =~ type
    tname = $1
    ntypes = native_database_types
    if ntypes[:primary_key] == type
      return :primary_key, nil
    else
      ntypes.each do |name, val|
        if val[:name].downcase == tname.downcase && val[:limit].nil?
          return name, nil
        end
      end
    end
  else
    return :string, 255
  end
  return nil, nil
end
pk_and_sequence_for(table) click to toggle source

@override

# File lib/arjdbc/jdbc/adapter.rb, line 370
def pk_and_sequence_for(table)
  ( key = primary_key(table) ) ? [ key, nil ] : nil
end
primary_keys(table) click to toggle source

@override

# File lib/arjdbc/jdbc/adapter.rb, line 375
def primary_keys(table)
  @connection.primary_keys(table)
end
select_rows(sql, name = nil, binds = []) click to toggle source

@private @override

# File lib/arjdbc/jdbc/adapter.rb, line 297
def select_rows(sql, name = nil, binds = [])
  exec_query_raw(sql, name, binds).map!(&:values)
end
structure_dump() click to toggle source

Abstract adapter default implementation does nothing silently. @override

# File lib/arjdbc/jdbc/adapter.rb, line 211
def structure_dump
  raise NotImplementedError, "structure_dump not supported"
end
supports_foreign_keys?() click to toggle source

Does our database (+ its JDBC driver) support foreign-keys? @since 1.3.18 @override

# File lib/arjdbc/jdbc/adapter.rb, line 387
def supports_foreign_keys?
  @connection.supports_foreign_keys?
end
supports_migrations?() click to toggle source

JDBC adapters support migration. @return [true] @override

# File lib/arjdbc/jdbc/adapter.rb, line 218
def supports_migrations?
  true
end
supports_views?() click to toggle source

@override

# File lib/arjdbc/jdbc/adapter.rb, line 269
def supports_views?
  @connection.supports_views?
end
table_exists?(name) click to toggle source

@override

# File lib/arjdbc/jdbc/adapter.rb, line 349
def table_exists?(name)
  return false unless name
  @connection.table_exists?(name) # schema_name = nil
end
tables(name = nil) click to toggle source

@override

# File lib/arjdbc/jdbc/adapter.rb, line 344
def tables(name = nil)
  @connection.tables
end
to_sql(arel, binds = nil) click to toggle source

@private

# File lib/arjdbc/jdbc/adapter.rb, line 408
def to_sql(arel, binds = nil)
  # NOTE: can not handle `visitor.accept(arel.ast)` right
  arel.respond_to?(:to_sql) ? arel.send(:to_sql) : arel
end
update_lob_value(record, column, value) click to toggle source

@param record the record e.g. `User.find(1)` @param column the model's column e.g. `User.columns_hash` @param value the lob value - string or (IO or Java) stream

# File lib/arjdbc/jdbc/adapter.rb, line 399
def update_lob_value(record, column, value)
  @connection.update_lob_value(record, column, value)
end
valid_type?(type) click to toggle source

@override introduced in AR 4.2

# File lib/arjdbc/jdbc/adapter.rb, line 198
def valid_type?(type)
  ! native_database_types[type].nil?
end
write_large_object(*args) click to toggle source

@deprecated Rather use {#update_lob_value} instead.

# File lib/arjdbc/jdbc/adapter.rb, line 392
def write_large_object(*args)
  @connection.write_large_object(*args)
end

Protected Instance Methods

add_column_options!(sql, options) click to toggle source

Provides backwards-compatibility on ActiveRecord 4.1 for DB adapters that override this and than call super expecting to work. @note This method is available in 4.0 but won't be in 4.1 @private

# File lib/arjdbc/jdbc/adapter.rb, line 495
def add_column_options!(sql, options)
  sql << " DEFAULT #{quote(options[:default], options[:column])}" if options_include_default?(options)
  # must explicitly check for :null to allow change_column to work on migrations
  sql << " NOT NULL" if options[:null] == false
  sql << " AUTO_INCREMENT" if options[:auto_increment] == true
end
create_table_definition(*args) click to toggle source

`TableDefinition.new native_database_types, name, temporary, options` and ActiveRecord 4.1 supports optional `as` argument (which defaults to nil) to provide the SQL to use to generate the table: `TableDefinition.new native_database_types, name, temporary, options, as` @private

# File lib/arjdbc/jdbc/adapter.rb, line 467
def create_table_definition(*args)
  table_definition(*args)
end
Also aliased as: table_definition
last_inserted_id(result) click to toggle source

Take an id from the result of an INSERT query. @return [Integer, NilClass]

# File lib/arjdbc/jdbc/adapter.rb, line 438
def last_inserted_id(result)
  if result.is_a?(Hash) || result.is_a?(ActiveRecord::Result)
    result.first.first[1] # .first = { "id"=>1 } .first = [ "id", 1 ]
  else
    result
  end
end
log(sql, name = nil, binds = []) click to toggle source

@override so that we do not have to care having 2 arguments on 3.0

Calls superclass method
# File lib/arjdbc/jdbc/adapter.rb, line 425
def log(sql, name = nil, binds = [])
  unless binds.blank?
    binds = binds.map do |column, value|
      column ? [column.name, value] : [nil, value]
    end
    sql = "#{sql} #{binds.inspect}"
  end
  super(sql, name || 'SQL') # `log(sql, name)` on AR <= 3.0
end
new_index_definition(table, name, unique, columns, lengths, orders = nil, where = nil, type = nil, using = nil) click to toggle source

@private

# File lib/arjdbc/jdbc/adapter.rb, line 483
def new_index_definition(table, name, unique, columns, lengths,
    orders = nil, where = nil, type = nil, using = nil)
  IndexDefinition.new(table, name, unique, columns, lengths, orders, where, type, using)
end
new_table_definition(table_definition, *args) click to toggle source

@note AR-4x arguments expected: `(name, temporary, options)` @private documented bellow

# File lib/arjdbc/jdbc/adapter.rb, line 473
def new_table_definition(table_definition, *args)
  if ActiveRecord::VERSION::MAJOR > 4
    table_definition.new(*args)
  else
    table_definition.new native_database_types, *args
  end
end
prepared_statements?() click to toggle source

@return whether `:prepared_statements` are to be used

# File lib/arjdbc/jdbc/adapter.rb, line 531
def prepared_statements?
  return @prepared_statements unless (@prepared_statements ||= nil).nil?
  @prepared_statements = self.class.prepared_statements?(config)
end
table_definition(*args)

Private Instance Methods

_execute(sql, name = nil) click to toggle source

We need to do it this way, to allow Rails stupid tests to always work even if we define a new `execute` method. Instead of mixing in a new `execute`, an `_execute` should be mixed in. @deprecated it was only introduced due tests @private

# File lib/arjdbc/jdbc/adapter.rb, line 327
def _execute(sql, name = nil)
  @connection.execute(sql)
end
extract_sql(arel) click to toggle source

@deprecated No longer used, kept for 1.2 API compatibility.

# File lib/arjdbc/jdbc/adapter.rb, line 568
def extract_sql(arel)
  arel.respond_to?(:to_sql) ? arel.send(:to_sql) : arel
end
get_time(value) click to toggle source

Helper to get local/UTC time (based on `ActiveRecord::Base.default_timezone`).

# File lib/arjdbc/jdbc/adapter.rb, line 582
def get_time(value)
  get = ::ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
  value.respond_to?(get) ? value.send(get) : value
end
sql_literal?(value) click to toggle source

Helper useful during {#quote} since AREL might pass in it's literals to be quoted, fixed since AREL 4.0.0.beta1 : git.io/7gyTig

# File lib/arjdbc/jdbc/adapter.rb, line 575
def sql_literal?(value); ::Arel::Nodes::SqlLiteral === value; end
suble_binds(sql, binds) click to toggle source

@private Supporting “string-subling” on AR 4.0 would require {#to_sql} to consume binds parameters otherwise it happens twice e.g. for a record insert it is called during {#insert} as well as on {#exec_insert} … but that than leads to other issues with libraries that save the binds array and run a query again since it's the very same instance on 4.0 !

# File lib/arjdbc/jdbc/adapter.rb, line 563
def suble_binds(sql, binds)
  sql
end