Class | Sequel::Database
In: | lib/sequel/extensions/query.rb lib/sequel/extensions/schema_dumper.rb lib/sequel/adapters/do.rb lib/sequel/adapters/jdbc.rb lib/sequel/adapters/shared/mysql.rb lib/sequel/database.rb lib/sequel/database/schema_methods.rb lib/sequel/database/schema_sql.rb
Parent: | Object

A Database object represents a virtual connection to a database. The Database class is meant to be subclassed by database adapters in order to provide the functionality needed for executing queries.

### Methods

<< [] adapter_class adapter_scheme add_column add_index alter_table call call_sproc cast_type_literal connect connect connect connect create_or_replace_view create_table create_table! create_view database_type dataset dataset dataset disconnect drop_column drop_index drop_table drop_view dump_indexes_migration dump_schema_migration dump_table_schema execute execute execute execute_ddl execute_ddl execute_dui execute_dui execute_dui execute_insert execute_insert execute_insert fetch from get identifier_input_method identifier_input_method identifier_input_method= identifier_input_method= identifier_output_method identifier_output_method identifier_output_method= identifier_output_method= indexes inspect literal log_info logger= new new new query quote_identifiers= quote_identifiers= quote_identifiers? rename_column rename_table schema select serial_primary_key_options set_column_default set_column_type single_threaded= single_threaded? subadapter synchronize table_exists? tables test_connection transaction transaction transaction typecast_value uri uri uri url

### Included Modules

Metaprogramming

### Constants

ADAPTERS | = | %w'ado db2 dbi do firebird informix jdbc mysql odbc openbase oracle postgres sqlite'.collect{|x| x.to_sym} |  | Array of supported database adapters
SQL_BEGIN | = | 'BEGIN'.freeze
SQL_COMMIT | = | 'COMMIT'.freeze
SQL_ROLLBACK | = | 'ROLLBACK'.freeze
AUTOINCREMENT | = | 'AUTOINCREMENT'.freeze
CASCADE | = | 'CASCADE'.freeze
COMMA_SEPARATOR | = | ', '.freeze
NO_ACTION | = | 'NO ACTION'.freeze
NOT_NULL | = | ' NOT NULL'.freeze
NULL | = | ' NULL'.freeze
PRIMARY_KEY | = | ' PRIMARY KEY'.freeze
RESTRICT | = | 'RESTRICT'.freeze
SET_DEFAULT | = | 'SET DEFAULT'.freeze
SET_NULL | = | 'SET NULL'.freeze
TEMPORARY | = | 'TEMPORARY '.freeze
UNDERSCORE | = | '_'.freeze
UNIQUE | = | ' UNIQUE'.freeze
UNSIGNED | = | ' UNSIGNED'.freeze

### External Aliases

column_references_sql | -> | default_column_references_sql
| Keep default column_references_sql for add_foreign_key support

### Attributes

converted_exceptions | [RW] | Convert the given exceptions to Sequel:Errors, necessary because DO raises errors specific to database types in certain cases.
database_type | [R] | The type of database we are connecting to
default_schema | [RW] | The default schema to use, generally should be nil.
loggers | [RW] | Array of SQL loggers to use for this database
opts | [R] | The options for this database
pool | [R] | The connection pool for this database
prepared_statements | [R] | The prepared statement objects for this database, keyed by name

### Public Class methods

adapter_class(scheme)

The Database subclass for the given adapter scheme. Raises Sequel::AdapterNotFound if the adapter could not be loaded.

[Source]

         # File lib/sequel/database.rb, line 93
     93:     def self.adapter_class(scheme)
     94:       scheme = scheme.to_s.gsub('-', '_').to_sym
     95:
     96:       unless klass = ADAPTER_MAP[scheme]
     97:         # attempt to load the adapter file
     98:         begin
     99:           Sequel.require "adapters/#{scheme}"
    100:         rescue LoadError => e
    101:           raise AdapterNotFound, "Could not load #{scheme} adapter:\n  #{e.message}"
    102:         end
    103:
    104:         # make sure we actually loaded the adapter
    105:         unless klass = ADAPTER_MAP[scheme]
    106:           raise AdapterNotFound, "Could not load #{scheme} adapter"
    107:         end
    108:       end
    109:       klass
    110:     end

adapter_scheme()

Returns the scheme for the Database class.

[Source]

         # File lib/sequel/database.rb, line 113
    113:     def self.adapter_scheme
    114:       @scheme
    115:     end

connect(conn_string, opts = {}) {|db = c.new(opts)| ...}

Connects to a database. See Sequel.connect.

