### Home Classes Methods

### In Files

- lib/sequel/database/dataset_defaults.rb
- lib/sequel/database/dataset.rb
- lib/sequel/database/connecting.rb
- lib/sequel/database/query.rb
- lib/sequel/database/logging.rb
- lib/sequel/database/schema_methods.rb
- lib/sequel/database/misc.rb
- lib/sequel/extensions/schema_dumper.rb
- lib/sequel/extensions/query.rb
- lib/sequel/database.rb

### Parent

Object

### Sections

- Methods relating to adapters, connecting, disconnecting, and sharding
- Methods relating to logging
- Methods that create datasets
- Methods that execute queries and/or return results
- Methods that modify the database schema
- Methods that set defaults for created datasets
- Miscellaneous methods

### Methods

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

### Included Modules

- Sequel::Metaprogramming

### Files

- CHANGELOG
- COPYING
- README.rdoc
- advanced_associations.rdoc
- association_basics.rdoc
- cheat_sheet.rdoc
- dataset_basics.rdoc
- dataset_filtering.rdoc
- migration.rdoc
- model_hooks.rdoc
- opening_databases.rdoc
- prepared_statements.rdoc
- querying.rdoc
- reflection.rdoc
- 1.0.txt
- 1.1.txt
- 1.3.txt
- 1.4.0.txt
- 1.5.0.txt
- 2.0.0.txt
- 2.1.0.txt
- 2.10.0.txt
- 2.11.0.txt
- 2.12.0.txt
- 2.2.0.txt
- 2.3.0.txt
- 2.4.0.txt
- 2.5.0.txt
- 2.6.0.txt
- 2.7.0.txt
- 2.8.0.txt
- 2.9.0.txt
- 3.0.0.txt
- 3.1.0.txt
- 3.10.0.txt
- 3.11.0.txt
- 3.12.0.txt
- 3.2.0.txt
- 3.3.0.txt
- 3.4.0.txt
- 3.5.0.txt
- 3.6.0.txt
- 3.7.0.txt
- 3.8.0.txt
- 3.9.0.txt
- sharding.rdoc
- sql.rdoc
- virtual_rows.rdoc

### Class/Module Index

Quicksearch

