Class: Sequel::Database

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

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_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 run schema select serial_primary_key_options set_column_default set_column_type single_threaded= single_threaded? subadapter supports_savepoints? synchronize table_exists? tables test_connection transaction typecast_value uri uri uri url

### Included Modules

Metaprogramming

### Constants

ADAPTERS | = | %w'ado amalgalite 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_RELEASE_SAVEPOINT | = | 'RELEASE SAVEPOINT autopoint_%d'.freeze
SQL_ROLLBACK | = | 'ROLLBACK'.freeze
SQL_ROLLBACK_TO_SAVEPOINT | = | 'ROLLBACK TO SAVEPOINT autopoint_%d'.freeze
SQL_SAVEPOINT | = | 'SAVEPOINT autopoint_%d'.freeze
TRANSACTION_BEGIN | = | 'Transaction.begin'.freeze
TRANSACTION_COMMIT | = | 'Transaction.commit'.freeze
TRANSACTION_ROLLBACK | = | 'Transaction.rollback'.freeze
POSTGRES_DEFAULT_RE | = | /\A(?:B?('.*')::[^']+|\((-?\d+(?:\.\d+)?)\))\z/
MSSQL_DEFAULT_RE | = | /\A(?:\(N?('.*')\)|\(\((-?\d+(?:\.\d+)?)\)\))\z/
MYSQL_TIMESTAMP_RE | = | /\ACURRENT_(?:DATE|TIMESTAMP)?\z/
STRING_DEFAULT_RE | = | /\A'(.*)'\z/
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

### Attributes

convert_types | [RW] | 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.
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 105
    105:     def self.adapter_class(scheme)
    106:       scheme = scheme.to_s.gsub('-', '_').to_sym
    107:
    108:       unless klass = ADAPTER_MAP[scheme]
    109:         # attempt to load the adapter file
    110:         begin
    111:           Sequel.require "adapters/#{scheme}"
    112:         rescue LoadError => e
    113:           raise Sequel.convert_exception_class(e, AdapterNotFound)
    114:         end
    115:
    116:         # make sure we actually loaded the adapter
    117:         unless klass = ADAPTER_MAP[scheme]
    118:           raise AdapterNotFound, "Could not load #{scheme} adapter"
    119:         end
    120:       end
    121:       klass
    122:     end

adapter_scheme()

Returns the scheme for the Database class.

[Source]

         # File lib/sequel/database.rb, line 125
    125:     def self.adapter_scheme
    126:       @scheme
    127:     end

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

Connects to a database. See Sequel.connect.

[Source]

         # File lib/sequel/database.rb, line 130
    130:     def self.connect(conn_string, opts = {}, &block)
    131:       case conn_string
    132:       when String
    133:         if match = /\A(jdbc|do):/o.match(conn_string)
    134:           c = adapter_class(match[1].to_sym)
    135:           opts = {:uri=>conn_string}.merge(opts)
    136:         else
    137:           uri = URI.parse(conn_string)
    138:           scheme = uri.scheme
    139:           scheme = :dbi if scheme =~ /\Adbi-/
    140:           c = adapter_class(scheme)
    141:           uri_options = c.send(:uri_to_options, uri)
    142:           uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v} unless uri.query.to_s.strip.empty?
    143:           uri_options.entries.each{|k,v| uri_options[k] = URI.unescape(v) if v.is_a?(String)}
    144:           opts = uri_options.merge(opts)
    145:         end
    146:       when Hash
    147:         opts = conn_string.merge(opts)
    148:         c = adapter_class(opts[:adapter] || opts['adapter'])
    149:       else
    150:         raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}"
    151:       end
    152:       # process opts a bit
    153:       opts = opts.inject({}) do |m, kv| k, v = *kv
    154:         k = :user if k.to_s == 'username'
    155:         m[k.to_sym] = v
    156:         m
    157:       end
    158:       if block
    159:         begin
    160:           yield(db = c.new(opts))
    161:         ensure
    162:           db.disconnect if db
    163:           ::Sequel::DATABASES.delete(db)
    164:         end
    165:         nil
    166:       else
    167:         c.new(opts)
    168:       end
    169:     end

identifier_input_method()

The method to call on identifiers going into the database