[Source]

         # File lib/sequel/database.rb, line 118
    118:     def self.connect(conn_string, opts = {}, &block)
    119:       if conn_string.is_a?(String)
    120:         if match = /\A(jdbc|do):/o.match(conn_string)
    121:           c = adapter_class(match[1].to_sym)
    122:           opts = {:uri=>conn_string}.merge(opts)
    123:         else
    124:           uri = URI.parse(conn_string)
    125:           scheme = uri.scheme
    126:           scheme = :dbi if scheme =~ /\Adbi-/
    127:           c = adapter_class(scheme)
    128:           uri_options = {}
    129:           uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v} unless uri.query.to_s.strip.empty?
    130:           opts = c.send(:uri_to_options, uri).merge(uri_options).merge(opts)
    131:         end
    132:       else
    133:         opts = conn_string.merge(opts)
    134:         c = adapter_class(opts[:adapter] || opts['adapter'])
    135:       end
    136:       # process opts a bit
    137:       opts = opts.inject({}) do |m, kv| k, v = *kv
    138:         k = :user if k.to_s == 'username'
    139:         m[k.to_sym] = v
    140:         m
    141:       end
    142:       if block
    143:         begin
    144:           yield(db = c.new(opts))
    145:         ensure
    146:           db.disconnect if db
    147:           ::Sequel::DATABASES.delete(db)
    148:         end
    149:         nil
    150:       else
    151:         c.new(opts)
    152:       end
    153:     end

identifier_input_method()

The method to call on identifiers going into the database

[Source]

         # File lib/sequel/database.rb, line 156
    156:     def self.identifier_input_method
    157:       @@identifier_input_method
    158:     end

identifier_input_method=(v)

Set the method to call on identifiers going into the database See Sequel.identifier_input_method=.

[Source]

         # File lib/sequel/database.rb, line 162
    162:     def self.identifier_input_method=(v)
    163:       @@identifier_input_method = v || ""
    164:     end

identifier_output_method()

The method to call on identifiers coming from the database

[Source]

         # File lib/sequel/database.rb, line 167
    167:     def self.identifier_output_method
    168:       @@identifier_output_method
    169:     end

identifier_output_method=(v)

Set the method to call on identifiers coming from the database See Sequel.identifier_output_method=.

[Source]

         # File lib/sequel/database.rb, line 173
    173:     def self.identifier_output_method=(v)
    174:       @@identifier_output_method = v || ""
    175:     end

new(opts = {}, &block)

Constructs a new instance of a database connection with the specified options hash.

Sequel::Database is an abstract class that is not useful by itself.

Takes the following options:

- :default_schema : The default schema to use, should generally be nil
- :disconnection_proc: A proc used to disconnect the connection.
- :identifier_input_method: A string method symbol to call on identifiers going into the database
- :identifier_output_method: A string method symbol to call on identifiers coming from the database
- :loggers : An array of loggers to use.
- :quote_identifiers : Whether to quote identifiers
- :single_threaded : Whether to use a single-threaded connection pool

All options given are also passed to the ConnectionPool. If a block is given, it is used as the connection_proc for the ConnectionPool.

[Source]

        # File lib/sequel/database.rb, line 69
    69:     def initialize(opts = {}, &block)
    70:       @opts ||= opts
    71:
    72:       @single_threaded = opts.include?(:single_threaded) ? opts[:single_threaded] : @@single_threaded
    73:       @schemas = nil
    74:       @default_schema = opts.include?(:default_schema) ? opts[:default_schema] : default_schema_default
    75:       @prepared_statements = {}
    76:       @transactions = []
    77:       @identifier_input_method = nil
    78:       @identifier_output_method = nil
    79:       @quote_identifiers = nil
    80:       @pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(connection_pool_default_options.merge(opts), &block)
    81:       @pool.connection_proc = proc{|server| connect(server)} unless block
    82:       @pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc]
    83:
    84:       @loggers = Array(opts[:logger]) + Array(opts[:loggers])
    85:       ::Sequel::DATABASES.push(self)
    86:     end

new(opts)

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 DataObjects requires one.

[Source]

        # File lib/sequel/adapters/do.rb, line 53
    53:       def initialize(opts)
    54:         @opts = opts
    55:         @converted_exceptions = []
    56:         raise(Error, "No connection string specified") unless uri
    57:         if prok = DATABASE_SETUP[subadapter.to_sym]
    58:           prok.call(self)
    59:         end
    60:         super(opts)
    61:       end

new(opts)

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.

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 95
     95:       def initialize(opts)
     96:         @opts = opts
     97:         raise(Error, "No connection string specified") unless uri
     98:         if match = /\Ajdbc:([^:]+)/.match(uri) and prok = DATABASE_SETUP[match[1].to_sym]
     99:           prok.call(self)
    100:         end
    101:         super(opts)
    102:       end

quote_identifiers=(value)

Sets the default quote_identifiers mode for new databases. See Sequel.quote_identifiers=.

[Source]

         # File lib/sequel/database.rb, line 179
    179:     def self.quote_identifiers=(value)
    180:       @@quote_identifiers = value
    181:     end

single_threaded=(value)

Sets the default single_threaded mode for new databases. See Sequel.single_threaded=.

[Source]

         # File lib/sequel/database.rb, line 185
    185:     def self.single_threaded=(value)
    186:       @@single_threaded = value
    187:     end

### Public Instance methods

<<(sql)

Executes the supplied SQL statement string.

[Source]

         # File lib/sequel/database.rb, line 223
    223:     def <<(sql)
    224:       execute_ddl(sql)
    225:     end

[](*args)

Returns a dataset from the database. If the first argument is a string, the method acts as an alias for Database#fetch, returning a dataset for arbitrary SQL:

      DB['SELECT * FROM items WHERE name = ?', my_name].all

Otherwise, acts as an alias for Database#from, setting the primary table for the dataset:

      DB[:items].sql #=> "SELECT * FROM items"

