Class: Sequel::JDBC::Database

Inherits:
Database show all
Defined in:
lib/sequel/adapters/jdbc.rb

Constant Summary

Constants inherited from Database

Database::ADAPTERS, Database::COLUMN_DEFINITION_ORDER, Database::COLUMN_SCHEMA_DATETIME_TYPES, Database::COLUMN_SCHEMA_STRING_TYPES, Database::COMBINABLE_ALTER_TABLE_OPS, Database::DEFAULT_DATABASE_ERROR_REGEXPS, Database::DEFAULT_STRING_COLUMN_SIZE, Database::EXTENSIONS, Database::OPTS, Database::SCHEMA_TYPE_CLASSES, Database::TRANSACTION_ISOLATION_LEVELS

Instance Attribute Summary collapse

Attributes inherited from Database

#cache_schema, #dataset_class, #default_string_column_size, #log_connection_info, #log_warn_duration, #loggers, #opts, #pool, #prepared_statements, #sql_log_level, #timezone, #transaction_isolation_level

Instance Method Summary collapse

Methods inherited from Database

#<<, #[], adapter_class, #adapter_scheme, adapter_scheme, #add_column, #add_index, #add_servers, #after_commit, after_initialize, #after_rollback, #alter_table, #alter_table_generator, #call, #cast_type_literal, connect, #create_join_table, #create_join_table!, #create_join_table?, #create_or_replace_view, #create_table, #create_table!, #create_table?, #create_table_generator, #create_view, #database_type, #dataset, #disconnect, #drop_column, #drop_index, #drop_join_table, #drop_table, #drop_table?, #drop_view, #extend_datasets, #extension, extension, #fetch, #from, #from_application_timestamp, #get, #global_index_namespace?, #in_transaction?, #initialize, #inspect, #literal, #literal_symbol, #literal_symbol_set, load_adapter, #log_connection_yield, #log_exception, #log_info, #logger=, #prepared_statement, #quote_identifier, register_extension, #remove_servers, #rename_column, #rename_table, #rollback_checker, #rollback_on_exit, #run, run_after_initialize, #schema, #schema_type_class, #select, #serial_primary_key_options, #servers, #set_column_default, #set_column_type, #set_prepared_statement, set_shared_adapter_scheme, #sharded?, #single_threaded?, #supports_create_table_if_not_exists?, #supports_deferrable_constraints?, #supports_deferrable_foreign_key_constraints?, #supports_drop_table_if_exists?, #supports_foreign_key_parsing?, #supports_index_parsing?, #supports_partial_indexes?, #supports_prepared_transactions?, #supports_savepoints?, #supports_savepoints_in_prepared_transactions?, #supports_schema_parsing?, #supports_table_listing?, #supports_transaction_isolation_levels?, #supports_transactional_ddl?, #supports_view_listing?, #supports_views_with_check_option?, #supports_views_with_local_check_option?, #synchronize, #table_exists?, #test_connection, #to_application_timestamp, #transaction, #typecast_value, #url, #valid_connection?

Constructor Details

This class inherits a constructor from Sequel::Database

Instance Attribute Details

#basic_type_convertor_mapObject (readonly)

Map of JDBC type ids to callable objects that return appropriate ruby or java values.



167
168
169
# File 'lib/sequel/adapters/jdbc.rb', line 167

def basic_type_convertor_map
  @basic_type_convertor_map
end

#convert_typesObject

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.



157
158
159
# File 'lib/sequel/adapters/jdbc.rb', line 157

def convert_types
  @convert_types
end

#driverObject (readonly)

The Java database driver we are using (should be a Java class)



152
153
154
# File 'lib/sequel/adapters/jdbc.rb', line 152

def driver
  @driver
end

#fetch_sizeObject

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.



161
162
163
# File 'lib/sequel/adapters/jdbc.rb', line 161

def fetch_size
  @fetch_size
end

#type_convertor_mapObject (readonly)

Map of JDBC type ids to callable objects that return appropriate ruby values.



164
165
166
# File 'lib/sequel/adapters/jdbc.rb', line 164

def type_convertor_map
  @type_convertor_map
end

Instance Method Details

#call_sproc(name, opts = OPTS) ⇒ Object

Execute the given stored procedure with the give name. If a block is given, the stored procedure should return rows.



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/sequel/adapters/jdbc.rb', line 171

def call_sproc(name, opts = OPTS)
  args = opts[:args] || []
  sql = "{call #{name}(#{args.map{'?'}.join(',')})}"
  synchronize(opts[:server]) do |conn|
    cps = conn.prepareCall(sql)

    i = 0
    args.each{|arg| set_ps_arg(cps, arg, i+=1)}

    begin
      if block_given?
        yield log_connection_yield(sql, conn){cps.executeQuery}
      else
        log_connection_yield(sql, conn){cps.executeUpdate}
        if opts[:type] == :insert
          last_insert_id(conn, opts)
        end
      end
    rescue *DATABASE_ERROR_CLASSES => e
      raise_error(e)
    ensure
      cps.close
    end
  end
end

#connect(server) ⇒ Object

Connect to the database using JavaSQL::DriverManager.getConnection, and falling back to driver.new.connect if the driver is known.



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/sequel/adapters/jdbc.rb', line 199

