Class Sequel::Database
In: lib/sequel/extensions/schema_dumper.rb
lib/sequel/extensions/query.rb
lib/sequel/extensions/schema_caching.rb
lib/sequel/database/dataset.rb
lib/sequel/database/transactions.rb
lib/sequel/database/connecting.rb
lib/sequel/database/logging.rb
lib/sequel/database/dataset_defaults.rb
lib/sequel/database/query.rb
lib/sequel/database/misc.rb
lib/sequel/database/schema_methods.rb
lib/sequel/database/features.rb
lib/sequel/adapters/sqlite.rb
lib/sequel/adapters/swift.rb
lib/sequel/adapters/mysql.rb
lib/sequel/adapters/jdbc.rb
lib/sequel/adapters/do.rb
lib/sequel/database.rb
Parent: Object

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

Methods

<<   []   _default_schema   adapter_class   adapter_scheme   adapter_scheme   add_column   add_index   add_servers   after_commit   after_initialize   after_rollback   alter_table   alter_table_generator   call   call_sproc   cast_type_literal   connect   connect   connect   connect   connect   connect   connect   convert_invalid_date_time=   convert_tinyint_to_bool=   create_join_table   create_or_replace_view   create_table   create_table!   create_table?   create_table_generator   create_view   database_type   dataset   dataset_class=   default_schema   default_schema=   disconnect   disconnect_connection   disconnect_connection   disconnect_connection   disconnect_connection   disconnect_connection   drop_column   drop_index   drop_join_table   drop_table   drop_table?   drop_view   dump_foreign_key_migration   dump_indexes_migration   dump_schema_cache   dump_schema_cache?   dump_schema_migration   dump_table_schema   each_server   execute   execute   execute   execute   execute   execute_ddl   execute_ddl   execute_ddl   execute_dui   execute_dui   execute_dui   execute_dui   execute_dui   execute_dui   execute_insert   execute_insert   execute_insert   execute_insert   execute_insert   execute_insert   extend_datasets   extension   extension   fetch   foreign_key_list   from   from_application_timestamp   get   global_index_namespace?   identifier_input_method=   identifier_input_method=   identifier_output_method=   identifier_output_method=   in_transaction?   indexes   indexes   inspect   jndi?   literal   load_schema_cache   load_schema_cache?   log_exception   log_info   log_yield   logger=   new   prepared_statement   query   quote_identifier   quote_identifiers=   quote_identifiers?   register_extension   remove_servers   rename_column   rename_table   run   run_after_initialize   schema   schema_type_class   select   serial_primary_key_options   server_version   servers   set_column_default   set_column_type   set_prepared_statement   single_threaded?   subadapter   supports_create_table_if_not_exists?   supports_deferrable_constraints?   supports_deferrable_foreign_key_constraints?   supports_drop_table_if_exists?   supports_foreign_key_parsing?   supports_index_parsing?   supports_prepared_transactions?   supports_savepoints?   supports_savepoints_in_prepared_transactions?   supports_schema_parsing?   supports_table_listing?   supports_transaction_isolation_levels?   supports_transactional_ddl?   supports_view_listing?   synchronize   synchronize   table_exists?   tables   tables   test_connection   timezone   to_application_timestamp   to_application_timestamp   transaction   typecast_value   uri   uri   uri   url   valid_connection?   views   views  

Included Modules

Public Instance methods

Dump foreign key constraints for all tables as a migration. This complements the :foreign_keys=>false option to dump_schema_migration. This only dumps the constraints (not the columns) using alter_table/add_foreign_key with an array of columns.

Note that the migration this produces does not have a down block, so you cannot reverse it.

[Source]

    # File lib/sequel/extensions/schema_dumper.rb, line 25
25:     def dump_foreign_key_migration(options={})
26:       Sequel::Deprecation.deprecate('Loading the schema_dumper extension globally', "Please use Database#extension to load the extension into this database") unless is_a?(SchemaDumper)
27:       ts = tables(options)
28:       "Sequel.migration do\n  change do\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_foreign_keys(t)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\nend\n"
29:     end

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.
:index_names :If set to false, don‘t record names of indexes. If set to :namespace, prepend the table name to the index name if the database does not use a global index namespace.

[Source]

    # File lib/sequel/extensions/schema_dumper.rb, line 45
45:     def dump_indexes_migration(options={})
46:       Sequel::Deprecation.deprecate('Loading the schema_dumper extension globally', "Please use Database#extension to load the extension into this database") unless is_a?(SchemaDumper)
47:       ts = tables(options)
48:       "Sequel.migration do\n  change do\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\nend\n"
49:     end

Dump the cached schema to the filename given in Marshal format.

[Source]

    # File lib/sequel/extensions/schema_caching.rb, line 51
51:     def dump_schema_cache(file)
52:       Sequel::Deprecation.deprecate('Loading the schema_caching extension globally', "Please use Database#extension to load the extension into this database") unless is_a?(SchemaCaching)
53:       File.open(file, 'wb'){|f| f.write(Marshal.dump(@schemas))}
54:       nil
55:     end

Dump the cached schema to the filename given unless the file already exists.

[Source]

    # File lib/sequel/extensions/schema_caching.rb, line 59