[Source]

         # File lib/sequel/database.rb, line 237
    237:     def [](*args)
    238:       (String === args.first) ? fetch(*args) : from(*args)
    239:     end

add_column(table, *args)

Adds a column to the specified table. This method expects a column name, a datatype and optionally a hash with additional constraints and options:

      DB.add_column :items, :name, :text, :unique => true, :null => false
      DB.add_column :items, :category, :text, :default => 'ruby'

See alter_table.

[Source]

        # File lib/sequel/database/schema_methods.rb, line 10
    10:     def add_column(table, *args)
    11:       alter_table(table) {add_column(*args)}
    12:     end

add_index(table, *args)

Adds an index to a table for the given columns:

      DB.add_index :posts, :title
      DB.add_index :posts, [:author, :title], :unique => true

See alter_table.

[Source]

        # File lib/sequel/database/schema_methods.rb, line 20
    20:     def add_index(table, *args)
    21:       alter_table(table) {add_index(*args)}
    22:     end

alter_table(name, generator=nil, &block)

Alters the given table with the specified block. Example:

      DB.alter_table :items do
        add_column :category, :text, :default => 'ruby'
        drop_column :category
        rename_column :cntr, :counter
        set_column_type :value, :float
        set_column_default :value, :float
        add_index [:group, :category]
        drop_index [:group, :category]
      end

Note that add_column accepts all the options available for column definitions using create_table, and add_index accepts all the options available for index definition.

See Schema::AlterTableGenerator.

[Source]

        # File lib/sequel/database/schema_methods.rb, line 41
    41:     def alter_table(name, generator=nil, &block)
    42:       remove_cached_schema(name)
    43:       generator ||= Schema::AlterTableGenerator.new(self, &block)
    44:       alter_table_sql_list(name, generator.operations).flatten.each {|sql| execute_ddl(sql)}
    45:     end

call(ps_name, hash={})

Call the prepared statement with the given name with the given hash of arguments.

[Source]

         # File lib/sequel/database.rb, line 243
    243:     def call(ps_name, hash={})
    244:       prepared_statements[ps_name].call(hash)
    245:     end

call_sproc(name, opts = {}) {|cps.executeQuery| ...}

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

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 106
    106:       def call_sproc(name, opts = {})
    107:         args = opts[:args] || []
    108:         sql = "{call #{name}(#{args.map{'?'}.join(',')})}"
    109:         synchronize(opts[:server]) do |conn|
    110:           cps = conn.prepareCall(sql)
    111:
    112:           i = 0
    113:           args.each{|arg| set_ps_arg(cps, arg, i+=1)}
    114:
    115:           begin
    116:             if block_given?
    117:               yield cps.executeQuery
    118:             else
    119:               case opts[:type]
    120:               when :insert
    121:                 cps.executeUpdate
    122:                 last_insert_id(conn, opts)
    123:               else
    124:                 cps.executeUpdate
    125:               end
    126:             end
    127:           rescue NativeException, JavaSQL::SQLException => e
    128:             raise_error(e)
    129:           ensure
    130:             cps.close
    131:           end
    132:         end
    133:       end

cast_type_literal(type)

Cast the given type to a literal type

[Source]

         # File lib/sequel/database.rb, line 248
    248:     def cast_type_literal(type)
    249:       type_literal(:type=>type)
    250:     end

connect(server)

Setup a DataObjects::Connection to the database.

[Source]

        # File lib/sequel/adapters/do.rb, line 64
    64:       def connect(server)
    65:         setup_connection(::DataObjects::Connection.new(uri(server_opts(server))))
    66:       end

connect()

Connects to the database. This method should be overridden by descendants.

[Source]

         # File lib/sequel/database.rb, line 253
    253:     def connect
    254:       raise NotImplementedError, "#connect should be overridden by adapters"
    255:     end

connect(server)

Connect to the database using JavaSQL::DriverManager.getConnection.

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 136
    136:       def connect(server)
    137:         setup_connection(JavaSQL::DriverManager.getConnection(uri(server_opts(server))))
    138:       end

create_or_replace_view(name, source)

Creates a view, replacing it if it already exists:

      DB.create_or_replace_view(:cheap_items, "SELECT * FROM items WHERE price < 100")
      DB.create_or_replace_view(:ruby_items, DB[:items].filter(:category => 'ruby'))

[Source]

        # File lib/sequel/database/schema_methods.rb, line 77
    77:     def create_or_replace_view(name, source)
    78:       remove_cached_schema(name)
    79:       source = source.sql if source.is_a?(Dataset)
    80:       execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}")
    81:     end

create_table(name, options={}, &block)

Creates a table with the columns given in the provided block:

      DB.create_table :posts do
        primary_key :id
        column :title, :text
        String :content
        index :title
      end

Options:

- :temp - Create the table as a temporary table.

See Schema::Generator.

[Source]

        # File lib/sequel/database/schema_methods.rb, line 60
    60:     def create_table(name, options={}, &block)
    61:       options = {:generator=>options} if options.is_a?(Schema::Generator)
    62:       generator = options[:generator] || Schema::Generator.new(self, &block)
    63:       execute_ddl(create_table_sql(name, generator, options))
    64:       index_sql_list(name, generator.indexes).each{|sql| execute_ddl(sql)}
    65:     end