- Sequel
- Sequel::ADO
- Sequel::ADO::Database
- Sequel::ADO::Dataset
- Sequel::ADO::MSSQL
- Sequel::ADO::MSSQL::DatabaseMethods
- Sequel::ADO::MSSQL::Dataset
- Sequel::AdapterNotFound
- Sequel::Amalgalite
- Sequel::Amalgalite::Database
- Sequel::Amalgalite::Dataset
- Sequel::Amalgalite::SequelTypeMap
- Sequel::BasicObject
- Sequel::BeforeHookFailed
- Sequel::ConnectionPool
- Sequel::ConnectionPool::ClassMethods
- Sequel::DB2
- Sequel::DB2::Database
- Sequel::DB2::Dataset
- Sequel::DBI
- Sequel::DBI::Database
- Sequel::DBI::Dataset
- Sequel::DataObjects
- Sequel::DataObjects::Database
- Sequel::DataObjects::Dataset
- Sequel::DataObjects::MySQL
- Sequel::DataObjects::MySQL::DatabaseMethods
- Sequel::DataObjects::MySQL::Dataset
- Sequel::DataObjects::Postgres
- Sequel::DataObjects::Postgres::AdapterMethods
- Sequel::DataObjects::Postgres::DatabaseMethods
- Sequel::DataObjects::Postgres::Dataset
- Sequel::DataObjects::SQLite
- Sequel::DataObjects::SQLite::DatabaseMethods
- Sequel::DataObjects::SQLite::Dataset
- Sequel::Database
- Sequel::DatabaseConnectionError
- Sequel::DatabaseDisconnectError
- Sequel::DatabaseError
- Sequel::Dataset
- Sequel::Dataset::ArgumentMapper
- Sequel::Dataset::Pagination
- Sequel::Dataset::PreparedStatementMethods
- Sequel::Dataset::QueryBlockCopy
- Sequel::Dataset::StoredProcedureMethods
- Sequel::Dataset::StoredProcedures
- Sequel::Dataset::UnnumberedArgumentMapper
- Sequel::Error
- Sequel::Error::AdapterNotFound
- Sequel::Error::InvalidOperation
- Sequel::Error::InvalidValue
- Sequel::Error::PoolTimeoutError
- Sequel::Error::Rollback
- Sequel::Firebird
- Sequel::Firebird::Database
- Sequel::Firebird::Dataset
- Sequel::Inflections
- Sequel::Informix
- Sequel::Informix::Database
- Sequel::Informix::Dataset
- Sequel::IntegerMigrator
- Sequel::InvalidOperation
- Sequel::InvalidValue
- Sequel::JDBC
- Sequel::JDBC::AS400
- Sequel::JDBC::AS400::DatabaseMethods
- Sequel::JDBC::AS400::Dataset
- Sequel::JDBC::Database
- Sequel::JDBC::Dataset
- Sequel::JDBC::Dataset::PreparedStatementMethods
- Sequel::JDBC::Dataset::StoredProcedureMethods
- Sequel::JDBC::H2
- Sequel::JDBC::H2::DatabaseMethods
- Sequel::JDBC::H2::Dataset
- Sequel::JDBC::JavaLang
- Sequel::JDBC::JavaSQL
- Sequel::JDBC::JavaxNaming
- Sequel::JDBC::MSSQL
- Sequel::JDBC::MSSQL::DatabaseMethods
- Sequel::JDBC::MSSQL::Dataset
- Sequel::JDBC::MySQL
- Sequel::JDBC::MySQL::DatabaseMethods
- Sequel::JDBC::MySQL::Dataset
- Sequel::JDBC::Oracle
- Sequel::JDBC::Oracle::DatabaseMethods
- Sequel::JDBC::Oracle::Dataset
- Sequel::JDBC::Postgres
- Sequel::JDBC::Postgres::AdapterMethods
- Sequel::JDBC::Postgres::DatabaseMethods
- Sequel::JDBC::Postgres::Dataset
- Sequel::JDBC::SQLite
- Sequel::JDBC::SQLite::DatabaseMethods
- Sequel::JDBC::SQLite::Dataset
- Sequel::LiteralString
- Sequel::LooserTypecasting
- Sequel::MSSQL
- Sequel::MSSQL::DatabaseMethods
- Sequel::MSSQL::DatasetMethods
- Sequel::Metaprogramming
- Sequel::Migration
- Sequel::MigrationDSL
- Sequel::Migrator
- Sequel::Migrator::Error
- Sequel::Model
- Sequel::Model::Associations
- Sequel::Model::Associations::AssociationDatasetMethods
- Sequel::Model::Associations::AssociationReflection
- Sequel::Model::Associations::ClassMethods
- Sequel::Model::Associations::DatasetMethods
- Sequel::Model::Associations::InstanceMethods
- Sequel::Model::Associations::ManyToManyAssociationReflection
- Sequel::Model::Associations::ManyToOneAssociationReflection
- Sequel::Model::Associations::OneToManyAssociationReflection
- Sequel::Model::Associations::OneToOneAssociationReflection
- Sequel::Model::ClassMethods
- Sequel::Model::DatasetMethods
- Sequel::Model::Errors
- Sequel::Model::InstanceMethods
- Sequel::MySQL
- Sequel::MySQL::Database
- Sequel::MySQL::DatabaseMethods
- Sequel::MySQL::Dataset
- Sequel::MySQL::Dataset::CallableStatementMethods
- Sequel::MySQL::Dataset::PreparedStatementMethods
- Sequel::MySQL::Dataset::StoredProcedureMethods
- Sequel::MySQL::DatasetMethods
- Sequel::NamedTimezones
- Sequel::NoExistingObject
- Sequel::NotImplemented
- Sequel::ODBC
- Sequel::ODBC::Database
- Sequel::ODBC::Dataset
- Sequel::ODBC::MSSQL
- Sequel::ODBC::MSSQL::DatabaseMethods
- Sequel::ODBC::MSSQL::Dataset
- Sequel::OpenBase
- Sequel::OpenBase::Database
- Sequel::OpenBase::Dataset
- Sequel::Oracle
- Sequel::Oracle::Database
- Sequel::Oracle::DatabaseMethods
- Sequel::Oracle::Dataset
- Sequel::Oracle::DatasetMethods
- Sequel::Plugins
- Sequel::Plugins::ActiveModel
- Sequel::Plugins::ActiveModel::InstanceMethods
- Sequel::Plugins::AssociationDependencies
- Sequel::Plugins::AssociationDependencies::ClassMethods
- Sequel::Plugins::AssociationDependencies::InstanceMethods
- Sequel::Plugins::AssociationPks
- Sequel::Plugins::AssociationPks::ClassMethods
- Sequel::Plugins::AssociationProxies
- Sequel::Plugins::AssociationProxies::AssociationProxy
- Sequel::Plugins::AssociationProxies::ClassMethods
- Sequel::Plugins::BooleanReaders
- Sequel::Plugins::BooleanReaders::ClassMethods
- Sequel::Plugins::Caching
- Sequel::Plugins::Caching::ClassMethods
- Sequel::Plugins::Caching::InstanceMethods
- Sequel::Plugins::ClassTableInheritance
- Sequel::Plugins::ClassTableInheritance::ClassMethods
- Sequel::Plugins::ClassTableInheritance::InstanceMethods
- Sequel::Plugins::Composition
- Sequel::Plugins::Composition::ClassMethods
- Sequel::Plugins::Composition::InstanceMethods
- Sequel::Plugins::ForceEncoding
- Sequel::Plugins::ForceEncoding::ClassMethods
- Sequel::Plugins::ForceEncoding::InstanceMethods
- Sequel::Plugins::HookClassMethods
- Sequel::Plugins::HookClassMethods::ClassMethods
- Sequel::Plugins::HookClassMethods::InstanceMethods
- Sequel::Plugins::IdentityMap
- Sequel::Plugins::IdentityMap::ClassMethods
- Sequel::Plugins::IdentityMap::InstanceMethods
- Sequel::Plugins::InstanceFilters
- Sequel::Plugins::InstanceFilters::InstanceMethods
- Sequel::Plugins::InstanceHooks
- Sequel::Plugins::InstanceHooks::InstanceMethods
- Sequel::Plugins::LazyAttributes
- Sequel::Plugins::LazyAttributes::ClassMethods
- Sequel::Plugins::LazyAttributes::InstanceMethods
- Sequel::Plugins::ManyThroughMany
- Sequel::Plugins::ManyThroughMany::ClassMethods
- Sequel::Plugins::ManyThroughMany::ManyThroughManyAssociationReflection
- Sequel::Plugins::NestedAttributes
- Sequel::Plugins::NestedAttributes::ClassMethods
- Sequel::Plugins::NestedAttributes::InstanceMethods
- Sequel::Plugins::OptimisticLocking
- Sequel::Plugins::OptimisticLocking::ClassMethods
- Sequel::Plugins::OptimisticLocking::InstanceMethods
- Sequel::Plugins::RcteTree
- Sequel::Plugins::Schema
- Sequel::Plugins::Schema::ClassMethods
- Sequel::Plugins::Serialization
- Sequel::Plugins::Serialization::ClassMethods
- Sequel::Plugins::Serialization::InstanceMethods
- Sequel::Plugins::Sharding
- Sequel::Plugins::Sharding::ClassMethods
- Sequel::Plugins::Sharding::DatasetMethods
- Sequel::Plugins::Sharding::InstanceMethods
- Sequel::Plugins::SingleTableInheritance
- Sequel::Plugins::SingleTableInheritance::ClassMethods
- Sequel::Plugins::SingleTableInheritance::InstanceMethods
- Sequel::Plugins::SkipCreateRefresh
- Sequel::Plugins::SkipCreateRefresh::InstanceMethods
- Sequel::Plugins::StringStripper
- Sequel::Plugins::StringStripper::InstanceMethods
- Sequel::Plugins::Subclasses
- Sequel::Plugins::Subclasses::ClassMethods
- Sequel::Plugins::TacticalEagerLoading
- Sequel::Plugins::TacticalEagerLoading::DatasetMethods
- Sequel::Plugins::TacticalEagerLoading::InstanceMethods
- Sequel::Plugins::Timestamps
- Sequel::Plugins::Timestamps::ClassMethods
- Sequel::Plugins::Timestamps::InstanceMethods
- Sequel::Plugins::Touch
- Sequel::Plugins::Touch::ClassMethods
- Sequel::Plugins::Touch::InstanceMethods
- Sequel::Plugins::TypecastOnLoad
- Sequel::Plugins::TypecastOnLoad::ClassMethods
- Sequel::Plugins::TypecastOnLoad::InstanceMethods
- Sequel::Plugins::UpdatePrimaryKey
- Sequel::Plugins::UpdatePrimaryKey::ClassMethods
- Sequel::Plugins::UpdatePrimaryKey::InstanceMethods
- Sequel::Plugins::ValidationClassMethods
- Sequel::Plugins::ValidationClassMethods::ClassMethods
- Sequel::Plugins::ValidationClassMethods::ClassMethods::Generator
- Sequel::Plugins::ValidationClassMethods::InstanceMethods
- Sequel::Plugins::ValidationHelpers
- Sequel::Plugins::ValidationHelpers::InstanceMethods
- Sequel::PoolTimeout
- Sequel::Postgres
- Sequel::Postgres::Adapter
- Sequel::Postgres::AdapterMethods
- Sequel::Postgres::Database
- Sequel::Postgres::DatabaseMethods
- Sequel::Postgres::Dataset
- Sequel::Postgres::Dataset::ArgumentMapper
- Sequel::Postgres::Dataset::BindArgumentMethods
- Sequel::Postgres::Dataset::PreparedStatementMethods
- Sequel::Postgres::DatasetMethods
- Sequel::Postgres::DatasetMethods::PreparedStatementMethods
- Sequel::PrettyTable
- Sequel::Progress
- Sequel::Progress::DatabaseMethods
- Sequel::Progress::DatasetMethods
- Sequel::Rollback
- Sequel::SQL
- Sequel::SQL::AliasMethods
- Sequel::SQL::AliasedExpression
- Sequel::SQL::BitwiseMethods
- Sequel::SQL::Blob
- Sequel::SQL::BooleanConstant
- Sequel::SQL::BooleanExpression
- Sequel::SQL::BooleanMethods
- Sequel::SQL::CaseExpression
- Sequel::SQL::Cast
- Sequel::SQL::CastMethods
- Sequel::SQL::ColumnAll
- Sequel::SQL::ComplexExpression
- Sequel::SQL::ComplexExpressionMethods
- Sequel::SQL::Constant
- Sequel::SQL::Constants
- Sequel::SQL::Expression
- Sequel::SQL::Function
- Sequel::SQL::GenericComplexExpression
- Sequel::SQL::GenericExpression
- Sequel::SQL::Identifier
- Sequel::SQL::IdentifierMethods
- Sequel::SQL::InequalityMethods
- Sequel::SQL::JoinClause
- Sequel::SQL::JoinOnClause
- Sequel::SQL::JoinUsingClause
- Sequel::SQL::NegativeBooleanConstant
- Sequel::SQL::NoBooleanInputMethods
- Sequel::SQL::NumericExpression
- Sequel::SQL::NumericMethods
- Sequel::SQL::OrderMethods
- Sequel::SQL::OrderedExpression
- Sequel::SQL::PlaceholderLiteralString
- Sequel::SQL::QualifiedIdentifier
- Sequel::SQL::QualifyingMethods
- Sequel::SQL::SQLArray
- Sequel::SQL::StringConcatenationMethods
- Sequel::SQL::StringExpression
- Sequel::SQL::StringMethods
- Sequel::SQL::Subscript
- Sequel::SQL::SubscriptMethods
- Sequel::SQL::VirtualRow
- Sequel::SQL::Window
- Sequel::SQL::WindowFunction
- Sequel::SQLite
- Sequel::SQLite::Database
- Sequel::SQLite::DatabaseMethods
- Sequel::SQLite::Dataset
- Sequel::SQLite::Dataset::ArgumentMapper
- Sequel::SQLite::Dataset::PreparedStatementMethods
- Sequel::SQLite::DatasetMethods
- Sequel::Schema
- Sequel::Schema::AlterTableGenerator
- Sequel::Schema::Generator
- Sequel::ShardedSingleConnectionPool
- Sequel::ShardedThreadedConnectionPool
- Sequel::SimpleMigration
- Sequel::SingleConnectionPool
- Sequel::ThreadLocalTimezones
- Sequel::ThreadedConnectionPool
- Sequel::TimestampMigrator
- Sequel::Timezones
- Sequel::ValidationFailed
- String
- String::Inflections
- Array
- FalseClass
- Hash
- NilClass
- Numeric
- Object
- PGconn
- PGresult
- Proc
- Symbol
- TrueClass

