Namespace

Methods

Class Index [+]

Quicksearch

Sequel::Database

Database class for MySQL databases used with Sequel.


Database class for PostgreSQL databases used with Sequel and the pg, postgres, or postgres-pr driver.


Database class for SQLite databases used with Sequel and the ruby-sqlite3 driver.


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.

Constants

MYSQL_DATABASE_DISCONNECT_ERRORS

Mysql::Error messages that indicate the current connection should be disconnected

AFFECTED_ROWS_RE

Regular expression used for getting accurate number of rows matched by an update statement.

INFINITE_TIMESTAMP_STRINGS
INFINITE_DATETIME_VALUES
AUTOINCREMENT
COMMA_SEPARATOR
NOT_NULL
NULL
PRIMARY_KEY
TEMPORARY
UNDERSCORE
UNIQUE
UNSIGNED
COLUMN_DEFINITION_ORDER

The order of column modifiers to use when defining a column.

DEFAULT_JOIN_TABLE_COLUMN_OPTIONS

The default options for join table columns.

ADAPTERS

Array of supported database adapters

DatasetClass

The default class to use for datasets

LEADING_ZERO_RE

Used for checking/removing leading zeroes from strings so they don’t get interpreted as octal.

LEADING_ZERO_REP

Replacement string when replacing leading zeroes.

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

Attributes

conversion_procs[R]

Hash of conversion procs for the current database

convert_tinyint_to_bool[R]

Whether to convert tinyint columns to bool 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.

conversion_procs[R]

A hash of conversion procs, keyed by type integer (oid) and having callable values for the conversion proc for that type.

convert_infinite_timestamps[RW]

Whether infinite timestamps should be converted on retrieval. By default, no conversion is done, so an error is raised if you attempt to retrieve an infinite timestamp. You can set this to :nil to convert to nil, :string to leave as a string, or :float to convert to an infinite float.

conversion_procs[R]

The conversion procs to use for this database

pool[R]

The connection pool for this Database instance. All Database instances have their own connection pools.

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.

default_schema[RW]

The default schema to use, generally should be nil. This sets the default schema used for some schema modification and introspection queries, but does not effect most dataset code.

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.

opts[R]

The options hash for this database

timezone[W]

Set the timezone to use for this database, overridding Sequel.database_timezone.

prepared_statements[R]

The prepared statement object hash for this database, keyed by name symbol

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.

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.

Public Class Methods

adapter_class(scheme) click to toggle source

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

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

Returns the scheme symbol for the Database class.

    # File lib/sequel/database/connecting.rb, line 39
39:     def self.adapter_scheme
40:       @scheme
41:     end
connect(conn_string, opts = {}) click to toggle source

Connects to a database. See Sequel.connect.

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

The method to call on identifiers going into the database

    # File lib/sequel/database/dataset_defaults.rb, line 21
21:     def self.identifier_input_method
22:       @@identifier_input_method
23:     end
identifier_input_method=(v) click to toggle source

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

    # File lib/sequel/database/dataset_defaults.rb, line 27
27:     def self.identifier_input_method=(v)
28:       @@identifier_input_method = v || ""
29:     end
identifier_output_method() click to toggle source

The method to call on identifiers coming from the database

    # File lib/sequel/database/dataset_defaults.rb, line 32
32:     def self.identifier_output_method
33:       @@identifier_output_method
34:     end
identifier_output_method=(v) click to toggle source

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

    # File lib/sequel/database/dataset_defaults.rb, line 38
38:     def self.identifier_output_method=(v)
39:       @@identifier_output_method = v || ""
40:     end
new(opts={}) click to toggle source
    # File lib/sequel/adapters/mysql.rb, line 65
65:       def initialize(opts={})
66:         super
67:         @conversion_procs = MYSQL_TYPES.dup
68:         self.convert_tinyint_to_bool = Sequel::MySQL.convert_tinyint_to_bool
69:         self.convert_invalid_date_time = Sequel::MySQL.convert_invalid_date_time
70:       end
new(opts = {}, &block) click to toggle source

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

Accepts the following options:

:default_schema

The default schema to use, see #.

:disconnection_proc

A proc used to disconnect the connection

:identifier_input_method

A string method symbol to call on identifiers going into the database

:identifier_output_method

A string method symbol to call on identifiers coming from the database

: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. If a block is given, it is used as the connection_proc for the ConnectionPool.

    # File lib/sequel/database/misc.rb, line 42
42:     def initialize(opts = {}, &block)
43:       @opts ||= opts
44:       @opts = connection_pool_default_options.merge(@opts)
45:       @loggers = Array(@opts[:logger]) + Array(@opts[:loggers])
46:       self.log_warn_duration = @opts[:log_warn_duration]
47:       @opts[:disconnection_proc] ||= proc{|conn| disconnect_connection(conn)}
48:       block ||= proc{|server| connect(server)}
49:       @opts[:servers] = {} if @opts[:servers].is_a?(String)
50:       @opts[:adapter_class] = self.class
51:       
52:       @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, @@single_threaded))
53:       @schemas = {}
54:       @default_schema = @opts.fetch(:default_schema, default_schema_default)
55:       @prepared_statements = {}
56:       @transactions = {}
57:       @identifier_input_method = nil
58:       @identifier_output_method = nil
59:       @quote_identifiers = nil
60:       @timezone = nil
61:       @dataset_class = dataset_class_default
62:       @cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true))
63:       @dataset_modules = []
64:       self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info
65:       @pool = ConnectionPool.get_pool(@opts, &block)
66: 
67:       Sequel.synchronize{::Sequel::DATABASES.push(self)}
68:     end
new(*args) click to toggle source

Add the primary_keys and primary_key_sequences instance variables, so we can get the correct return values for inserted rows.

     # File lib/sequel/adapters/postgres.rb, line 228
228:       def initialize(*args)
229:         super
230:         @convert_infinite_timestamps = false
231:         @primary_keys = {}
232:         @primary_key_sequences = {}
233:       end
new(opts={}) click to toggle source
    # File lib/sequel/adapters/sqlite.rb, line 94
94:       def initialize(opts={})
95:         super
96:         @conversion_procs = SQLITE_TYPES.dup
97:         @conversion_procs['datetime'] = @conversion_procs['timestamp'] = method(:to_application_timestamp)
98:         set_integer_booleans
99:       end
quote_identifiers=(value) click to toggle source

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

    # File lib/sequel/database/dataset_defaults.rb, line 44
44:     def self.quote_identifiers=(value)
45:       @@quote_identifiers = value
46:     end
single_threaded=(value) click to toggle source

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

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

Private Class Methods

uri_to_options(uri) click to toggle source

Converts a uri to an options hash. These options are then passed to a newly created database object.

    # File lib/sequel/database/misc.rb, line 10
10:     def self.uri_to_options(uri)
11:       { :user => uri.user,
12:         :password => uri.password,
13:         :host => uri.host,
14:         :port => uri.port,
15:         :database => (m = /\/(.*)/.match(uri.path)) && (m[1]) }
16:     end

Public Instance Methods

<<(sql) click to toggle source

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"
    # File lib/sequel/database/query.rb, line 48
48:     def <<(sql)
49:       run(sql)
50:       self
51:     end
[](*args) click to toggle source

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"
    # File lib/sequel/database/dataset.rb, line 19
19:     def [](*args)
20:       (String === args.first) ? fetch(*args) : from(*args)
21:     end
adapter_scheme() click to toggle source

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
     # File lib/sequel/database/connecting.rb, line 124
124:     def adapter_scheme
125:       self.class.adapter_scheme
126:     end
add_column(table, *args) click to toggle source

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

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

See alter_table.

    # File lib/sequel/database/schema_methods.rb, line 31
31:     def add_column(table, *args)
32:       alter_table(table) {add_column(*args)}
33:     end
add_index(table, columns, options={}) click to toggle source

Adds an index to a table for the given columns:

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

Options:

:ignore_errors

Ignore any DatabaseErrors that are raised

See alter_table.

    # File lib/sequel/database/schema_methods.rb, line 44
44:     def add_index(table, columns, options={})
45:       e = options[:ignore_errors]
46:       begin
47:         alter_table(table){add_index(columns, options)}
48:       rescue DatabaseError
49:         raise unless e
50:       end
51:     end
add_servers(servers) click to toggle source

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

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

  DB.add_servers(:f=>{:host=>"hash_host_f"})
     # File lib/sequel/database/connecting.rb, line 137
137:     def add_servers(servers)
138:       if h = @opts[:servers]
139:         Sequel.synchronize{h.merge!(servers)}
140:         @pool.add_servers(servers.keys)
141:       end
142:     end
after_commit(opts={}, &block) click to toggle source

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.

    # File lib/sequel/database/misc.rb, line 75
75:     def after_commit(opts={}, &block)
76:       raise Error, "must provide block to after_commit" unless block
77:       synchronize(opts[:server]) do |conn|
78:         if h = _trans(conn)
79:           raise Error, "cannot call after_commit in a prepared transaction" if h[:prepare]
80:           (h[:after_commit] ||= []) << block
81:         else
82:           yield
83:         end
84:       end
85:     end
after_rollback(opts={}, &block) click to toggle source

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.

     # File lib/sequel/database/misc.rb, line 92
 92:     def after_rollback(opts={}, &block)
 93:       raise Error, "must provide block to after_rollback" unless block
 94:       synchronize(opts[:server]) do |conn|
 95:         if h = _trans(conn)
 96:           raise Error, "cannot call after_rollback in a prepared transaction" if h[:prepare]
 97:           (h[:after_rollback] ||= []) << block
 98:         end
 99:       end
100:     end
alter_table(name, generator=nil, &block) click to toggle source

Alters the given table with the specified block. Example:

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

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

See Schema::AlterTableGenerator and the "Migrations and Schema Modification" guide.

    # File lib/sequel/database/schema_methods.rb, line 70
70:     def alter_table(name, generator=nil, &block)
71:       generator ||= Schema::AlterTableGenerator.new(self, &block)
72:       remove_cached_schema(name)
73:       apply_alter_table(name, generator.operations)
74:       nil
75:     end
bound_variable_arg(arg, conn) click to toggle source

Convert given argument so that it can be used directly by pg. Currently, pg doesn’t handle fractional seconds in Time/DateTime or blobs with “0“, and it won’t ever handle Sequel::SQLTime values correctly. Only public for use by the adapter, shouldn’t be used by external code.

     # File lib/sequel/adapters/postgres.rb, line 239
239:       def bound_variable_arg(arg, conn)
240:         case arg
241:         when Sequel::SQL::Blob
242:           conn.escape_bytea(arg)
243:         when Sequel::SQLTime
244:           literal(arg)
245:         when DateTime, Time
246:           literal(arg)
247:         else
248:           arg
249:         end
250:       end
call(ps_name, hash={}, &block) click to toggle source

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
    # File lib/sequel/database/query.rb, line 58
58:     def call(ps_name, hash={}, &block)
59:       prepared_statement(ps_name).call(hash, &block)
60:     end
cast_type_literal(type) click to toggle source

Cast the given type to a literal type

  DB.cast_type_literal(Float) # double precision
  DB.cast_type_literal(:foo) # foo
     # File lib/sequel/database/misc.rb, line 106
106:     def cast_type_literal(type)
107:       type_literal(:type=>type)
108:     end
connect(server) click to toggle source

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

     # File lib/sequel/adapters/sqlite.rb, line 105
105:       def connect(server)
106:         opts = server_opts(server)
107:         opts[:database] = ':memory:' if blank_object?(opts[:database])
108:         db = ::SQLite3::Database.new(opts[:database])
109:         db.busy_timeout(opts.fetch(:timeout, 5000))
110:         
111:         connection_pragmas.each{|s| log_yield(s){db.execute_batch(s)}}
112:         
113:         class << db
114:           attr_reader :prepared_statements
115:         end
connect(server) click to toggle source

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

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

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

     # File lib/sequel/database/connecting.rb, line 145
145:     def connect(server)
146:       raise NotImplemented, "#connect should be overridden by adapters"
147:     end
connect(server) click to toggle source

Connects to the database. In addition to the standard database options, using the :encoding or :charset option changes the client encoding for the connection, :connect_timeout is a connection timeout in seconds, and :sslmode sets whether postgres’s sslmode. :connect_timeout and :ssl_mode are only supported if the pg driver is used.

     # File lib/sequel/adapters/postgres.rb, line 258
258:       def connect(server)
259:         opts = server_opts(server)
260:         conn = if SEQUEL_POSTGRES_USES_PG
261:           connection_params = {
262:             :host => opts[:host],
263:             :port => opts[:port] || 5432,
264:             :dbname => opts[:database],
265:             :user => opts[:user],
266:             :password => opts[:password],
267:             :connect_timeout => opts[:connect_timeout] || 20,
268:             :sslmode => opts[:sslmode]
269:           }.delete_if { |key, value| blank_object?(value) }
270:           Adapter.connect(connection_params)
271:         else
272:           Adapter.connect(
273:             (opts[:host] unless blank_object?(opts[:host])),
274:             opts[:port] || 5432,
275:             nil, '',
276:             opts[:database],
277:             opts[:user],
278:             opts[:password]
279:           )
280:         end
281:         if encoding = opts[:encoding] || opts[:charset]
282:           if conn.respond_to?(:set_client_encoding)
283:             conn.set_client_encoding(encoding)
284:           else
285:             conn.async_exec("set client_encoding to '#{encoding}'")
286:           end
287:         end
288:         conn.instance_variable_set(:@db, self)
289:         conn.instance_variable_set(:@prepared_statements, {}) if SEQUEL_POSTGRES_USES_PG
290:         connection_configuration_sqls.each{|sql| conn.execute(sql)}
291:         @conversion_procs ||= get_conversion_procs(conn)
292:         conn
293:       end
convert_invalid_date_time=(v) click to toggle source

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

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

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

     # File lib/sequel/adapters/mysql.rb, line 151
151:       def convert_tinyint_to_bool=(v)
152:         @conversion_procs[1] = TYPE_TRANSLATOR.method(v ? :boolean : :integer)
153:         @convert_tinyint_to_bool = v
154:       end
copy_table(table, opts={}) click to toggle source