59:     def dump_schema_cache?(file)
60:       Sequel::Deprecation.deprecate('Loading the schema_caching extension globally', "Please use Database#extension to load the extension into this database") unless is_a?(SchemaCaching)
61:       dump_schema_cache(file) unless File.exist?(file)
62:     end

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.
:foreign_keys :If set to false, don‘t dump foreign_keys (they can be
            added later via #dump_foreign_key_migration)
:indexes :If set to false, don‘t dump indexes (they can be added later via dump_index_migration).
:index_names :If set to false, don‘t record names of indexes. If set to :namespace, prepend the table name to the index name.

[Source]

    # File lib/sequel/extensions/schema_dumper.rb, line 71
71:     def dump_schema_migration(options={})
72:       Sequel::Deprecation.deprecate('Loading the schema_dumper extension globally', "Please use Database#extension to load the extension into this database") unless is_a?(SchemaDumper)
73:       options = options.dup
74:       if options[:indexes] == false && !options.has_key?(:foreign_keys)
75:         # Unless foreign_keys option is specifically set, disable if indexes
76:         # are disabled, as foreign keys that point to non-primary keys rely
77:         # on unique indexes being created first
78:         options[:foreign_keys] = false
79:       end
80: 
81:       ts = sort_dumped_tables(tables(options), options)
82:       skipped_fks = if sfk = options[:skipped_foreign_keys]
83:         # Handle skipped foreign keys by adding them at the end via
84:         # alter_table/add_foreign_key.  Note that skipped foreign keys
85:         # probably result in a broken down migration.
86:         sfka = sfk.sort_by{|table, fks| table.to_s}.map{|table, fks| dump_add_fk_constraints(table, fks.values)}
87:         sfka.join("\n\n").gsub(/^/o, '    ') unless sfka.empty?
88:       end
89: 
90:       "Sequel.migration do\n  change do\n\#{ts.map{|t| dump_table_schema(t, options)}.join(\"\\n\\n\").gsub(/^/o, '    ')}\#{\"\\n    \\n\" if skipped_fks}\#{skipped_fks}\n  end\nend\n"
91:     end

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 102
102:     def dump_table_schema(table, options={})
103:       Sequel::Deprecation.deprecate('Loading the schema_dumper extension globally', "Please use Database#extension to load the extension into this database") unless is_a?(SchemaDumper)
104:       table = table.value.to_s if table.is_a?(SQL::Identifier)
105:       gen = dump_table_generator(table, options)
106:       commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n")
107:       "create_table(#{table.inspect}#{', :ignore_index_errors=>true' if !options[:same_db] && options[:indexes] != false && !gen.indexes.empty?}) do\n#{commands.gsub(/^/o, '  ')}\nend"
108:     end

Replace the schema cache with the data from the given file, which should be in Marshal format.

[Source]

    # File lib/sequel/extensions/schema_caching.rb, line 66
66:     def load_schema_cache(file)
67:       Sequel::Deprecation.deprecate('Loading the schema_caching extension globally', "Please use Database#extension to load the extension into this database") unless is_a?(SchemaCaching)
68:       @schemas = Marshal.load(File.read(file))
69:       nil
70:     end

Replace the schema cache with the data from the given file if the file exists.

[Source]

    # File lib/sequel/extensions/schema_caching.rb, line 74
74:     def load_schema_cache?(file)
75:       Sequel::Deprecation.deprecate('Loading the schema_caching extension globally', "Please use Database#extension to load the extension into this database") unless is_a?(SchemaCaching)
76:       load_schema_cache(file) if File.exist?(file)
77:     end

Return a dataset modified by the query block

[Source]

    # File lib/sequel/extensions/query.rb, line 24
24:     def query(&block)
25:       Sequel::Deprecation.deprecate('Loading the query extension globally', "Please use Database#extension to load the extension into this database") unless is_a?(DatabaseQuery)
26:       dataset.query(&block)
27:     end

3 - Methods that create datasets

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

Public Instance methods

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

  DB['SELECT * FROM items'].all
  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/dataset.rb, line 19
19:     def [](*args)
20:       args.first.is_a?(String) ? fetch(*args) : from(*args)
21:     end

Returns a blank dataset for this database.

  DB.dataset # SELECT *
  DB.dataset.from(:items) # SELECT * FROM items

[Source]

    # File lib/sequel/database/dataset.rb, line 27
27:     def dataset(opts=(no_arg_given=true; nil))
28:       # REMOVE40
29:       if no_arg_given
30:         @dataset_class.new(self)
31:       else
32:         @dataset_class.new(self, opts)
33:       end
34:     end

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 fetch 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/dataset.rb, line 49
49:     def fetch(sql, *args, &block)
50:       ds = @default_dataset.with_sql(sql, *args)
51:       ds.each(&block) if block
52:       ds
53:     end

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

  DB.from(:items) # SELECT * FROM items
  DB.from(:items){id > 2} # SELECT * FROM items WHERE (id > 2)

[Source]

    # File lib/sequel/database/dataset.rb, line 60
60:     def from(*args, &block)
61:       ds = @default_dataset.from(*args)
62:       block ? ds.filter(&block) : ds
63:     end

Returns a new dataset with the select method invoked.

  DB.select(1) # SELECT 1
  DB.select{server_version{}} # SELECT server_version()
  DB.select(:id).from(:items) # SELECT id FROM items

[Source]

    # File lib/sequel/database/dataset.rb, line 70
70:     def select(*args, &block)
71:       @default_dataset.select(*args, &block)
72:     end

8 - Methods related to database transactions

Database transactions make multiple queries atomic, so that either all of the queries take effect or none of them do.

Constants

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
TRANSACTION_ISOLATION_LEVELS = {:uncommitted=>'READ UNCOMMITTED'.freeze, :committed=>'READ COMMITTED'.freeze, :repeatable=>'REPEATABLE READ'.freeze, :serializable=>'SERIALIZABLE'.freeze}

Attributes

transaction_isolation_level  [RW]  The default transaction isolation level for this database, used for all future transactions. For MSSQL, this should be set to something if you ever plan to use the :isolation option to Database#transaction, as on MSSQL if affects all future transactions on the same connection.

Public Instance methods

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 tables do not support transactions.

The following general options are respected:

:disconnect :If set to :retry, automatically sets the :retry_on option with a Sequel::DatabaseDisconnectError. This option is only present for backwards compatibility, please use the :retry_on option instead.
:isolation :The transaction isolation level to use for this transaction, should be :uncommitted, :committed, :repeatable, or :serializable, used if given and the database/adapter supports customizable transaction isolation levels.
:num_retries :The number of times to retry if the :retry_on option is used. The default is 5 times. Can be set to nil to retry indefinitely, but that is not recommended.
:prepare :A string to use as the transaction identifier for a prepared transaction (two-phase commit), if the database/adapter supports prepared transactions.
:retry_on :An exception class or array of exception classes for which to automatically retry the transaction. Can only be set if not inside an existing transaction. Note that this should not be used unless the entire transaction block is idempotent, as otherwise it can cause non-idempotent behavior to execute multiple times.
:rollback :Can the set to :reraise to reraise any Sequel::Rollback exceptions raised, or :always to always rollback even if no exceptions occur (useful for testing).
: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.

PostgreSQL specific options:

:deferrable :(9.1+) If present, set to DEFERRABLE if true or NOT DEFERRABLE if false.
:read_only :If present, set to READ ONLY if true or READ WRITE if false.
:synchronous :if non-nil, set synchronous_commit appropriately. Valid values true, :on, false, :off, :local (9.1+), and :remote_write (9.2+).

[Source]

     # File lib/sequel/database/transactions.rb, line 75
 75:     def transaction(opts={}, &block)
 76:       if opts[:disconnect] == :retry
 77:         Sequel::Deprecation.deprecate('Database#transaction :disconnect=>:retry option', 'Please switch to :retry_on=>Sequel::DatabaseDisconnectError.')
 78:         raise(Error, 'cannot specify both :disconnect=>:retry and :retry_on') if opts[:retry_on]
 79:         return transaction(opts.merge(:retry_on=>Sequel::DatabaseDisconnectError, :disconnect=>nil), &block)
 80:       end
 81: 
 82:       if retry_on = opts[:retry_on]
 83:         num_retries = opts.fetch(:num_retries, 5)
 84:         begin
 85:           transaction(opts.merge(:retry_on=>nil, :retrying=>true), &block)
 86:         rescue *retry_on
 87:           if num_retries
 88:             num_retries -= 1
 89:             retry if num_retries >= 0
 90:           else
 91:             retry
 92:           end
 93:           raise
 94:         end
 95:       else
 96:         synchronize(opts[:server]) do |conn|
 97:           if already_in_transaction?(conn, opts)
 98:             if opts[:retrying]
 99:               raise Sequel::Error, "cannot set :disconnect=>:retry or :retry_on options if you are already inside a transaction"
100:             end
101:             return yield(conn)
102:           end
103:           _transaction(conn, opts, &block)
104:         end
105:       end
106:     end

4 - Methods relating to adapters, connecting, disconnecting, and sharding

This methods involve the Database‘s connection pool.

Constants

ADAPTERS = %w'ado amalgalite cubrid db2 dbi do firebird ibmdb informix jdbc mock mysql mysql2 odbc openbase oracle postgres sqlite swift tinytds'.collect{|x| x.to_sym}   Array of supported database adapters

Attributes

pool  [R]  The connection pool for this Database instance. All Database instances have their own connection pools.
single_threaded  [RW]  Whether to use the single threaded connection pool by default

Public Class methods

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

[Source]

    # File lib/sequel/database/connecting.rb, line 21
21:     def self.adapter_class(scheme)
22:       return scheme if scheme.is_a?(Class)
23: 
24:       scheme = scheme.to_s.gsub('-', '_').to_sym
25:       
26:       unless klass = ADAPTER_MAP[scheme]
27:         # attempt to load the adapter file
28:         begin
29:           require "sequel/adapters/#{scheme}"
30:         rescue LoadError => e
31:           raise Sequel.convert_exception_class(e, AdapterNotFound)
32:         end
33:         
34:         # make sure we actually loaded the adapter
35:         unless klass = ADAPTER_MAP[scheme]
36:           raise AdapterNotFound, "Could not load #{scheme} adapter: adapter class not registered in ADAPTER_MAP"
37:         end
38:       end
39:       klass
40:     end

Returns the scheme symbol for the Database class.

[Source]

    # File lib/sequel/database/connecting.rb, line 43
43:     def self.adapter_scheme
44:       @scheme
45:     end

Connects to a database. See Sequel.connect.

[Source]

    # File lib/sequel/database/connecting.rb, line 48
48:     def self.connect(conn_string, opts = {})
49:       case conn_string
50:       when String
51:         if match = /\A(jdbc|do):/o.match(conn_string)
52:           c = adapter_class(match[1].to_sym)
53:           opts = opts.merge(:orig_opts=>opts.dup)
54:           opts = {:uri=>conn_string}.merge(opts)
55:         else
56:           uri = URI.parse(conn_string)
57:           scheme = uri.scheme
58:           scheme = :dbi if scheme =~ /\Adbi-/
59:           c = adapter_class(scheme)
60:           uri_options = c.send(:uri_to_options, uri)
61:           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?
62:           uri_options.to_a.each{|k,v| uri_options[k] = (defined?(URI::DEFAULT_PARSER) ? URI::DEFAULT_PARSER : URI).unescape(v) if v.is_a?(String)}
63:           opts = uri_options.merge(opts).merge!(:orig_opts=>opts.dup, :uri=>conn_string, :adapter=>scheme)
64:         end
65:       when Hash
66:         opts = conn_string.merge(opts)
67:         opts = opts.merge(:orig_opts=>opts.dup)
68:         c = adapter_class(opts[:adapter_class] || opts[:adapter] || opts['adapter'])
69:       else
70:         raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}"
71:       end
72:       # process opts a bit
73:       opts = opts.inject({}) do |m, (k,v)|
74:         k = :user if k.to_s == 'username'
75:         m[k.to_sym] = v
76:         m
77:       end
78:       begin
79:         db = c.new(opts)
80:         db.test_connection if opts[:test] && db.send(:typecast_value_boolean, opts[:test])
81:         if block_given?
82:           return yield(db)
83:         end
84:       ensure
85:         if block_given?
86:           db.disconnect if db
87:           Sequel.synchronize{::Sequel::DATABASES.delete(db)}
88:         end
89:       end
90:       db
91:     end

Public Instance methods

Returns the scheme symbol for this instance‘s class, which reflects which adapter is being used. In some cases, this can be the same as the database_type (for native adapters), in others (i.e. adapters with subadapters), it will be different.

  Sequel.connect('jdbc:postgres://...').adapter_scheme # => :jdbc

[Source]

     # File lib/sequel/database/connecting.rb, line 121
121:     def adapter_scheme
122:       self.class.adapter_scheme
123:     end

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"})

[Source]

     # File lib/sequel/database/connecting.rb, line 134
134:     def add_servers(servers)
135:       if h = @opts[:servers]
136:         Sequel.synchronize{h.merge!(servers)}
137:         @pool.add_servers(servers.keys)
138:       end
139:     end

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

[Source]

     # File lib/sequel/database/connecting.rb, line 142
142:     def connect(server)
143:       Sequel::Deprecation.deprecate('Database#connect default implementation and Sequel::NotImplemented', 'All database instance can be assumed to implement connect.')
144:       raise NotImplemented, "#connect should be overridden by adapters"
145:     end

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

  Sequel.connect('jdbc:postgres://...').database_type # => :postgres

[Source]

     # File lib/sequel/database/connecting.rb, line 156
156:     def database_type
157:       adapter_scheme
158:     end

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.

Example:

  DB.disconnect # All servers
  DB.disconnect(:servers=>:server1) # Single server
  DB.disconnect(:servers=>[:server1, :server2]) # Multiple servers

[Source]

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

Should only be called by the connection pool code to disconnect a connection. By default, calls the close method on the connection object, since most adapters use that, but should be overwritten on other adapters.