No matching classes.

# 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 relating to adapters, connecting, disconnecting, and sharding ↑ top

This methods involve the Database’s connection pool.

### Constants

ADAPTERS

  Array of supported database adapters

### Attributes

pool[R]

The connection pool for this database

### Public Class Methods

adapter_class(scheme) click to toggle source

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

    # File lib/sequel/database/connecting.rb, line 17
    def self.adapter_class(scheme)
      scheme = scheme.to_s.gsub('-', '_').to_sym

      unless klass = ADAPTER_MAP[scheme]
        # attempt to load the adapter file
        begin
          Sequel.tsk_require "sequel/adapters/#{scheme}"
        rescue LoadError => e
          raise Sequel.convert_exception_class(e, AdapterNotFound)
        end

        # make sure we actually loaded the adapter
        unless klass = ADAPTER_MAP[scheme]
          raise AdapterNotFound, "Could not load #{scheme} adapter"
        end
      end
      klass
    end

adapter_scheme() click to toggle source

Returns the scheme for the Database class.

    # File lib/sequel/database/connecting.rb, line 37
    def self.adapter_scheme
      @scheme
    end

connect(conn_string, opts = {}) click to toggle source

Connects to a database. See Sequel.connect.

    # File lib/sequel/database/connecting.rb, line 42
    def self.connect(conn_string, opts = {})
      case conn_string
      when String
        if match = /\A(jdbc|do):/.match(conn_string)
          c = adapter_class(match[1].to_sym)
          opts = {:uri=>conn_string}.merge(opts)
        else
          uri = URI.parse(conn_string)
          scheme = uri.scheme
          scheme = :dbi if scheme =~ /\Adbi-/
          c = adapter_class(scheme)
          uri_options = c.send(:uri_to_options, uri)
          uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v if k && !k.empty?} unless uri.query.to_s.strip.empty?
          uri_options.entries.each{|k,v| uri_options[k] = URI.unescape(v) if v.is_a?(String)}
          opts = uri_options.merge(opts)
        end
      when Hash
        opts = conn_string.merge(opts)
        c = adapter_class(opts[:adapter] || opts['adapter'])
      else
        raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}"
      end
      # process opts a bit
      opts = opts.inject({}) do |m, kv| k, v = *kv
        k = :user if k.to_s == 'username'
        m[k.to_sym] = v
        m
      end
      begin
        db = c.new(opts)
        db.test_connection if opts[:test] && db.send(:typecast_value_boolean, opts[:test])
        result = yield(db) if block_given?
      ensure
        if block_given?
          db.disconnect if db
          ::Sequel::DATABASES.delete(db)
        end
      end
      block_given? ? result : db
    end