[Source]

         # File lib/sequel/database.rb, line 172
    172:     def self.identifier_input_method
    173:       @@identifier_input_method
    174:     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 178
    178:     def self.identifier_input_method=(v)
    179:       @@identifier_input_method = v || ""
    180:     end

identifier_output_method()

The method to call on identifiers coming from the database

[Source]

         # File lib/sequel/database.rb, line 183
    183:     def self.identifier_output_method
    184:       @@identifier_output_method
    185:     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 189
    189:     def self.identifier_output_method=(v)
    190:       @@identifier_output_method = v || ""
    191:     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 100
    100:       def initialize(opts)
    101:         @opts = opts
    102:         @convert_types = opts.include?(:convert_types) ? typecast_value_boolean(opts[:convert_types]) : true
    103:         raise(Error, "No connection string specified") unless uri
    104:         if match = /\Ajdbc:([^:]+)/.match(uri) and prok = DATABASE_SETUP[match[1].to_sym]
    105:           prok.call(self)
    106:         end
    107:         super(opts)
    108:       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 81
    81:     def initialize(opts = {}, &block)
    82:       @opts ||= opts
    83:
    84:       @single_threaded = opts.include?(:single_threaded) ? typecast_value_boolean(opts[:single_threaded]) : @@single_threaded
    85:       @schemas = {}
    86:       @default_schema = opts.include?(:default_schema) ? opts[:default_schema] : default_schema_default
    87:       @prepared_statements = {}
    88:       @transactions = []
    89:       @identifier_input_method = nil
    90:       @identifier_output_method = nil
    91:       @quote_identifiers = nil
    92:       @pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(connection_pool_default_options.merge(opts), &block)
    93:       @pool.connection_proc = proc{|server| connect(server)} unless block
    94:       @pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc]
    95:
    96:       @loggers = Array(opts[:logger]) + Array(opts[:loggers])
    97:       ::Sequel::DATABASES.push(self)
    98:     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 45
    45:       def initialize(opts)
    46:         @opts = opts
    47:         raise(Error, "No connection string specified") unless uri
    48:         if prok = DATABASE_SETUP[subadapter.to_sym]
    49:           prok.call(self)
    50:         end
    51:         super(opts)
    52:       end

quote_identifiers=(value)

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

[Source]

         # File lib/sequel/database.rb, line 195
    195:     def self.quote_identifiers=(value)
    196:       @@quote_identifiers = value
    197:     end

single_threaded=(value)

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

[Source]

         # File lib/sequel/database.rb, line 201
    201:     def self.single_threaded=(value)
    202:       @@single_threaded = value
    203:     end

### Public Instance methods

<<(sql)

Runs the supplied SQL statement string on the database server. Alias for run.

[Source]

         # File lib/sequel/database.rb, line 240
    240:     def <<(sql)
    241:       run(sql)
    242:     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 254
    254:     def [](*args)
    255:       (String === args.first) ? fetch(*args) : from(*args)
    256:     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, columns, options={})

Adds an index to a table for the given columns:

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

Options:

- :ignore_errors - Ignore any DatabaseErrors that are raised

See alter_table.

[Source]

        # File lib/sequel/database/schema_methods.rb, line 24
    24:     def add_index(table, columns, options={})
    25:       e = options[:ignore_errors]
    26:       begin
    27:         alter_table(table){add_index(columns, options)}
    28:       rescue DatabaseError
    29:         raise unless e
    30:       end
    31:     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 50
    50:     def alter_table(name, generator=nil, &block)
    51:       remove_cached_schema(name)
    52:       generator ||= Schema::AlterTableGenerator.new(self, &block)
    53:       alter_table_sql_list(name, generator.operations).flatten.each {|sql| execute_ddl(sql)}
    54:     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 260
    260:     def call(ps_name, hash={})
    261:       prepared_statements[ps_name].call(hash)
    262:     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 112
    112:       def call_sproc(name, opts = {})
    113:         args = opts[:args] || []
    114:         sql = "{call #{name}(#{args.map{'?'}.join(',')})}"
    115:         synchronize(opts[:server]) do |conn|
    116:           cps = conn.prepareCall(sql)
    117:
    118:           i = 0
    119:           args.each{|arg| set_ps_arg(cps, arg, i+=1)}
    120:
    121:           begin
    122:             if block_given?
    123:               yield cps.executeQuery
    124:             else
    125:               case opts[:type]
    126:               when :insert
    127:                 cps.executeUpdate
    128:                 last_insert_id(conn, opts)
    129:               else
    130:                 cps.executeUpdate
    131:               end
    132:             end
    133:           rescue NativeException, JavaSQL::SQLException => e
    134:             raise_error(e)
    135:           ensure
    136:             cps.close
    137:           end
    138:         end
    139:       end