[Source]

     # File lib/sequel/database/connecting.rb, line 177
177:     def disconnect_connection(conn)
178:       conn.close
179:     end

Yield a new Database instance 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}}

[Source]

     # File lib/sequel/database/connecting.rb, line 186
186:     def each_server(&block)
187:       raise(Error, "Database#each_server must be passed a block") unless block
188:       servers.each{|s| self.class.connect(server_opts(s), &block)}
189:     end

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)

[Source]

     # File lib/sequel/database/connecting.rb, line 201
201:     def remove_servers(*servers)
202:       if h = @opts[:servers]
203:         servers.flatten.each{|s| Sequel.synchronize{h.delete(s)}}
204:         @pool.remove_servers(servers)
205:       end
206:     end

An array of servers/shards for this Database object.

  DB.servers # Unsharded: => [:default]
  DB.servers # Sharded:   => [:default, :server1, :server2]

[Source]

     # File lib/sequel/database/connecting.rb, line 212
212:     def servers
213:       pool.servers
214:     end

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

[Source]

     # File lib/sequel/database/connecting.rb, line 217
217:     def single_threaded?
218:       @single_threaded
219:     end

Acquires a database connection, yielding it to the passed block. This is useful if you want to make sure the same connection is used for all database queries in the block. It is also useful if you want to gain direct access to the underlying connection object if you need to do something Sequel does not natively support.

If a server option is given, acquires a connection for that specific server, instead of the :default server.

  DB.synchronize do |conn|
    ...
  end

[Source]

     # File lib/sequel/database/connecting.rb, line 234
234:       def synchronize(server=nil)
235:         @pool.hold(server || :default){|conn| yield conn}
236:       end

:nocov:

[Source]

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

Attempts to acquire a database connection. Returns true if successful. Will probably raise an Error if unsuccessful. If a server argument is given, attempts to acquire a database connection to the given server/shard.

[Source]

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

Check whether the given connection is currently valid, by running a query against it. If the query fails, the connection should probably be removed from the connection pool.

[Source]

     # File lib/sequel/database/connecting.rb, line 258
258:     def valid_connection?(conn)
259:       sql = valid_connection_sql
260:       begin
261:         log_connection_execute(conn, sql)
262:       rescue Sequel::DatabaseError, *database_error_classes
263:         false
264:       else
265:         true
266:       end
267:     end

6 - Methods relating to logging

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.
sql_log_level  [RW]  Log level at which to log SQL queries. This is actually the method sent to the logger, so it should be the method name symbol. The default is :info, it can be set to :debug to log at DEBUG level.

Public Instance methods

Log a message at error level, with information about the exception.

[Source]

    # File lib/sequel/database/logging.rb, line 21
21:     def log_exception(exception, message)
22:       log_each(:error, "#{exception.class}: #{exception.message.strip if exception.message}: #{message}")
23:     end

Log a message at level info to all loggers.

[Source]

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

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.

[Source]

    # File lib/sequel/database/logging.rb, line 32
32:     def log_yield(sql, args=nil)
33:       return yield if @loggers.empty?
34:       sql = "#{sql}; #{args.inspect}" if args
35:       start = Time.now
36:       begin
37:         yield
38:       rescue => e
39:         log_exception(e, sql)
40:         raise
41:       ensure
42:         log_duration(Time.now - start, sql) unless e
43:       end
44:     end

Remove any existing loggers and just use the given logger:

  DB.logger = Logger.new($stdout)

[Source]

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

5 - Methods that set defaults for created datasets

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

Constants

DatasetClass = Sequel::Dataset   The default class to use for datasets

Attributes

dataset_class  [R]  The class to use for creating datasets. Should respond to new with the Database argument as the first argument, and an optional options hash.
identifier_input_method  [R]  The identifier input method to use by default for this database (default: adapter default)
identifier_input_method  [R]  The identifier input method to use by default for all databases (default: adapter default)
identifier_output_method  [R]  The identifier output method to use by default for this database (default: adapter default)
identifier_output_method  [R]  The identifier output method to use by default for all databases (default: adapter default)
quote_identifiers  [RW]  Whether to quote identifiers (columns and tables) by default for all databases (default: adapter default)

Public Class methods

Change the default identifier input method to use for all databases,

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 27
27:     def self.identifier_input_method=(v)
28:       @identifier_input_method = v.nil? ? false : v
29:     end

Change the default identifier output method to use for all databases,

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 32
32:     def self.identifier_output_method=(v)
33:       @identifier_output_method = v.nil? ? false : v
34:      end

Public Instance methods

REMOVE40

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 48
48:     def _default_schema
49:       @default_schema
50:     end

If the database has any dataset modules associated with it, use a subclass of the given class that includes the modules as the dataset class.

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 63
63:     def dataset_class=(c)
64:       unless @dataset_modules.empty?
65:         c = Class.new(c)
66:         @dataset_modules.each{|m| c.send(:include, m)}
67:       end
68:       @dataset_class = c
69:       reset_default_dataset
70:     end

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 51
51:     def default_schema
52:       Sequel::Deprecation.deprecate('Database#default_schema', 'Use qualified tables instead')
53:       @default_schema
54:     end

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 55
55:     def default_schema=(v)
56:       Sequel::Deprecation.deprecate('Database#default_schema=', 'Use qualified tables instead') if v
57:       @default_schema = v
58:     end

Equivalent to extending all datasets produced by the database with a module. What it actually does is use a subclass of the current dataset_class as the new dataset_class, and include the module in the subclass. Instead of a module, you can provide a block that is used to create an anonymous module.

This allows you to override any of the dataset methods even if they are defined directly on the dataset class that this Database object uses.

Examples:

  # Introspec columns for all of DB's datasets
  DB.extend_datasets(Sequel::ColumnsIntrospection)

  # Trace all SELECT queries by printing the SQL and the full backtrace
  DB.extend_datasets do
    def fetch_rows(sql)
      puts sql
      puts caller
      super
    end
  end

[Source]

     # File lib/sequel/database/dataset_defaults.rb, line 94
 94:     def extend_datasets(mod=nil, &block)
 95:       raise(Error, "must provide either mod or block, not both") if mod && block
 96:       mod = Module.new(&block) if block
 97:       if @dataset_modules.empty?
 98:        @dataset_modules = [mod]
 99:        @dataset_class = Class.new(@dataset_class)
100:       else
101:        @dataset_modules << mod
102:       end
103:       @dataset_class.send(:include, mod)
104:       reset_default_dataset
105:     end

Set the method to call on identifiers going into the database:

  DB[:items] # SELECT * FROM items
  DB.identifier_input_method = :upcase
  DB[:items] # SELECT * FROM ITEMS

[Source]

     # File lib/sequel/database/dataset_defaults.rb, line 112
112:     def identifier_input_method=(v)
113:       reset_default_dataset
114:       @identifier_input_method = v
115:     end

Set the method to call on identifiers coming from the database:

  DB[:items].first # {:id=>1, :name=>'foo'}
  DB.identifier_output_method = :upcase
  DB[:items].first # {:ID=>1, :NAME=>'foo'}

[Source]

     # File lib/sequel/database/dataset_defaults.rb, line 122
122:     def identifier_output_method=(v)
123:       reset_default_dataset
124:       @identifier_output_method = v
125:     end

Set whether to quote identifiers (columns and tables) for this database:

  DB[:items] # SELECT * FROM items
  DB.quote_identifiers = true
  DB[:items] # SELECT * FROM "items"

[Source]

     # File lib/sequel/database/dataset_defaults.rb, line 132
132:     def quote_identifiers=(v)
133:       reset_default_dataset
134:       @quote_identifiers = v
135:     end

Returns true if the database quotes identifiers.

[Source]

     # File lib/sequel/database/dataset_defaults.rb, line 138
138:     def quote_identifiers?
139:       @quote_identifiers
140:     end

1 - Methods that execute queries and/or return results

This methods generally execute SQL code on the database server.

Constants

STRING_DEFAULT_RE = /\A'(.*)'\z/
CURRENT_TIMESTAMP_RE = /now|CURRENT|getdate|\ADate\(\)\z/io
COLUMN_SCHEMA_DATETIME_TYPES = [:date, :datetime]
COLUMN_SCHEMA_STRING_TYPES = [:string, :blob, :date, :datetime, :time, :enum, :set, :interval]

Attributes

cache_schema  [RW]  Whether the schema should be cached for this database. True by default for performance, can be set to false to always issue a database query to get the schema.
prepared_statements  [R]  The prepared statement object hash for this database, keyed by name symbol

Public Instance methods

Runs the supplied SQL statement string on the database server. Returns self so it can be safely chained:

  DB << "UPDATE albums SET artist_id = NULL" << "DROP TABLE artists"

[Source]

    # File lib/sequel/database/query.rb, line 25
25:     def <<(sql)
26:       run(sql)
27:       self
28:     end

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

  DB[:items].filter(:id=>1).prepare(:first, :sa)
  DB.call(:sa) # SELECT * FROM items WHERE id = 1

[Source]

    # File lib/sequel/database/query.rb, line 35
35:     def call(ps_name, hash={}, &block)
36:       prepared_statement(ps_name).call(hash, &block)
37:     end

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/query.rb, line 41
41:     def execute(sql, opts={})
42:       Sequel::Deprecation.deprecate('Database#execute default implementation and Sequel::NotImplemented', 'All database instances can be assumed to implement execute')
43:       raise NotImplemented, "#execute should be overridden by adapters"
44:     end

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