create_table!(name, options={}, &block)

Forcibly creates a table, attempting to drop it unconditionally (and catching any errors), then creating it.

[Source]

        # File lib/sequel/database/schema_methods.rb, line 68
    68:     def create_table!(name, options={}, &block)
    69:       drop_table(name) rescue nil
    70:       create_table(name, options, &block)
    71:     end

create_view(name, source)

Creates a view based on a dataset or an SQL string:

      DB.create_view(:cheap_items, "SELECT * FROM items WHERE price < 100")
      DB.create_view(:ruby_items, DB[:items].filter(:category => 'ruby'))

[Source]

        # File lib/sequel/database/schema_methods.rb, line 87
    87:     def create_view(name, source)
    88:       source = source.sql if source.is_a?(Dataset)
    89:       execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}")
    90:     end

database_type()

The database type for this database object, the same as the adapter scheme by default. Should be overridden in adapters (especially shared adapters) to be the correct type, so that even if two separate Database objects are using different adapters you can tell that they are using the same database type. Even better, you can tell that two Database objects that are using the same adapter are connecting to different database types (think JDBC or DataObjects).

[Source]

         # File lib/sequel/database.rb, line 264
    264:     def database_type
    265:       self.class.adapter_scheme
    266:     end

dataset(opts = nil)

Return instances of JDBC::Dataset with the given opts.

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 141
    141:       def dataset(opts = nil)
    142:         JDBC::Dataset.new(self, opts)
    143:       end

dataset(opts = nil)

Return a Sequel::DataObjects::Dataset object for this database.

[Source]

        # File lib/sequel/adapters/do.rb, line 69
    69:       def dataset(opts = nil)
    70:         DataObjects::Dataset.new(self, opts)
    71:       end

dataset()

Returns a blank dataset for this database

[Source]

         # File lib/sequel/database.rb, line 269
    269:     def dataset
    270:       ds = Sequel::Dataset.new(self)
    271:     end

disconnect()

Disconnects all available connections from the connection pool. Any connections currently in use will not be disconnected.

[Source]

         # File lib/sequel/database.rb, line 275
    275:     def disconnect
    276:       pool.disconnect
    277:     end

drop_column(table, *args)

Removes a column from the specified table:

      DB.drop_column :items, :category

See alter_table.

[Source]

        # File lib/sequel/database/schema_methods.rb, line 97
    97:     def drop_column(table, *args)
    98:       alter_table(table) {drop_column(*args)}
    99:     end

drop_index(table, columns, options={})

Removes an index for the given table and column/s:

      DB.drop_index :posts, :title
      DB.drop_index :posts, [:author, :title]

See alter_table.

[Source]

         # File lib/sequel/database/schema_methods.rb, line 107
    107:     def drop_index(table, columns, options={})
    108:       alter_table(table){drop_index(columns, options)}
    109:     end

drop_table(*names)

Drops one or more tables corresponding to the given names:

      DB.drop_table(:posts, :comments)

[Source]

         # File lib/sequel/database/schema_methods.rb, line 114
    114:     def drop_table(*names)
    115:       names.each do |n|
    116:         remove_cached_schema(n)
    117:         execute_ddl(drop_table_sql(n))
    118:       end
    119:     end

drop_view(*names)

Drops one or more views corresponding to the given names:

      DB.drop_view(:cheap_items)

[Source]

         # File lib/sequel/database/schema_methods.rb, line 124
    124:     def drop_view(*names)
    125:       names.each do |n|
    126:         remove_cached_schema(n)
    127:         execute_ddl("DROP VIEW #{quote_schema_table(n)}")
    128:       end
    129:     end

dump_indexes_migration()

Dump indexes for all tables as a migration. This complements the :indexes=>false option to dump_schema_migration.

[Source]

       # File lib/sequel/extensions/schema_dumper.rb, line 5
    5:     def dump_indexes_migration
    6:       ts = tables
    7:       "Class.new(Sequel::Migration) do\n  def up\n\#{ts.map{|t| dump_table_indexes(t, :add_index)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\n  \n  def down\n\#{ts.map{|t| dump_table_indexes(t, :drop_index)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\nend\n"
    8:     end

dump_schema_migration(options={})

Return a string that contains a Sequel::Migration subclass that when run would recreate the database structure. Options:

- :same_db - Don‘t attempt to translate database types to ruby types. If this isn‘t set to true, all database types will be translated to ruby types, but there is no guarantee that the migration generated will yield the same type. Without this set, types that aren‘t recognized will be translated to a string-like type.
- :indexes - If set to false, don‘t dump indexes (they can be added later via dump_index_migration).

[Source]

        # File lib/sequel/extensions/schema_dumper.rb, line 30
    30:     def dump_schema_migration(options={})
    31:       ts = tables
    32:       "Class.new(Sequel::Migration) do\n  def up\n\#{ts.map{|t| dump_table_schema(t, options)}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\n  \n  def down\n    drop_table(\#{ts.inspect[1...-1]})\n  end\nend\n"
    33:     end

dump_table_schema(table, options={})

Return a string with a create table block that will recreate the given table‘s schema. Takes the same options as dump_schema_migration.