cast_type_literal(type)

Cast the given type to a literal type

[Source]

         # File lib/sequel/database.rb, line 265
    265:     def cast_type_literal(type)
    266:       type_literal(:type=>type)
    267:     end

connect(server)

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

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 142
    142:       def connect(server)
    143:         args = [uri(server_opts(server))]
    144:         args.concat([opts[:user], opts[:password]]) if opts[:user] && opts[:password]
    145:         setup_connection(JavaSQL::DriverManager.getConnection(*args))
    146:       end

connect(server)

Setup a DataObjects::Connection to the database.

[Source]

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

connect()

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

[Source]

         # File lib/sequel/database.rb, line 270
    270:     def connect
    271:       raise NotImplementedError, "#connect should be overridden by adapters"
    272:     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 92
    92:     def create_or_replace_view(name, source)
    93:       remove_cached_schema(name)
    94:       source = source.sql if source.is_a?(Dataset)
    95:       execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}")
    96:     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.
- :ignore_index_errors - Ignore any errors when creating indexes.

See Schema::Generator.

[Source]

        # File lib/sequel/database/schema_methods.rb, line 70
    70:     def create_table(name, options={}, &block)
    71:       options = {:generator=>options} if options.is_a?(Schema::Generator)
    72:       generator = options[:generator] || Schema::Generator.new(self, &block)
    73:       create_table_from_generator(name, generator, options)
    74:       create_table_indexes_from_generator(name, generator, options)
    75:     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 78
    78:     def create_table!(name, options={}, &block)
    79:       drop_table(name) rescue nil
    80:       create_table(name, options, &block)
    81:     end

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

Creates the table unless the table already exists

[Source]

        # File lib/sequel/database/schema_methods.rb, line 84
    84:     def create_table?(name, options={}, &block)
    85:       create_table(name, options, &block) unless table_exists?(name)
    86:     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 102
    102:     def create_view(name, source)
    103:       source = source.sql if source.is_a?(Dataset)
    104:       execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}")
    105:     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 281
    281:     def database_type
    282:       self.class.adapter_scheme
    283:     end

dataset()

Returns a blank dataset for this database

[Source]

         # File lib/sequel/database.rb, line 286
    286:     def dataset
    287:       ds = Sequel::Dataset.new(self)
    288:     end

dataset(opts = nil)

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

[Source]

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

dataset(opts = nil)

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

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 149
    149:       def dataset(opts = nil)
    150:         JDBC::Dataset.new(self, opts)
    151:       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 292
    292:     def disconnect
    293:       pool.disconnect
    294:     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 112
    112:     def drop_column(table, *args)
    113:       alter_table(table) {drop_column(*args)}
    114:     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 122
    122:     def drop_index(table, columns, options={})
    123:       alter_table(table){drop_index(columns, options)}
    124:     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 129
    129:     def drop_table(*names)
    130:       names.each do |n|
    131:         remove_cached_schema(n)
    132:         execute_ddl(drop_table_sql(n))
    133:       end
    134:     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 139
    139:     def drop_view(*names)
    140:       names.each do |n|
    141:         remove_cached_schema(n)
    142:         execute_ddl("DROP VIEW #{quote_schema_table(n)}")
    143:       end
    144:     end

dump_indexes_migration(options={})

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

- :same_db - Create a dump for the same database type, so don‘t ignore errors if the index statements fail.