copy_table uses PostgreSQL’s COPY SQL statement to return formatted results directly to the caller. This method is only supported if pg is the underlying ruby driver. This method should only be called if you want results returned to the client. If you are using +COPY FROM+ or +COPY TO+ with a filename, you should just use run instead of this method. This method does not currently support +COPY FROM STDIN+, but that may be supported in the future.

The table argument supports the following types:

String

Uses the first argument directly as literal SQL. If you are using a version of PostgreSQL before 9.0, you will probably want to use a string if you are using any options at all, as the syntax Sequel uses for options is only compatible with PostgreSQL 9.0+.

Dataset

Uses a query instead of a table name when copying.

other

Uses a table name (usually a symbol) when copying.

The following options are respected:

:format

The format to use. text is the default, so this should be :csv or :binary.

:options

An options SQL string to use, which should contain comma separated options.

:server

The server on which to run the query.

If a block is provided, the method continually yields to the block, one yield per row. If a block is not provided, a single string is returned with all of the data.

     # File lib/sequel/adapters/postgres.rb, line 327
327:         def copy_table(table, opts={})
328:           sql = if table.is_a?(String)
329:             sql = table
330:           else
331:             if opts[:options] || opts[:format]
332:               options = " ("
333:               options << "FORMAT #{opts[:format]}" if opts[:format]
334:               options << "#{', ' if opts[:format]}#{opts[:options]}" if opts[:options]
335:               options << ')'
336:             end
337:             table = if table.is_a?(::Sequel::Dataset)
338:               "(#{table.sql})"
339:             else
340:               literal(table)
341:             end
342:            sql = "COPY #{table} TO STDOUT#{options}"
343:           end
344:           synchronize(opts[:server]) do |conn| 
345:             conn.execute(sql)
346:             begin
347:               if block_given?
348:                 while buf = conn.get_copy_data
349:                   yield buf
350:                 end
351:                 nil
352:               else
353:                 b = ''
354:                 b << buf while buf = conn.get_copy_data
355:                 b
356:               end
357:             ensure
358:               raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state" if buf
359:             end
360:           end 
361:         end
create_join_table(hash, options={}) click to toggle source

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.

     # File lib/sequel/database/schema_methods.rb, line 109
109:     def create_join_table(hash, options={})
110:       keys = hash.keys.sort_by{|k| k.to_s}
111:       create_table(join_table_name(hash, options), options) do
112:         keys.each do |key|
113:           v = hash[key]
114:           unless v.is_a?(Hash)
115:             v = {:table=>v}
116:           end
117:           v = DEFAULT_JOIN_TABLE_COLUMN_OPTIONS.merge(v)
118:           foreign_key(key, v)
119:         end
120:         primary_key(keys) unless options[:no_primary_key]
121:         index(keys.reverse, options[:index_options] || {}) unless options[:no_index]
122:       end
123:     end
create_or_replace_view(name, source) click to toggle source

Creates a view, replacing it if it already exists:

  DB.create_or_replace_view(:cheap_items, "SELECT * FROM items WHERE price < 100")
  DB.create_or_replace_view(:ruby_items, DB[:items].filter(:category => 'ruby'))
     # File lib/sequel/database/schema_methods.rb, line 189
189:     def create_or_replace_view(name, source)
190:       source = source.sql if source.is_a?(Dataset)
191:       execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}")
192:       remove_cached_schema(name)
193:       nil
194:     end
create_table(name, options={}, &block) click to toggle source

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

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

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.

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

     # File lib/sequel/database/schema_methods.rb, line 147
147:     def create_table(name, options={}, &block)
148:       remove_cached_schema(name)
149:       options = {:generator=>options} if options.is_a?(Schema::Generator)
150:       if sql = options[:as]
151:         raise(Error, "can't provide both :as option and block to create_table") if block
152:         create_table_as(name, sql, options)
153:       else
154:         generator = options[:generator] || Schema::Generator.new(self, &block)
155:         create_table_from_generator(name, generator, options)
156:         create_table_indexes_from_generator(name, generator, options)
157:         nil
158:       end
159:     end
create_table!(name, options={}, &block) click to toggle source

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)
     # File lib/sequel/database/schema_methods.rb, line 167
167:     def create_table!(name, options={}, &block)
168:       drop_table?(name)
169:       create_table(name, options, &block)
170:     end
create_table?(name, options={}, &block) click to toggle source

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
     # File lib/sequel/database/schema_methods.rb, line 177
177:     def create_table?(name, options={}, &block)
178:       if supports_create_table_if_not_exists?
179:         create_table(name, options.merge(:if_not_exists=>true), &block)
180:       elsif !table_exists?(name)
181:         create_table(name, options, &block)
182:       end
183:     end
create_view(name, source) click to toggle source

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

  DB.create_view(:cheap_items, "SELECT * FROM items WHERE price < 100")
  DB.create_view(:ruby_items, DB[:items].filter(:category => 'ruby'))
     # File lib/sequel/database/schema_methods.rb, line 200
200:     def create_view(name, source)
201:       source = source.sql if source.is_a?(Dataset)
202:       execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}")
203:     end
database_type() click to toggle source

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

  Sequel.connect('jdbc:postgres://...').database_type # => :postgres
     # File lib/sequel/database/connecting.rb, line 158
158:     def database_type
159:       adapter_scheme
160:     end
dataset(opts=nil) click to toggle source

Returns a blank dataset for this database.

  DB.dataset # SELECT *
  DB.dataset.from(:items) # SELECT * FROM items
    # File lib/sequel/database/dataset.rb, line 27
27:     def dataset(opts=nil)
28:       @dataset_class.new(self, opts)
29:     end
dataset_class=(c) click to toggle source

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.

    # File lib/sequel/database/dataset_defaults.rb, line 61
61:     def dataset_class=(c)
62:       unless @dataset_modules.empty?
63:         c = Class.new(c)
64:         @dataset_modules.each{|m| c.send(:include, m)}
65:       end
66:       @dataset_class = c
67:     end
disconnect(opts = {}) click to toggle source

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

:servers

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

Example:

  DB.disconnect # All servers
  DB.disconnect(:servers=>:server1) # Single server
  DB.disconnect(:servers=>[:server1, :server2]) # Multiple servers
     # File lib/sequel/database/connecting.rb, line 172
172:     def disconnect(opts = {})
173:       pool.disconnect(opts)
174:     end
drop_column(table, *args) click to toggle source

Removes a column from the specified table:

  DB.drop_column :items, :category

See alter_table.

     # File lib/sequel/database/schema_methods.rb, line 210
210:     def drop_column(table, *args)
211:       alter_table(table) {drop_column(*args)}
212:     end
drop_index(table, columns, options={}) click to toggle source

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

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

See alter_table.

     # File lib/sequel/database/schema_methods.rb, line 220
220:     def drop_index(table, columns, options={})
221:       alter_table(table){drop_index(columns, options)}
222:     end
drop_join_table(hash, options={}) click to toggle source

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
     # File lib/sequel/database/schema_methods.rb, line 229
229:     def drop_join_table(hash, options={})
230:       drop_table(join_table_name(hash, options), options)
231:     end
drop_table(*names) click to toggle source

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)
     # File lib/sequel/database/schema_methods.rb, line 238
238:     def drop_table(*names)
239:       options = names.last.is_a?(Hash) ? names.pop : {}
240:       names.each do |n|
241:         execute_ddl(drop_table_sql(n, options))
242:         remove_cached_schema(n)
243:       end
244:       nil
245:     end
drop_table?(*names) click to toggle source

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
     # File lib/sequel/database/schema_methods.rb, line 253
253:     def drop_table?(*names)
254:       options = names.last.is_a?(Hash) ? names.pop : {}
255:       if supports_drop_table_if_exists?
256:         options = options.merge(:if_exists=>true)
257:         names.each do |name|
258:           drop_table(name, options)
259:         end
260:       else
261:         names.each do |name|
262:           drop_table(name, options) if table_exists?(name)
263:         end
264:       end
265:     end
drop_view(*names) click to toggle source

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)
     # File lib/sequel/database/schema_methods.rb, line 272
272:     def drop_view(*names)
273:       options = names.last.is_a?(Hash) ? names.pop : {}
274:       names.each do |n|
275:         execute_ddl(drop_view_sql(n, options))
276:         remove_cached_schema(n)
277:       end
278:       nil
279:     end
dump_foreign_key_migration(options={}) click to toggle source

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.

    # File lib/sequel/extensions/schema_dumper.rb, line 16
16:     def dump_foreign_key_migration(options={})
17:       ts = tables(options)
18:       Sequel.migration do  up do#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_foreign_keys(t)}.reject{|x| x == ''}.join("\n\n").gsub(/^/o, '    ')}  endend
19:     end
dump_indexes_migration(options={}) click to toggle source

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

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

  • :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.

    # File lib/sequel/extensions/schema_dumper.rb, line 34
34:     def dump_indexes_migration(options={})
35:       ts = tables(options)
36:       Sequel.migration do  up do#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :add_index, options)}.reject{|x| x == ''}.join("\n\n").gsub(/^/o, '    ')}  end    down do#{ts.sort_by{|t| t.to_s}.reverse.map{|t| dump_table_indexes(t, :drop_index, options)}.reject{|x| x == ''}.join("\n\n").gsub(/^/o, '    ')}  endend
37:     end
dump_schema_cache(file) click to toggle source

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

    # File lib/sequel/extensions/schema_caching.rb, line 52
52:     def dump_schema_cache(file)
53:       File.open(file, 'wb'){|f| f.write(Marshal.dump(@schemas))}
54:       nil
55:     end
dump_schema_cache?(file) click to toggle source

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

    # File lib/sequel/extensions/schema_caching.rb, line 59
59:     def dump_schema_cache?(file)
60:       dump_schema_cache(file) unless File.exist?(file)
61:     end
dump_schema_migration(options={}) click to toggle source

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

  • :same_db - Don’t attempt to translate database types to ruby types. If this isn’t set to true, all database types will be translated to ruby types, but there is no guarantee that the migration generated will yield the same type. Without this set, types that aren’t recognized will be translated to a string-like type.

  • :foreign_keys - If set to false, don’t dump foreign_keys

  • :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.

    # File lib/sequel/extensions/schema_dumper.rb, line 61
61:     def dump_schema_migration(options={})
62:       options = options.dup
63:       if options[:indexes] == false && !options.has_key?(:foreign_keys)
64:         # Unless foreign_keys option is specifically set, disable if indexes
65:         # are disabled, as foreign keys that point to non-primary keys rely
66:         # on unique indexes being created first
67:         options[:foreign_keys] = false
68:       end
69: 
70:       ts = sort_dumped_tables(tables(options), options)
71:       skipped_fks = if sfk = options[:skipped_foreign_keys]
72:         # Handle skipped foreign keys by adding them at the end via
73:         # alter_table/add_foreign_key.  Note that skipped foreign keys
74:         # probably result in a broken down migration.
75:         sfka = sfk.sort_by{|table, fks| table.to_s}.map{|table, fks| dump_add_fk_constraints(table, fks.values)}
76:         sfka.join("\n\n").gsub(/^/, '    ') unless sfka.empty?
77:       end
78: 
79:       Sequel.migration do  up do#{ts.map{|t| dump_table_schema(t, options)}.join("\n\n").gsub(/^/o, '    ')}#{"\n    \n" if skipped_fks}#{skipped_fks}  end    down do    drop_table(#{ts.reverse.inspect[1...-1]})  endend
80:     end
dump_table_schema(table, options={}) click to toggle source

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

    # File lib/sequel/extensions/schema_dumper.rb, line 94
94:     def dump_table_schema(table, options={})
95:       table = table.value.to_s if table.is_a?(SQL::Identifier)
96:       gen = dump_table_generator(table, options)
97:       commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n")
98:       "create_table(#{table.inspect}#{', :ignore_index_errors=>true' if !options[:same_db] && options[:indexes] != false && !gen.indexes.empty?}) do\n#{commands.gsub(/^/o, '  ')}\nend"
99:     end
each_server(&block) click to toggle source

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}}
     # File lib/sequel/database/connecting.rb, line 181
181:     def each_server(&block)
182:       servers.each{|s| self.class.connect(server_opts(s), &block)}
183:     end
execute(sql, opts={}) click to toggle source

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

    # File lib/sequel/database/query.rb, line 64
64:     def execute(sql, opts={})
65:       raise NotImplemented, "#execute should be overridden by adapters"
66:     end
execute(sql, opts={}, &block) click to toggle source

Execute the given SQL with the given args on an available connection.

     # File lib/sequel/adapters/postgres.rb, line 296
296:       def execute(sql, opts={}, &block)
297:         synchronize(opts[:server]){|conn| check_database_errors{_execute(conn, sql, opts, &block)}}
298:       end
execute_ddl(sql, opts={}, &block) click to toggle source

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.

    # File lib/sequel/database/query.rb, line 71
71:     def execute_ddl(sql, opts={}, &block)
72:       execute_dui(sql, opts, &block)
73:     end
execute_dui(sql, opts={}, &block) click to toggle source

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

    # File lib/sequel/database/query.rb, line 78
78:     def execute_dui(sql, opts={}, &block)
79:       execute(sql, opts, &block)
80:     end
execute_dui(sql, opts={}) click to toggle source

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

     # File lib/sequel/adapters/mysql.rb, line 157
157:       def execute_dui(sql, opts={})
158:         execute(sql, opts){|c| return affected_rows(c)}
159:       end
execute_insert(sql, opts={}, &block) click to toggle source

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

    # File lib/sequel/database/query.rb, line 85
85:     def execute_insert(sql, opts={}, &block)
86:       execute_dui(sql, opts, &block)
87:     end
execute_insert(sql, opts={}) click to toggle source

Return the last inserted id when executing an insert statement.

     # File lib/sequel/adapters/mysql.rb, line 162