[Source]

        # File lib/sequel/extensions/schema_dumper.rb, line 48
    48:     def dump_table_schema(table, options={})
    49:       s = schema(table).dup
    50:       pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first}
    51:       options = options.merge(:single_pk=>true) if pks.length == 1
    52:       m = method(:column_schema_to_generator_opts)
    53:       im = method(:index_to_generator_opts)
    54:       indexes = indexes(table).sort_by{|k,v| k.to_s} if options[:indexes] != false and respond_to?(:indexes)
    55:       gen = Schema::Generator.new(self) do
    56:         s.each{|name, info| send(*m.call(name, info, options))}
    57:         primary_key(pks) if !@primary_key && pks.length > 0
    58:         indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts))} if indexes
    59:       end
    60:       commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n")
    61:       "create_table(#{table.inspect}) do\n#{commands.gsub(/^/o, '  ')}\nend"
    62:     end

execute(sql, opts={})

Executes the given SQL on the database. This method should be overridden in descendants. This method should not be called directly by user code.

[Source]

         # File lib/sequel/database.rb, line 281
    281:     def execute(sql, opts={})
    282:       raise NotImplementedError, "#execute should be overridden by adapters"
    283:     end

execute(sql, opts={}) {|res| ...}

Execute the given SQL. If a block is given, the DataObjects::Reader created is yielded to it. A block should not be provided unless a a SELECT statement is being used (or something else that returns rows). Otherwise, the return value is the insert id if opts[:type] is :insert, or the number of affected rows, otherwise.

[Source]

        # File lib/sequel/adapters/do.rb, line 78
    78:       def execute(sql, opts={})
    79:         log_info(sql)
    80:         synchronize(opts[:server]) do |conn|
    81:           begin
    82:             command = conn.create_command(sql)
    83:             res = block_given? ? command.execute_reader : command.execute_non_query
    84:           rescue Exception => e
    85:             raise_error(e, :classes=>@converted_exceptions)
    86:           end
    87:           if block_given?
    88:             begin
    89:               yield(res)
    90:             ensure
    91:              res.close if res
    92:             end
    93:           elsif opts[:type] == :insert
    94:             res.insert_id
    95:           else
    96:             res.affected_rows
    97:           end
    98:         end
    99:       end

execute(sql, opts={}) {|stmt.executeQuery(sql)| ...}

Execute the given SQL. If a block is given, if should be a SELECT statement or something else that returns rows.

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 147
    147:       def execute(sql, opts={}, &block)
    148:         return call_sproc(sql, opts, &block) if opts[:sproc]
    149:         return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)}
    150:         log_info(sql)
    151:         synchronize(opts[:server]) do |conn|
    152:           stmt = conn.createStatement
    153:           begin
    154:             if block_given?
    155:               yield stmt.executeQuery(sql)
    156:             else
    157:               case opts[:type]
    158:               when :ddl
    159:                 stmt.execute(sql)
    160:               when :insert
    161:                 stmt.executeUpdate(sql)
    162:                 last_insert_id(conn, opts)
    163:               else
    164:                 stmt.executeUpdate(sql)
    165:               end
    166:             end
    167:           rescue NativeException, JavaSQL::SQLException => e
    168:             raise_error(e)
    169:           ensure
    170:             stmt.close
    171:           end
    172:         end
    173:       end

execute_ddl(sql, opts={}, &block)

Method that should be used when submitting any DDL (Data Definition Language) SQL. By default, calls execute_dui. This method should not be called directly by user code.

[Source]

         # File lib/sequel/database.rb, line 288
    288:     def execute_ddl(sql, opts={}, &block)
    289:       execute_dui(sql, opts, &block)
    290:     end

execute_ddl(sql, opts={})

Execute the given DDL SQL, which should not return any values or rows.

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 178
    178:       def execute_ddl(sql, opts={})
    179:         execute(sql, {:type=>:ddl}.merge(opts))
    180:       end

execute_dui(sql, opts={})

Execute the SQL on the this database, returning the number of affected rows.

[Source]

         # File lib/sequel/adapters/do.rb, line 103
    103:       def execute_dui(sql, opts={})
    104:         execute(sql, opts)
    105:       end

execute_dui(sql, opts={})

Alias for execute

execute_dui(sql, opts={}, &block)

Method that should be used when issuing a DELETE, UPDATE, or INSERT statement. By default, calls execute. This method should not be called directly by user code.

[Source]

         # File lib/sequel/database.rb, line 295
    295:     def execute_dui(sql, opts={}, &block)
    296:       execute(sql, opts, &block)
    297:     end

execute_insert(sql, opts={})

Execute the SQL on this database, returning the primary key of the table being inserted to.

[Source]

         # File lib/sequel/adapters/do.rb, line 109
    109:       def execute_insert(sql, opts={})
    110:         execute(sql, opts.merge(:type=>:insert))
    111:       end

execute_insert(sql, opts={})

Execute the given INSERT SQL, returning the last inserted row id.

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 184
    184:       def execute_insert(sql, opts={})
    185:         execute(sql, {:type=>:insert}.merge(opts))
    186:       end

execute_insert(sql, opts={}, &block)

Method that should be used when issuing a INSERT statement. By default, calls execute_dui. This method should not be called directly by user code.