[Source]

        # File lib/sequel/extensions/schema_dumper.rb, line 13
    13:     def dump_indexes_migration(options={})
    14:       ts = tables
    15:       "Class.new(Sequel::Migration) do\n  def up\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :add_index, options)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\n  \n  def down\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :drop_index, options)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\nend\n"
    16:     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 38
    38:     def dump_schema_migration(options={})
    39:       ts = tables
    40:       "Class.new(Sequel::Migration) do\n  def up\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_schema(t, options)}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\n  \n  def down\n    drop_table(\#{ts.sort_by{|t| t.to_s}.inspect[1...-1]})\n  end\nend\n"
    41:     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 56
    56:     def dump_table_schema(table, options={})
    57:       s = schema(table).dup
    58:       pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first}
    59:       options = options.merge(:single_pk=>true) if pks.length == 1
    60:       m = method(:column_schema_to_generator_opts)
    61:       im = method(:index_to_generator_opts)
    62:       indexes = indexes(table).sort_by{|k,v| k.to_s} if options[:indexes] != false and respond_to?(:indexes)
    63:       gen = Schema::Generator.new(self) do
    64:         s.each{|name, info| send(*m.call(name, info, options))}
    65:         primary_key(pks) if !@primary_key && pks.length > 0
    66:         indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts))} if indexes
    67:       end
    68:       commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n")
    69:       "create_table(#{table.inspect}#{', :ignore_index_errors=>true' if !options[:same_db] && options[:indexes] != false && indexes && !indexes.empty?}) do\n#{commands.gsub(/^/o, '  ')}\nend"
    70:     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 298
    298:     def execute(sql, opts={})
    299:       raise NotImplementedError, "#execute should be overridden by adapters"
    300:     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 69
    69:       def execute(sql, opts={})
    70:         log_info(sql)
    71:         synchronize(opts[:server]) do |conn|
    72:           begin
    73:             command = conn.create_command(sql)
    74:             res = block_given? ? command.execute_reader : command.execute_non_query
    75:           rescue ::DataObjects::Error => e
    76:             raise_error(e)
    77:           end
    78:           if block_given?
    79:             begin
    80:               yield(res)
    81:             ensure
    82:              res.close if res
    83:             end
    84:           elsif opts[:type] == :insert
    85:             res.insert_id
    86:           else
    87:             res.affected_rows
    88:           end
    89:         end
    90:       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 155
    155:       def execute(sql, opts={}, &block)
    156:         return call_sproc(sql, opts, &block) if opts[:sproc]
    157:         return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)}
    158:         log_info(sql)
    159:         synchronize(opts[:server]) do |conn|
    160:           stmt = conn.createStatement
    161:           begin
    162:             if block_given?
    163:               yield stmt.executeQuery(sql)
    164:             else
    165:               case opts[:type]
    166:               when :ddl
    167:                 stmt.execute(sql)
    168:               when :insert
    169:                 stmt.executeUpdate(sql)
    170:                 last_insert_id(conn, opts.merge(:stmt=>stmt))
    171:               else
    172:                 stmt.executeUpdate(sql)
    173:               end
    174:             end
    175:           rescue NativeException, JavaSQL::SQLException => e
    176:             raise_error(e)
    177:           ensure
    178:             stmt.close
    179:           end
    180:         end
    181:       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 305
    305:     def execute_ddl(sql, opts={}, &block)
    306:       execute_dui(sql, opts, &block)
    307:     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 186
    186:       def execute_ddl(sql, opts={})
    187:         execute(sql, {:type=>:ddl}.merge(opts))
    188:       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 94
    94:       def execute_dui(sql, opts={})
    95:         execute(sql, opts)
    96:       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 312
    312:     def execute_dui(sql, opts={}, &block)
    313:       execute(sql, opts, &block)
    314:     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 319
    319:     def execute_insert(sql, opts={}, &block)
    320:       execute_dui(sql, opts, &block)
    321:     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 100
    100:       def execute_insert(sql, opts={})
    101:         execute(sql, opts.merge(:type=>:insert))
    102:       end

execute_insert(sql, opts={})

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

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 192
    192:       def execute_insert(sql, opts={})
    193:         execute(sql, {:type=>:insert}.merge(opts))
    194:       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 336
    336:     def fetch(sql, *args, &block)
    337:       ds = dataset.with_sql(sql, *args)
    338:       ds.each(&block) if block
    339:       ds
    340:     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 344
    344:     def from(*args, &block)
    345:       ds = dataset.from(*args)
    346:       block ? ds.filter(&block) : ds
    347:     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 356
    356:     def get(*args, &block)
    357:       dataset.get(*args, &block)
    358:     end