[Source]

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

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/query.rb, line 56
56:     def execute_dui(sql, opts={}, &block)
57:       execute(sql, opts, &block)
58:     end

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/query.rb, line 63
63:     def execute_insert(sql, opts={}, &block)
64:       execute_dui(sql, opts, &block)
65:     end

Returns an array of hashes containing foreign key information from the table. Each hash will contain at least the following fields:

:columns :An array of columns in the given table
:table :The table referenced by the columns
:key :An array of columns referenced (in the table specified by :table), but can be nil on certain adapters if the primary key is referenced.

The hash may also contain entries for:

:deferrable :Whether the constraint is deferrable
:name :The name of the constraint
:on_delete :The action to take ON DELETE
:on_update :The action to take ON UPDATE

[Source]

    # File lib/sequel/database/query.rb, line 81
81:     def foreign_key_list(table, opts={})
82:       Sequel::Deprecation.deprecate('Database#foreign_key_list default implementation and Sequel::NotImplemented', 'Use Database#supports_foreign_key_parsing? to check for support')
83:       raise NotImplemented, "#foreign_key_list should be overridden by adapters"
84:     end

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

  DB.get(1) # SELECT 1
  # => 1
  DB.get{server_version{}} # SELECT server_version()

[Source]

    # File lib/sequel/database/query.rb, line 91
91:     def get(*args, &block)
92:       @default_dataset.get(*args, &block)
93:     end

Return a hash containing index information for the table. 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.

  DB.indexes(:artists)
  # => {:artists_name_ukey=>{:columns=>[:name], :unique=>true}}

[Source]

     # File lib/sequel/database/query.rb, line 104
104:     def indexes(table, opts={})
105:       Sequel::Deprecation.deprecate('Database#indexes default implementation and Sequel::NotImplemented', 'Use Database#supports_index_parsing? to check for support')
106:       raise NotImplemented, "#indexes should be overridden by adapters"
107:     end

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

:server :The server to run the SQL on.
  DB.run("SET some_server_variable = 42")

[Source]

     # File lib/sequel/database/query.rb, line 114
114:     def run(sql, opts={})
115:       execute_ddl(sql, opts)
116:       nil
117:     end

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. The table argument can also be a dataset, as long as it only has one table. Available options are:

:reload :Ignore any cached results, and get fresh information from the database.
:schema :An explicit schema to use. It may also be implicitly provided via the table name.

If schema parsing is supported by the database, the column information should hash at least contain the following entries:

:allow_null :Whether NULL is an allowed value for the column.
:db_type :The database type for the column, as a database specific string.
:default :The database default for the column, as a database specific string.
:primary_key :Whether the columns is a primary key column. If this column is not present, it means that primary key information is unavailable, not that the column is not a primary key.
:ruby_default :The database default for the column, as a ruby object. In many cases, complex database defaults cannot be parsed into ruby objects, in which case nil will be used as the value.
:type :A symbol specifying the type, such as :integer or :string.

Example:

  DB.schema(:artists)
  # [[:id,
  #   {:type=>:integer,
  #    :primary_key=>true,
  #    :default=>"nextval('artist_id_seq'::regclass)",
  #    :ruby_default=>nil,
  #    :db_type=>"integer",
  #    :allow_null=>false}],
  #  [:name,
  #   {:type=>:string,
  #    :primary_key=>false,
  #    :default=>nil,
  #    :ruby_default=>nil,
  #    :db_type=>"text",
  #    :allow_null=>false}]]

[Source]

     # File lib/sequel/database/query.rb, line 159
159:     def schema(table, opts={})
160:       raise(Error, 'schema parsing is not implemented on this database') unless supports_schema_parsing?
161: 
162:       opts = opts.dup
163:       tab = if table.is_a?(Dataset)
164:         o = table.opts
165:         from = o[:from]
166:         raise(Error, "can only parse the schema for a dataset with a single from table") unless from && from.length == 1 && !o.include?(:join) && !o.include?(:sql)
167:         table.first_source_table
168:       else
169:         table
170:       end
171: 
172:       qualifiers = split_qualifiers(tab)
173:       table_name = qualifiers.pop
174:       sch = qualifiers.pop
175:       information_schema_schema = case qualifiers.length
176:       when 1
177:         Sequel.identifier(*qualifiers)
178:       when 2
179:         Sequel.qualify(*qualifiers)
180:       end
181: 
182:       if table.is_a?(Dataset)
183:         quoted_name = table.literal(tab)
184:         opts[:dataset] = table
185:       else
186:         quoted_name = schema_utility_dataset.literal(table)
187:       end
188: 
189:       opts[:schema] = sch if sch && !opts.include?(:schema)
190:       opts[:information_schema_schema] = information_schema_schema if information_schema_schema && !opts.include?(:information_schema_schema)
191: 
192:       Sequel.synchronize{@schemas.delete(quoted_name)} if opts[:reload]
193:       if v = Sequel.synchronize{@schemas[quoted_name]}
194:         return v
195:       end
196: 
197:       cols = schema_parse_table(table_name, opts)
198:       raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty?
199:       cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])}
200:       Sequel.synchronize{@schemas[quoted_name] = cols} if cache_schema
201:       cols
202:     end

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

  DB.table_exists?(:foo) # => false
  # SELECT NULL FROM foo LIMIT 1

Note that since this does a SELECT from the table, it can give false negatives if you don‘t have permission to SELECT from the table.

[Source]

     # File lib/sequel/database/query.rb, line 212
212:     def table_exists?(name)
213:       sch, table_name = schema_and_table(name)
214:       name = SQL::QualifiedIdentifier.new(sch, table_name) if sch
215:       _table_exists?(from(name))
216:       true
217:     rescue DatabaseError
218:       false
219:     end

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

  DB.tables # => [:albums, :artists]

[Source]

     # File lib/sequel/database/query.rb, line 224
224:     def tables(opts={})
225:       Sequel::Deprecation.deprecate('Database#tables default implementation and Sequel::NotImplemented', 'Use Database#supports_table_listing? to check for support')
226:       raise NotImplemented, "#tables should be overridden by adapters"
227:     end

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

  DB.views # => [:gold_albums, :artists_with_many_albums]

[Source]

     # File lib/sequel/database/query.rb, line 232
232:     def views(opts={})
233:       Sequel::Deprecation.deprecate('Database#views default implementation and Sequel::NotImplemented', 'Use Database#supports_view_listing? to check for support')
234:       raise NotImplemented, "#views should be overridden by adapters"
235:     end

7 - Miscellaneous methods

These methods don‘t fit neatly into another category.

Classes and Modules

Module Sequel::Database::ResetIdentifierMangling

Constants

EXTENSIONS = {}   Hash of extension name symbols to callable objects to load the extension into the Database object (usually by extending it with a module defined in the extension).
DEFAULT_STRING_COLUMN_SIZE = 255   The general default size for string columns for all Sequel::Database instances.
DEFAULT_DATABASE_ERROR_REGEXPS = {}.freeze   Empty exception regexp to class map, used by default if Sequel doesn‘t have specific support for the database in use.
SCHEMA_TYPE_CLASSES = {:string=>String, :integer=>Integer, :date=>Date, :datetime=>[Time, DateTime].freeze, :time=>Sequel::SQLTime, :boolean=>[TrueClass, FalseClass].freeze, :float=>Float, :decimal=>BigDecimal, :blob=>Sequel::SQL::Blob}.freeze   Mapping of schema type symbols to class or arrays of classes for that symbol.
NOT_NULL_CONSTRAINT_SQLSTATES = %w'23502'.freeze.each{|s| s.freeze}
FOREIGN_KEY_CONSTRAINT_SQLSTATES = %w'23503 23506 23504'.freeze.each{|s| s.freeze}
UNIQUE_CONSTRAINT_SQLSTATES = %w'23505'.freeze.each{|s| s.freeze}
CHECK_CONSTRAINT_SQLSTATES = %w'23513 23514'.freeze.each{|s| s.freeze}
SERIALIZATION_CONSTRAINT_SQLSTATES = %w'40001'.freeze.each{|s| s.freeze}
LEADING_ZERO_RE = /\A0+(\d)/.freeze   Used for checking/removing leading zeroes from strings so they don‘t get interpreted as octal.
LEADING_ZERO_REP = "\\1".freeze   :nocov: Replacement string when replacing leading zeroes.

Attributes

default_string_column_size  [RW]  The specific default size of string columns for this Sequel::Database, usually 255 by default.
opts  [R]  The options hash for this database
timezone  [W]  Set the timezone to use for this database, overridding Sequel.database_timezone.

Public Class methods

Register a hook that will be run when a new Database is instantiated. It is called with the new database handle.

[Source]

    # File lib/sequel/database/misc.rb, line 40
40:     def self.after_initialize(&block)
41:       raise Error, "must provide block to after_initialize" unless block
42:       Sequel.synchronize do
43:         previous = @initialize_hook
44:         @initialize_hook = Proc.new do |db|
45:           previous.call(db)
46:           block.call(db)
47:         end
48:       end
49:     end

Apply an extension to all Database objects created in the future.

[Source]

    # File lib/sequel/database/misc.rb, line 52
52:     def self.extension(*extensions)
53:       after_initialize{|db| db.extension(*extensions)}
54:     end

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

Accepts the following options:

:default_string_column_size :The default size of string columns, 255 by default.
: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
:logger :A specific logger to use
:loggers :An array of loggers to use
:quote_identifiers :Whether to quote identifiers
:servers :A hash specifying a server/shard specific options, keyed by shard symbol
:single_threaded :Whether to use a single-threaded connection pool
:sql_log_level :Method to use to log SQL to a logger, :info by default.