single_threaded=(value) click to toggle source

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

    # File lib/sequel/database/connecting.rb, line 85
    def self.single_threaded=(value)
      @@single_threaded = value
    end

### Public Instance Methods

add_servers(servers) click to toggle source

Dynamically add new servers or modify server options at runtime. Also adds new servers to the connection pool. Intended for use with master/slave or shard configurations where it is useful to add new server hosts at runtime.

servers argument should be a hash with server name symbol keys and hash or proc values. If a servers key is already in use, it’s value is overridden with the value provided.

    DB.add_servers(:f=>{:host=>"hash_host_f"})

    # File lib/sequel/database/connecting.rb, line 119
    def add_servers(servers)
      @opts[:servers] = @opts[:servers] ? @opts[:servers].merge(servers) : servers
      @pool.add_servers(servers.keys)
    end

connect(server) click to toggle source

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

    # File lib/sequel/database/connecting.rb, line 125
    def connect(server)
      raise NotImplemented, "#connect should be overridden by adapters"
    end

database_type() click to toggle source

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).

    # File lib/sequel/database/connecting.rb, line 136
    def database_type
      self.class.adapter_scheme
    end

disconnect(opts = {}) click to toggle source

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

- :servers - Should be a symbol specifing the server to disconnect from, or an array of symbols to specify multiple servers.

    # File lib/sequel/database/connecting.rb, line 144
    def disconnect(opts = {})
      pool.disconnect(opts)
    end