[Source]

         # File lib/sequel/database.rb, line 302
    302:     def execute_insert(sql, opts={}, &block)
    303:       execute_dui(sql, opts, &block)
    304:     end

fetch(sql, *args, &block)

Fetches records for an arbitrary SQL statement. If a block is given, it is used to iterate over the records:

      DB.fetch('SELECT * FROM items'){|r| p r}

The method returns a dataset instance:

      DB.fetch('SELECT * FROM items').all

Fetch can also perform parameterized queries for protection against SQL injection:

      DB.fetch('SELECT * FROM items WHERE name = ?', my_name).all

[Source]

         # File lib/sequel/database.rb, line 319
    319:     def fetch(sql, *args, &block)
    320:       ds = dataset.with_sql(sql, *args)
    321:       ds.each(&block) if block
    322:       ds
    323:     end

from(*args, &block)

Returns a new dataset with the from method invoked. If a block is given, it is used as a filter on the dataset.

[Source]

         # File lib/sequel/database.rb, line 327
    327:     def from(*args, &block)
    328:       ds = dataset.from(*args)
    329:       block ? ds.filter(&block) : ds
    330:     end

get(*args, &block)

Returns a single value from the database, e.g.:

      # SELECT 1
      DB.get(1) #=> 1

      # SELECT version()
      DB.get(:version.sql_function) #=> ...

[Source]

         # File lib/sequel/database.rb, line 339
    339:     def get(*args, &block)
    340:       dataset.get(*args, &block)
    341:     end

identifier_input_method()

The method to call on identifiers going into the database

[Source]

         # File lib/sequel/database.rb, line 344
    344:     def identifier_input_method
    345:       case @identifier_input_method
    346:       when nil
    347:         @identifier_input_method = @opts.include?(:identifier_input_method) ? @opts[:identifier_input_method] : (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method)
    348:         @identifier_input_method == "" ? nil : @identifier_input_method
    349:       when ""
    350:         nil
    351:       else
    352:         @identifier_input_method
    353:       end
    354:     end

identifier_input_method=(v)

Set the method to call on identifiers going into the database

[Source]

         # File lib/sequel/database.rb, line 357
    357:     def identifier_input_method=(v)
    358:       reset_schema_utility_dataset
    359:       @identifier_input_method = v || ""
    360:     end

identifier_output_method()

The method to call on identifiers coming from the database

[Source]

         # File lib/sequel/database.rb, line 363
    363:     def identifier_output_method
    364:       case @identifier_output_method
    365:       when nil
    366:         @identifier_output_method = @opts.include?(:identifier_output_method) ? @opts[:identifier_output_method] : (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method)
    367:         @identifier_output_method == "" ? nil : @identifier_output_method
    368:       when ""
    369:         nil
    370:       else
    371:         @identifier_output_method
    372:       end
    373:     end

identifier_output_method=(v)

Set the method to call on identifiers coming from the database

[Source]

         # File lib/sequel/database.rb, line 376
    376:     def identifier_output_method=(v)
    377:       reset_schema_utility_dataset
    378:       @identifier_output_method = v || ""
    379:     end

indexes(table)

Return a hash containing index information. Hash keys are index name symbols. Values are subhashes with two keys, :columns and :unique. The value of :columns is an array of symbols of column names. The value of :unique is true or false depending on if the index is unique.

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 192
    192:       def indexes(table)
    193:         indexes = {}
    194:         m = output_identifier_meth
    195:         metadata(:getIndexInfo, nil, nil, input_identifier_meth.call(table), false, true) do |r|
    196:           next unless name = r[:column_name]
    197:           next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re
    198:           i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>!r[:non_unique]}
    199:           i[:columns] << m.call(name)
    200:         end
    201:         indexes
    202:       end

inspect()

Returns a string representation of the database object including the class name and the connection URI (or the opts if the URI cannot be constructed).

[Source]

         # File lib/sequel/database.rb, line 384
    384:     def inspect
    385:       "#<#{self.class}: #{(uri rescue opts).inspect}>"
    386:     end

literal(v)

Proxy the literal call to the dataset, used for default values.

[Source]

         # File lib/sequel/database.rb, line 389
    389:     def literal(v)
    390:       schema_utility_dataset.literal(v)
    391:     end

log_info(message, args=nil)

Log a message at level info to all loggers. All SQL logging goes through this method.

[Source]

         # File lib/sequel/database.rb, line 395
    395:     def log_info(message, args=nil)
    396:       message = "#{message}; #{args.inspect}" if args
    397:       @loggers.each{|logger| logger.info(message)}
    398:     end

logger=(logger)

Remove any existing loggers and just use the given logger.

[Source]

         # File lib/sequel/database.rb, line 401
    401:     def logger=(logger)
    402:       @loggers = Array(logger)
    403:     end

query(&block)

Return a dataset modified by the query block

[Source]

       # File lib/sequel/extensions/query.rb, line 4
    4:     def query(&block)
    5:       dataset.query(&block)
    6:     end

quote_identifiers=(v)

Whether to quote identifiers (columns and tables) for this database

[Source]

         # File lib/sequel/database.rb, line 406
    406:     def quote_identifiers=(v)
    407:       reset_schema_utility_dataset
    408:       @quote_identifiers = v
    409:     end