162:       def execute_insert(sql, opts={})
163:         execute(sql, opts){|c| return c.insert_id}
164:       end
extend_datasets(mod=nil, &block) click to toggle source

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
     # File lib/sequel/database/dataset_defaults.rb, line 91
 91:     def extend_datasets(mod=nil, &block)
 92:       raise(Error, "must provide either mod or block, not both") if mod && block
 93:       reset_schema_utility_dataset
 94:       mod = Module.new(&block) if block
 95:       if @dataset_modules.empty?
 96:        @dataset_modules = [mod]
 97:        @dataset_class = Class.new(@dataset_class)
 98:       else
 99:        @dataset_modules << mod
100:       end
101:       @dataset_class.send(:include, mod)
102:     end
fetch(sql, *args, &block) click to toggle source

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

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

The 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
    # File lib/sequel/database/dataset.rb, line 44
44:     def fetch(sql, *args, &block)
45:       ds = dataset.with_sql(sql, *args)
46:       ds.each(&block) if block
47:       ds
48:     end
foreign_key_list(table, opts={}) click to toggle source

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

     # File lib/sequel/database/query.rb, line 103
103:     def foreign_key_list(table, opts={})
104:       raise NotImplemented, "#foreign_key_list should be overridden by adapters"
105:     end
from(*args, &block) click to toggle source

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

  DB.from(:items) # SELECT * FROM items
  DB.from(:items){id > 2} # SELECT * FROM items WHERE (id > 2)
    # File lib/sequel/database/dataset.rb, line 55
55:     def from(*args, &block)
56:       ds = dataset.from(*args)
57:       block ? ds.filter(&block) : ds
58:     end
from_application_timestamp(v) click to toggle source

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.

     # File lib/sequel/database/misc.rb, line 113
113:     def from_application_timestamp(v)
114:       Sequel.convert_output_timestamp(v, timezone)
115:     end
get(*args, &block) click to toggle source

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

  DB.get(1) # SELECT 1
  # => 1
  DB.get{server_version{}} # SELECT server_version()
     # File lib/sequel/database/query.rb, line 112
112:     def get(*args, &block)
113:       dataset.get(*args, &block)
114:     end
global_index_namespace?() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 119
119:     def global_index_namespace?
120:       true
121:     end
identifier_input_method() click to toggle source

The method to call on identifiers going into the database

     # File lib/sequel/database/dataset_defaults.rb, line 105
105:     def identifier_input_method
106:       case @identifier_input_method
107:       when nil
108:         @identifier_input_method = @opts.fetch(:identifier_input_method, (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method))
109:         @identifier_input_method == "" ? nil : @identifier_input_method
110:       when ""
111:         nil
112:       else
113:         @identifier_input_method
114:       end
115:     end
identifier_input_method=(v) click to toggle source

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
     # File lib/sequel/database/dataset_defaults.rb, line 122
122:     def identifier_input_method=(v)
123:       reset_schema_utility_dataset
124:       @identifier_input_method = v || ""
125:     end
identifier_output_method() click to toggle source

The method to call on identifiers coming from the database

     # File lib/sequel/database/dataset_defaults.rb, line 128
128:     def identifier_output_method
129:       case @identifier_output_method
130:       when nil
131:         @identifier_output_method = @opts.fetch(:identifier_output_method, (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method))
132:         @identifier_output_method == "" ? nil : @identifier_output_method
133:       when ""
134:         nil
135:       else
136:         @identifier_output_method
137:       end
138:     end
identifier_output_method=(v) click to toggle source

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'}
     # File lib/sequel/database/dataset_defaults.rb, line 145
145:     def identifier_output_method=(v)
146:       reset_schema_utility_dataset
147:       @identifier_output_method = v || ""
148:     end
in_transaction?(opts={}) click to toggle source

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

     # File lib/sequel/database/misc.rb, line 126
126:     def in_transaction?(opts={})
127:       synchronize(opts[:server]){|conn| !!_trans(conn)}
128:     end
indexes(table, opts={}) click to toggle source

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}}
     # File lib/sequel/database/query.rb, line 125
125:     def indexes(table, opts={})
126:       raise NotImplemented, "#indexes should be overridden by adapters"
127:     end
inspect() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 132
132:     def inspect
133:       a = []
134:       a << uri.inspect if uri
135:       if (oo = opts[:orig_opts]) && !oo.empty?
136:         a << oo.inspect
137:       end
138:       "#<#{self.class}: #{a.join(' ')}>"
139:     end
listen(channels, opts={}, &block) click to toggle source

Listens on the given channel (or multiple channels if channel is an array), waiting for notifications. After a notification is received, or the timeout has passed, stops listening to the channel. Options:

:after_listen

An object that responds to call that is called with the underlying connection after the LISTEN statement is sent, but before the connection starts waiting for notifications.

:loop

Whether to continually wait for notifications, instead of just waiting for a single notification. If this option is given, a block must be provided. If this object responds to call, it is called with the underlying connection after each notification is received (after the block is called). If a :timeout option is used, and a callable object is given, the object will also be called if the timeout expires. If :loop is used and you want to stop listening, you can either break from inside the block given to #, or you can throw :stop from inside the :loop object’s call method or the block.

:server

The server on which to listen, if the sharding support is being used.

:timeout

How long to wait for a notification, in seconds (can provide a float value for fractional seconds). If not given or nil, waits indefinitely.

This method is only supported if pg is used as the underlying ruby driver. It returns the channel the notification was sent to (as a string), unless :loop was used, in which case it returns nil. If a block is given, it is yielded 3 arguments:

  • the channel the notification was sent to (as a string)

  • the backend pid of the notifier (as an integer),

  • and the payload of the notification (as a string or nil).

     # File lib/sequel/adapters/postgres.rb, line 384
384:         def listen(channels, opts={}, &block)
385:           check_database_errors do
386:             synchronize(opts[:server]) do |conn|
387:               begin
388:                 channels = Array(channels)
389:                 channels.each{|channel| conn.execute("LISTEN #{channel}")}
390:                 opts[:after_listen].call(conn) if opts[:after_listen]
391:                 timeout = opts[:timeout] ? [opts[:timeout]] : []
392:                 if l = opts[:loop]
393:                   raise Error, 'calling #listen with :loop requires a block' unless block
394:                   loop_call = l.respond_to?(:call)
395:                   catch(:stop) do
396:                     loop do
397:                       conn.wait_for_notify(*timeout, &block)
398:                       l.call(conn) if loop_call
399:                     end
400:                   end
401:                   nil
402:                 else
403:                   conn.wait_for_notify(*timeout, &block)
404:                 end
405:               ensure
406:                 conn.execute("UNLISTEN *")
407:               end
408:             end
409:           end
410:         end
literal(v) click to toggle source

Proxy the literal call to the dataset.

  DB.literal(1) # 1
  DB.literal(:a) # a
  DB.literal('a') # 'a'
     # File lib/sequel/database/misc.rb, line 146
146:     def literal(v)
147:       schema_utility_dataset.literal(v)
148:     end
load_schema_cache(file) click to toggle source

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

    # File lib/sequel/extensions/schema_caching.rb, line 65
65:     def load_schema_cache(file)
66:       @schemas = Marshal.load(File.read(file))
67:       nil
68:     end
load_schema_cache?(file) click to toggle source

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

    # File lib/sequel/extensions/schema_caching.rb, line 72
72:     def load_schema_cache?(file)
73:       load_schema_cache(file) if File.exist?(file)
74:     end
log_exception(exception, message) click to toggle source

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

    # File lib/sequel/database/logging.rb, line 21
21:     def log_exception(exception, message)
22:       log_each(:error, "#{exception.class}: #{exception.message.strip}: #{message}")
23:     end
log_info(message, args=nil) click to toggle source

Log a message at level info to all loggers.

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

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

    # File lib/sequel/database/logging.rb, line 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
logger=(logger) click to toggle source

Remove any existing loggers and just use the given logger:

  DB.logger = Logger.new($stdout)
    # File lib/sequel/database/logging.rb, line 49
49:     def logger=(logger)
50:       @loggers = Array(logger)
51:     end
prepared_statement(name) click to toggle source

Synchronize access to the prepared statements cache.

     # File lib/sequel/database/misc.rb, line 151
151:     def prepared_statement(name)
152:       Sequel.synchronize{prepared_statements[name]}
153:     end
query(&block) click to toggle source

Return a dataset modified by the query block

    # File lib/sequel/extensions/query.rb, line 8
 8:     def query(&block)
 9:       dataset.query(&block)
10:     end
quote_identifiers=(v) click to toggle source

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"
     # File lib/sequel/database/dataset_defaults.rb, line 155
155:     def quote_identifiers=(v)
156:       reset_schema_utility_dataset
157:       @quote_identifiers = v
158:     end
quote_identifiers?() click to toggle source

Returns true if the database quotes identifiers.

     # File lib/sequel/database/dataset_defaults.rb, line 161
161:     def quote_identifiers?
162:       return @quote_identifiers unless @quote_identifiers.nil?
163:       @quote_identifiers = @opts.fetch(:quote_identifiers, (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers))
164:     end
remove_servers(*servers) click to toggle source

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

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

  DB.remove_servers(:f1, :f2)
     # File lib/sequel/database/connecting.rb, line 195
195:     def remove_servers(*servers)
196:       if h = @opts[:servers]
197:         servers.flatten.each{|s| Sequel.synchronize{h.delete(s)}}
198:         @pool.remove_servers(servers)
199:       end
200:     end
rename_column(table, *args) click to toggle source

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

  DB.rename_column :items, :cntr, :counter

See alter_table.

     # File lib/sequel/database/schema_methods.rb, line 298
298:     def rename_column(table, *args)
299:       alter_table(table) {rename_column(*args)}
300:     end
rename_table(name, new_name) click to toggle source

Renames a table:

  DB.tables #=> [:items]
  DB.rename_table :items, :old_items
  DB.tables #=> [:old_items]
     # File lib/sequel/database/schema_methods.rb, line 286
286:     def rename_table(name, new_name)
287:       execute_ddl(rename_table_sql(name, new_name))
288:       remove_cached_schema(name)
289:       nil
290:     end
reset_conversion_procs() click to toggle source

Reset the database’s conversion procs, requires a server query if there any named types.

     # File lib/sequel/adapters/postgres.rb, line 415
415:       def reset_conversion_procs
416:         synchronize{|conn| @conversion_procs = get_conversion_procs(conn)}
417:       end
run(sql, opts={}) click to toggle source

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

:server

The server to run the SQL on.

  DB.run("SET some_server_variable = 42")
     # File lib/sequel/database/query.rb, line 134
134:     def run(sql, opts={})
135:       execute_ddl(sql, opts)
136:       nil
137:     end
schema(table, opts={}) click to toggle source

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}]]
     # File lib/sequel/database/query.rb, line 179
179:     def schema(table, opts={})
180:       raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true)
181: 
182:       opts = opts.dup
183:       if table.is_a?(Dataset)
184:         o = table.opts
185:         from = o[:from]
186:         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)
187:         tab = table.first_source_table
188:         sch, table_name = schema_and_table(tab)
189:         quoted_name = table.literal(tab)
190:         opts[:dataset] = table
191:       else
192:         sch, table_name = schema_and_table(table)
193:         quoted_name = quote_schema_table(table)
194:       end
195:       opts[:schema] = sch if sch && !opts.include?(:schema)
196: 
197:       Sequel.synchronize{@schemas.delete(quoted_name)} if opts[:reload]
198:       return Sequel.synchronize{@schemas[quoted_name]} if @schemas[quoted_name]
199: 
200:       cols = schema_parse_table(table_name, opts)
201:       raise(Error, 'schema parsing returned no columns, table probably doesn\t exist') if cols.nil? || cols.empty?
202:       cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])}
203:       Sequel.synchronize{@schemas[quoted_name] = cols} if cache_schema
204:       cols
205:     end
select(*args, &block) click to toggle source

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
    # File lib/sequel/database/dataset.rb, line 65
65:     def select(*args, &block)
66:       dataset.select(*args, &block)
67:     end
serial_primary_key_options() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 157
157:     def serial_primary_key_options
158:       {:primary_key => true, :type => Integer, :auto_increment => true}
159:     end
server_version(server=nil) click to toggle source

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

     # File lib/sequel/adapters/mysql.rb, line 167
167:       def server_version(server=nil)
168:         @server_version ||= (synchronize(server){|conn| conn.server_version if conn.respond_to?(:server_version)} || super)
169:       end
servers() click to toggle source

An array of servers/shards for this Database object.

  DB.servers # Unsharded: => [:default]
  DB.servers # Sharded:   => [:default, :server1, :server2]
     # File lib/sequel/database/connecting.rb, line 206
206:     def servers
207:       pool.servers
208:     end
set_column_default(table, *args) click to toggle source

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

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

See alter_table.

     # File lib/sequel/database/schema_methods.rb, line 307
307:     def set_column_default(table, *args)
308:       alter_table(table) {set_column_default(*args)}
309:     end
set_column_type(table, *args) click to toggle source

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

  DB.set_column_type :items, :price, :float

See alter_table.

     # File lib/sequel/database/schema_methods.rb, line 316
316:     def set_column_type(table, *args)
317:       alter_table(table) {set_column_type(*args)}
318:     end
set_prepared_statement(name, ps) click to toggle source

Cache the prepared statement object at the given name.

     # File lib/sequel/database/misc.rb, line 162
162:     def set_prepared_statement(name, ps)
163:       Sequel.synchronize{prepared_statements[name] = ps}
164:     end
single_threaded?() click to toggle source

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

     # File lib/sequel/database/connecting.rb, line 211
211:     def single_threaded?
212:       @single_threaded
213:     end
supports_create_table_if_not_exists?() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 168
168:     def supports_create_table_if_not_exists?
169:       false
170:     end
supports_drop_table_if_exists?() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 174
174:     def supports_drop_table_if_exists?
175:       supports_create_table_if_not_exists?
176:     end
supports_prepared_transactions?() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 180
180:     def supports_prepared_transactions?
181:       false
182:     end
supports_savepoints?() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 185
185:     def supports_savepoints?
186:       false
187:     end
supports_savepoints_in_prepared_transactions?() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 191
191:     def supports_savepoints_in_prepared_transactions?
192:       supports_prepared_transactions? && supports_savepoints?
193:     end
supports_transaction_isolation_levels?() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 196
196:     def supports_transaction_isolation_levels?
197:       false
198:     end
supports_transactional_ddl?() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 201
201:     def supports_transactional_ddl?
202:       false
203:     end
synchronize(server=nil) click to toggle source

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
     # File lib/sequel/database/connecting.rb, line 228