each_server(&block) click to toggle source

Yield a new database object for every server in the connection pool. Intended for use in sharded environments where there is a need to make schema modifications (DDL queries) on each shard.

    DB.each_server{|db| db.create_table(:users){primary_key :id; String :name}}

    # File lib/sequel/database/connecting.rb, line 153
    def each_server(&block)
      servers.each{|s| self.class.connect(server_opts(s), &block)}
    end

remove_servers(*servers) click to toggle source

Dynamically remove existing servers from the connection pool. Intended for use with master/slave or shard configurations where it is useful to remove existing server hosts at runtime.

servers should be symbols or arrays of symbols. If a nonexistent server is specified, it is ignored. If no servers have been specified for this database, no changes are made. If you attempt to remove the :default server, an error will be raised.

    DB.remove_servers(:f1, :f2)

    # File lib/sequel/database/connecting.rb, line 167
    def remove_servers(*servers)
      if @opts[:servers] && !@opts[:servers].empty?
        servs = @opts[:servers].dup
        servers.flatten!
        servers.each{|s| servs.delete(s)}
        @opts[:servers] = servs
        @pool.remove_servers(servers)
      end
    end

servers() click to toggle source

An array of servers/shards for this Database object.

    # File lib/sequel/database/connecting.rb, line 178
    def servers
      pool.servers
    end

single_threaded?() click to toggle source

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

    # File lib/sequel/database/connecting.rb, line 183
    def single_threaded?
      @single_threaded
    end

synchronize(server=nil, &block) click to toggle source

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

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

test_connection(server=nil) click to toggle source

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

    # File lib/sequel/database/connecting.rb, line 194
    def test_connection(server=nil)
      synchronize(server){|conn|}
      true
    end

## Methods relating to logging ↑ top

This methods affect relating to the logging of executed SQL.

### Attributes

log_warn_duration[RW]

Numeric specifying the duration beyond which queries are logged at warn level instead of info level.

loggers[RW]

Array of SQL loggers to use for this database

### Public Instance Methods

log_info(message, args=nil) click to toggle source

Log a message at level info to all loggers.

    # File lib/sequel/database/logging.rb, line 16
    def log_info(message, args=nil)
      log_each(:info, args ? "#{message}; #{args.inspect}" : message)
    end

log_yield(sql, args=nil) click to toggle source

Yield to the block, logging any errors at error level to all loggers, and all other queries with the duration at warn or info level.

    # File lib/sequel/database/logging.rb, line 22
    def log_yield(sql, args=nil)
      return yield if @loggers.empty?
      sql = "#{sql}; #{args.inspect}" if args
      start = Time.now
      begin
        yield
      rescue => e
        log_each(:error, "#{e.class}: #{e.message.strip}: #{sql}")
        raise
      ensure
        log_duration(Time.now - start, sql) unless e
      end
    end

logger=(logger) click to toggle source

Remove any existing loggers and just use the given logger.

    # File lib/sequel/database/logging.rb, line 37
    def logger=(logger)
      @loggers = Array(logger)
    end

## Methods that create datasets ↑ top

These methods all return instances of this database’s dataset class.

### Public Instance Methods

[](*args) click to toggle source

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"

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

dataset() click to toggle source

Returns a blank dataset for this database

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

fetch(sql, *args, &block) click to toggle source

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

    # File lib/sequel/database/dataset.rb, line 40
    def fetch(sql, *args, &block)
      ds = dataset.with_sql(sql, *args)
      ds.each(&block) if block
      ds
    end

from(*args, &block) click to toggle source

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

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

select(*args, &block) click to toggle source

Returns a new dataset with the select method invoked.

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

## Methods that execute queries and/or return results ↑ top

This methods generally execute SQL code on the database server.

### Constants