All options given are also passed to the connection pool.

[Source]

     # File lib/sequel/database/misc.rb, line 113
113:     def initialize(opts = {}, &block)
114:       @opts ||= opts
115:       @opts = connection_pool_default_options.merge(@opts)
116:       @loggers = Array(@opts[:logger]) + Array(@opts[:loggers])
117:       self.log_warn_duration = @opts[:log_warn_duration]
118:       block ||= proc{|server| connect(server)}
119:       @opts[:servers] = {} if @opts[:servers].is_a?(String)
120:       @opts[:adapter_class] = self.class
121:       
122:       @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, Database.single_threaded))
123:       @schemas = {}
124:       @default_schema = @opts.fetch(:default_schema, default_schema_default)
125:       @default_string_column_size = @opts[:default_string_column_size] || DEFAULT_STRING_COLUMN_SIZE
126:       @prepared_statements = {}
127:       @transactions = {}
128:       @identifier_input_method = nil
129:       @identifier_output_method = nil
130:       @quote_identifiers = nil
131:       @timezone = nil
132:       @dataset_class = dataset_class_default
133:       @cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true))
134:       @dataset_modules = []
135:       @schema_type_classes = SCHEMA_TYPE_CLASSES.dup
136:       self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info
137:       @pool = ConnectionPool.get_pool(self, @opts)
138: 
139:       reset_identifier_mangling
140:       adapter_initialize
141: 
142:       unless typecast_value_boolean(@opts[:keep_reference]) == false
143:         Sequel.synchronize{::Sequel::DATABASES.push(self)}
144:       end
145:       Sequel::Database.run_after_initialize(self)
146:     end

Register an extension callback for Database objects. ext should be the extension name symbol, and mod should either be a Module that the database is extended with, or a callable object called with the database object. If mod is not provided, a block can be provided and is treated as the mod object.

[Source]

    # File lib/sequel/database/misc.rb, line 61
61:     def self.register_extension(ext, mod=nil, &block)
62:       if mod
63:         raise(Error, "cannot provide both mod and block to Database.register_extension") if block
64:         if mod.is_a?(Module)
65:           block = proc{|db| db.extend(mod)}
66:         else
67:           block = mod
68:         end
69:       end
70:       Sequel.synchronize{EXTENSIONS[ext] = block}
71:     end

Run the after_initialize hook for the given instance.

[Source]

    # File lib/sequel/database/misc.rb, line 74
74:     def self.run_after_initialize(instance)
75:       @initialize_hook.call(instance)
76:     end

Public Instance methods

If a transaction is not currently in process, yield to the block immediately. Otherwise, add the block to the list of blocks to call after the currently in progress transaction commits (and only if it commits). Options:

:server :The server/shard to use.

[Source]

     # File lib/sequel/database/misc.rb, line 153
153:     def after_commit(opts={}, &block)
154:       raise Error, "must provide block to after_commit" unless block
155:       synchronize(opts[:server]) do |conn|
156:         if h = _trans(conn)
157:           raise Error, "cannot call after_commit in a prepared transaction" if h[:prepare]
158:           (h[:after_commit] ||= []) << block
159:         else
160:           yield
161:         end
162:       end
163:     end

If a transaction is not currently in progress, ignore the block. Otherwise, add the block to the list of the blocks to call after the currently in progress transaction rolls back (and only if it rolls back). Options:

:server :The server/shard to use.

[Source]

     # File lib/sequel/database/misc.rb, line 170
170:     def after_rollback(opts={}, &block)
171:       raise Error, "must provide block to after_rollback" unless block
172:       synchronize(opts[:server]) do |conn|
173:         if h = _trans(conn)
174:           raise Error, "cannot call after_rollback in a prepared transaction" if h[:prepare]
175:           (h[:after_rollback] ||= []) << block
176:         end
177:       end
178:     end

Cast the given type to a literal type

  DB.cast_type_literal(Float) # double precision
  DB.cast_type_literal(:foo) # foo

[Source]

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

Load an extension into the receiver. In addition to requiring the extension file, this also modifies the database to work with the extension (usually extending it with a module defined in the extension file). If no related extension file exists or the extension does not have specific support for Database objects, an Error will be raised. Returns self.

[Source]

     # File lib/sequel/database/misc.rb, line 193
193:     def extension(*exts)
194:       Sequel.extension(*exts)
195:       exts.each do |ext|
196:         if pr = Sequel.synchronize{EXTENSIONS[ext]}
197:           pr.call(self)
198:         else
199:           raise(Error, "Extension #{ext} does not have specific support handling individual databases")
200:         end
201:       end
202:       self
203:     end

Convert the given timestamp from the application‘s timezone, to the databases‘s timezone or the default database timezone if the database does not have a timezone.

[Source]

     # File lib/sequel/database/misc.rb, line 208
208:     def from_application_timestamp(v)
209:       Sequel.convert_output_timestamp(v, timezone)
210:     end

Return true if already in a transaction given the options, false otherwise. Respects the :server option for selecting a shard.

[Source]

     # File lib/sequel/database/misc.rb, line 215
215:     def in_transaction?(opts={})
216:       synchronize(opts[:server]){|conn| !!_trans(conn)}
217:     end

Returns a string representation of the database object including the class name and connection URI and options used when connecting (if any).

[Source]

     # File lib/sequel/database/misc.rb, line 221
221:     def inspect
222:       a = []
223:       a << uri.inspect if uri
224:       if (oo = opts[:orig_opts]) && !oo.empty?
225:         a << oo.inspect
226:       end
227:       "#<#{self.class}: #{a.join(' ')}>"
228:     end

Proxy the literal call to the dataset.

  DB.literal(1) # 1
  DB.literal(:a) # a
  DB.literal('a') # 'a'

[Source]

     # File lib/sequel/database/misc.rb, line 235
235:     def literal(v)
236:       schema_utility_dataset.literal(v)
237:     end

Synchronize access to the prepared statements cache.

[Source]

     # File lib/sequel/database/misc.rb, line 240
240:     def prepared_statement(name)
241:       Sequel.synchronize{prepared_statements[name]}
242:     end

Proxy the quote_identifier method to the dataset, useful for quoting unqualified identifiers for use outside of datasets.

[Source]

     # File lib/sequel/database/misc.rb, line 247
247:     def quote_identifier(v)
248:       schema_utility_dataset.quote_identifier(v)
249:     end

Return ruby class or array of classes for the given type symbol.

[Source]

     # File lib/sequel/database/misc.rb, line 252
252:     def schema_type_class(type)
253:       @schema_type_classes[type]
254:     end

Default serial primary key options, used by the table creation code.

[Source]

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

Cache the prepared statement object at the given name.

[Source]

     # File lib/sequel/database/misc.rb, line 263
263:     def set_prepared_statement(name, ps)
264:       ps.prepared_sql
265:       Sequel.synchronize{prepared_statements[name] = ps}
266:     end

The timezone to use for this database, defaulting to Sequel.database_timezone.

[Source]

     # File lib/sequel/database/misc.rb, line 269
269:     def timezone
270:       @timezone || Sequel.database_timezone
271:     end

Convert the given timestamp to the application‘s timezone, from the databases‘s timezone or the default database timezone if the database does not have a timezone.

[Source]

     # File lib/sequel/database/misc.rb, line 276
276:     def to_application_timestamp(v)
277:       Sequel.convert_timestamp(v, timezone)
278:     end

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/misc.rb, line 285
285:     def typecast_value(column_type, value)
286:       return nil if value.nil?
287:       meth = "typecast_value_#{column_type}"
288:       begin
289:         respond_to?(meth, true) ? send(meth, value) : value
290:       rescue ArgumentError, TypeError => e
291:         raise Sequel.convert_exception_class(e, InvalidValue)
292:       end
293:     end

Returns the URI use to connect to the database. If a URI was not used when connecting, returns nil.

[Source]

     # File lib/sequel/database/misc.rb, line 297
297:     def uri
298:       opts[:uri]
299:     end

Explicit alias of uri for easier subclassing.

[Source]

     # File lib/sequel/database/misc.rb, line 302
302:     def url
303:       uri
304:     end

2 - Methods that modify the database schema

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

Constants

AUTOINCREMENT = 'AUTOINCREMENT'.freeze
COMMA_SEPARATOR = ', '.freeze
NOT_NULL = ' NOT NULL'.freeze
NULL = ' NULL'.freeze
PRIMARY_KEY = ' PRIMARY KEY'.freeze
TEMPORARY = 'TEMPORARY '.freeze
UNDERSCORE = '_'.freeze
UNIQUE = ' UNIQUE'.freeze
UNSIGNED = ' UNSIGNED'.freeze
COLUMN_DEFINITION_ORDER = [:collate, :default, :null, :unique, :primary_key, :auto_increment, :references]   The order of column modifiers to use when defining a column.
DEFAULT_JOIN_TABLE_COLUMN_OPTIONS = {:null=>false}   The default options for join table columns.
COMBINABLE_ALTER_TABLE_OPS = [:add_column, :drop_column, :rename_column, :set_column_type, :set_column_default, :set_column_null, :add_constraint, :drop_constraint]   The alter table operations that are combinable.

Public Instance methods

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 36
36:     def add_column(table, *args)
37:       alter_table(table) {add_column(*args)}
38:     end

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 49
49:     def add_index(table, columns, options={})
50:       e = options[:ignore_errors]
51:       begin
52:         alter_table(table){add_index(columns, options)}
53:       rescue DatabaseError
54:         raise unless e
55:       end
56:     end

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.

[Source]

    # File lib/sequel/database/schema_methods.rb, line 75