228:       def synchronize(server=nil)
229:         @pool.hold(server || :default){|conn| yield conn}
230:       end
synchronize(server=nil, &block) click to toggle source
     # File lib/sequel/database/connecting.rb, line 232
232:       def synchronize(server=nil, &block)
233:         @pool.hold(server || :default, &block)
234:       end
table_exists?(name) click to toggle source

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

  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.

     # File lib/sequel/database/query.rb, line 215
215:     def table_exists?(name)
216:       sch, table_name = schema_and_table(name)
217:       name = SQL::QualifiedIdentifier.new(sch, table_name) if sch
218:       _table_exists?(from(name))
219:       true
220:     rescue DatabaseError
221:       false
222:     end
tables(opts={}) click to toggle source

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

  DB.tables # => [:albums, :artists]
     # File lib/sequel/database/query.rb, line 227
227:     def tables(opts={})
228:       raise NotImplemented, "#tables should be overridden by adapters"
229:     end
test_connection(server=nil) click to toggle source

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

     # File lib/sequel/database/connecting.rb, line 241
241:     def test_connection(server=nil)
242:       synchronize(server){|conn|}
243:       true
244:     end
timezone() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 206
206:     def timezone
207:       @timezone || Sequel.database_timezone
208:     end
to_application_timestamp(value) click to toggle source

If convert_infinite_timestamps is true and the value is infinite, return an appropriate value based on the convert_infinite_timestamps setting.

     # File lib/sequel/adapters/postgres.rb, line 421
421:       def to_application_timestamp(value)
422:         if c = convert_infinite_timestamps
423:           case value
424:           when *INFINITE_TIMESTAMP_STRINGS
425:             infinite_timestamp_value(value)
426:           else
427:             super
428:           end
429:         else
430:           super
431:         end
432:       end
to_application_timestamp(v) click to toggle source

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.

     # File lib/sequel/database/misc.rb, line 213
213:     def to_application_timestamp(v)
214:       Sequel.convert_timestamp(v, timezone)
215:     end
transaction(opts={}, &block) click to toggle source

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

The following general options are respected:

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

:prepare

A string to use as the transaction identifier for a prepared transaction (two-phase commit), if the database/adapter supports prepared transactions.

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

     # File lib/sequel/database/query.rb, line 260
260:     def transaction(opts={}, &block)
261:       synchronize(opts[:server]) do |conn|
262:         return yield(conn) if already_in_transaction?(conn, opts)
263:         _transaction(conn, opts, &block)
264:       end
265:     end
typecast_value(column_type, value) click to toggle source

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

     # File lib/sequel/database/misc.rb, line 222
222:     def typecast_value(column_type, value)
223:       return nil if value.nil?
224:       meth = "typecast_value_#{column_type}"
225:       begin
226:         respond_to?(meth, true) ? send(meth, value) : value
227:       rescue ArgumentError, TypeError => e
228:         raise Sequel.convert_exception_class(e, InvalidValue)
229:       end
230:     end
uri() click to toggle source

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

     # File lib/sequel/database/misc.rb, line 234
234:     def uri
235:       opts[:uri]
236:     end
url() click to toggle source

Explicit alias of uri for easier subclassing.

     # File lib/sequel/database/misc.rb, line 239
239:     def url
240:       uri
241:     end
views(opts={}) click to toggle source

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

  DB.views # => [:gold_albums, :artists_with_many_albums]
     # File lib/sequel/database/query.rb, line 270
270:     def views(opts={})
271:       raise NotImplemented, "#views should be overridden by adapters"
272:     end

Private Instance Methods

_execute(conn, sql, opts) click to toggle source

Execute the given SQL on the given connection. If the :type option is :select, yield the result of the query, otherwise yield the connection if a block is given.

     # File lib/sequel/adapters/mysql.rb, line 176
176:       def _execute(conn, sql, opts)
177:         begin
178:           r = log_yield((log_sql = opts[:log_sql]) ? sql + log_sql : sql){conn.query(sql)}
179:           if opts[:type] == :select
180:             yield r if r
181:           elsif block_given?
182:             yield conn
183:           end
184:           if conn.respond_to?(:more_results?)
185:             while conn.more_results? do
186:               if r
187:                 r.free
188:                 r = nil
189:               end
190:               begin
191:                 conn.next_result
192:                 r = conn.use_result
193:               rescue Mysql::Error => e
194:                 raise_error(e, :disconnect=>true) if MYSQL_DATABASE_DISCONNECT_ERRORS.match(e.message)
195:                 break
196:               end
197:               yield r if opts[:type] == :select
198:             end
199:           end
200:         rescue Mysql::Error => e
201:           raise_error(e)
202:         ensure
203:           r.free if r
204:           # Use up all results to avoid a commands out of sync message.
205:           if conn.respond_to?(:more_results?)
206:             while conn.more_results? do
207:               begin
208:                 conn.next_result
209:                 r = conn.use_result
210:               rescue Mysql::Error => e
211:                 raise_error(e, :disconnect=>true) if MYSQL_DATABASE_DISCONNECT_ERRORS.match(e.message)
212:                 break
213:               end
214:               r.free if r
215:             end
216:           end
217:         end
218:       end
_execute(conn, sql, opts, &block) click to toggle source

Execute the given SQL string or prepared statement on the connection object.

     # File lib/sequel/adapters/postgres.rb, line 437
437:       def _execute(conn, sql, opts, &block)
438:         if sql.is_a?(Symbol)
439:           execute_prepared_statement(conn, sql, opts, &block)
440:         else
441:           conn.execute(sql, opts[:arguments], &block)
442:         end
443:       end
_table_exists?(ds) click to toggle source

Should raise an error if the table doesn’t not exist, and not raise an error if the table does exist.

     # File lib/sequel/database/query.rb, line 278
278:     def _table_exists?(ds)
279:       ds.get(Sequel::NULL)
280:     end
_trans(conn) click to toggle source

Synchronize access to the current transactions, returning the hash of options for the current transaction (if any)

     # File lib/sequel/database/query.rb, line 322
322:     def _trans(conn)
323:       Sequel.synchronize{@transactions[conn]}
324:     end
_transaction(conn, opts={}) click to toggle source

Internal generic transaction method. Any exception raised by the given block will cause the transaction to be rolled back. If the exception is not a Sequel::Rollback, the error will be reraised. If no exception occurs inside the block, the transaction is commited.

     # File lib/sequel/database/query.rb, line 286
286:     def _transaction(conn, opts={})
287:       rollback = opts[:rollback]
288:       begin
289:         add_transaction(conn, opts)
290:         begin_transaction(conn, opts)
291:         if rollback == :always
292:           begin
293:             yield(conn)
294:           rescue Exception => e1
295:             raise e1
296:           ensure
297:             raise ::Sequel::Rollback unless e1
298:           end
299:         else
300:           yield(conn)
301:         end
302:       rescue Exception => e
303:         begin
304:           rollback_transaction(conn, opts)
305:         rescue Exception => e3
306:           raise_error(e3, :classes=>database_error_classes, :conn=>conn)
307:         end
308:         transaction_error(e, :conn=>conn, :rollback=>rollback)
309:       ensure
310:         begin
311:           committed = commit_or_rollback_transaction(e, conn, opts)
312:         rescue Exception => e2
313:           raise_error(e2, :classes=>database_error_classes, :conn=>conn)
314:         ensure
315:           remove_transaction(conn, committed)
316:         end
317:       end
318:     end
add_transaction(conn, opts) click to toggle source

Add the current thread to the list of active transactions

     # File lib/sequel/database/query.rb, line 327
327:     def add_transaction(conn, opts)
328:       if supports_savepoints?
329:         unless _trans(conn)
330:           if (prep = opts[:prepare]) && supports_prepared_transactions?
331:             Sequel.synchronize{@transactions[conn] = {:savepoint_level=>0, :prepare=>prep}}
332:           else
333:             Sequel.synchronize{@transactions[conn] = {:savepoint_level=>0}}
334:           end
335:         end
336:       elsif (prep = opts[:prepare]) && supports_prepared_transactions?
337:         Sequel.synchronize{@transactions[conn] = {:prepare => prep}}
338:       else
339:         Sequel.synchronize{@transactions[conn] = {}}
340:       end
341:     end
affected_rows(conn) click to toggle source

Try to get an accurate number of rows matched using the query info. Fall back to affected_rows if there was no match, but that may be inaccurate.

     # File lib/sequel/adapters/mysql.rb, line 223
223:       def affected_rows(conn)
224:         s = conn.info
225:         if s && s =~ AFFECTED_ROWS_RE
226:           $1.to_i
227:         else
228:           conn.affected_rows
229:         end
230:       end
after_transaction_commit(conn) click to toggle source

Call all stored after_commit blocks for the given transaction

     # File lib/sequel/database/query.rb, line 344
344:     def after_transaction_commit(conn)
345:       if ary = _trans(conn)[:after_commit]
346:         ary.each{|b| b.call}
347:       end
348:     end
after_transaction_rollback(conn) click to toggle source

Call all stored after_rollback blocks for the given transaction

     # File lib/sequel/database/query.rb, line 351
351:     def after_transaction_rollback(conn)
352:       if ary = _trans(conn)[:after_rollback]
353:         ary.each{|b| b.call}
354:       end
355:     end
already_in_transaction?(conn, opts) click to toggle source

Whether the current thread/connection is already inside a transaction

     # File lib/sequel/database/query.rb, line 358
358:     def already_in_transaction?(conn, opts)
359:       _trans(conn) && (!supports_savepoints? || !opts[:savepoint])
360:     end
alter_table_sql(table, op) click to toggle source

The SQL to execute to modify the DDL for the given table name. op should be one of the operations returned by the AlterTableGenerator.

     # File lib/sequel/database/schema_methods.rb, line 329
329:     def alter_table_sql(table, op)
330:       quoted_name = quote_identifier(op[:name]) if op[:name]
331:       alter_table_op = case op[:op]
332:       when :add_column
333:         "ADD COLUMN #{column_definition_sql(op)}"
334:       when :drop_column
335:         "DROP COLUMN #{quoted_name}#{' CASCADE' if op[:cascade]}"
336:       when :rename_column
337:         "RENAME COLUMN #{quoted_name} TO #{quote_identifier(op[:new_name])}"
338:       when :set_column_type
339:         "ALTER COLUMN #{quoted_name} TYPE #{type_literal(op)}"
340:       when :set_column_default
341:         "ALTER COLUMN #{quoted_name} SET DEFAULT #{literal(op[:default])}"
342:       when :set_column_null
343:         "ALTER COLUMN #{quoted_name} #{op[:null] ? 'DROP' : 'SET'} NOT NULL"
344:       when :add_index
345:         return index_definition_sql(table, op)
346:       when :drop_index
347:         return drop_index_sql(table, op)
348:       when :add_constraint
349:         "ADD #{constraint_definition_sql(op)}"
350:       when :drop_constraint
351:         "DROP CONSTRAINT #{quoted_name}#{' CASCADE' if op[:cascade]}"
352:       else
353:         raise Error, "Unsupported ALTER TABLE operation"
354:       end
355:       "ALTER TABLE #{quote_schema_table(table)} #{alter_table_op}"
356:     end
alter_table_sql_list(table, operations) click to toggle source

Array of SQL DDL modification statements for the given table, corresponding to the DDL changes specified by the operations.

     # File lib/sequel/database/schema_methods.rb, line 360
360:     def alter_table_sql_list(table, operations)
361:       operations.map{|op| alter_table_sql(table, op)}
362:     end
apply_alter_table(name, ops) click to toggle source

Apply the changes in the given alter table ops to the table given by name.

     # File lib/sequel/database/schema_methods.rb, line 323
323:     def apply_alter_table(name, ops)
324:       alter_table_sql_list(name, ops).flatten.each{|sql| execute_ddl(sql)}
325:     end
auto_increment_sql() click to toggle source

The SQL string specify the autoincrement property, generally used by primary keys.

     # File lib/sequel/database/schema_methods.rb, line 366
366:     def auto_increment_sql
367:       AUTOINCREMENT
368:     end
begin_new_transaction(conn, opts) click to toggle source

Start a new database connection on the given connection

     # File lib/sequel/database/query.rb, line 368
368:     def begin_new_transaction(conn, opts)
369:       log_connection_execute(conn, begin_transaction_sql)
370:       set_transaction_isolation(conn, opts)
371:     end
begin_savepoint_sql(depth) click to toggle source

SQL to start a new savepoint

     # File lib/sequel/database/query.rb, line 363
363:     def begin_savepoint_sql(depth)
364:       SQL_SAVEPOINT % depth
365:     end
begin_transaction(conn, opts={}) click to toggle source

Start a new database transaction or a new savepoint on the given connection.

     # File lib/sequel/database/query.rb, line 374
374:     def begin_transaction(conn, opts={})
375:       if supports_savepoints?
376:         th = _trans(conn)
377:         if (depth = th[:savepoint_level]) > 0
378:           log_connection_execute(conn, begin_savepoint_sql(depth))
379:         else
380:           begin_new_transaction(conn, opts)
381:         end
382:         th[:savepoint_level] += 1
383:       else
384:         begin_new_transaction(conn, opts)
385:       end
386:     end
begin_transaction_sql() click to toggle source

SQL to BEGIN a transaction.

     # File lib/sequel/database/query.rb, line 389
389:     def begin_transaction_sql
390:       SQL_BEGIN
391:     end
blank_object?(obj) click to toggle source

Returns true when the object is considered blank. The only objects that are blank are nil, false, strings with all whitespace, and ones that respond true to empty?

     # File lib/sequel/database/misc.rb, line 249
249:     def blank_object?(obj)
250:       return obj.blank? if obj.respond_to?(:blank?)
251:       case obj
252:       when NilClass, FalseClass
253:         true
254:       when Numeric, TrueClass
255:         false
256:       when String
257:         obj.strip.empty?
258:       else
259:         obj.respond_to?(:empty?) ? obj.empty? : false
260:       end
261:     end
check_database_errors() click to toggle source