quote_identifiers?()

Returns true if the database quotes identifiers.

[Source]

         # File lib/sequel/database.rb, line 412
    412:     def quote_identifiers?
    413:       return @quote_identifiers unless @quote_identifiers.nil?
    414:       @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers)
    415:     end

rename_column(table, *args)

Renames a column in the specified table. This method expects the current column name and the new column name:

      DB.rename_column :items, :cntr, :counter

See alter_table.

[Source]

         # File lib/sequel/database/schema_methods.rb, line 147
    147:     def rename_column(table, *args)
    148:       alter_table(table) {rename_column(*args)}
    149:     end

rename_table(name, new_name)

Renames a table:

      DB.tables #=> [:items]
      DB.rename_table :items, :old_items
      DB.tables #=> [:old_items]

[Source]

         # File lib/sequel/database/schema_methods.rb, line 136
    136:     def rename_table(name, new_name)
    137:       remove_cached_schema(name)
    138:       execute_ddl(rename_table_sql(name, new_name))
    139:     end

schema(table, opts={})

Parse the schema from the database. Returns the schema for the given table as an array with all members being arrays of length 2, the first member being the column name, and the second member being a hash of column information. Available options are:

- :reload - Get fresh information from the database, instead of using cached information. If table_name is blank, :reload should be used unless you are sure that schema has not been called before with a table_name, otherwise you may only getting the schemas for tables that have been requested explicitly.
- :schema - An explicit schema to use. It may also be implicitly provided via the table name.

[Source]

         # File lib/sequel/database.rb, line 434
    434:     def schema(table, opts={})
    435:       raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true)
    436:
    437:       sch, table_name = schema_and_table(table)
    438:       quoted_name = quote_schema_table(table)
    439:       opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema)
    440:
    441:       @schemas.delete(quoted_name) if opts[:reload] && @schemas
    442:       return @schemas[quoted_name] if @schemas && @schemas[quoted_name]
    443:
    444:       @schemas ||= Hash.new do |h,k|
    445:         quote_name = quote_schema_table(k)
    446:         h[quote_name] if h.include?(quote_name)
    447:       end
    448:
    449:       cols = schema_parse_table(table_name, opts)
    450:       raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty?
    451:       @schemas[quoted_name] = cols
    452:     end

select(*args, &block)

Returns a new dataset with the select method invoked.

[Source]

         # File lib/sequel/database.rb, line 418
    418:     def select(*args, &block)
    419:       dataset.select(*args, &block)
    420:     end

serial_primary_key_options()

Default serial primary key options.

[Source]

        # File lib/sequel/database/schema_sql.rb, line 19
    19:     def serial_primary_key_options
    20:       {:primary_key => true, :type => Integer, :auto_increment => true}
    21:     end

set_column_default(table, *args)

Sets the default value for the given column in the given table:

      DB.set_column_default :items, :category, 'perl!'

See alter_table.

[Source]

         # File lib/sequel/database/schema_methods.rb, line 156
    156:     def set_column_default(table, *args)
    157:       alter_table(table) {set_column_default(*args)}
    158:     end

set_column_type(table, *args)

Set the data type for the given column in the given table:

      DB.set_column_type :items, :price, :float

See alter_table.

[Source]

         # File lib/sequel/database/schema_methods.rb, line 165
    165:     def set_column_type(table, *args)
    166:       alter_table(table) {set_column_type(*args)}
    167:     end

single_threaded?()

Returns true if the database is using a single-threaded connection pool.

[Source]

         # File lib/sequel/database.rb, line 455
    455:     def single_threaded?
    456:       @single_threaded
    457:     end

subadapter()

Return the subadapter type for this database, i.e. sqlite3 for do:sqlite3::memory:.

[Source]

         # File lib/sequel/adapters/do.rb, line 115
    115:       def subadapter
    116:         uri.split(":").first
    117:       end

synchronize(server=nil, &block)

Acquires a database connection, yielding it to the passed block.

[Source]

         # File lib/sequel/database.rb, line 460
    460:     def synchronize(server=nil, &block)
    461:       @pool.hold(server || :default, &block)
    462:     end

table_exists?(name)

Returns true if a table with the given name exists. This requires a query to the database unless this database object already has the schema for the given table name.

[Source]

         # File lib/sequel/database.rb, line 467
    467:     def table_exists?(name)
    468:       if @schemas && @schemas[name]
    469:         true
    470:       else
    471:         begin
    472:           from(name).first
    473:           true
    474:         rescue
    475:           false
    476:         end
    477:       end
    478:     end

tables()

All tables in this database

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 205
    205:       def tables
    206:         ts = []
    207:         m = output_identifier_meth
    208:         metadata(:getTables, nil, nil, nil, ['TABLE'].to_java(:string)){|h| ts << m.call(h[:table_name])}
    209:         ts
    210:       end

test_connection(server=nil)

Attempts to acquire a database connection. Returns true if successful. Will probably raise an error if unsuccessful.

[Source]

         # File lib/sequel/database.rb, line 482
    482:     def test_connection(server=nil)
    483:       synchronize(server){|conn|}
    484:       true
    485:     end

transaction(opts={}) {|conn| ...}