75:     def alter_table(name, generator=nil, &block)
76:       generator ||= alter_table_generator(&block)
77:       remove_cached_schema(name)
78:       apply_alter_table_generator(name, generator)
79:       nil
80:     end

Return a new Schema::AlterTableGenerator instance with the receiver as the database and the given block.

[Source]

    # File lib/sequel/database/schema_methods.rb, line 84
84:     def alter_table_generator(&block)
85:       alter_table_generator_class.new(self, &block)
86:     end

Create a join table using a hash of foreign keys to referenced table names. Example:

  create_join_table(:cat_id=>:cats, :dog_id=>:dogs)
  # CREATE TABLE cats_dogs (
  #  cat_id integer NOT NULL REFERENCES cats,
  #  dog_id integer NOT NULL REFERENCES dogs,
  #  PRIMARY KEY (cat_id, dog_id)
  # )
  # CREATE INDEX cats_dogs_dog_id_cat_id_index ON cats_dogs(dog_id, cat_id)

The primary key and index are used so that almost all operations on the table can benefit from one of the two indexes, and the primary key ensures that entries in the table are unique, which is the typical desire for a join table.

You can provide column options by making the values in the hash be option hashes, so long as the option hashes have a :table entry giving the table referenced:

  create_join_table(:cat_id=>{:table=>:cats, :type=>Bignum}, :dog_id=>:dogs)

You can provide a second argument which is a table options hash:

  create_join_table({:cat_id=>:cats, :dog_id=>:dogs}, :temp=>true)

Some table options are handled specially:

:index_options :The options to pass to the index
:name :The name of the table to create
:no_index :Set to true not to create the second index.
:no_primary_key :Set to true to not create the primary key.

[Source]

     # File lib/sequel/database/schema_methods.rb, line 120
120:     def create_join_table(hash, options={})
121:       keys = hash.keys.sort_by{|k| k.to_s}
122:       create_table(join_table_name(hash, options), options) do
123:         keys.each do |key|
124:           v = hash[key]
125:           unless v.is_a?(Hash)
126:             v = {:table=>v}
127:           end
128:           v = DEFAULT_JOIN_TABLE_COLUMN_OPTIONS.merge(v)
129:           foreign_key(key, v)
130:         end
131:         primary_key(keys) unless options[:no_primary_key]
132:         index(keys.reverse, options[:index_options] || {}) unless options[:no_index]
133:       end
134:     end

Creates a view, replacing a view with the same name if one already exists.

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

For databases where replacing a view is not natively supported, support is emulated by dropping a view with the same name before creating the view.

[Source]

     # File lib/sequel/database/schema_methods.rb, line 212
212:     def create_or_replace_view(name, source, options = {})
213:       if supports_create_or_replace_view?
214:         options = options.merge(:replace=>true)
215:       else
216:         drop_view(name) rescue nil
217:       end
218: 
219:       create_view(name, source, options)
220:     end

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

General options:

:as :Create the table using the value, which should be either a dataset or a literal SQL string. If this option is used, a block should not be given to the method.
:ignore_index_errors :Ignore any errors when creating indexes.
:temp :Create the table as a temporary table.

MySQL specific options:

:charset :The character set to use for the table.
:collate :The collation to use for the table.
:engine :The table engine to use for the table.

PostgreSQL specific options:

:unlogged :Create the table as an unlogged table.

See Schema::Generator and the "Schema Modification" guide.

[Source]

     # File lib/sequel/database/schema_methods.rb, line 161
161:     def create_table(name, options={}, &block)
162:       remove_cached_schema(name)
163:       options = {:generator=>options} if options.is_a?(Schema::CreateTableGenerator)
164:       if sql = options[:as]
165:         raise(Error, "can't provide both :as option and block to create_table") if block
166:         create_table_as(name, sql, options)
167:       else
168:         generator = options[:generator] || create_table_generator(&block)
169:         create_table_from_generator(name, generator, options)
170:         create_table_indexes_from_generator(name, generator, options)
171:         nil
172:       end
173:     end

Forcibly create a table, attempting to drop it if it already exists, then creating it.

  DB.create_table!(:a){Integer :a}
  # SELECT NULL FROM a LIMIT 1 -- check existence
  # DROP TABLE a -- drop table if already exists
  # CREATE TABLE a (a integer)

[Source]

     # File lib/sequel/database/schema_methods.rb, line 181
181:     def create_table!(name, options={}, &block)
182:       drop_table?(name)
183:       create_table(name, options, &block)
184:     end

Creates the table unless the table already exists.

  DB.create_table?(:a){Integer :a}
  # SELECT NULL FROM a LIMIT 1 -- check existence
  # CREATE TABLE a (a integer) -- if it doesn't already exist

[Source]

     # File lib/sequel/database/schema_methods.rb, line 191
191:     def create_table?(name, options={}, &block)
192:       if supports_create_table_if_not_exists?
193:         create_table(name, options.merge(:if_not_exists=>true), &block)
194:       elsif !table_exists?(name)
195:         create_table(name, options, &block)
196:       end
197:     end

Return a new Schema::CreateTableGenerator instance with the receiver as the database and the given block.

[Source]

     # File lib/sequel/database/schema_methods.rb, line 201
201:     def create_table_generator(&block)
202:       create_table_generator_class.new(self, &block)
203:     end

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

PostgreSQL/SQLite specific option:

:temp :Create a temporary view, automatically dropped on disconnect.

[Source]

     # File lib/sequel/database/schema_methods.rb, line 229
229:     def create_view(name, source, options = {})
230:       execute_ddl(create_view_sql(name, source, options))
231:       remove_cached_schema(name)
232:       nil
233:     end

Removes a column from the specified table:

  DB.drop_column :items, :category

See alter_table.

[Source]

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

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 250
250:     def drop_index(table, columns, options={})
251:       alter_table(table){drop_index(columns, options)}
252:     end

Drop the join table that would have been created with the same arguments to create_join_table:

  drop_join_table(:cat_id=>:cats, :dog_id=>:dogs)
  # DROP TABLE cats_dogs

[Source]

     # File lib/sequel/database/schema_methods.rb, line 259
259:     def drop_join_table(hash, options={})
260:       drop_table(join_table_name(hash, options), options)
261:     end

Drops one or more tables corresponding to the given names:

  DB.drop_table(:posts) # DROP TABLE posts
  DB.drop_table(:posts, :comments)
  DB.drop_table(:posts, :comments, :cascade=>true)

[Source]

     # File lib/sequel/database/schema_methods.rb, line 268
268:     def drop_table(*names)
269:       options = names.last.is_a?(Hash) ? names.pop : {}
270:       names.each do |n|
271:         execute_ddl(drop_table_sql(n, options))
272:         remove_cached_schema(n)
273:       end
274:       nil
275:     end

Drops the table if it already exists. If it doesn‘t exist, does nothing.

  DB.drop_table?(:a)
  # SELECT NULL FROM a LIMIT 1 -- check existence
  # DROP TABLE a -- if it already exists

[Source]

     # File lib/sequel/database/schema_methods.rb, line 283
283:     def drop_table?(*names)
284:       options = names.last.is_a?(Hash) ? names.pop : {}
285:       if supports_drop_table_if_exists?
286:         options = options.merge(:if_exists=>true)
287:         names.each do |name|
288:           drop_table(name, options)
289:         end
290:       else
291:         names.each do |name|
292:           drop_table(name, options) if table_exists?(name)
293:         end
294:       end
295:     end

Drops one or more views corresponding to the given names:

  DB.drop_view(:cheap_items)
  DB.drop_view(:cheap_items, :pricey_items)
  DB.drop_view(:cheap_items, :pricey_items, :cascade=>true)

[Source]

     # File lib/sequel/database/schema_methods.rb, line 302
302:     def drop_view(*names)
303:       options = names.last.is_a?(Hash) ? names.pop : {}
304:       names.each do |n|
305:         execute_ddl(drop_view_sql(n, options))
306:         remove_cached_schema(n)
307:       end
308:       nil
309:     end

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 328
328:     def rename_column(table, *args)
329:       alter_table(table) {rename_column(*args)}
330:     end

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 316
316:     def rename_table(name, new_name)
317:       execute_ddl(rename_table_sql(name, new_name))
318:       remove_cached_schema(name)
319:       nil
320:     end

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 337
337:     def set_column_default(table, *args)
338:       alter_table(table) {set_column_default(*args)}
339:     end

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 346
346:     def set_column_type(table, *args)
347:       alter_table(table) {set_column_type(*args)}
348:     end

9 - Methods that describe what the database supports

These methods all return booleans, with most describing whether or not the database supprots a given feature.

Classes and Modules

Module Sequel::Database::SplitAlterTable

Constants

AFFECTED_ROWS_RE = /Rows matched:\s+(\d+)\s+Changed:\s+\d+\s+Warnings:\s+\d+/.freeze   Regular expression used for getting accurate number of rows matched by an update statement.
DISCONNECT_ERROR_RE = /terminating connection due to administrator command/

Attributes

conversion_procs  [R]  The conversion procs to use for this database
conversion_procs  [R]  Hash of conversion procs for the current database
convert_invalid_date_time  [R]  By default, Sequel raises an exception if in invalid date or time is used. However, if this is set to nil or :nil, the adapter treats dates like 0000-00-00 and times like 838:00:00 as nil values. If set to :string, it returns the strings as is.
convert_tinyint_to_bool  [R]  Whether to convert tinyint columns to bool for the current database
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
driver  [R]  The Java database driver we are using
swift_class  [RW]  The Swift adapter class being used by this database. Connections in this database‘s connection pool will be instances of this class.