Convert exceptions raised from the block into DatabaseErrors.

     # File lib/sequel/adapters/postgres.rb, line 446
446:       def check_database_errors
447:         begin
448:           yield
449:         rescue => e
450:           raise_error(e, :classes=>CONVERTED_EXCEPTIONS)
451:         end
452:       end
column_definition_auto_increment_sql(sql, column) click to toggle source

Add auto increment SQL fragment to column creation SQL.

     # File lib/sequel/database/schema_methods.rb, line 383
383:     def column_definition_auto_increment_sql(sql, column)
384:       sql << " #{auto_increment_sql}" if column[:auto_increment]
385:     end
column_definition_collate_sql(sql, column) click to toggle source

Add collate SQL fragment to column creation SQL.

     # File lib/sequel/database/schema_methods.rb, line 388
388:     def column_definition_collate_sql(sql, column)
389:       sql << " COLLATE #{column[:collate]}" if column[:collate]
390:     end
column_definition_default_sql(sql, column) click to toggle source

Add default SQL fragment to column creation SQL.

     # File lib/sequel/database/schema_methods.rb, line 393
393:     def column_definition_default_sql(sql, column)
394:       sql << " DEFAULT #{literal(column[:default])}" if column.include?(:default)
395:     end
column_definition_null_sql(sql, column) click to toggle source

Add null/not null SQL fragment to column creation SQL.

     # File lib/sequel/database/schema_methods.rb, line 398
398:     def column_definition_null_sql(sql, column)
399:       null = column.fetch(:null, column[:allow_null])
400:       sql << NOT_NULL if null == false
401:       sql << NULL if null == true
402:     end
column_definition_order() click to toggle source

The order of the column definition, as an array of symbols.

     # File lib/sequel/database/schema_methods.rb, line 371
371:     def column_definition_order
372:       self.class.const_get(:COLUMN_DEFINITION_ORDER)
373:     end
column_definition_primary_key_sql(sql, column) click to toggle source

Add primary key SQL fragment to column creation SQL.

     # File lib/sequel/database/schema_methods.rb, line 405
405:     def column_definition_primary_key_sql(sql, column)
406:       sql << PRIMARY_KEY if column[:primary_key]
407:     end
column_definition_references_sql(sql, column) click to toggle source

Add foreign key reference SQL fragment to column creation SQL.

     # File lib/sequel/database/schema_methods.rb, line 410
410:     def column_definition_references_sql(sql, column)
411:       sql << column_references_column_constraint_sql(column) if column[:table]
412:     end
column_definition_sql(column) click to toggle source

SQL DDL fragment containing the column creation SQL for the given column.

     # File lib/sequel/database/schema_methods.rb, line 376
376:     def column_definition_sql(column)
377:       sql = "#{quote_identifier(column[:name])} #{type_literal(column)}"
378:       column_definition_order.each{|m| send(:"column_definition_#{m}_sql", sql, column)}
379:       sql
380:     end
column_definition_unique_sql(sql, column) click to toggle source

Add unique constraint SQL fragment to column creation SQL.

     # File lib/sequel/database/schema_methods.rb, line 415
415:     def column_definition_unique_sql(sql, column)
416:       sql << UNIQUE if column[:unique]
417:     end
column_list_sql(generator) click to toggle source

SQL for all given columns, used inside a CREATE TABLE block.

     # File lib/sequel/database/schema_methods.rb, line 420
420:     def column_list_sql(generator)
421:       (generator.columns.map{|c| column_definition_sql(c)} + generator.constraints.map{|c| constraint_definition_sql(c)}).join(COMMA_SEPARATOR)
422:     end
column_references_column_constraint_sql(column) click to toggle source

SQL DDL fragment for column foreign key references (column constraints)

     # File lib/sequel/database/schema_methods.rb, line 425
425:     def column_references_column_constraint_sql(column)
426:       column_references_sql(column)
427:     end
column_references_sql(column) click to toggle source

SQL DDL fragment for column foreign key references

     # File lib/sequel/database/schema_methods.rb, line 430
430:     def column_references_sql(column)
431:       sql = " REFERENCES #{quote_schema_table(column[:table])}"
432:       sql << "(#{Array(column[:key]).map{|x| quote_identifier(x)}.join(COMMA_SEPARATOR)})" if column[:key]
433:       sql << " ON DELETE #{on_delete_clause(column[:on_delete])}" if column[:on_delete]
434:       sql << " ON UPDATE #{on_update_clause(column[:on_update])}" if column[:on_update]
435:       sql << " DEFERRABLE INITIALLY DEFERRED" if column[:deferrable]
436:       sql
437:     end
column_references_table_constraint_sql(constraint) click to toggle source

SQL DDL fragment for table foreign key references (table constraints)

     # File lib/sequel/database/schema_methods.rb, line 440
440:     def column_references_table_constraint_sql(constraint)
441:       "FOREIGN KEY #{literal(constraint[:columns])}#{column_references_sql(constraint)}"
442:     end
column_schema_to_generator_opts(name, schema, options) click to toggle source

Convert the given name and parsed database schema into an array with a method name and arguments to it to pass to a Schema::Generator to recreate the column.

     # File lib/sequel/extensions/schema_dumper.rb, line 118
118:     def column_schema_to_generator_opts(name, schema, options)
119:       if options[:single_pk] && schema_autoincrementing_primary_key?(schema)
120:         type_hash = options[:same_db] ? {:type=>schema[:db_type]} : column_schema_to_ruby_type(schema)
121:         [:table, :key, :on_delete, :on_update, :deferrable].each{|f| type_hash[f] = schema[f] if schema[f]}
122:         if type_hash == {:type=>Integer} || type_hash == {:type=>"integer"}
123:           [:primary_key, name]
124:         else
125:           [:primary_key, name, type_hash]
126:         end
127:       else
128:         col_opts = options[:same_db] ? {:type=>schema[:db_type]} : column_schema_to_ruby_type(schema)
129:         type = col_opts.delete(:type)
130:         col_opts.delete(:size) if col_opts[:size].nil?
131:         col_opts[:default] = if schema[:ruby_default].nil?
132:           column_schema_to_ruby_default_fallback(schema[:default], options)
133:         else
134:           schema[:ruby_default]
135:         end
136:         col_opts.delete(:default) if col_opts[:default].nil?
137:         col_opts[:null] = false if schema[:allow_null] == false
138:         if table = schema[:table]
139:           [:key, :on_delete, :on_update, :deferrable].each{|f| col_opts[f] = schema[f] if schema[f]}
140:           [:foreign_key, name, table, col_opts]
141:         else
142:           [:column, name, type, col_opts]
143:         end
144:       end
145:     end
column_schema_to_ruby_default(default, type) click to toggle source

Convert the given default, which should be a database specific string, into a ruby object.

     # File lib/sequel/database/query.rb, line 395
395:     def column_schema_to_ruby_default(default, type)
396:       return if default.nil?
397:       orig_default = default
398:       if database_type == :postgres and m = POSTGRES_DEFAULT_RE.match(default)
399:         default = m[1] || m[2]
400:       end
401:       if database_type == :mssql and m = MSSQL_DEFAULT_RE.match(default)
402:         default = m[1] || m[2]
403:       end
404:       if [:string, :blob, :date, :datetime, :time, :enum].include?(type)
405:         if database_type == :mysql
406:           return if [:date, :datetime, :time].include?(type) && MYSQL_TIMESTAMP_RE.match(default)
407:           orig_default = default = "'#{default.gsub("'", "''").gsub('\\', '\\\\')}'"
408:         end
409:         return unless m = STRING_DEFAULT_RE.match(default)
410:         default = m[1].gsub("''", "'")
411:       end
412:       res = begin
413:         case type
414:         when :boolean
415:           case default 
416:           when /[f0]/
417:             false
418:           when /[t1]/
419:             true
420:           end
421:         when :string, :enum
422:           default
423:         when :blob
424:           Sequel::SQL::Blob.new(default)
425:         when :integer
426:           Integer(default)
427:         when :float
428:           Float(default)
429:         when :date
430:           Sequel.string_to_date(default)
431:         when :datetime
432:           DateTime.parse(default)
433:         when :time
434:           Sequel.string_to_time(default)
435:         when :decimal
436:           BigDecimal.new(default)
437:         end
438:       rescue
439:         nil
440:       end
441:     end
column_schema_to_ruby_default_fallback(default, options) click to toggle source

If a database default exists and can’t be converted, return the string with the inspect method modified so that .lit is always appended after it, only if the :same_db option is used.

     # File lib/sequel/extensions/schema_dumper.rb, line 106
106:     def column_schema_to_ruby_default_fallback(default, options)
107:       if default.is_a?(String) && options[:same_db] && use_column_schema_to_ruby_default_fallback?
108:         default = default.to_s
109:         def default.inspect
110:           "#{super}.lit"  # core_sql use
111:         end
112:         default
113:       end
114:     end
column_schema_to_ruby_type(schema) click to toggle source

Convert the column schema information to a hash of column options, one of which must be :type. The other options added should modify that type (e.g. :size). If a database type is not recognized, return it as a String type.

     # File lib/sequel/extensions/schema_dumper.rb, line 150
150:     def column_schema_to_ruby_type(schema)
151:       case t = schema[:db_type].downcase
152:       when /\A(medium|small)?int(?:eger)?(?:\((\d+)\))?( unsigned)?\z/
153:         if !$1 && $2 && $2.to_i >= 10 && $3
154:           # Unsigned integer type with 10 digits can potentially contain values which
155:           # don't fit signed integer type, so use bigint type in target database.
156:           {:type=>Bignum}
157:         else
158:           {:type=>Integer}
159:         end
160:       when /\Atinyint(?:\((\d+)\))?(?: unsigned)?\z/
161:         {:type =>schema[:type] == :boolean ? TrueClass : Integer}
162:       when /\Abigint(?:\((?:\d+)\))?(?: unsigned)?\z/
163:         {:type=>Bignum}
164:       when /\A(?:real|float|double(?: precision)?)\z/
165:         {:type=>Float}
166:       when 'boolean'
167:         {:type=>TrueClass}
168:       when /\A(?:(?:tiny|medium|long|n)?text|clob)\z/
169:         {:type=>String, :text=>true}
170:       when 'date'
171:         {:type=>Date}
172:       when /\A(?:small)?datetime\z/
173:         {:type=>DateTime}
174:       when /\Atimestamp(?:\((\d+)\))?(?: with(?:out)? time zone)?\z/
175:         {:type=>DateTime, :size=>($1.to_i if $1)}
176:       when /\Atime(?: with(?:out)? time zone)?\z/
177:         {:type=>Time, :only_time=>true}
178:       when /\An?char(?:acter)?(?:\((\d+)\))?\z/
179:         {:type=>String, :size=>($1.to_i if $1), :fixed=>true}
180:       when /\A(?:n?varchar|character varying|bpchar|string)(?:\((\d+)\))?\z/
181:         {:type=>String, :size=>($1.to_i if $1)}
182:       when /\A(?:small)?money\z/
183:         {:type=>BigDecimal, :size=>[19,2]}
184:       when /\A(?:decimal|numeric|number)(?:\((\d+)(?:,\s*(\d+))?\))?\z/
185:         s = [($1.to_i if $1), ($2.to_i if $2)].compact
186:         {:type=>BigDecimal, :size=>(s.empty? ? nil : s)}
187:       when /\A(?:bytea|(?:tiny|medium|long)?blob|(?:var)?binary)(?:\((\d+)\))?\z/
188:         {:type=>File, :size=>($1.to_i if $1)}
189:       when /\A(?:year|(?:int )?identity)\z/
190:         {:type=>Integer}
191:       else
192:         {:type=>String}
193:       end
194:     end
commit_or_rollback_transaction(exception, conn, opts) click to toggle source

Whether to commit the current transaction. On ruby 1.8 and rubinius, Thread.current.status is checked because Thread#kill skips rescue blocks (so exception would be nil), but the transaction should still be rolled back.

     # File lib/sequel/database/query.rb, line 448
448:       def commit_or_rollback_transaction(exception, conn, opts)
449:         if exception
450:           false
451:         else
452:           if Thread.current.status == 'aborting'
453:             rollback_transaction(conn, opts)
454:             false
455:           else
456:             commit_transaction(conn, opts)
457:             true
458:           end
459:         end
460:       end
commit_or_rollback_transaction(exception, conn, opts) click to toggle source

Whether to commit the current transaction. On ruby 1.9 and JRuby, transactions will be committed if Thread#kill is used on an thread that has a transaction open, and there isn’t a work around.

     # File lib/sequel/database/query.rb, line 465
465:       def commit_or_rollback_transaction(exception, conn, opts)
466:         if exception
467:           false
468:         else
469:           commit_transaction(conn, opts)
470:           true
471:         end
472:       end
commit_savepoint_sql(depth) click to toggle source

SQL to commit a savepoint

     # File lib/sequel/database/query.rb, line 476
476:     def commit_savepoint_sql(depth)
477:       SQL_RELEASE_SAVEPOINT % depth
478:     end
commit_transaction(conn, opts={}) click to toggle source

Commit the active transaction on the connection

     # File lib/sequel/database/query.rb, line 481
481:     def commit_transaction(conn, opts={})
482:       if supports_savepoints?
483:         depth = _trans(conn)[:savepoint_level]
484:         log_connection_execute(conn, depth > 1 ? commit_savepoint_sql(depth-1) : commit_transaction_sql)
485:       else
486:         log_connection_execute(conn, commit_transaction_sql)
487:       end
488:     end
commit_transaction_sql() click to toggle source

SQL to COMMIT a transaction.

     # File lib/sequel/database/query.rb, line 491
491:     def commit_transaction_sql
492:       SQL_COMMIT
493:     end
connection_configuration_sqls() click to toggle source

Set the DateStyle to ISO if configured, for faster date parsing.

     # File lib/sequel/adapters/postgres.rb, line 455
455:       def connection_configuration_sqls
456:         sqls = super
457:         sqls << "SET DateStyle = 'ISO'" if Postgres.use_iso_date_format
458:         sqls
459:       end
connection_execute_method() click to toggle source