MSSQL_DEFAULT_RE
MYSQL_TIMESTAMP_RE
POSTGRES_DEFAULT_RE
SQL_BEGIN
SQL_COMMIT
SQL_RELEASE_SAVEPOINT
SQL_ROLLBACK
SQL_ROLLBACK_TO_SAVEPOINT
SQL_SAVEPOINT
STRING_DEFAULT_RE
TRANSACTION_BEGIN
TRANSACTION_COMMIT
TRANSACTION_ROLLBACK

### Attributes

prepared_statements[R]

The prepared statement objects for this database, keyed by name

### Public Instance Methods

<<(sql) click to toggle source

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

    # File lib/sequel/database/query.rb, line 29
    def <<(sql)
      run(sql)
    end

call(ps_name, hash={}) click to toggle source

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

    # File lib/sequel/database/query.rb, line 35
    def call(ps_name, hash={})
      prepared_statements[ps_name].call(hash)
    end

execute(sql, opts={}) click to toggle source

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

    # File lib/sequel/database/query.rb, line 41
    def execute(sql, opts={})
      raise NotImplemented, "#execute should be overridden by adapters"
    end

execute_ddl(sql, opts={}, &block) click to toggle source

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.

    # File lib/sequel/database/query.rb, line 48
    def execute_ddl(sql, opts={}, &block)
      execute_dui(sql, opts, &block)
    end

execute_dui(sql, opts={}, &block) click to toggle source

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.

    # File lib/sequel/database/query.rb, line 55
    def execute_dui(sql, opts={}, &block)
      execute(sql, opts, &block)
    end

execute_insert(sql, opts={}, &block) click to toggle source

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.

    # File lib/sequel/database/query.rb, line 62
    def execute_insert(sql, opts={}, &block)
      execute_dui(sql, opts, &block)
    end

get(*args, &block) click to toggle source

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

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

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

    # File lib/sequel/database/query.rb, line 73
    def get(*args, &block)
      dataset.get(*args, &block)
    end

indexes(table, opts={}) click to toggle source

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.

Should not include the primary key index, functional indexes, or partial indexes.

    # File lib/sequel/database/query.rb, line 83
    def indexes(table, opts={})
      raise NotImplemented, "#indexes should be overridden by adapters"
    end

run(sql, opts={}) click to toggle source

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

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

    # File lib/sequel/database/query.rb, line 90
    def run(sql, opts={})
      execute_ddl(sql, opts)
      nil
    end

schema(table, opts={}) click to toggle source

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.

    # File lib/sequel/database/query.rb, line 107
    def schema(table, opts={})
      raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true)

      sch, table_name = schema_and_table(table)
      quoted_name = quote_schema_table(table)
      opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema)

      @schemas.delete(quoted_name) if opts[:reload]
      return @schemas[quoted_name] if @schemas[quoted_name]

      cols = schema_parse_table(table_name, opts)
      raise(Error, 'schema parsing returned no columns, table probably doesn\t exist') if cols.nil? || cols.empty?
      cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])}
      @schemas[quoted_name] = cols
    end

table_exists?(name) click to toggle source

Returns true if a table with the given name exists. This requires a query to the database.

    # File lib/sequel/database/query.rb, line 125
    def table_exists?(name)
      begin
        from(name).first
        true
      rescue
        false
      end
    end

tables(opts={}) click to toggle source

Return all tables in the database as an array of symbols.

    # File lib/sequel/database/query.rb, line 135
    def tables(opts={})
      raise NotImplemented, "#tables should be overridden by adapters"
    end

transaction(opts={}, &block) click to toggle source

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.

    # File lib/sequel/database/query.rb, line 150
    def transaction(opts={}, &block)
      synchronize(opts[:server]) do |conn|
        return yield(conn) if already_in_transaction?(conn, opts)
        _transaction(conn, &block)
      end
    end

## Methods that modify the database schema ↑ top

These methods execute code on the database that modifies the database’s schema.

### Constants

AUTOINCREMENT
CASCADE
COMMA_SEPARATOR
NOT_NULL
NO_ACTION
NULL
PRIMARY_KEY
RESTRICT
SET_DEFAULT
SET_NULL
TEMPORARY
UNDERSCORE
UNIQUE
UNSIGNED

### Public Instance Methods

add_column(table, *args) click to toggle source

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.

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

add_index(table, columns, options={}) click to toggle source

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.

    # File lib/sequel/database/schema_methods.rb, line 44
    def add_index(table, columns, options={})
      e = options[:ignore_errors]
      begin
        alter_table(table){add_index(columns, options)}
      rescue DatabaseError
        raise unless e
      end
    end

alter_table(name, generator=nil, &block) click to toggle source

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 and the “Migrations and Schema Modification” guide.

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

create_or_replace_view(name, source) click to toggle 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'))

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

create_table(name, options={}, &block) click to toggle source

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 and the “Migrations and Schema Modification” guide.

    # File lib/sequel/database/schema_methods.rb, line 91
    def create_table(name, options={}, &block)
      remove_cached_schema(name)
      options = {:generator=>options} if options.is_a?(Schema::Generator)
      generator = options[:generator] || Schema::Generator.new(self, &block)
      create_table_from_generator(name, generator, options)
      create_table_indexes_from_generator(name, generator, options)
      nil
    end