Public Instance methods

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 182
182:       def call_sproc(name, opts = {})
183:         args = opts[:args] || []
184:         sql = "{call #{name}(#{args.map{'?'}.join(',')})}"
185:         synchronize(opts[:server]) do |conn|
186:           cps = conn.prepareCall(sql)
187: 
188:           i = 0
189:           args.each{|arg| set_ps_arg(cps, arg, i+=1)}
190: 
191:           begin
192:             if block_given?
193:               yield log_yield(sql){cps.executeQuery}
194:             else
195:               case opts[:type]
196:               when :insert
197:                 log_yield(sql){cps.executeUpdate}
198:                 last_insert_id(conn, opts)
199:               else
200:                 log_yield(sql){cps.executeUpdate}
201:               end
202:             end
203:           rescue NativeException, JavaSQL::SQLException => e
204:             raise_error(e)
205:           ensure
206:             cps.close
207:           end
208:         end
209:       end

Create an instance of swift_class for the given options.

[Source]

    # File lib/sequel/adapters/swift.rb, line 41
41:       def connect(server)
42:         opts = server_opts(server)
43:         opts[:pass] = opts[:password]
44:         setup_connection(swift_class.new(opts))
45:       end

Connect to the database. In addition to the usual database options, the following options have effect:

  • :auto_is_null - Set to true to use MySQL default behavior of having a filter for an autoincrement column equals NULL to return the last inserted row.
  • :charset - Same as :encoding (:encoding takes precendence)
  • :compress - Set to false to not compress results from the server
  • :config_default_group - The default group to read from the in the MySQL config file.
  • :config_local_infile - If provided, sets the Mysql::OPT_LOCAL_INFILE option on the connection with the given value.
  • :connect_timeout - Set the timeout in seconds before a connection attempt is abandoned.
  • :encoding - Set all the related character sets for this connection (connection, client, database, server, and results).
  • :read_timeout - Set the timeout in seconds for reading back results to a query.
  • :socket - Use a unix socket file instead of connecting via TCP/IP.
  • :timeout - Set the timeout in seconds before the server will disconnect this connection (a.k.a @@wait_timeout).

[Source]

     # File lib/sequel/adapters/mysql.rb, line 83
 83:       def connect(server)
 84:         opts = server_opts(server)
 85:         conn = Mysql.init
 86:         conn.options(Mysql::READ_DEFAULT_GROUP, opts[:config_default_group] || "client")
 87:         conn.options(Mysql::OPT_LOCAL_INFILE, opts[:config_local_infile]) if opts.has_key?(:config_local_infile)
 88:         conn.ssl_set(opts[:sslkey], opts[:sslcert], opts[:sslca], opts[:sslcapath], opts[:sslcipher]) if opts[:sslca] || opts[:sslkey]
 89:         if encoding = opts[:encoding] || opts[:charset]
 90:           # Set encoding before connecting so that the mysql driver knows what
 91:           # encoding we want to use, but this can be overridden by READ_DEFAULT_GROUP.
 92:           conn.options(Mysql::SET_CHARSET_NAME, encoding)
 93:         end
 94:         if read_timeout = opts[:read_timeout] and defined? Mysql::OPT_READ_TIMEOUT
 95:           conn.options(Mysql::OPT_READ_TIMEOUT, read_timeout)
 96:         end
 97:         if connect_timeout = opts[:connect_timeout] and defined? Mysql::OPT_CONNECT_TIMEOUT
 98:           conn.options(Mysql::OPT_CONNECT_TIMEOUT, connect_timeout)
 99:         end
100:         conn.real_connect(
101:           opts[:host] || 'localhost',
102:           opts[:user],
103:           opts[:password],
104:           opts[:database],
105:           (opts[:port].to_i if opts[:port]),
106:           opts[:socket],
107:           Mysql::CLIENT_MULTI_RESULTS +
108:           Mysql::CLIENT_MULTI_STATEMENTS +
109:           (opts[:compress] == false ? 0 : Mysql::CLIENT_COMPRESS)
110:         )
111:         sqls = mysql_connection_setting_sqls
112: 
113:         # Set encoding a slightly different way after connecting,
114:         # in case the READ_DEFAULT_GROUP overrode the provided encoding.
115:         # Doesn't work across implicit reconnects, but Sequel doesn't turn on
116:         # that feature.
117:         sqls.unshift("SET NAMES #{literal(encoding.to_s)}") if encoding
118: 
119:         sqls.each{|sql| log_yield(sql){conn.query(sql)}}
120: 
121:         add_prepared_statements_cache(conn)
122:         conn
123:       end

Connect to the database. Since SQLite is a file based database, the only options available are :database (to specify the database name), and :timeout, to specify how long to wait for the database to be available if it is locked, given in milliseconds (default is 5000).

[Source]

     # File lib/sequel/adapters/sqlite.rb, line 98
 98:       def connect(server)
 99:         opts = server_opts(server)
100:         opts[:database] = ':memory:' if blank_object?(opts[:database])
101:         db = ::SQLite3::Database.new(opts[:database])
102:         db.busy_timeout(opts.fetch(:timeout, 5000))
103:         
104:         connection_pragmas.each{|s| log_yield(s){db.execute_batch(s)}}
105:         
106:         class << db
107:           attr_reader :prepared_statements
108:         end
109:         db.instance_variable_set(:@prepared_statements, {})
110:         
111:         db
112:       end

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 212
212:       def connect(server)
213:         opts = server_opts(server)
214:         conn = if jndi?
215:           get_connection_from_jndi
216:         else
217:           args = [uri(opts)]
218:           args.concat([opts[:user], opts[:password]]) if opts[:user] && opts[:password]
219:           begin
220:             JavaSQL::DriverManager.setLoginTimeout(opts[:login_timeout]) if opts[:login_timeout]
221:             JavaSQL::DriverManager.getConnection(*args)
222:           rescue JavaSQL::SQLException, NativeException, StandardError => e
223:             raise e unless driver
224:             # If the DriverManager can't get the connection - use the connect
225:             # method of the driver. (This happens under Tomcat for instance)
226:             props = java.util.Properties.new
227:             if opts && opts[:user] && opts[:password]
228:               props.setProperty("user", opts[:user])
229:               props.setProperty("password", opts[:password])
230:             end
231:             opts[:jdbc_properties].each{|k,v| props.setProperty(k.to_s, v)} if opts[:jdbc_properties]
232:             begin
233:               c = driver.new.connect(args[0], props)
234:               raise(Sequel::DatabaseError, 'driver.new.connect returned nil: probably bad JDBC connection string') unless c
235:               c
236:             rescue JavaSQL::SQLException, NativeException, StandardError => e2
237:               unless e2.message == e.message
238:                 e2.message << "\n#{e.class.name}: #{e.message}"
239:               end
240:               raise e2
241:             end
242:           end
243:         end
244:         setup_connection(conn)
245:       end

Setup a DataObjects::Connection to the database.

[Source]

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

Modify the type translators for the date, time, and timestamp types depending on the value given.

[Source]

     # File lib/sequel/adapters/mysql.rb, line 134
134:       def convert_invalid_date_time=(v)
135:         m0 = ::Sequel.method(:string_to_time)
136:         @conversion_procs[11] = (v != false) ?  lambda{|v| convert_date_time(v, &m0)} : m0
137:         m1 = ::Sequel.method(:string_to_date) 
138:         m = (v != false) ? lambda{|v| convert_date_time(v, &m1)} : m1
139:         [10, 14].each{|i| @conversion_procs[i] = m}
140:         m2 = method(:to_application_timestamp)
141:         m = (v != false) ? lambda{|v| convert_date_time(v, &m2)} : m2
142:         [7, 12].each{|i| @conversion_procs[i] = m}
143:         @convert_invalid_date_time = v
144:       end

Modify the type translator used for the tinyint type based on the value given.

[Source]

     # File lib/sequel/adapters/mysql.rb, line 148
148:       def convert_tinyint_to_bool=(v)
149:         @conversion_procs[1] = TYPE_TRANSLATOR.method(v ? :boolean : :integer)
150:         @convert_tinyint_to_bool = v
151:       end

Closes given database connection.

[Source]

     # File lib/sequel/adapters/mysql.rb, line 126
126:       def disconnect_connection(c)
127:         c.close
128:       rescue Mysql::Error
129:         nil
130:       end

[Source]

    # File lib/sequel/adapters/do.rb, line 52
52:       def disconnect_connection(conn)
53:         conn.dispose
54:       end

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 248
248:       def disconnect_connection(c)
249:         @connection_prepared_statements_mutex.synchronize{@connection_prepared_statements.delete(c)}
250:         c.close
251:       end

Disconnect given connections from the database.

[Source]

     # File lib/sequel/adapters/sqlite.rb, line 115
115:       def disconnect_connection(c)
116:         c.prepared_statements.each_value{|v| v.first.close}
117:         c.close
118:       end

Run the given SQL with the given arguments and yield each row.

[Source]

     # File lib/sequel/adapters/sqlite.rb, line 121
121:       def execute(sql, opts={}, &block)
122:         _execute(:select, sql, opts, &block)
123:       end

Execute the given SQL, yielding a Swift::Result if a block is given.

[Source]

    # File lib/sequel/adapters/swift.rb, line 48