MySQL connections use the query method to execute SQL without a result

     # File lib/sequel/adapters/mysql.rb, line 233
233:       def connection_execute_method
234:         :query
235:       end
connection_execute_method() click to toggle source

Method called on the connection object to execute SQL on the database, used by the transaction code.

     # File lib/sequel/database/query.rb, line 497
497:     def connection_execute_method
498:       :execute
499:     end
connection_pool_default_options() click to toggle source

The default options for the connection pool.

     # File lib/sequel/database/connecting.rb, line 249
249:     def connection_pool_default_options
250:       {}
251:     end
constraint_definition_sql(constraint) click to toggle source

SQL DDL fragment specifying a constraint on a table.

     # File lib/sequel/database/schema_methods.rb, line 445
445:     def constraint_definition_sql(constraint)
446:       sql = constraint[:name] ? "CONSTRAINT #{quote_identifier(constraint[:name])} " : ""
447:       case constraint[:type]
448:       when :check
449:         check = constraint[:check]
450:         sql << "CHECK #{filter_expr((check.is_a?(Array) && check.length == 1) ? check.first : check)}"
451:       when :primary_key
452:         sql << "PRIMARY KEY #{literal(constraint[:columns])}"
453:       when :foreign_key
454:         sql << column_references_table_constraint_sql(constraint)
455:       when :unique
456:         sql << "UNIQUE #{literal(constraint[:columns])}"
457:       else
458:         raise Error, "Invalid constriant type #{constraint[:type]}, should be :check, :primary_key, :foreign_key, or :unique"
459:       end
460:       sql
461:     end
convert_date_time(v) click to toggle source

If convert_invalid_date_time is nil, :nil, or :string and the conversion raises an InvalidValue exception, return v if :string and nil otherwise.

     # File lib/sequel/adapters/mysql.rb, line 240
240:       def convert_date_time(v)
241:         begin
242:           yield v
243:         rescue InvalidValue
244:           case @convert_invalid_date_time
245:           when nil, :nil
246:             nil
247:           when :string
248:             v
249:           else 
250:             raise
251:           end
252:         end
253:       end
create_table_as(name, sql, options) click to toggle source

Run a command to create the table with the given name from the given SELECT sql statement.

     # File lib/sequel/database/schema_methods.rb, line 487
487:     def create_table_as(name, sql, options)
488:       sql = sql.sql if sql.is_a?(Sequel::Dataset)
489:       run(create_table_as_sql(name, sql, options))
490:     end
create_table_as_sql(name, sql, options) click to toggle source

DDL statement for creating a table from the result of a SELECT statement. sql should be a string representing a SELECT query.

     # File lib/sequel/database/schema_methods.rb, line 494
494:     def create_table_as_sql(name, sql, options)
495:       "#{create_table_prefix_sql(name, options)} AS #{sql}"
496:     end
create_table_from_generator(name, generator, options) click to toggle source

Execute the create table statements using the generator.

     # File lib/sequel/database/schema_methods.rb, line 464
464:     def create_table_from_generator(name, generator, options)
465:       execute_ddl(create_table_sql(name, generator, options))
466:     end
create_table_indexes_from_generator(name, generator, options) click to toggle source

Execute the create index statements using the generator.

     # File lib/sequel/database/schema_methods.rb, line 469
469:     def create_table_indexes_from_generator(name, generator, options)
470:       e = options[:ignore_index_errors] || options[:if_not_exists]
471:       generator.indexes.each do |index|
472:         begin
473:           index_sql_list(name, [index]).each{|sql| execute_ddl(sql)}
474:         rescue Error
475:           raise unless e
476:         end
477:       end
478:     end
create_table_prefix_sql(name, options) click to toggle source

DDL statement for creating a table with the given name, columns, and options

     # File lib/sequel/database/schema_methods.rb, line 499
499:     def create_table_prefix_sql(name, options)
500:       "CREATE #{temporary_table_sql if options[:temp]}TABLE#{' IF NOT EXISTS' if options[:if_not_exists]} #{options[:temp] ? quote_identifier(name) : quote_schema_table(name)}"
501:     end
create_table_sql(name, generator, options) click to toggle source

DDL statement for creating a table with the given name, columns, and options

     # File lib/sequel/database/schema_methods.rb, line 481
481:     def create_table_sql(name, generator, options)
482:       "#{create_table_prefix_sql(name, options)} (#{column_list_sql(generator)})"
483:     end
database_error_classes() click to toggle source

Which transaction errors to translate, blank by default.

     # File lib/sequel/database/misc.rb, line 264
264:     def database_error_classes
265:       []
266:     end
database_error_classes() click to toggle source

The MySQL adapter main error class is Mysql::Error

     # File lib/sequel/adapters/mysql.rb, line 256
256:       def database_error_classes
257:         [Mysql::Error]
258:       end
database_name() click to toggle source

The database name when using the native adapter is always stored in the :database option.

     # File lib/sequel/adapters/mysql.rb, line 268
268:       def database_name
269:         @opts[:database]
270:       end
dataset_class_default() click to toggle source

The default dataset class to use for the database

     # File lib/sequel/database/dataset_defaults.rb, line 169
169:     def dataset_class_default
170:       self.class.const_get(:DatasetClass)
171:     end
default_index_name(table_name, columns) click to toggle source

Default index name for the table and columns, may be too long for certain databases.

     # File lib/sequel/database/schema_methods.rb, line 505
505:     def default_index_name(table_name, columns)
506:       schema, table = schema_and_table(table_name)
507:       "#{"#{schema}_" if schema and schema != default_schema}#{table}_#{columns.map{|c| [String, Symbol].any?{|cl| c.is_a?(cl)} ? c : literal(c).gsub(/\W/, '_')}.join(UNDERSCORE)}_index"
508:     end
default_schema_default() click to toggle source

The default value for default_schema.

     # File lib/sequel/database/dataset_defaults.rb, line 174
174:     def default_schema_default
175:       nil
176:     end
disconnect_connection(conn) click to toggle source

Disconnect given connection

     # File lib/sequel/adapters/postgres.rb, line 462
462:       def disconnect_connection(conn)
463:         begin
464:           conn.finish
465:         rescue PGError
466:         end
467:       end
disconnect_connection(c) click to toggle source

Closes given database connection.

     # File lib/sequel/adapters/mysql.rb, line 273
273:       def disconnect_connection(c)
274:         c.close
275:       rescue Mysql::Error
276:         nil
277:       end
disconnect_error?(e, opts) click to toggle source

Raise a disconnect error if the exception message matches the list of recognized exceptions.

     # File lib/sequel/adapters/mysql.rb, line 262
262:       def disconnect_error?(e, opts)
263:         super || (e.is_a?(::Mysql::Error) && MYSQL_DATABASE_DISCONNECT_ERRORS.match(e.message))
264:       end
disconnect_error?(exception, opts) click to toggle source

Return true if exception represents a disconnect error, false otherwise.

     # File lib/sequel/database/misc.rb, line 269
269:     def disconnect_error?(exception, opts)
270:       opts[:disconnect]
271:     end
drop_index_sql(table, op) click to toggle source

The SQL to drop an index for the table.

     # File lib/sequel/database/schema_methods.rb, line 511
511:     def drop_index_sql(table, op)
512:       "DROP INDEX #{quote_identifier(op[:name] || default_index_name(table, op[:columns]))}"
513:     end
drop_table_sql(name, options) click to toggle source

SQL DDL statement to drop the table with the given name.

     # File lib/sequel/database/schema_methods.rb, line 516
516:     def drop_table_sql(name, options)
517:       "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}"
518:     end
drop_view_sql(name, options) click to toggle source

SQL DDL statement to drop a view with the given name.

     # File lib/sequel/database/schema_methods.rb, line 521
521:     def drop_view_sql(name, options)
522:       "DROP VIEW #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}"
523:     end
dump_add_fk_constraints(table, fks) click to toggle source

For the table and foreign key metadata array, return an alter_table string that would add the foreign keys if run in a migration.

     # File lib/sequel/extensions/schema_dumper.rb, line 198
198:     def dump_add_fk_constraints(table, fks)
199:       sfks = "alter_table(#{table.inspect}) do\n"
200:       sfks << Schema::Generator.new(self) do
201:         fks.sort_by{|fk| fk[:columns].map{|c| c.to_s}}.each do |fk|
202:           foreign_key fk[:columns], fk
203:         end
204:       end.dump_constraints.gsub(/^foreign_key /, '  add_foreign_key ')
205:       sfks << "\nend"
206:     end
dump_table_foreign_keys(table, options={}) click to toggle source

For the table given, get the list of foreign keys and return an alter_table string that would add the foreign keys if run in a migration.

     # File lib/sequel/extensions/schema_dumper.rb, line 210
210:     def dump_table_foreign_keys(table, options={})
211:       begin
212:         fks = foreign_key_list(table, options).sort_by{|fk| fk[:columns].map{|c| c.to_s}}
213:       rescue Sequel::NotImplemented
214:         return ''
215:       end
216: 
217:       if fks.empty?
218:         ''
219:       else
220:         dump_add_fk_constraints(table, fks)
221:       end
222:     end
dump_table_generator(table, options={}) click to toggle source

Return a Schema::Generator object that will recreate the table’s schema. Takes the same options as dump_schema_migration.

     # File lib/sequel/extensions/schema_dumper.rb, line 226
226:     def dump_table_generator(table, options={})
227:       table = table.value.to_s if table.is_a?(SQL::Identifier)
228:       raise(Error, "must provide table as a Symbol, String, or Sequel::SQL::Identifier") unless [String, Symbol].any?{|c| table.is_a?(c)}
229:       s = schema(table).dup
230:       pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first}
231:       options = options.merge(:single_pk=>true) if pks.length == 1
232:       m = method(:column_schema_to_generator_opts)
233:       im = method(:index_to_generator_opts)
234: 
235:       if options[:indexes] != false
236:         begin
237:           indexes = indexes(table).sort_by{|k,v| k.to_s}
238:         rescue Sequel::NotImplemented
239:           nil
240:         end
241:       end
242: 
243:       if options[:foreign_keys] != false
244:         begin
245:           fk_list = foreign_key_list(table)
246:           
247:           if (sfk = options[:skipped_foreign_keys]) && (sfkt = sfk[table])
248:             fk_list.delete_if{|fk| sfkt.has_key?(fk[:columns])}
249:           end
250: 
251:           composite_fks, single_fks = fk_list.partition{|h| h[:columns].length > 1}
252:           fk_hash = {}
253: 
254:           single_fks.each do |fk|
255:             column = fk.delete(:columns).first
256:             fk.delete(:name)
257:             fk_hash[column] = fk
258:           end
259: 
260:           s = s.map do |name, info|
261:             if fk_info = fk_hash[name]
262:               [name, fk_info.merge(info)]
263:             else
264:               [name, info]
265:             end
266:           end
267:         rescue Sequel::NotImplemented
268:           nil
269:         end
270:       end
271: 
272:       Schema::Generator.new(self) do
273:         s.each{|name, info| send(*m.call(name, info, options))}
274:         primary_key(pks) if !@primary_key && pks.length > 0
275:         indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts, options))} if indexes
276:         composite_fks.each{|fk| send(:foreign_key, fk[:columns], fk)} if composite_fks
277:       end
278:     end
dump_table_indexes(table, meth, options={}) click to toggle source

Return a string that containing add_index/drop_index method calls for creating the index migration.

     # File lib/sequel/extensions/schema_dumper.rb, line 282
282:     def dump_table_indexes(table, meth, options={})
283:       begin
284:         indexes = indexes(table).sort_by{|k,v| k.to_s}
285:       rescue Sequel::NotImplemented
286:         return ''
287:       end
288:       im = method(:index_to_generator_opts)
289:       gen = Schema::Generator.new(self) do
290:         indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts, options))}
291:       end
292:       gen.dump_indexes(meth=>table, :ignore_errors=>!options[:same_db])
293:     end
execute_prepared_statement(conn, name, opts={}, &block) click to toggle source

Execute the prepared statement with the given name on an available connection, using the given args. If the connection has not prepared a statement with the given name yet, prepare it. If the connection has prepared a statement with the same name and different SQL, deallocate that statement first and then prepare this statement. If a block is given, yield the result, otherwise, return the number of rows changed.

     # File lib/sequel/adapters/postgres.rb, line 476
476:       def execute_prepared_statement(conn, name, opts={}, &block)
477:         ps = prepared_statement(name)
478:         sql = ps.prepared_sql
479:         ps_name = name.to_s
480: 
481:         if args = opts[:arguments]
482:           args = args.map{|arg| bound_variable_arg(arg, conn)}
483:         end
484: 
485:         unless conn.prepared_statements[ps_name] == sql
486:           conn.execute("DEALLOCATE #{ps_name}") if conn.prepared_statements.include?(ps_name)
487:           conn.prepared_statements[ps_name] = sql
488:           conn.check_disconnect_errors{log_yield("PREPARE #{ps_name} AS #{sql}"){conn.prepare(ps_name, sql)}}
489:         end
490: 
491:         log_sql = "EXECUTE #{ps_name}"
492:         if ps.log_sql
493:           log_sql << " ("
494:           log_sql << sql
495:           log_sql << ")"
496:         end
497: 
498:         q = conn.check_disconnect_errors{log_yield(log_sql, args){conn.exec_prepared(ps_name, args)}}
499:         begin
500:           block_given? ? yield(q) : q.cmd_tuples
501:         ensure
502:           q.clear
503:         end
504:       end
filter_expr(*args, &block) click to toggle source

Proxy the filter_expr call to the dataset, used for creating constraints.

     # File lib/sequel/database/schema_methods.rb, line 526
526:     def filter_expr(*args, &block)
527:       schema_utility_dataset.literal(schema_utility_dataset.send(:filter_expr, *args, &block))
528:     end
get_conversion_procs(conn) click to toggle source

Return the conversion procs hash to use for this database.

     # File lib/sequel/adapters/postgres.rb, line 507