identifier_input_method()

The method to call on identifiers going into the database

[Source]

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

identifier_input_method=(v)

Set the method to call on identifiers going into the database

[Source]

         # File lib/sequel/database.rb, line 374
    374:     def identifier_input_method=(v)
    375:       reset_schema_utility_dataset
    376:       @identifier_input_method = v || ""
    377:     end

identifier_output_method()

The method to call on identifiers coming from the database

[Source]

         # File lib/sequel/database.rb, line 380
    380:     def identifier_output_method
    381:       case @identifier_output_method
    382:       when nil
    383:         @identifier_output_method = @opts.include?(:identifier_output_method) ? @opts[:identifier_output_method] : (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method)
    384:         @identifier_output_method == "" ? nil : @identifier_output_method
    385:       when ""
    386:         nil
    387:       else
    388:         @identifier_output_method
    389:       end
    390:     end

identifier_output_method=(v)

Set the method to call on identifiers coming from the database

[Source]

         # File lib/sequel/database.rb, line 393
    393:     def identifier_output_method=(v)
    394:       reset_schema_utility_dataset
    395:       @identifier_output_method = v || ""
    396:     end

indexes(table, opts={})

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 200
    200:       def indexes(table, opts={})
    201:         m = output_identifier_meth
    202:         im = input_identifier_meth
    203:         schema, table = schema_and_table(table)
    204:         schema ||= opts[:schema]
    205:         schema = im.call(schema) if schema
    206:         table = im.call(table)
    207:         indexes = {}
    208:         metadata(:getIndexInfo, nil, schema, table, false, true) do |r|
    209:           next unless name = r[:column_name]
    210:           next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re
    211:           i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>[false, 0].include?(r[:non_unique])}
    212:           i[:columns] << m.call(name)
    213:         end
    214:         indexes
    215:       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 401
    401:     def inspect
    402:       "#<#{self.class}: #{(uri rescue opts).inspect}>"
    403:     end

literal(v)

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

[Source]

         # File lib/sequel/database.rb, line 406
    406:     def literal(v)
    407:       schema_utility_dataset.literal(v)
    408:     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 412
    412:     def log_info(message, args=nil)
    413:       message = "#{message}; #{args.inspect}" if args
    414:       @loggers.each{|logger| logger.info(message)}
    415:     end

logger=(logger)

Remove any existing loggers and just use the given logger.

[Source]

         # File lib/sequel/database.rb, line 418
    418:     def logger=(logger)
    419:       @loggers = Array(logger)
    420:     end

query(&block)

Return a dataset modified by the query block

[Source]

        # File lib/sequel/extensions/query.rb, line 8
     8:     def query(&block)
     9:       dataset.query(&block)
    10:     end

quote_identifiers=(v)

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

[Source]

         # File lib/sequel/database.rb, line 423
    423:     def quote_identifiers=(v)
    424:       reset_schema_utility_dataset
    425:       @quote_identifiers = v
    426:     end

quote_identifiers?()

Returns true if the database quotes identifiers.

[Source]

         # File lib/sequel/database.rb, line 429
    429:     def quote_identifiers?
    430:       return @quote_identifiers unless @quote_identifiers.nil?
    431:       @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers)
    432:     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 162
    162:     def rename_column(table, *args)
    163:       alter_table(table) {rename_column(*args)}
    164:     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 151
    151:     def rename_table(name, new_name)
    152:       remove_cached_schema(name)
    153:       execute_ddl(rename_table_sql(name, new_name))
    154:     end

run(sql, opts={})

Runs the supplied SQL statement string on the database server. Returns nil. Options:

- :server - The server to run the SQL on.

[Source]

         # File lib/sequel/database.rb, line 437
    437:     def run(sql, opts={})
    438:       execute_ddl(sql, opts)
    439:       nil
    440:     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 459
    459:     def schema(table, opts={})
    460:       raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true)
    461:
    462:       sch, table_name = schema_and_table(table)
    463:       quoted_name = quote_schema_table(table)
    464:       opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema)
    465:
    466:       @schemas.delete(quoted_name) if opts[:reload]
    467:       return @schemas[quoted_name] if @schemas[quoted_name]
    468:
    469:       cols = schema_parse_table(table_name, opts)
    470:       raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty?
    471:       cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])}
    472:       @schemas[quoted_name] = cols
    473:     end