48:       def execute(sql, opts={})
49:         synchronize(opts[:server]) do |conn|
50:           begin
51:             res = log_yield(sql){conn.execute(sql)}
52:             yield res if block_given?
53:             nil
54:           rescue ::Swift::Error => e
55:             raise_error(e)
56:           end
57:         end
58:       end

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 61
61:       def execute(sql, opts={})
62:         synchronize(opts[:server]) do |conn|
63:           begin
64:             command = conn.create_command(sql)
65:             res = log_yield(sql){block_given? ? command.execute_reader : command.execute_non_query}
66:           rescue ::DataObjects::Error => e
67:             raise_error(e)
68:           end
69:           if block_given?
70:             begin
71:               yield(res)
72:             ensure
73:              res.close if res
74:             end
75:           elsif opts[:type] == :insert
76:             res.insert_id
77:           else
78:             res.affected_rows
79:           end
80:         end
81:       end

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 255
255:       def execute(sql, opts={}, &block)
256:         return call_sproc(sql, opts, &block) if opts[:sproc]
257:         return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)}
258:         synchronize(opts[:server]) do |conn|
259:           statement(conn) do |stmt|
260:             if block
261:               yield log_yield(sql){stmt.executeQuery(sql)}
262:             else
263:               case opts[:type]
264:               when :ddl
265:                 log_yield(sql){stmt.execute(sql)}
266:               when :insert
267:                 log_yield(sql){execute_statement_insert(stmt, sql)}
268:                 last_insert_id(conn, opts.merge(:stmt=>stmt))
269:               else
270:                 log_yield(sql){stmt.executeUpdate(sql)}
271:               end
272:             end
273:           end
274:         end
275:       end

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

[Source]

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

Drop any prepared statements on the connection when executing DDL. This is because prepared statements lock the table in such a way that you can‘t drop or alter the table while a prepared statement that references it still exists.

[Source]

     # File lib/sequel/adapters/sqlite.rb, line 133
133:       def execute_ddl(sql, opts={})
134:         synchronize(opts[:server]) do |conn|
135:           conn.prepared_statements.values.each{|cps, s| cps.close}
136:           conn.prepared_statements.clear
137:           super
138:         end
139:       end

Return the number of matched rows when executing a delete/update statement.

[Source]

     # File lib/sequel/adapters/mysql.rb, line 154
154:       def execute_dui(sql, opts={})
155:         execute(sql, opts){|c| return affected_rows(c)}
156:       end

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

[Source]

    # File lib/sequel/adapters/swift.rb, line 62
62:       def execute_dui(sql, opts={})
63:         synchronize(opts[:server]) do |conn|
64:           begin
65:             log_yield(sql){conn.execute(sql).affected_rows}
66:           rescue ::Swift::Error => e
67:             raise_error(e)
68:           end
69:         end
70:       end

Run the given SQL with the given arguments and return the number of changed rows.

[Source]

     # File lib/sequel/adapters/sqlite.rb, line 126
126:       def execute_dui(sql, opts={})
127:         _execute(:update, sql, opts)
128:       end

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

[Source]

    # File lib/sequel/adapters/do.rb, line 85
85:       def execute_dui(sql, opts={})
86:         execute(sql, opts)
87:       end
execute_dui(sql, opts={})

Alias for execute

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

[Source]

    # File lib/sequel/adapters/swift.rb, line 74
74:       def execute_insert(sql, opts={})
75:         synchronize(opts[:server]) do |conn|
76:           begin
77:             log_yield(sql){conn.execute(sql).insert_id}
78:           rescue ::Swift::Error => e
79:             raise_error(e)
80:           end
81:         end
82:       end

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

[Source]

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

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

[Source]

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

Run the given SQL with the given arguments and return the last inserted row id.

[Source]

     # File lib/sequel/adapters/sqlite.rb, line 142
142:       def execute_insert(sql, opts={})
143:         _execute(:insert, sql, opts)
144:       end

Return the last inserted id when executing an insert statement.

[Source]

     # File lib/sequel/adapters/mysql.rb, line 159
159:       def execute_insert(sql, opts={})
160:         execute(sql, opts){|c| return c.insert_id}
161:       end

Whether the database uses a global namespace for the index. If false, the indexes are going to be namespaced per table.

[Source]

    # File lib/sequel/database/features.rb, line 11
11:     def global_index_namespace?
12:       true
13:     end

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 291
291:       def indexes(table, opts={})
292:         m = output_identifier_meth
293:         im = input_identifier_meth
294:         schema, table = schema_and_table(table)
295:         schema ||= opts[:schema]
296:         schema = im.call(schema) if schema
297:         table = im.call(table)
298:         indexes = {}
299:         metadata(:getIndexInfo, nil, schema, table, false, true) do |r|
300:           next unless name = r[:column_name]
301:           next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re 
302:           i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>[false, 0].include?(r[:non_unique])}
303:           i[:columns] << m.call(name)
304:         end
305:         indexes
306:       end

Whether or not JNDI is being used for this connection.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 309
309:       def jndi?
310:         !!(uri =~ JNDI_URI_REGEXP)
311:       end

Return the version of the MySQL server two which we are connecting.

[Source]

     # File lib/sequel/adapters/mysql.rb, line 164
164:       def server_version(server=nil)
165:         @server_version ||= (synchronize(server){|conn| conn.server_version if conn.respond_to?(:server_version)} || super)
166:       end

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

[Source]

    # File lib/sequel/adapters/do.rb, line 97
97:       def subadapter
98:         uri.split(":").first
99:       end

Whether the database supports CREATE TABLE IF NOT EXISTS syntax, false by default.

[Source]

    # File lib/sequel/database/features.rb, line 17
17:     def supports_create_table_if_not_exists?
18:       false
19:     end

Whether the database supports deferrable constraints, false by default as few databases do.

[Source]

    # File lib/sequel/database/features.rb, line 23
23:     def supports_deferrable_constraints?
24:       false
25:     end

Whether the database supports deferrable foreign key constraints, false by default as few databases do.

[Source]

    # File lib/sequel/database/features.rb, line 29
29:     def supports_deferrable_foreign_key_constraints?
30:       supports_deferrable_constraints?
31:     end

Whether the database supports DROP TABLE IF EXISTS syntax, default is the same as supports_create_table_if_not_exists?.

[Source]

    # File lib/sequel/database/features.rb, line 35
35:     def supports_drop_table_if_exists?
36:       supports_create_table_if_not_exists?
37:     end

Whether the database supports Database#foreign_key_list for parsing foreign keys.

[Source]

    # File lib/sequel/database/features.rb, line 41
41:     def supports_foreign_key_parsing?
42:       [:access, :mssql, :mysql, :postgres, :sqlite].include?(database_type)
43:     end

Whether the database supports Database#indexes for parsing indexes.

[Source]

    # File lib/sequel/database/features.rb, line 46
46:     def supports_index_parsing?
47:       [:access, :cubrid, :db2, :mssql, :mysql, :postgres, :sqlite].include?(database_type) || adapter_scheme == :jdbc
48:     end

Whether the database and adapter support prepared transactions (two-phase commit), false by default.

[Source]

    # File lib/sequel/database/features.rb, line 52
52:     def supports_prepared_transactions?
53:       false
54:     end

Whether the database and adapter support savepoints, false by default.

[Source]

    # File lib/sequel/database/features.rb, line 57
57:     def supports_savepoints?
58:       false
59:     end

Whether the database and adapter support savepoints inside prepared transactions (two-phase commit), default is false.

[Source]

    # File lib/sequel/database/features.rb, line 63
63:     def supports_savepoints_in_prepared_transactions?
64:       supports_prepared_transactions? && supports_savepoints?
65:     end

Whether the database supports schema parsing via Database#schema.

[Source]

    # File lib/sequel/database/features.rb, line 68
68:     def supports_schema_parsing?
69:       respond_to?(:schema_parse_table, true)
70:     end

Whether the database supports Database#tables for getting list of tables.

[Source]

    # File lib/sequel/database/features.rb, line 73
73:     def supports_table_listing?
74:       [:access, :cubrid, :db2, :firebird, :mssql, :mysql, :oracle, :postgres, :sqlite].include?(database_type) || adapter_scheme == :jdbc
75:     end

Whether the database and adapter support transaction isolation levels, false by default.

[Source]

    # File lib/sequel/database/features.rb, line 83
83:     def supports_transaction_isolation_levels?
84:       false
85:     end

Whether DDL statements work correctly in transactions, false by default.

[Source]

    # File lib/sequel/database/features.rb, line 88
88:     def supports_transactional_ddl?
89:       false
90:     end

Whether the database supports Database#views for getting list of views.

[Source]

    # File lib/sequel/database/features.rb, line 78
78:     def supports_view_listing?
79:       supports_table_listing?
80:     end

All tables in this database

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 314
314:       def tables(opts={})
315:         get_tables('TABLE', opts)
316:       end

Handle Integer and Float arguments, since SQLite can store timestamps as integers and floats.

[Source]

     # File lib/sequel/adapters/sqlite.rb, line 147
147:       def to_application_timestamp(s)
148:         case s
149:         when String
150:           super
151:         when Integer
152:           super(Time.at(s).to_s)
153:         when Float
154:           super(DateTime.jd(s).to_s)
155:         else
156:           raise Sequel::Error, "unhandled type when converting to : #{s.inspect} (#{s.class.inspect})"
157:         end
158:       end

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

[Source]

     # File lib/sequel/adapters/do.rb, line 103
103:       def uri(opts={})
104:         opts = @opts.merge(opts)
105:         (opts[:uri] || opts[:url]).sub(/\Ado:/, '')
106:       end

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 322
322:       def uri(opts={})
323:         opts = @opts.merge(opts)
324:         ur = opts[:uri] || opts[:url] || opts[:database]
325:         ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}"
326:       end

All views in this database

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 329
329:       def views(opts={})
330:         get_tables('VIEW', opts)
331:       end