507:       def get_conversion_procs(conn)
508:         procs = PG_TYPES.dup
509:         procs[1184] = procs[1114] = method(:to_application_timestamp)
510:         unless (pgnt = PG_NAMED_TYPES).empty?
511:           conn.execute("SELECT oid, typname FROM pg_type where typtype = 'b' AND typname IN ('#{pgnt.keys.map{|type| conn.escape_string(type.to_s)}.join("', '")}')") do |res|
512:             res.ntuples.times do |i|
513:               procs[res.getvalue(i, 0).to_i] ||= pgnt[res.getvalue(i, 1).untaint.to_sym]
514:             end
515:           end
516:         end
517:         procs
518:       end
identifier_input_method_default() click to toggle source

The method to apply to identifiers going into the database by default. Should be overridden in subclasses for databases that fold unquoted identifiers to lower case instead of uppercase, such as MySQL, PostgreSQL, and SQLite.

     # File lib/sequel/database/dataset_defaults.rb, line 182
182:     def identifier_input_method_default
183:       :upcase
184:     end
identifier_output_method_default() click to toggle source

The method to apply to identifiers coming the database by default. Should be overridden in subclasses for databases that fold unquoted identifiers to lower case instead of uppercase, such as MySQL, PostgreSQL, and SQLite.

     # File lib/sequel/database/dataset_defaults.rb, line 190
190:     def identifier_output_method_default
191:       :downcase
192:     end
index_definition_sql(table_name, index) click to toggle source

SQL DDL statement for creating an index for the table with the given name and index specifications.

     # File lib/sequel/database/schema_methods.rb, line 532
532:     def index_definition_sql(table_name, index)
533:       index_name = index[:name] || default_index_name(table_name, index[:columns])
534:       if index[:type]
535:         raise Error, "Index types are not supported for this database"
536:       elsif index[:where]
537:         raise Error, "Partial indexes are not supported for this database"
538:       else
539:         "CREATE #{'UNIQUE ' if index[:unique]}INDEX #{quote_identifier(index_name)} ON #{quote_schema_table(table_name)} #{literal(index[:columns])}"
540:       end
541:     end
index_sql_list(table_name, indexes) click to toggle source

Array of SQL DDL statements, one for each index specification, for the given table.

     # File lib/sequel/database/schema_methods.rb, line 545
545:     def index_sql_list(table_name, indexes)
546:       indexes.map{|i| index_definition_sql(table_name, i)}
547:     end
index_to_generator_opts(table, name, index_opts, options={}) click to toggle source

Convert the parsed index information into options to the Generators index method.

     # File lib/sequel/extensions/schema_dumper.rb, line 296
296:     def index_to_generator_opts(table, name, index_opts, options={})
297:       h = {}
298:       if options[:index_names] != false && default_index_name(table, index_opts[:columns]) != name.to_s
299:         if options[:index_names] == :namespace && !global_index_namespace?
300:           h[:name] = "#{table}_#{name}".to_sym
301:         else
302:           h[:name] = name
303:         end
304:       end
305:       h[:unique] = true if index_opts[:unique]
306:       h
307:     end
infinite_timestamp_value(value) click to toggle source

Return an appropriate value for the given infinite timestamp string.

     # File lib/sequel/adapters/postgres.rb, line 521
521:       def infinite_timestamp_value(value)
522:         case convert_infinite_timestamps
523:         when :nil
524:           nil
525:         when :string
526:           value
527:         else
528:           value == 'infinity' ? PLUS_INFINITY : MINUS_INFINITY
529:         end
530:       end
input_identifier_meth(ds=nil) click to toggle source

Return a Method object for the dataset’s output_identifier_method. Used in metadata parsing to make sure the returned information is in the correct format.

     # File lib/sequel/database/query.rb, line 504
504:     def input_identifier_meth(ds=nil)
505:       (ds || dataset).method(:input_identifier)
506:     end
join_table_name(hash, options) click to toggle source

Extract the join table name from the arguments given to create_join_table. Also does argument validation for the create_join_table method.

     # File lib/sequel/database/schema_methods.rb, line 551
551:     def join_table_name(hash, options)
552:       entries = hash.values
553:       raise Error, "must have 2 entries in hash given to (create|drop)_join_table" unless entries.length == 2
554:       if options[:name]
555:         options[:name]
556:       else
557:         table_names = entries.map{|e| join_table_name_extract(e)}
558:         table_names.map{|t| t.to_s}.sort.join('_')
559:       end
560:     end
join_table_name_extract(entry) click to toggle source

Extract an individual join table name, which should either be a string or symbol, or a hash containing one of those as the value for :table.

     # File lib/sequel/database/schema_methods.rb, line 564
564:     def join_table_name_extract(entry)
565:       case entry
566:       when Symbol, String
567:         entry
568:       when Hash
569:         join_table_name_extract(entry[:table])
570:       else
571:         raise Error, "can't extract table name from #{entry.inspect}"
572:       end
573:     end
log_connection_execute(conn, sql) click to toggle source

Don’t log, since logging is done by the underlying connection.

     # File lib/sequel/adapters/postgres.rb, line 533
533:       def log_connection_execute(conn, sql)
534:         conn.execute(sql)
535:       end
log_connection_execute(conn, sql) click to toggle source

Log the given SQL and then execute it on the connection, used by the transaction code.

    # File lib/sequel/database/logging.rb, line 57
57:     def log_connection_execute(conn, sql)
58:       log_yield(sql){conn.send(connection_execute_method, sql)}
59:     end
log_duration(duration, message) click to toggle source

Log message with message prefixed by duration at info level, or warn level if duration is greater than log_warn_duration.

    # File lib/sequel/database/logging.rb, line 63
63:     def log_duration(duration, message)
64:       log_each((lwd = log_warn_duration and duration >= lwd) ? :warn : sql_log_level, "(#{sprintf('%0.6fs', duration)}) #{message}")
65:     end
log_each(level, message) click to toggle source

Log message at level (which should be :error, :warn, or :info) to all loggers.

    # File lib/sequel/database/logging.rb, line 69
69:     def log_each(level, message)
70:       @loggers.each{|logger| logger.send(level, message)}
71:     end
metadata_dataset() click to toggle source

Return a dataset that uses the default identifier input and output methods for this database. Used when parsing metadata so that column symbols are returned as expected.

     # File lib/sequel/database/query.rb, line 511
511:     def metadata_dataset
512:       return @metadata_dataset if @metadata_dataset
513:       ds = dataset
514:       ds.identifier_input_method = identifier_input_method_default
515:       ds.identifier_output_method = identifier_output_method_default
516:       @metadata_dataset = ds
517:     end
on_delete_clause(action) click to toggle source

SQL DDL ON DELETE fragment to use, based on the given action. The following actions are recognized:

  • :cascade - Delete rows referencing this row.

  • :no_action (default) - Raise an error if other rows reference this row, allow deferring of the integrity check.

  • :restrict - Raise an error if other rows reference this row, but do not allow deferring the integrity check.

  • :set_default - Set columns referencing this row to their default value.

  • :set_null - Set columns referencing this row to NULL.

Any other object given is just converted to a string, with “_” converted to “ “ and upcased.

     # File lib/sequel/database/schema_methods.rb, line 587
587:     def on_delete_clause(action)
588:       action.to_s.gsub("_", " ").upcase
589:     end
on_update_clause(action) click to toggle source

Alias of #, since the two usually behave the same.

     # File lib/sequel/database/schema_methods.rb, line 592
592:     def on_update_clause(action)
593:       on_delete_clause(action)
594:     end
output_identifier_meth(ds=nil) click to toggle source

Return a Method object for the dataset’s output_identifier_method. Used in metadata parsing to make sure the returned information is in the correct format.

     # File lib/sequel/database/query.rb, line 522
522:     def output_identifier_meth(ds=nil)
523:       (ds || dataset).method(:output_identifier)
524:     end
quote_identifier(v) click to toggle source

Proxy the quote_identifier method to the dataset, used for quoting tables and columns.

     # File lib/sequel/database/schema_methods.rb, line 602
602:     def quote_identifier(v)
603:       schema_utility_dataset.quote_identifier(v)
604:     end
quote_identifiers_default() click to toggle source

Whether to quote identifiers by default for this database, true by default.

     # File lib/sequel/database/dataset_defaults.rb, line 196
196:     def quote_identifiers_default
197:       true
198:     end
quote_schema_table(table) click to toggle source

Proxy the quote_schema_table method to the dataset

     # File lib/sequel/database/schema_methods.rb, line 597
597:     def quote_schema_table(table)
598:       schema_utility_dataset.quote_schema_table(table)
599:     end
raise_error(exception, opts={}) click to toggle source

Convert the given exception to a DatabaseError, keeping message and traceback.

     # File lib/sequel/database/misc.rb, line 275
275:     def raise_error(exception, opts={})
276:       if !opts[:classes] || Array(opts[:classes]).any?{|c| exception.is_a?(c)}
277:         raise Sequel.convert_exception_class(exception, disconnect_error?(exception, opts) ? DatabaseDisconnectError : DatabaseError)
278:       else
279:         raise exception
280:       end
281:     end
remove_cached_schema(table) click to toggle source

Remove the cached schema for the given schema name

     # File lib/sequel/database/query.rb, line 527
527:     def remove_cached_schema(table)
528:       @schemas.delete(quote_schema_table(table)) if @schemas
529:     end
remove_transaction(conn, committed) click to toggle source

Remove the current thread from the list of active transactions

     # File lib/sequel/database/query.rb, line 532
532:     def remove_transaction(conn, committed)
533:       if !supports_savepoints? || ((_trans(conn)[:savepoint_level] -= 1) <= 0)
534:         begin
535:           if committed
536:             after_transaction_commit(conn)
537:           else
538:             after_transaction_rollback(conn)
539:           end
540:         ensure
541:           Sequel.synchronize{@transactions.delete(conn)}
542:         end
543:       end
544:     end
rename_table_sql(name, new_name) click to toggle source

SQL DDL statement for renaming a table.

     # File lib/sequel/database/schema_methods.rb, line 607
607:     def rename_table_sql(name, new_name)
608:       "ALTER TABLE #{quote_schema_table(name)} RENAME TO #{quote_schema_table(new_name)}"
609:     end
reset_schema_utility_dataset() click to toggle source

Remove the cached schema_utility_dataset, because the identifier quoting has changed.

     # File lib/sequel/database/schema_methods.rb, line 613
613:     def reset_schema_utility_dataset
614:       @schema_utility_dataset = nil
615:     end
rollback_savepoint_sql(depth) click to toggle source

SQL to rollback to a savepoint

     # File lib/sequel/database/query.rb, line 547
547:     def rollback_savepoint_sql(depth)
548:       SQL_ROLLBACK_TO_SAVEPOINT % depth
549:     end
rollback_transaction(conn, opts={}) click to toggle source

Rollback the active transaction on the connection

     # File lib/sequel/database/query.rb, line 552
552:     def rollback_transaction(conn, opts={})
553:       if supports_savepoints?
554:         depth = _trans(conn)[:savepoint_level]
555:         log_connection_execute(conn, depth > 1 ? rollback_savepoint_sql(depth-1) : rollback_transaction_sql)
556:       else
557:         log_connection_execute(conn, rollback_transaction_sql)
558:       end
559:     end
rollback_transaction_sql() click to toggle source

SQL to ROLLBACK a transaction.

     # File lib/sequel/database/query.rb, line 562
562:     def rollback_transaction_sql
563:       SQL_ROLLBACK
564:     end
schema_and_table(table_name) click to toggle source

Split the schema information from the table

     # File lib/sequel/database/schema_methods.rb, line 618
618:     def schema_and_table(table_name)
619:       schema_utility_dataset.schema_and_table(table_name)
620:     end
schema_autoincrementing_primary_key?(schema) click to toggle source

Return true if the given column schema represents an autoincrementing primary key.

     # File lib/sequel/database/schema_methods.rb, line 623
623:     def schema_autoincrementing_primary_key?(schema)
624:       !!schema[:primary_key]
625:     end
schema_column_type(db_type) click to toggle source

Match the database’s column type to a ruby type via a regular expression, and return the ruby type as a symbol such as :integer or :string.

     # File lib/sequel/database/query.rb, line 569
569:     def schema_column_type(db_type)
570:       case db_type
571:       when /\Ainterval\z/o
572:         :interval
573:       when /\A(character( varying)?|n?(var)?char|n?text)/o
574:         :string
575:       when /\A(int(eger)?|(big|small|tiny)int)/o
576:         :integer
577:       when /\Adate\z/o
578:         :date
579:       when /\A((small)?datetime|timestamp( with(out)? time zone)?)\z/o
580:         :datetime
581:       when /\Atime( with(out)? time zone)?\z/o
582:         :time
583:       when /\A(bool(ean)?)\z/o
584:         :boolean
585:       when /\A(real|float|double( precision)?)\z/o
586:         :float
587:       when /\A(?:(?:(?:num(?:ber|eric)?|decimal)(?:\(\d+,\s*(\d+|false|true)\))?)|(?:small)?money)\z/o
588:         $1 && ['0', 'false'].include?($1) ? :integer : :decimal
589:       when /bytea|[bc]lob|image|(var)?binary/o
590:         :blob
591:       when /\Aenum/o
592:         :enum
593:       end
594:     end
schema_column_type(db_type) click to toggle source

Convert tinyint(1) type to boolean if convert_tinyint_to_bool is true

     # File lib/sequel/adapters/mysql.rb, line 280
280:       def schema_column_type(db_type)
281:         convert_tinyint_to_bool && db_type == 'tinyint(1)' ? :boolean : super
282:       end
schema_utility_dataset() click to toggle source

The dataset to use for proxying certain schema methods.

     # File lib/sequel/database/schema_methods.rb, line 628
628:     def schema_utility_dataset
629:       @schema_utility_dataset ||= dataset
630:     end
server_opts(server) click to toggle source

Return the options for the given server by merging the generic options for all server with the specific options for the given server specified in the :servers option.

     # File lib/sequel/database/connecting.rb, line 256