select(*args, &block)

Returns a new dataset with the select method invoked.

[Source]

         # File lib/sequel/database.rb, line 443
    443:     def select(*args, &block)
    444:       dataset.select(*args, &block)
    445:     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 171
    171:     def set_column_default(table, *args)
    172:       alter_table(table) {set_column_default(*args)}
    173:     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 180
    180:     def set_column_type(table, *args)
    181:       alter_table(table) {set_column_type(*args)}
    182:     end

single_threaded?()

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

[Source]

         # File lib/sequel/database.rb, line 476
    476:     def single_threaded?
    477:       @single_threaded
    478:     end

subadapter()

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

[Source]

         # File lib/sequel/adapters/do.rb, line 106
    106:       def subadapter
    107:         uri.split(":").first
    108:       end

supports_savepoints?()

Whether the database and adapter support savepoints, false by default

[Source]

         # File lib/sequel/database.rb, line 486
    486:     def supports_savepoints?
    487:       false
    488:     end

synchronize(server=nil, &block)

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

[Source]

         # File lib/sequel/database.rb, line 481
    481:     def synchronize(server=nil, &block)
    482:       @pool.hold(server || :default, &block)
    483:     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 493
    493:     def table_exists?(name)
    494:       begin
    495:         from(name).first
    496:         true
    497:       rescue
    498:         false
    499:       end
    500:     end

tables()

All tables in this database

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 218
    218:       def tables
    219:         ts = []
    220:         m = output_identifier_meth
    221:         metadata(:getTables, nil, nil, nil, ['TABLE'].to_java(:string)){|h| ts << m.call(h[:table_name])}
    222:         ts
    223:       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 504
    504:     def test_connection(server=nil)
    505:       synchronize(server){|conn|}
    506:       true
    507:     end

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

Starts a database transaction. When a database transaction is used, either all statements are successful or none of the statements are successful. Note that MySQL MyISAM tabels do not support transactions.

The following options are respected:

- :server - The server to use for the transaction
- :savepoint - Whether to create a new savepoint for this transaction, only respected if the database adapter supports savepoints. By default Sequel will reuse an existing transaction, so if you want to use a savepoint you must use this option.

[Source]

         # File lib/sequel/database.rb, line 520
    520:     def transaction(opts={}, &block)
    521:       synchronize(opts[:server]) do |conn|
    522:         return yield(conn) if already_in_transaction?(conn, opts)
    523:         _transaction(conn, &block)
    524:       end
    525:     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 532
    532:     def typecast_value(column_type, value)
    533:       return nil if value.nil?
    534:       meth = "typecast_value_#{column_type}"
    535:       begin
    536:         respond_to?(meth, true) ? send(meth, value) : value
    537:       rescue ArgumentError, TypeError => e
    538:         raise Sequel.convert_exception_class(e, InvalidValue)
    539:       end
    540:     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 545
    545:     def uri
    546:       uri = URI::Generic.new(
    547:         self.class.adapter_scheme.to_s,
    548:         nil,
    549:         @opts[:host],
    550:         @opts[:port],
    551:         nil,
    552:         "/#{@opts[:database]}",
    553:         nil,
    554:         nil,
    555:         nil
    556:       )
    557:       uri.user = @opts[:user]
    558:       uri.password = @opts[:password] if uri.user
    559:       uri.to_s
    560:     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 229
    229:       def uri(opts={})
    230:         opts = @opts.merge(opts)
    231:         ur = opts[:uri] || opts[:url] || opts[:database]
    232:         ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}"
    233:       end

uri(opts={})

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

[Source]

         # File lib/sequel/adapters/do.rb, line 112
    112:       def uri(opts={})
    113:         opts = @opts.merge(opts)
    114:         (opts[:uri] || opts[:url]).sub(/\Ado:/, '')
    115:       end

url()

Explicit alias of uri for easier subclassing.

[Source]

         # File lib/sequel/database.rb, line 563
    563:     def url
    564:       uri
    565:     end

[Validate]