create_table!(name, options={}, &block) click to toggle source

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

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

create_table?(name, options={}, &block) click to toggle source

Creates the table unless the table already exists

    # File lib/sequel/database/schema_methods.rb, line 107
    def create_table?(name, options={}, &block)
      create_table(name, options, &block) unless table_exists?(name)
    end

create_view(name, source) click to toggle 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'))

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

drop_column(table, *args) click to toggle source

Removes a column from the specified table:

    DB.drop_column :items, :category

See alter_table.

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

drop_index(table, columns, options={}) click to toggle source

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

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

See alter_table.

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

drop_table(*names) click to toggle source

Drops one or more tables corresponding to the given names:

    DB.drop_table(:posts, :comments)

    # File lib/sequel/database/schema_methods.rb, line 153
    def drop_table(*names)
      names.each do |n|
        execute_ddl(drop_table_sql(n))
        remove_cached_schema(n)
      end
      nil
    end

drop_view(*names) click to toggle source

Drops one or more views corresponding to the given names:

    DB.drop_view(:cheap_items)

    # File lib/sequel/database/schema_methods.rb, line 164
    def drop_view(*names)
      names.each do |n|
        execute_ddl("DROP VIEW #{quote_schema_table(n)}")
        remove_cached_schema(n)
      end
      nil
    end

rename_column(table, *args) click to toggle source

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.

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

rename_table(name, new_name) click to toggle source

Renames a table:

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

    # File lib/sequel/database/schema_methods.rb, line 177
    def rename_table(name, new_name)
      execute_ddl(rename_table_sql(name, new_name))
      remove_cached_schema(name)
      nil
    end

set_column_default(table, *args) click to toggle source

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

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

See alter_table.

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

set_column_type(table, *args) click to toggle source

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

    DB.set_column_type :items, :price, :float

See alter_table.

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

## Methods that set defaults for created datasets ↑ top

This methods change the default behavior of this database’s datasets.

### Attributes

default_schema[RW]

The default schema to use, generally should be nil.

### Public Class Methods

identifier_input_method() click to toggle source

The method to call on identifiers going into the database

    # File lib/sequel/database/dataset_defaults.rb, line 18
    def self.identifier_input_method
      @@identifier_input_method
    end

identifier_input_method=(v) click to toggle source

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

    # File lib/sequel/database/dataset_defaults.rb, line 24
    def self.identifier_input_method=(v)
      @@identifier_input_method = v || ""
    end

identifier_output_method() click to toggle source

The method to call on identifiers coming from the database

    # File lib/sequel/database/dataset_defaults.rb, line 29
    def self.identifier_output_method
      @@identifier_output_method
    end

identifier_output_method=(v) click to toggle source

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

    # File lib/sequel/database/dataset_defaults.rb, line 35
    def self.identifier_output_method=(v)
      @@identifier_output_method = v || ""
    end

quote_identifiers=(value) click to toggle source

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

    # File lib/sequel/database/dataset_defaults.rb, line 41
    def self.quote_identifiers=(value)
      @@quote_identifiers = value
    end

### Public Instance Methods

identifier_input_method() click to toggle source

The method to call on identifiers going into the database

    # File lib/sequel/database/dataset_defaults.rb, line 49
    def identifier_input_method
      case @identifier_input_method
      when nil
        @identifier_input_method = @opts.fetch(:identifier_input_method, (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method))
        @identifier_input_method == "" ? nil : @identifier_input_method
      when ""
        nil
      else
        @identifier_input_method
      end
    end

identifier_input_method=(v) click to toggle source

Set the method to call on identifiers going into the database

    # File lib/sequel/database/dataset_defaults.rb, line 62
    def identifier_input_method=(v)
      reset_schema_utility_dataset
      @identifier_input_method = v || ""
    end

identifier_output_method() click to toggle source

The method to call on identifiers coming from the database

    # File lib/sequel/database/dataset_defaults.rb, line 68
    def identifier_output_method
      case @identifier_output_method
      when nil
        @identifier_output_method = @opts.fetch(:identifier_output_method, (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method))
        @identifier_output_method == "" ? nil : @identifier_output_method
      when ""
        nil
      else
        @identifier_output_method
      end
    end

identifier_output_method=(v) click to toggle source

Set the method to call on identifiers coming from the database

    # File lib/sequel/database/dataset_defaults.rb, line 81
    def identifier_output_method=(v)
      reset_schema_utility_dataset
      @identifier_output_method = v || ""
    end

quote_identifiers=(v) click to toggle source

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

    # File lib/sequel/database/dataset_defaults.rb, line 87
    def quote_identifiers=(v)
      reset_schema_utility_dataset
      @quote_identifiers = v
    end

quote_identifiers?() click to toggle source

Returns true if the database quotes identifiers.

    # File lib/sequel/database/dataset_defaults.rb, line 93
    def quote_identifiers?
      return @quote_identifiers unless @quote_identifiers.nil?
      @quote_identifiers = @opts.fetch(:quote_identifiers, (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers))
    end