256:     def server_opts(server)
257:       opts = if @opts[:servers] and server_options = @opts[:servers][server]
258:         case server_options
259:         when Hash
260:           @opts.merge(server_options)
261:         when Proc
262:           @opts.merge(server_options.call(self))
263:         else
264:           raise Error, 'Server opts should be a hash or proc'
265:         end
266:       elsif server.is_a?(Hash)
267:         @opts.merge(server)
268:       else
269:         @opts.dup
270:       end
271:       opts.delete(:servers)
272:       opts
273:     end
set_transaction_isolation(conn, opts) click to toggle source

Set the transaction isolation level on the given connection

     # File lib/sequel/database/query.rb, line 597
597:     def set_transaction_isolation(conn, opts)
598:       if supports_transaction_isolation_levels? and level = opts.fetch(:isolation, transaction_isolation_level)
599:         log_connection_execute(conn, set_transaction_isolation_sql(level))
600:       end
601:     end
set_transaction_isolation_sql(level) click to toggle source

SQL to set the transaction isolation level

     # File lib/sequel/database/query.rb, line 604
604:     def set_transaction_isolation_sql(level)
605:       "SET TRANSACTION ISOLATION LEVEL #{TRANSACTION_ISOLATION_LEVELS[level]}"
606:     end
sort_dumped_tables(tables, options={}) click to toggle source

Sort the tables so that referenced tables are created before tables that reference them, and then by name. If foreign keys are disabled, just sort by name.

     # File lib/sequel/extensions/schema_dumper.rb, line 311
311:     def sort_dumped_tables(tables, options={})
312:       sort_topologically = if options[:foreign_keys] != false
313:         begin
314:           foreign_key_list(:some_table_that_does_not_exist)
315:           true
316:         rescue Sequel::NotImplemented
317:           false
318:         rescue
319:           true
320:         end
321:       end
322: 
323:       if sort_topologically
324:         table_fks = {}
325:         tables.each{|t| table_fks[t] = foreign_key_list(t)}
326:         # Remove self referential foreign keys, not important when sorting.
327:         table_fks.each{|t, fks| fks.delete_if{|fk| fk[:table] == t}}
328:         tables, skipped_foreign_keys = sort_dumped_tables_topologically(table_fks, [])
329:         options[:skipped_foreign_keys] = skipped_foreign_keys
330:         tables
331:       else
332:         tables.sort_by{|t| t.to_s}
333:       end
334:     end
sort_dumped_tables_topologically(table_fks, sorted_tables) click to toggle source

Do a topological sort of tables, so that referenced tables come before referencing tables. Returns an array of sorted tables and a hash of skipped foreign keys. The hash will be empty unless there are circular dependencies.

     # File lib/sequel/extensions/schema_dumper.rb, line 340
340:     def sort_dumped_tables_topologically(table_fks, sorted_tables)
341:       skipped_foreign_keys = {}
342: 
343:       until table_fks.empty? 
344:         this_loop = []
345: 
346:         table_fks.each do |table, fks|
347:           fks.delete_if{|fk| !table_fks.has_key?(fk[:table])}
348:           this_loop << table if fks.empty?
349:         end
350: 
351:         if this_loop.empty?
352:           # No tables were changed this round, there must be a circular dependency.
353:           # Break circular dependency by picking the table with the least number of
354:           # outstanding foreign keys and skipping those foreign keys.
355:           # The skipped foreign keys will be added at the end of the
356:           # migration.
357:           skip_table, skip_fks = table_fks.sort_by{|table, fks| [fks.length, table.to_s]}.first
358:           skip_fks_hash = skipped_foreign_keys[skip_table] = {}
359:           skip_fks.each{|fk| skip_fks_hash[fk[:columns]] = fk}
360:           this_loop << skip_table
361:         end
362: 
363:         # Add sorted tables from this loop to the final list
364:         sorted_tables.concat(this_loop.sort_by{|t| t.to_s})
365: 
366:         # Remove tables that were handled this loop
367:         this_loop.each{|t| table_fks.delete(t)}
368:       end
369: 
370:       [sorted_tables, skipped_foreign_keys]
371:     end
temporary_table_sql() click to toggle source

SQL DDL fragment for temporary table

     # File lib/sequel/database/schema_methods.rb, line 633
633:     def temporary_table_sql
634:       self.class.const_get(:TEMPORARY)
635:     end
transaction_error(e, opts={}) click to toggle source

Raise a database error unless the exception is an Rollback.

     # File lib/sequel/database/query.rb, line 609
609:     def transaction_error(e, opts={})
610:       if e.is_a?(Rollback)
611:         raise e if opts[:rollback] == :reraise
612:       else
613:         raise_error(e, opts.merge(:classes=>database_error_classes))
614:       end
615:     end
type_literal(column) click to toggle source

SQL fragment specifying the type of a given column.

     # File lib/sequel/database/schema_methods.rb, line 638
638:     def type_literal(column)
639:       column[:type].is_a?(Class) ? type_literal_generic(column) : type_literal_specific(column)
640:     end
type_literal_generic(column) click to toggle source

SQL fragment specifying the full type of a column, consider the type with possible modifiers.

     # File lib/sequel/database/schema_methods.rb, line 644
644:     def type_literal_generic(column)
645:       meth = "type_literal_generic_#{column[:type].name.to_s.downcase}"
646:       if respond_to?(meth, true)
647:         send(meth, column)
648:       else
649:         raise Error, "Unsupported ruby class used as database type: #{column[:type]}"
650:       end
651:     end
type_literal_generic_bigdecimal(column) click to toggle source

Alias for type_literal_generic_numeric, to make overriding in a subclass easier.

     # File lib/sequel/database/schema_methods.rb, line 654
654:     def type_literal_generic_bigdecimal(column)
655:       type_literal_generic_numeric(column)
656:     end
type_literal_generic_bignum(column) click to toggle source

Sequel uses the bigint type by default for Bignums.

     # File lib/sequel/database/schema_methods.rb, line 659
659:     def type_literal_generic_bignum(column)
660:       :bigint
661:     end
type_literal_generic_date(column) click to toggle source

Sequel uses the date type by default for Dates.

     # File lib/sequel/database/schema_methods.rb, line 664
664:     def type_literal_generic_date(column)
665:       :date
666:     end
type_literal_generic_datetime(column) click to toggle source

Sequel uses the timestamp type by default for DateTimes.

     # File lib/sequel/database/schema_methods.rb, line 669
669:     def type_literal_generic_datetime(column)
670:       :timestamp
671:     end
type_literal_generic_falseclass(column) click to toggle source

Alias for type_literal_generic_trueclass, to make overriding in a subclass easier.

     # File lib/sequel/database/schema_methods.rb, line 674
674:     def type_literal_generic_falseclass(column)
675:       type_literal_generic_trueclass(column)
676:     end
type_literal_generic_file(column) click to toggle source

Sequel uses the blob type by default for Files.

     # File lib/sequel/database/schema_methods.rb, line 679
679:     def type_literal_generic_file(column)
680:       :blob
681:     end
type_literal_generic_fixnum(column) click to toggle source

Alias for type_literal_generic_integer, to make overriding in a subclass easier.

     # File lib/sequel/database/schema_methods.rb, line 684
684:     def type_literal_generic_fixnum(column)
685:       type_literal_generic_integer(column)
686:     end
type_literal_generic_float(column) click to toggle source

Sequel uses the double precision type by default for Floats.

     # File lib/sequel/database/schema_methods.rb, line 689
689:     def type_literal_generic_float(column)
690:       :"double precision"
691:     end
type_literal_generic_integer(column) click to toggle source

Sequel uses the integer type by default for integers

     # File lib/sequel/database/schema_methods.rb, line 694
694:     def type_literal_generic_integer(column)
695:       :integer
696:     end
type_literal_generic_numeric(column) click to toggle source

Sequel uses the numeric type by default for Numerics and BigDecimals. If a size is given, it is used, otherwise, it will default to whatever the database default is for an unsized value.

     # File lib/sequel/database/schema_methods.rb, line 701
701:     def type_literal_generic_numeric(column)
702:       column[:size] ? "numeric(#{Array(column[:size]).join(', ')})" : :numeric
703:     end
type_literal_generic_string(column) click to toggle source

Sequel uses the varchar type by default for Strings. If a size isn’t present, Sequel assumes a size of 255. If the :fixed option is used, Sequel uses the char type. If the :text option is used, Sequel uses the :text type.

     # File lib/sequel/database/schema_methods.rb, line 709
709:     def type_literal_generic_string(column)
710:       if column[:text]
711:         :text
712:       elsif column[:fixed]
713:         "char(#{column[:size]||255})"
714:       else
715:         "varchar(#{column[:size]||255})"
716:       end
717:     end
type_literal_generic_time(column) click to toggle source

Sequel uses the timestamp type by default for Time values. If the :only_time option is used, the time type is used.

     # File lib/sequel/database/schema_methods.rb, line 721
721:     def type_literal_generic_time(column)
722:       column[:only_time] ? :time : :timestamp
723:     end
type_literal_generic_trueclass(column) click to toggle source

Sequel uses the boolean type by default for TrueClass and FalseClass.

     # File lib/sequel/database/schema_methods.rb, line 726
726:     def type_literal_generic_trueclass(column)
727:       :boolean
728:     end
type_literal_specific(column) click to toggle source

SQL fragment for the given type of a column if the column is not one of the generic types specified with a ruby class.

     # File lib/sequel/database/schema_methods.rb, line 732
732:     def type_literal_specific(column)
733:       type = column[:type]
734:       type = "double precision" if type.to_s == 'double'
735:       column[:size] ||= 255 if type.to_s == 'varchar'
736:       elements = column[:size] || column[:elements]
737:       "#{type}#{literal(Array(elements)) if elements}#{UNSIGNED if column[:unsigned]}"
738:     end
typecast_value_blob(value) click to toggle source

Typecast the value to an SQL::Blob

     # File lib/sequel/database/misc.rb, line 284
284:     def typecast_value_blob(value)
285:       value.is_a?(Sequel::SQL::Blob) ? value : Sequel::SQL::Blob.new(value)
286:     end
typecast_value_boolean(value) click to toggle source

Typecast the value to true, false, or nil

     # File lib/sequel/database/misc.rb, line 289
289:     def typecast_value_boolean(value)
290:       case value
291:       when false, 0, "0", /\Af(alse)?\z/, /\Ano?\z/
292:         false
293:       else
294:         blank_object?(value) ? nil : true
295:       end
296:     end
typecast_value_date(value) click to toggle source

Typecast the value to a Date

     # File lib/sequel/database/misc.rb, line 299
299:     def typecast_value_date(value)
300:       case value
301:       when DateTime, Time
302:         Date.new(value.year, value.month, value.day)
303:       when Date
304:         value
305:       when String
306:         Sequel.string_to_date(value)
307:       when Hash
308:         Date.new(*[:year, :month, :day].map{|x| (value[x] || value[x.to_s]).to_i})
309:       else
310:         raise InvalidValue, "invalid value for Date: #{value.inspect}"
311:       end
312:     end
typecast_value_datetime(value) click to toggle source

Typecast the value to a DateTime or Time depending on Sequel.datetime_class

     # File lib/sequel/database/misc.rb, line 315
315:     def typecast_value_datetime(value)
316:       Sequel.typecast_to_application_timestamp(value)
317:     end
typecast_value_datetime(value) click to toggle source

If the value is an infinite value (either an infinite float or a string returned by by PostgreSQL for an infinite timestamp), return it without converting it if convert_infinite_timestamps is set.

     # File lib/sequel/adapters/postgres.rb, line 540
540:       def typecast_value_datetime(value)
541:         if convert_infinite_timestamps
542:           case value
543:           when *INFINITE_DATETIME_VALUES
544:             value
545:           else
546:             super
547:           end
548:         else
549:           super
550:         end
551:       end
typecast_value_decimal(value) click to toggle source

Typecast the value to a BigDecimal

     # File lib/sequel/database/misc.rb, line 320
320:     def typecast_value_decimal(value)
321:       case value
322:       when BigDecimal
323:         value
324:       when String, Numeric
325:         BigDecimal.new(value.to_s)
326:       else
327:         raise InvalidValue, "invalid value for BigDecimal: #{value.inspect}"
328:       end
329:     end
typecast_value_float(value) click to toggle source

Typecast the value to a Float

     # File lib/sequel/database/misc.rb, line 332
332:     def typecast_value_float(value)
333:       Float(value)
334:     end
typecast_value_integer(value) click to toggle source

Typecast the value to an Integer

     # File lib/sequel/database/misc.rb, line 341
341:       def typecast_value_integer(value)
342:         (value.is_a?(String) && value =~ LEADING_ZERO_RE) ? Integer(value, 10) : Integer(value)
343:       end
typecast_value_integer(value) click to toggle source

Typecast the value to an Integer

     # File lib/sequel/database/misc.rb, line 348
348:       def typecast_value_integer(value)
349:         Integer(value.is_a?(String) ? value.sub(LEADING_ZERO_RE, LEADING_ZERO_REP) : value)
350:       end
typecast_value_string(value) click to toggle source

Typecast the value to a String

     # File lib/sequel/database/misc.rb, line 354
354:     def typecast_value_string(value)
355:       value.to_s
356:     end
typecast_value_time(value) click to toggle source

Typecast the value to a Time

     # File lib/sequel/database/misc.rb, line 359
359:     def typecast_value_time(value)
360:       case value
361:       when Time
362:         if value.is_a?(SQLTime)
363:           value
364:         else
365:           SQLTime.create(value.hour, value.min, value.sec, value.respond_to?(:nsec) ? value.nsec/1000.0 : value.usec)
366:         end
367:       when String
368:         Sequel.string_to_time(value)
369:       when Hash
370:         SQLTime.create(*[:hour, :minute, :second].map{|x| (value[x] || value[x.to_s]).to_i})
371:       else
372:         raise Sequel::InvalidValue, "invalid value for Time: #{value.inspect}"
373:       end
374:     end
use_column_schema_to_ruby_default_fallback?() click to toggle source

Don’t use the “…”.lit fallback on MySQL, since the defaults it uses aren’t valid literal SQL values.

     # File lib/sequel/extensions/schema_dumper.rb, line 375
375:     def use_column_schema_to_ruby_default_fallback?
376:       database_type != :mysql
377:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.