def connect(server)
  opts = server_opts(server)
  conn = if jndi?
    get_connection_from_jndi
  else
    args = [uri(opts)]
    args.concat([opts[:user], opts[:password]]) if opts[:user] && opts[:password]
    begin
      JavaSQL::DriverManager.setLoginTimeout(opts[:login_timeout]) if opts[:login_timeout]
      raise StandardError, "skipping regular connection" if opts[:jdbc_properties]
      JavaSQL::DriverManager.getConnection(*args)
    rescue StandardError, *DATABASE_ERROR_CLASSES => e
      raise e unless driver
      # If the DriverManager can't get the connection - use the connect
      # method of the driver. (This happens under Tomcat for instance)
      props = java.util.Properties.new
      if opts && opts[:user] && opts[:password]
        props.setProperty("user", opts[:user])
        props.setProperty("password", opts[:password])
      end
      opts[:jdbc_properties].each{|k,v| props.setProperty(k.to_s, v)} if opts[:jdbc_properties]
      begin
        c = driver.new.connect(args[0], props)
        raise(Sequel::DatabaseError, 'driver.new.connect returned nil: probably bad JDBC connection string') unless c
        c
      rescue StandardError, *DATABASE_ERROR_CLASSES => e2
        if e2.respond_to?(:message=) && e2.message != e.message
          e2.message = "#{e2.message}\n#{e.class.name}: #{e.message}"
        end
        raise e2
      end
    end
  end
  setup_connection_with_opts(conn, opts)
end

#disconnect_connection(c) ⇒ Object

Close given adapter connections, and delete any related prepared statements.



236
237
238
239
# File 'lib/sequel/adapters/jdbc.rb', line 236

def disconnect_connection(c)
  @connection_prepared_statements_mutex.synchronize{@connection_prepared_statements.delete(c)}
  c.close
end

#execute(sql, opts = OPTS, &block) ⇒ Object Also known as: execute_dui



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/sequel/adapters/jdbc.rb', line 241

def execute(sql, opts=OPTS, &block)
  return call_sproc(sql, opts, &block) if opts[:sproc]
  return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)}
  synchronize(opts[:server]) do |conn|
    statement(conn) do |stmt|
      if block
        if size = fetch_size
          stmt.setFetchSize(size)
        end
        yield log_connection_yield(sql, conn){stmt.executeQuery(sql)}
      else
        case opts[:type]
        when :ddl
          log_connection_yield(sql, conn){stmt.execute(sql)}
        when :insert
          log_connection_yield(sql, conn){execute_statement_insert(stmt, sql)}
          opts = Hash[opts]
          opts[:stmt] = stmt
          last_insert_id(conn, opts)
        else
          log_connection_yield(sql, conn){stmt.executeUpdate(sql)}
        end
      end
    end
  end
end

#execute_ddl(sql, opts = OPTS) ⇒ Object



269
270
271
272
273
# File 'lib/sequel/adapters/jdbc.rb', line 269

def execute_ddl(sql, opts=OPTS)
  opts = Hash[opts]
  opts[:type] = :ddl
  execute(sql, opts)
end

#execute_insert(sql, opts = OPTS) ⇒ Object



275
276
277
278
279
# File 'lib/sequel/adapters/jdbc.rb', line 275

def execute_insert(sql, opts=OPTS)
  opts = Hash[opts]
  opts[:type] = :insert
  execute(sql, opts)
end

#foreign_key_list(table, opts = OPTS) ⇒ Object

Use the JDBC metadata to get a list of foreign keys for the table.



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/sequel/adapters/jdbc.rb', line 288

def foreign_key_list(table, opts=OPTS)
  m = output_identifier_meth
  schema, table = (table, opts)
  foreign_keys = {}
  (:getImportedKeys, nil, schema, table) do |r|
    if fk = foreign_keys[r[:fk_name]]
      fk[:columns] << [r[:key_seq], m.call(r[:fkcolumn_name])]
      fk[:key] << [r[:key_seq], m.call(r[:pkcolumn_name])]
    elsif r[:fk_name]
      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])]]}
    end
  end
  foreign_keys.values.each do |fk|
    [:columns, :key].each do |k|
      fk[k] = fk[k].sort.map{|_, v| v}
    end
  end
end

#freezeObject



281
282
283
284
285
# File 'lib/sequel/adapters/jdbc.rb', line 281

def freeze
  @type_convertor_map.freeze
  @basic_type_convertor_map.freeze
  super
end

#indexes(table, opts = OPTS) ⇒ Object

Use the JDBC metadata to get the index information for the table.



308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/sequel/adapters/jdbc.rb', line 308

def indexes(table, opts=OPTS)
  m = output_identifier_meth
  schema, table = (table, opts)
  indexes = {}
  (:getIndexInfo, nil, schema, table, false, true) do |r|
    next unless name = r[:column_name]
    next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re 
    i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>[false, 0].include?(r[:non_unique])}
    i[:columns] << m.call(name)
  end
  indexes
end

#jndi?Boolean

Whether or not JNDI is being used for this connection.

Returns:

  • (Boolean)


322
323
324
# File 'lib/sequel/adapters/jdbc.rb', line 322

def jndi?
  !!(uri =~ JNDI_URI_REGEXP)
end

#tables(opts = OPTS) ⇒ Object

All tables in this database



327
328
329
# File 'lib/sequel/adapters/jdbc.rb', line 327

def tables(opts=OPTS)
  get_tables('TABLE', opts)
end

#uri(opts = OPTS) ⇒ Object

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.



335
336
337
338
339
# File 'lib/sequel/adapters/jdbc.rb', line 335

def uri(opts=OPTS)
  opts = @opts.merge(opts)
  ur = opts[:uri] || opts[:url] || opts[:database]
  ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}"
end

#views(opts = OPTS) ⇒ Object

All views in this database



342
343
344
# File 'lib/sequel/adapters/jdbc.rb', line 342

def views(opts=OPTS)
  get_tables('VIEW', opts)
end