Default transaction method that should work on most JDBC databases. Does not use the JDBC transaction methods, uses SQL BEGIN/ROLLBACK/COMMIT statements instead.

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 215
    215:       def transaction(opts={})
    216:         synchronize(opts[:server]) do |conn|
    217:           return yield(conn) if @transactions.include?(Thread.current)
    218:           stmt = conn.createStatement
    219:           begin
    220:             log_info(begin_transaction_sql)
    221:             stmt.execute(begin_transaction_sql)
    222:             @transactions << Thread.current
    223:             yield(conn)
    224:           rescue Exception => e
    225:             log_info(rollback_transaction_sql)
    226:             stmt.execute(rollback_transaction_sql)
    227:             transaction_error(e)
    228:           ensure
    229:             unless e
    230:               log_info(commit_transaction_sql)
    231:               stmt.execute(commit_transaction_sql)
    232:             end
    233:             stmt.close
    234:             @transactions.delete(Thread.current)
    235:           end
    236:         end
    237:       end

transaction(opts={}) {|conn| ...}

Use DataObject‘s transaction support for transactions. This only supports single level transactions, and it always prepares transactions and commits them immediately after. It‘s wasteful, but required by DataObject‘s API.

[Source]

         # File lib/sequel/adapters/do.rb, line 123
    123:       def transaction(opts={})
    124:         th = Thread.current
    125:         synchronize(opts[:server]) do |conn|
    126:           return yield(conn) if @transactions.include?(th)
    127:           t = ::DataObjects::Transaction.create_for_uri(uri)
    128:           t.instance_variable_get(:@connection).close
    129:           t.instance_variable_set(:@connection, conn)
    130:           begin
    131:             log_info("Transaction.begin")
    132:             t.begin
    133:             @transactions << th
    134:             yield(conn)
    135:           rescue Exception => e
    136:             log_info("Transaction.rollback")
    137:             t.rollback
    138:             transaction_error(e)
    139:           ensure
    140:             unless e
    141:               log_info("Transaction.commit")
    142:               t.prepare
    143:               t.commit
    144:             end
    145:             @transactions.delete(th)
    146:           end
    147:         end
    148:       end

transaction(opts={}) {|conn| ...}

A simple implementation of SQL transactions. Nested transactions are not supported - calling transaction within a transaction will reuse the current transaction. Should be overridden for databases that support nested transactions.

[Source]

         # File lib/sequel/database.rb, line 491
    491:     def transaction(opts={})
    492:       synchronize(opts[:server]) do |conn|
    493:         return yield(conn) if @transactions.include?(Thread.current)
    494:         log_info(begin_transaction_sql)
    495:         conn.execute(begin_transaction_sql)
    496:         begin
    497:           @transactions << Thread.current
    498:           yield(conn)
    499:         rescue Exception => e
    500:           log_info(rollback_transaction_sql)
    501:           conn.execute(rollback_transaction_sql)
    502:           transaction_error(e)
    503:         ensure
    504:           unless e
    505:             log_info(commit_transaction_sql)
    506:             conn.execute(commit_transaction_sql)
    507:           end
    508:           @transactions.delete(Thread.current)
    509:         end
    510:       end
    511:     end

typecast_value(column_type, value)

Typecast the value to the given column_type. Calls typecast_value_#{column_type} if the method exists, otherwise returns the value. This method should raise Sequel::InvalidValue if assigned value is invalid.

[Source]

         # File lib/sequel/database.rb, line 518
    518:     def typecast_value(column_type, value)
    519:       return nil if value.nil?
    520:       meth = "typecast_value_#{column_type}"
    521:       begin
    522:         respond_to?(meth, true) ? send(meth, value) : value
    523:       rescue ArgumentError, TypeError => exp
    524:         e = Sequel::InvalidValue.new("#{exp.class} #{exp.message}")
    525:         e.set_backtrace(exp.backtrace)
    526:         raise e
    527:       end
    528:     end

uri(opts={})

Return the DataObjects URI for the Sequel URI, removing the do: prefix.

[Source]

         # File lib/sequel/adapters/do.rb, line 152
    152:       def uri(opts={})
    153:         opts = @opts.merge(opts)
    154:         (opts[:uri] || opts[:url]).sub(/\Ado:/, '')
    155:       end

uri()

Returns the URI identifying the database. This method can raise an error if the database used options instead of a connection string.

[Source]

         # File lib/sequel/database.rb, line 533
    533:     def uri
    534:       uri = URI::Generic.new(
    535:         self.class.adapter_scheme.to_s,
    536:         nil,
    537:         @opts[:host],
    538:         @opts[:port],
    539:         nil,
    540:         "/#{@opts[:database]}",
    541:         nil,
    542:         nil,
    543:         nil
    544:       )
    545:       uri.user = @opts[:user]
    546:       uri.password = @opts[:password] if uri.user
    547:       uri.to_s
    548:     end

uri(opts={})

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.

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 243
    243:       def uri(opts={})
    244:         opts = @opts.merge(opts)
    245:         ur = opts[:uri] || opts[:url] || opts[:database]
    246:         ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}"
    247:       end

url()

Explicit alias of uri for easier subclassing.

[Source]

         # File lib/sequel/database.rb, line 551
    551:     def url
    552:       uri
    553:     end

[Validate]