## Miscellaneous methods ↑ top

These methods don’t fit neatly into another category.

### Attributes

opts[R]

The options for this database

### Public Class Methods

new(opts = {}, &block) click to toggle source

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.

    # File lib/sequel/database/misc.rb, line 38
    def initialize(opts = {}, &block)
      @opts ||= opts
      @opts = connection_pool_default_options.merge(@opts)
      @loggers = Array(@opts[:logger]) + Array(@opts[:loggers])
      self.log_warn_duration = @opts[:log_warn_duration]
      @opts[:disconnection_proc] ||= proc{|conn| disconnect_connection(conn)}
      block ||= proc{|server| connect(server)}
      @opts[:servers] = {} if @opts[:servers].is_a?(String)

      @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, @@single_threaded))
      @schemas = {}
      @default_schema = @opts.fetch(:default_schema, default_schema_default)
      @prepared_statements = {}
      @transactions = []
      @identifier_input_method = nil
      @identifier_output_method = nil
      @quote_identifiers = nil
      @pool = ConnectionPool.get_pool(@opts, &block)

      ::Sequel::DATABASES.push(self)
    end

### Public Instance Methods

cast_type_literal(type) click to toggle source

Cast the given type to a literal type

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

dump_indexes_migration(options={}) click to toggle source

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.

    # File lib/sequel/extensions/schema_dumper.rb, line 13
    def dump_indexes_migration(options={})
      ts = tables(options)
      Sequel.migration do  up do#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :add_index, options)}.reject{|x| x == ''}.join("\n\n").gsub(/^/o, '    ')}  end    down do#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :drop_index, options)}.reject{|x| x == ''}.join("\n\n").gsub(/^/o, '    ')}  endend
    end

dump_schema_migration(options={}) click to toggle source

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).

    # File lib/sequel/extensions/schema_dumper.rb, line 37
    def dump_schema_migration(options={})
      ts = tables(options)
      Sequel.migration do  up do#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_schema(t, options)}.join("\n\n").gsub(/^/o, '    ')}  end    down do    drop_table(#{ts.sort_by{|t| t.to_s}.inspect[1...-1]})  endend
    end

dump_table_schema(table, options={}) click to toggle source

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

    # File lib/sequel/extensions/schema_dumper.rb, line 54
    def dump_table_schema(table, options={})
      table = table.value.to_s if table.is_a?(SQL::Identifier)
      raise(Error, "must provide table as a Symbol, String, or Sequel::SQL::Identifier") unless [String, Symbol].any?{|c| table.is_a?(c)}
      s = schema(table).dup
      pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first}
      options = options.merge(:single_pk=>true) if pks.length == 1
      m = method(:column_schema_to_generator_opts)
      im = method(:index_to_generator_opts)
      begin
        indexes = indexes(table).sort_by{|k,v| k.to_s} if options[:indexes] != false
      rescue Sequel::NotImplemented
        nil
      end
      gen = Schema::Generator.new(self) do
        s.each{|name, info| send(*m.call(name, info, options))}
        primary_key(pks) if !@primary_key && pks.length > 0
        indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts))} if indexes
      end
      commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n")
      "create_table(#{table.inspect}#{', :ignore_index_errors=>true' if !options[:same_db] && options[:indexes] != false && indexes && !indexes.empty?}) do\n#{commands.gsub(/^/o, '  ')}\nend"
    end

inspect() click to toggle source

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).

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

literal(v) click to toggle source

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

    # File lib/sequel/database/misc.rb, line 73
    def literal(v)
      schema_utility_dataset.literal(v)
    end

query(&block) click to toggle source

Return a dataset modified by the query block

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

serial_primary_key_options() click to toggle source

Default serial primary key options.

    # File lib/sequel/database/misc.rb, line 78
    def serial_primary_key_options
      {:primary_key => true, :type => Integer, :auto_increment => true}
    end

supports_savepoints?() click to toggle source

Whether the database and adapter support savepoints, false by default

    # File lib/sequel/database/misc.rb, line 83
    def supports_savepoints?
      false
    end

typecast_value(column_type, value) click to toggle source

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.

    # File lib/sequel/database/misc.rb, line 92
    def typecast_value(column_type, value)
      return nil if value.nil?
      meth = "typecast_value_#{column_type}"
      begin
        respond_to?(meth, true) ? send(meth, value) : value
      rescue ArgumentError, TypeError => e
        raise Sequel.convert_exception_class(e, InvalidValue)
      end
    end

uri() click to toggle source

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

    # File lib/sequel/database/misc.rb, line 105
    def uri
      uri = URI::Generic.new(
        self.class.adapter_scheme.to_s,
        nil,
        @opts[:host],
        @opts[:port],
        nil,
        "/#{@opts[:database]}",
        nil,
        nil,
        nil
      )
      uri.user = @opts[:user]
      uri.password = @opts[:password] if uri.user
      uri.to_s
    end

url() click to toggle source

Explicit alias of uri for easier subclassing.

    # File lib/sequel/database/misc.rb, line 123
    def url
      uri
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.