class Sequel::Database

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

Constants

OPTS

1 - Methods that execute queries and/or return results

↑ top

Constants

COLUMN_SCHEMA_DATETIME_TYPES
COLUMN_SCHEMA_STRING_TYPES

Attributes

cache_schema[RW]

Whether the schema should be cached for this database. True by default for performance, can be set to false to always issue a database query to get the schema.

prepared_statements[R]

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

Public Instance Methods

<<(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
25 def <<(sql)
26   run(sql)
27   self
28 end
call(ps_name, hash=OPTS, &block) click to toggle source

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

DB[:items].where(id: 1).prepare(:first, :sa)
DB.call(:sa) # SELECT * FROM items WHERE id = 1
   # File lib/sequel/database/query.rb
35 def call(ps_name, hash=OPTS, &block)
36   prepared_statement(ps_name).call(hash, &block)
37 end
execute_ddl(sql, opts=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
42 def execute_ddl(sql, opts=OPTS, &block)
43   execute_dui(sql, opts, &block)
44 end
execute_dui(sql, opts=OPTS, &block) click to toggle source

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

   # File lib/sequel/database/query.rb
49 def execute_dui(sql, opts=OPTS, &block)
50   execute(sql, opts, &block)
51 end
execute_insert(sql, opts=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
56 def execute_insert(sql, opts=OPTS, &block)
57   execute_dui(sql, opts, &block)
58 end
get(*args, &block) click to toggle source

Returns a single value from the database, see Dataset#get.

DB.get(1) # SELECT 1
# => 1
DB.get{server_version.function} # SELECT server_version()
   # File lib/sequel/database/query.rb
65 def get(*args, &block)
66   @default_dataset.get(*args, &block)
67 end
run(sql, opts=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
74 def run(sql, opts=OPTS)
75   sql = literal(sql) if sql.is_a?(SQL::PlaceholderLiteralString)
76   execute_ddl(sql, opts)
77   nil
78 end
schema(table, opts=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 hash should contain at least 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, or nil if there is no default value.

: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
121 def schema(table, opts=OPTS)
122   raise(Error, 'schema parsing is not implemented on this database') unless supports_schema_parsing?
123 
124   opts = opts.dup
125   tab = if table.is_a?(Dataset)
126     o = table.opts
127     from = o[:from]
128     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)
129     table.first_source_table
130   else
131     table
132   end
133 
134   qualifiers = split_qualifiers(tab)
135   table_name = qualifiers.pop
136   sch = qualifiers.pop
137   information_schema_schema = case qualifiers.length
138   when 1
139     Sequel.identifier(*qualifiers)
140   when 2
141     Sequel.qualify(*qualifiers)
142   end
143 
144   if table.is_a?(Dataset)
145     quoted_name = table.literal(tab)
146     opts[:dataset] = table
147   else
148     quoted_name = schema_utility_dataset.literal(table)
149   end
150 
151   opts[:schema] = sch if sch && !opts.include?(:schema)
152   opts[:information_schema_schema] = information_schema_schema if information_schema_schema && !opts.include?(:information_schema_schema)
153 
154   Sequel.synchronize{@schemas.delete(quoted_name)} if opts[:reload]
155   if v = Sequel.synchronize{@schemas[quoted_name]}
156     return v
157   end
158 
159   cols = schema_parse_table(table_name, opts)
160   raise(Error, "schema parsing returned no columns, table #{table_name.inspect} probably doesn't exist") if cols.nil? || cols.empty?
161 
162   primary_keys = 0
163   auto_increment_set = false
164   cols.each do |_,c|
165     auto_increment_set = true if c.has_key?(:auto_increment)
166     primary_keys += 1 if c[:primary_key]
167   end
168 
169   cols.each do |_,c|
170     c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type]) unless c.has_key?(:ruby_default)
171     if c[:primary_key] && !auto_increment_set
172       # If adapter didn't set it, assume that integer primary keys are auto incrementing
173       c[:auto_increment] = primary_keys == 1 && !!(c[:db_type] =~ /int/io)
174     end
175     if !c[:max_length] && c[:type] == :string && (max_length = column_schema_max_length(c[:db_type]))
176       c[:max_length] = max_length
177     end
178   end
179   schema_post_process(cols)
180 
181   Sequel.synchronize{@schemas[quoted_name] = cols} if cache_schema
182   cols
183 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
193 def table_exists?(name)
194   sch, table_name = schema_and_table(name)
195   name = SQL::QualifiedIdentifier.new(sch, table_name) if sch
196   ds = from(name)
197   transaction(:savepoint=>:only){_table_exists?(ds)}
198   true
199 rescue DatabaseError
200   false
201 end

Private Instance Methods

_metadata_dataset() click to toggle source

Uncached version of metadata_dataset, designed for overriding.

    # File lib/sequel/database/query.rb
291 def _metadata_dataset
292   dataset
293 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
207 def _table_exists?(ds)
208   ds.get(SQL::AliasedExpression.new(Sequel::NULL, :nil))
209 end
column_schema_default_string_type?(type) click to toggle source

Whether the type should be treated as a string type when parsing the column schema default value.

    # File lib/sequel/database/query.rb
213 def column_schema_default_string_type?(type)
214   COLUMN_SCHEMA_STRING_TYPES.include?(type)
215 end
column_schema_default_to_ruby_value(default, type) click to toggle source

Transform the given normalized default string into a ruby object for the given type.

    # File lib/sequel/database/query.rb
219 def column_schema_default_to_ruby_value(default, type)
220   case type
221   when :boolean
222     case default 
223     when /[f0]/i
224       false
225     when /[t1]/i
226       true
227     end
228   when :string, :enum, :set, :interval
229     default
230   when :blob
231     Sequel::SQL::Blob.new(default)
232   when :integer
233     Integer(default)
234   when :float
235     Float(default)
236   when :date
237     Sequel.string_to_date(default)
238   when :datetime
239     DateTime.parse(default)
240   when :time
241     Sequel.string_to_time(default)
242   when :decimal
243     BigDecimal(default)
244   end
245 end
column_schema_max_length(db_type) click to toggle source

Look at the db_type and guess the maximum length of the column. This assumes types such as varchar(255).

    # File lib/sequel/database/query.rb
277 def column_schema_max_length(db_type)
278   if db_type =~ /\((\d+)\)/
279     $1.to_i
280   end
281 end
column_schema_normalize_default(default, type) click to toggle source

Normalize the default value string for the given type and return the normalized value.

    # File lib/sequel/database/query.rb
249 def column_schema_normalize_default(default, type)
250   if column_schema_default_string_type?(type)
251     return unless m = /\A'(.*)'\z/.match(default)
252     m[1].gsub("''", "'")
253   else
254     default
255   end
256 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
260 def column_schema_to_ruby_default(default, type)
261   return default unless default.is_a?(String)
262   if COLUMN_SCHEMA_DATETIME_TYPES.include?(type)
263     if /now|today|CURRENT|getdate|\ADate\(\)\z/i.match(default)
264       if type == :date
265         return Sequel::CURRENT_DATE
266       else
267         return Sequel::CURRENT_TIMESTAMP
268       end
269     end
270   end
271   default = column_schema_normalize_default(default, type)
272   column_schema_default_to_ruby_value(default, type) rescue nil
273 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
286 def input_identifier_meth(ds=nil)
287   (ds || dataset).method(:input_identifier)
288 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
298 def metadata_dataset
299   @metadata_dataset ||= _metadata_dataset
300 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
305 def output_identifier_meth(ds=nil)
306   (ds || dataset).method(:output_identifier)
307 end
remove_cached_schema(table) click to toggle source

Remove the cached schema for the given schema name

    # File lib/sequel/database/query.rb
310 def remove_cached_schema(table)
311   cache = @default_dataset.send(:cache)
312   Sequel.synchronize{cache.clear}
313   k = quote_schema_table(table)
314   Sequel.synchronize{@schemas.delete(k)}
315 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
320 def schema_column_type(db_type)
321   case db_type
322   when /\A(character( varying)?|n?(var)?char|n?text|string|clob)/io
323     :string
324   when /\A(int(eger)?|(big|small|tiny)int)/io
325     :integer
326   when /\Adate\z/io
327     :date
328   when /\A((small)?datetime|timestamp( with(out)? time zone)?)(\(\d+\))?\z/io
329     :datetime
330   when /\Atime( with(out)? time zone)?\z/io
331     :time
332   when /\A(bool(ean)?)\z/io
333     :boolean
334   when /\A(real|float( unsigned)?|double( precision)?|double\(\d+,\d+\)( unsigned)?)\z/io
335     :float
336   when /\A(?:(?:(?:num(?:ber|eric)?|decimal)(?:\(\d+,\s*(\d+|false|true)\))?))\z/io
337     $1 && ['0', 'false'].include?($1) ? :integer : :decimal
338   when /bytea|blob|image|(var)?binary/io
339     :blob
340   when /\Aenum/io
341     :enum
342   end
343 end
schema_post_process(cols) click to toggle source

Post process the schema values.

    # File lib/sequel/database/query.rb
346 def schema_post_process(cols)
347   if RUBY_VERSION >= '2.5'
348     cols.each do |_, h|
349       db_type = h[:db_type]
350       if db_type.is_a?(String)
351         h[:db_type] = -db_type
352       end
353     end
354   end
355 
356   cols.each do |_,c|
357     c.each_value do |val|
358       val.freeze if val.is_a?(String)
359     end
360   end
361 end

2 - Methods that modify the database schema

↑ top

Constants

COLUMN_DEFINITION_ORDER

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

COMBINABLE_ALTER_TABLE_OPS

The alter table operations that are combinable.

Public Instance Methods

add_column(table, *args) click to toggle source

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

DB.add_column :items, :name, String, unique: true, null: false
DB.add_column :items, :category, String, default: 'ruby'

See alter_table.

   # File lib/sequel/database/schema_methods.rb
25 def add_column(table, *args)
26   alter_table(table) {add_column(*args)}
27 end
add_index(table, columns, options=OPTS) 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

:name

Name to use for index instead of default

See alter_table.

   # File lib/sequel/database/schema_methods.rb
40 def add_index(table, columns, options=OPTS)
41   e = options[:ignore_errors]
42   begin
43     alter_table(table){add_index(columns, options)}
44   rescue DatabaseError
45     raise unless e
46   end
47   nil
48 end
alter_table(name, &block) click to toggle source

Alters the given table with the specified block. Example:

DB.alter_table :items do
  add_column :category, String, default: 'ruby'
  drop_column :category
  rename_column :cntr, :counter
  set_column_type :value, Float
  set_column_default :value, 4.2
  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
67 def alter_table(name, &block)
68   generator = alter_table_generator(&block)
69   remove_cached_schema(name)
70   apply_alter_table_generator(name, generator)
71   nil
72 end
alter_table_generator(&block) click to toggle source

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

   # File lib/sequel/database/schema_methods.rb
76 def alter_table_generator(&block)
77   alter_table_generator_class.new(self, &block)
78 end
create_join_table(hash, options=OPTS) 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.

The default table name this will create is the sorted version of the two hash values, joined by an underscore. So the following two method calls create the same table:

create_join_table(cat_id: :cats, dog_id: :dogs) # cats_dogs
create_join_table(dog_id: :dogs, cat_id: :cats) # cats_dogs

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
119 def create_join_table(hash, options=OPTS)
120   keys = hash.keys.sort
121   create_table(join_table_name(hash, options), options) do
122     keys.each do |key|
123       v = hash[key]
124       unless v.is_a?(Hash)
125         v = {:table=>v}
126       end
127       v[:null] = false unless v.has_key?(:null)
128       foreign_key(key, v)
129     end
130     primary_key(keys) unless options[:no_primary_key]
131     index(keys.reverse, options[:index_options] || OPTS) unless options[:no_index]
132   end
133   nil
134 end
create_join_table!(hash, options=OPTS) click to toggle source

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

    # File lib/sequel/database/schema_methods.rb
137 def create_join_table!(hash, options=OPTS)
138   drop_table?(join_table_name(hash, options))
139   create_join_table(hash, options)
140 end
create_join_table?(hash, options=OPTS) click to toggle source

Creates the join table unless it already exists.

    # File lib/sequel/database/schema_methods.rb
143 def create_join_table?(hash, options=OPTS)
144   if supports_create_table_if_not_exists? && options[:no_index]
145     create_join_table(hash, options.merge(:if_not_exists=>true))
146   elsif !table_exists?(join_table_name(hash, options))
147     create_join_table(hash, options)
148   end
149 end
create_or_replace_view(name, source, options = OPTS) click to toggle source

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

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

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

    # File lib/sequel/database/schema_methods.rb
239 def create_or_replace_view(name, source, options = OPTS)
240   if supports_create_or_replace_view?
241     options = options.merge(:replace=>true)
242   else
243     drop_view(name) rescue nil
244   end
245 
246   create_view(name, source, options)
247   nil
248 end
create_table(name, options=OPTS, &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, String
  String :content
  index :title
end

General options:

:as

Create the table using the value, which should be either a dataset or a literal SQL string. If this option is used, a block should not be given to the method.

:ignore_index_errors

Ignore any errors when creating indexes.

:temp

Create the table as a temporary table.

MySQL specific options:

:charset

The character set to use for the table.

:collate

The collation to use for the table.

:engine

The table engine to use for the table.

PostgreSQL specific options:

:on_commit

Either :preserve_rows (default), :drop or :delete_rows. Should only be specified when creating a temporary table.

:foreign

Create a foreign table. The value should be the name of the foreign server that was specified in CREATE SERVER.

:inherits

Inherit from a different table. An array can be specified to inherit from multiple tables.

:unlogged

Create the table as an unlogged table.

:options

The OPTIONS clause to use for foreign tables. Should be a hash where keys are option names and values are option values. Note that option names are unquoted, so you should not use untrusted keys.

:tablespace

The tablespace to use for the table.

See Schema::CreateTableGenerator and the “Schema Modification” guide.

    # File lib/sequel/database/schema_methods.rb
187 def create_table(name, options=OPTS, &block)
188   remove_cached_schema(name)
189   if sql = options[:as]
190     raise(Error, "can't provide both :as option and block to create_table") if block
191     create_table_as(name, sql, options)
192   else
193     generator = options[:generator] || create_table_generator(&block)
194     create_table_from_generator(name, generator, options)
195     create_table_indexes_from_generator(name, generator, options)
196   end
197   nil
198 end
create_table!(name, options=OPTS, &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
206 def create_table!(name, options=OPTS, &block)
207   drop_table?(name)
208   create_table(name, options, &block)
209 end
create_table?(name, options=OPTS, &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
216 def create_table?(name, options=OPTS, &block)
217   options = options.dup
218   generator = options[:generator] ||= create_table_generator(&block)
219   if generator.indexes.empty? && supports_create_table_if_not_exists?
220     create_table(name, options.merge!(:if_not_exists=>true))
221   elsif !table_exists?(name)
222     create_table(name, options)
223   end
224 end
create_table_generator(&block) click to toggle source

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

    # File lib/sequel/database/schema_methods.rb
228 def create_table_generator(&block)
229   create_table_generator_class.new(self, &block)
230 end
create_view(name, source, options = OPTS) 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")
# CREATE VIEW cheap_items AS
# SELECT * FROM items WHERE price < 100

DB.create_view(:ruby_items, DB[:items].where(category: 'ruby'))
# CREATE VIEW ruby_items AS
# SELECT * FROM items WHERE (category = 'ruby')

DB.create_view(:checked_items, DB[:items].where(:foo), check: true)
# CREATE VIEW checked_items AS
# SELECT * FROM items WHERE foo
# WITH CHECK OPTION

Options:

:columns

The column names to use for the view. If not given, automatically determined based on the input dataset.

:check

Adds a WITH CHECK OPTION clause, so that attempting to modify rows in the underlying table that would not be returned by the view is not allowed. This can be set to :local to use WITH LOCAL CHECK OPTION.

PostgreSQL/SQLite specific option:

:temp

Create a temporary view, automatically dropped on disconnect.

PostgreSQL specific options:

:materialized

Creates a materialized view, similar to a regular view, but backed by a physical table.

:recursive

Creates a recursive view. As columns must be specified for recursive views, you can also set them as the value of this option. Since a recursive view requires a union that isn't in a subquery, if you are providing a Dataset as the source argument, if should probably call the union method with the all: true and from_self: false options.

:tablespace

The tablespace to use for materialized views.

    # File lib/sequel/database/schema_methods.rb
286 def create_view(name, source, options = OPTS)
287   execute_ddl(create_view_sql(name, source, options))
288   remove_cached_schema(name)
289   nil
290 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
297 def drop_column(table, *args)
298   alter_table(table) {drop_column(*args)}
299 end
drop_index(table, columns, options=OPTS) 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
307 def drop_index(table, columns, options=OPTS)
308   alter_table(table){drop_index(columns, options)}
309 end
drop_join_table(hash, options=OPTS) 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
316 def drop_join_table(hash, options=OPTS)
317   drop_table(join_table_name(hash, options), options)
318 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
325 def drop_table(*names)
326   options = names.last.is_a?(Hash) ? names.pop : OPTS 
327   names.each do |n|
328     execute_ddl(drop_table_sql(n, options))
329     remove_cached_schema(n)
330   end
331   nil
332 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
340 def drop_table?(*names)
341   options = names.last.is_a?(Hash) ? names.pop : OPTS
342   if supports_drop_table_if_exists?
343     options = options.merge(:if_exists=>true)
344     names.each do |name|
345       drop_table(name, options)
346     end
347   else
348     names.each do |name|
349       drop_table(name, options) if table_exists?(name)
350     end
351   end
352   nil
353 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)
DB.drop_view(:cheap_items, :pricey_items, if_exists: true)

Options:

:cascade

Also drop objects depending on this view.

:if_exists

Do not raise an error if the view does not exist.

PostgreSQL specific options:

:materialized

Drop a materialized view.

    # File lib/sequel/database/schema_methods.rb
368 def drop_view(*names)
369   options = names.last.is_a?(Hash) ? names.pop : OPTS
370   names.each do |n|
371     execute_ddl(drop_view_sql(n, options))
372     remove_cached_schema(n)
373   end
374   nil
375 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
394 def rename_column(table, *args)
395   alter_table(table) {rename_column(*args)}
396 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
382 def rename_table(name, new_name)
383   execute_ddl(rename_table_sql(name, new_name))
384   remove_cached_schema(name)
385   nil
386 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
403 def set_column_default(table, *args)
404   alter_table(table) {set_column_default(*args)}
405 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
412 def set_column_type(table, *args)
413   alter_table(table) {set_column_type(*args)}
414 end

Private Instance Methods

alter_table_add_column_sql(table, op) click to toggle source
    # File lib/sequel/database/schema_methods.rb
452 def alter_table_add_column_sql(table, op)
453   "ADD COLUMN #{column_definition_sql(op)}"
454 end
alter_table_add_constraint_sql(table, op) click to toggle source
    # File lib/sequel/database/schema_methods.rb
476 def alter_table_add_constraint_sql(table, op)
477   "ADD #{constraint_definition_sql(op)}"
478 end
alter_table_drop_column_sql(table, op) click to toggle source
    # File lib/sequel/database/schema_methods.rb
456 def alter_table_drop_column_sql(table, op)
457   "DROP COLUMN #{quote_identifier(op[:name])}#{' CASCADE' if op[:cascade]}"
458 end
alter_table_drop_constraint_sql(table, op) click to toggle source
    # File lib/sequel/database/schema_methods.rb
480 def alter_table_drop_constraint_sql(table, op)
481   quoted_name = quote_identifier(op[:name]) if op[:name]
482   if op[:type] == :foreign_key
483     quoted_name ||= quote_identifier(foreign_key_name(table, op[:columns]))
484   end
485   "DROP CONSTRAINT #{quoted_name}#{' CASCADE' if op[:cascade]}"
486 end
alter_table_generator_class() click to toggle source

The class used for alter_table generators.

    # File lib/sequel/database/schema_methods.rb
437 def alter_table_generator_class
438   Schema::AlterTableGenerator
439 end
alter_table_op_sql(table, op) click to toggle source

SQL fragment for given alter table operation.

    # File lib/sequel/database/schema_methods.rb
442 def alter_table_op_sql(table, op)
443   meth = "alter_table_#{op[:op]}_sql"
444   if respond_to?(meth, true)
445     # Allow calling private methods as alter table op sql methods are private
446     send(meth, table, op)
447   else
448     raise Error, "Unsupported ALTER TABLE operation: #{op[:op]}"
449   end
450 end
alter_table_rename_column_sql(table, op) click to toggle source
    # File lib/sequel/database/schema_methods.rb
460 def alter_table_rename_column_sql(table, op)
461   "RENAME COLUMN #{quote_identifier(op[:name])} TO #{quote_identifier(op[:new_name])}"
462 end
alter_table_set_column_default_sql(table, op) click to toggle source
    # File lib/sequel/database/schema_methods.rb
468 def alter_table_set_column_default_sql(table, op)
469   "ALTER COLUMN #{quote_identifier(op[:name])} SET DEFAULT #{literal(op[:default])}"
470 end
alter_table_set_column_null_sql(table, op) click to toggle source
    # File lib/sequel/database/schema_methods.rb
472 def alter_table_set_column_null_sql(table, op)
473   "ALTER COLUMN #{quote_identifier(op[:name])} #{op[:null] ? 'DROP' : 'SET'} NOT NULL"
474 end
alter_table_set_column_type_sql(table, op) click to toggle source
    # File lib/sequel/database/schema_methods.rb
464 def alter_table_set_column_type_sql(table, op)
465   "ALTER COLUMN #{quote_identifier(op[:name])} TYPE #{type_literal(op)}"
466 end
alter_table_sql(table, op) click to toggle source

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

    # File lib/sequel/database/schema_methods.rb
490 def alter_table_sql(table, op)
491   case op[:op]
492   when :add_index
493     index_definition_sql(table, op)
494   when :drop_index
495     drop_index_sql(table, op)
496   else
497     "ALTER TABLE #{quote_schema_table(table)} #{alter_table_op_sql(table, op)}"
498   end
499 end
alter_table_sql_list(table, operations) click to toggle source

Array of SQL statements used to modify the table, corresponding to changes specified by the operations.

    # File lib/sequel/database/schema_methods.rb
503 def alter_table_sql_list(table, operations)
504   if supports_combining_alter_table_ops?
505     grouped_ops = []
506     last_combinable = false
507     operations.each do |op|
508       if combinable_alter_table_op?(op)
509         if sql = alter_table_op_sql(table, op)
510           grouped_ops << [] unless last_combinable
511           grouped_ops.last << sql
512           last_combinable = true
513         end
514       elsif sql = alter_table_sql(table, op)
515         Array(sql).each{|s| grouped_ops << s}
516         last_combinable = false
517       end
518     end
519     grouped_ops.map do |gop|
520       if gop.is_a?(Array)
521         "ALTER TABLE #{quote_schema_table(table)} #{gop.join(', ')}"
522       else
523         gop
524       end
525     end
526   else
527     operations.map{|op| alter_table_sql(table, op)}.flatten.compact
528   end
529 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
419 def apply_alter_table(name, ops)
420   alter_table_sql_list(name, ops).each{|sql| execute_ddl(sql)}
421 end
apply_alter_table_generator(name, generator) click to toggle source

Apply the operations in the given generator to the table given by name.

    # File lib/sequel/database/schema_methods.rb
424 def apply_alter_table_generator(name, generator)
425   ops = generator.operations
426 
427   unless can_add_primary_key_constraint_on_nullable_columns?
428     if add_pk = ops.find{|op| op[:op] == :add_constraint && op[:type] == :primary_key}
429       ops = add_pk[:columns].map{|column| {:op => :set_column_null, :name => column, :null => false}} + ops
430     end
431   end
432 
433   apply_alter_table(name, ops)
434 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
533 def auto_increment_sql
534   'AUTOINCREMENT'
535 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
551 def column_definition_auto_increment_sql(sql, column)
552   sql << " #{auto_increment_sql}" if column[:auto_increment]
553 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
556 def column_definition_collate_sql(sql, column)
557   if collate = column[:collate]
558     sql << " COLLATE #{collate}"
559   end
560 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
563 def column_definition_default_sql(sql, column)
564   sql << " DEFAULT #{literal(column[:default])}" if column.include?(:default)
565 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
568 def column_definition_null_sql(sql, column)
569   null = column.fetch(:null, column[:allow_null])
570   if null.nil? && !can_add_primary_key_constraint_on_nullable_columns? && column[:primary_key]
571     null = false
572   end
573 
574   case null
575   when false
576     sql << ' NOT NULL'
577   when true
578     sql << ' NULL'
579   end
580 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
538 def column_definition_order
539   COLUMN_DEFINITION_ORDER
540 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
583 def column_definition_primary_key_sql(sql, column)
584   if column[:primary_key]
585     if name = column[:primary_key_constraint_name]
586       sql << " CONSTRAINT #{quote_identifier(name)}"
587     end
588     sql << ' PRIMARY KEY'
589     constraint_deferrable_sql_append(sql, column[:primary_key_deferrable])
590   end
591 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
594 def column_definition_references_sql(sql, column)
595   if column[:table]
596     if name = column[:foreign_key_constraint_name]
597      sql << " CONSTRAINT #{quote_identifier(name)}"
598     end
599     sql << column_references_column_constraint_sql(column)
600   end
601 end
column_definition_sql(column) click to toggle source

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

    # File lib/sequel/database/schema_methods.rb
543 def column_definition_sql(column)
544   sql = String.new
545   sql << "#{quote_identifier(column[:name])} #{type_literal(column)}"
546   column_definition_order.each{|m| send(:"column_definition_#{m}_sql", sql, column)}
547   sql
548 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
604 def column_definition_unique_sql(sql, column)
605   if column[:unique]
606     if name = column[:unique_constraint_name]
607       sql << " CONSTRAINT #{quote_identifier(name)}"
608     end
609     sql << ' UNIQUE'
610     constraint_deferrable_sql_append(sql, column[:unique_deferrable])
611   end
612 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
615 def column_list_sql(generator)
616   (generator.columns.map{|c| column_definition_sql(c)} + generator.constraints.map{|c| constraint_definition_sql(c)}).join(', ')
617 end
column_references_column_constraint_sql(column) click to toggle source

SQL fragment for column foreign key references (column constraints)

    # File lib/sequel/database/schema_methods.rb
620 def column_references_column_constraint_sql(column)
621   column_references_sql(column)
622 end
column_references_sql(column) click to toggle source

SQL fragment for column foreign key references

    # File lib/sequel/database/schema_methods.rb
625 def column_references_sql(column)
626   sql = String.new
627   sql << " REFERENCES #{quote_schema_table(column[:table])}"
628   sql << "(#{Array(column[:key]).map{|x| quote_identifier(x)}.join(', ')})" if column[:key]
629   sql << " ON DELETE #{on_delete_clause(column[:on_delete])}" if column[:on_delete]
630   sql << " ON UPDATE #{on_update_clause(column[:on_update])}" if column[:on_update]
631   constraint_deferrable_sql_append(sql, column[:deferrable])
632   sql
633 end
column_references_table_constraint_sql(constraint) click to toggle source

SQL fragment for table foreign key references (table constraints)

    # File lib/sequel/database/schema_methods.rb
636 def column_references_table_constraint_sql(constraint)
637   "FOREIGN KEY #{literal(constraint[:columns])}#{column_references_sql(constraint)}"
638 end
combinable_alter_table_op?(op) click to toggle source

Whether the given alter table operation is combinable.

    # File lib/sequel/database/schema_methods.rb
641 def combinable_alter_table_op?(op)
642   COMBINABLE_ALTER_TABLE_OPS.include?(op[:op])
643 end
constraint_deferrable_sql_append(sql, defer) click to toggle source

SQL fragment specifying the deferrable constraint attributes.

    # File lib/sequel/database/schema_methods.rb
670 def constraint_deferrable_sql_append(sql, defer)
671   case defer
672   when nil
673   when false
674     sql << ' NOT DEFERRABLE'
675   when :immediate
676     sql << ' DEFERRABLE INITIALLY IMMEDIATE'
677   else
678     sql << ' DEFERRABLE INITIALLY DEFERRED'
679   end
680 end
constraint_definition_sql(constraint) click to toggle source

SQL fragment specifying a constraint on a table.

    # File lib/sequel/database/schema_methods.rb
646 def constraint_definition_sql(constraint)
647   sql = String.new
648   sql << "CONSTRAINT #{quote_identifier(constraint[:name])} " if constraint[:name] 
649   case constraint[:type]
650   when :check
651     check = constraint[:check]
652     check = check.first if check.is_a?(Array) && check.length == 1
653     check = filter_expr(check)
654     check = "(#{check})" unless check[0..0] == '(' && check[-1..-1] == ')'
655     sql << "CHECK #{check}"
656   when :primary_key
657     sql << "PRIMARY KEY #{literal(constraint[:columns])}"
658   when :foreign_key
659     sql << column_references_table_constraint_sql(constraint.merge(:deferrable=>nil))
660   when :unique
661     sql << "UNIQUE #{literal(constraint[:columns])}"
662   else
663     raise Error, "Invalid constraint type #{constraint[:type]}, should be :check, :primary_key, :foreign_key, or :unique"
664   end
665   constraint_deferrable_sql_append(sql, constraint[:deferrable])
666   sql
667 end
create_table_as(name, sql, options) click to toggle source

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

    # File lib/sequel/database/schema_methods.rb
740 def create_table_as(name, sql, options)
741   sql = sql.sql if sql.is_a?(Sequel::Dataset)
742   run(create_table_as_sql(name, sql, options))
743 end
create_table_as_sql(name, sql, options) click to toggle source

SQL 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
747 def create_table_as_sql(name, sql, options)
748   "#{create_table_prefix_sql(name, options)} AS #{sql}"
749 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
683 def create_table_from_generator(name, generator, options)
684   execute_ddl(create_table_sql(name, generator, options))
685 end
create_table_generator_class() click to toggle source

The class used for create_table generators.

    # File lib/sequel/database/schema_methods.rb
688 def create_table_generator_class
689   Schema::CreateTableGenerator
690 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
693 def create_table_indexes_from_generator(name, generator, options)
694   e = options[:ignore_index_errors] || options[:if_not_exists]
695   generator.indexes.each do |index|
696     begin
697       pr = proc{index_sql_list(name, [index]).each{|sql| execute_ddl(sql)}}
698       supports_transactional_ddl? ? transaction(:savepoint=>:only, &pr) : pr.call
699     rescue Error
700       raise unless e
701     end
702   end
703 end
create_table_prefix_sql(name, options) click to toggle source

SQL fragment for initial part of CREATE TABLE statement

    # File lib/sequel/database/schema_methods.rb
752 def create_table_prefix_sql(name, options)
753   "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)}"
754 end
create_table_sql(name, generator, options) click to toggle source

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

    # File lib/sequel/database/schema_methods.rb
706 def create_table_sql(name, generator, options)
707   unless supports_named_column_constraints?
708     # Split column constraints into table constraints if they have a name
709     generator.columns.each do |c|
710       if (constraint_name = c.delete(:foreign_key_constraint_name)) && (table = c.delete(:table))
711         opts = {}
712         opts[:name] = constraint_name
713         [:key, :on_delete, :on_update, :deferrable].each{|k| opts[k] = c[k]}
714         generator.foreign_key([c[:name]], table, opts)
715       end
716       if (constraint_name = c.delete(:unique_constraint_name)) && c.delete(:unique)
717         generator.unique(c[:name], :name=>constraint_name)
718       end
719       if (constraint_name = c.delete(:primary_key_constraint_name)) && c.delete(:primary_key)
720         generator.primary_key([c[:name]], :name=>constraint_name)
721       end
722     end
723   end
724 
725   unless can_add_primary_key_constraint_on_nullable_columns?
726     if pk = generator.constraints.find{|op| op[:type] == :primary_key}
727       pk[:columns].each do |column|
728         if matched_column = generator.columns.find{|gc| gc[:name] == column}
729           matched_column[:null] = false
730         end
731       end
732     end
733   end
734 
735   "#{create_table_prefix_sql(name, options)} (#{column_list_sql(generator)})"
736 end
create_view_prefix_sql(name, options) click to toggle source

SQL fragment for initial part of CREATE VIEW statement

    # File lib/sequel/database/schema_methods.rb
757 def create_view_prefix_sql(name, options)
758   create_view_sql_append_columns("CREATE #{'OR REPLACE 'if options[:replace]}VIEW #{quote_schema_table(name)}", options[:columns])
759 end
create_view_sql(name, source, options) click to toggle source

SQL statement for creating a view.

    # File lib/sequel/database/schema_methods.rb
762 def create_view_sql(name, source, options)
763   source = source.sql if source.is_a?(Dataset)
764   sql = String.new
765   sql << "#{create_view_prefix_sql(name, options)} AS #{source}"
766   if check = options[:check]
767     sql << " WITH#{' LOCAL' if check == :local} CHECK OPTION"
768   end
769   sql
770 end
create_view_sql_append_columns(sql, columns) click to toggle source

Append the column list to the SQL, if a column list is given.

    # File lib/sequel/database/schema_methods.rb
773 def create_view_sql_append_columns(sql, columns)
774   if columns
775     sql += ' ('
776     schema_utility_dataset.send(:identifier_list_append, sql, columns)
777     sql << ')'
778   end
779   sql
780 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
784 def default_index_name(table_name, columns)
785   schema, table = schema_and_table(table_name)
786   "#{"#{schema}_" if schema}#{table}_#{columns.map{|c| [String, Symbol].any?{|cl| c.is_a?(cl)} ? c : literal(c).gsub(/\W/, '_')}.join('_')}_index"
787 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
797 def drop_index_sql(table, op)
798   "DROP INDEX #{quote_identifier(op[:name] || default_index_name(table, op[:columns]))}"
799 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
802 def drop_table_sql(name, options)
803   "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}"
804 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
807 def drop_view_sql(name, options)
808   "DROP VIEW#{' IF EXISTS' if options[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}"
809 end
filter_expr(*args, &block) click to toggle source

Proxy the filter_expr call to the dataset, used for creating constraints. Support passing Proc arguments as blocks, as well as treating plain strings as literal strings, so that previous migrations that used this API do not break.

    # File lib/sequel/database/schema_methods.rb
814 def filter_expr(*args, &block)
815   if args.length == 1
816     arg = args.first
817     if arg.is_a?(Proc) && !block
818       block = args.first
819       args = nil
820     elsif arg.is_a?(String)
821       args = [Sequel.lit(*args)]
822     elsif arg.is_a?(Array)
823       if arg.first.is_a?(String)
824         args = [Sequel.lit(*arg)]
825       elsif arg.length > 1
826         args = [Sequel.&(*arg)]
827       end
828     end
829   end
830   schema_utility_dataset.literal(schema_utility_dataset.send(:filter_expr, *args, &block))
831 end
foreign_key_name(table_name, columns) click to toggle source

Get foreign key name for given table and columns.

    # File lib/sequel/database/schema_methods.rb
790 def foreign_key_name(table_name, columns)
791   keys = foreign_key_list(table_name).select{|key| key[:columns] == columns}
792   raise(Error, "#{keys.empty? ? 'Missing' : 'Ambiguous'} foreign key for #{columns.inspect}") unless keys.size == 1
793   keys.first[:name]
794 end
index_definition_sql(table_name, index) click to toggle source

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

    # File lib/sequel/database/schema_methods.rb
835 def index_definition_sql(table_name, index)
836   index_name = index[:name] || default_index_name(table_name, index[:columns])
837   raise Error, "Index types are not supported for this database" if index[:type]
838   raise Error, "Partial indexes are not supported for this database" if index[:where] && !supports_partial_indexes?
839   "CREATE #{'UNIQUE ' if index[:unique]}INDEX #{quote_identifier(index_name)} ON #{quote_schema_table(table_name)} #{literal(index[:columns])}#{" WHERE #{filter_expr(index[:where])}" if index[:where]}"
840 end
index_sql_list(table_name, indexes) click to toggle source

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

    # File lib/sequel/database/schema_methods.rb
844 def index_sql_list(table_name, indexes)
845   indexes.map{|i| index_definition_sql(table_name, i)}
846 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
850 def join_table_name(hash, options)
851   entries = hash.values
852   raise Error, "must have 2 entries in hash given to (create|drop)_join_table" unless entries.length == 2
853   if options[:name]
854     options[:name]
855   else
856     table_names = entries.map{|e| join_table_name_extract(e)}
857     table_names.map(&:to_s).sort.join('_')
858   end
859 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
863 def join_table_name_extract(entry)
864   case entry
865   when Symbol, String
866     entry
867   when Hash
868     join_table_name_extract(entry[:table])
869   else
870     raise Error, "can't extract table name from #{entry.inspect}"
871   end
872 end
on_delete_clause(action) click to toggle source

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

:cascade

Delete rows referencing this row.

:no_action

Raise an error if other rows reference this row, allow deferring of the integrity check. This is the default.

: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
887 def on_delete_clause(action)
888   action.to_s.gsub("_", " ").upcase
889 end
on_update_clause(action) click to toggle source

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

    # File lib/sequel/database/schema_methods.rb
892 def on_update_clause(action)
893   on_delete_clause(action)
894 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
897 def quote_schema_table(table)
898   schema_utility_dataset.quote_schema_table(table)
899 end
rename_table_sql(name, new_name) click to toggle source

SQL statement for renaming a table.

    # File lib/sequel/database/schema_methods.rb
902 def rename_table_sql(name, new_name)
903   "ALTER TABLE #{quote_schema_table(name)} RENAME TO #{quote_schema_table(new_name)}"
904 end
schema_and_table(table_name) click to toggle source

Split the schema information from the table

    # File lib/sequel/database/schema_methods.rb
907 def schema_and_table(table_name)
908   schema_utility_dataset.schema_and_table(table_name)
909 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
912 def schema_autoincrementing_primary_key?(schema)
913   !!(schema[:primary_key] && schema[:auto_increment])
914 end
schema_utility_dataset() click to toggle source

The dataset to use for proxying certain schema methods.

    # File lib/sequel/database/schema_methods.rb
917 def schema_utility_dataset
918   @default_dataset
919 end
split_qualifiers(table_name) click to toggle source

Split the schema information from the table

    # File lib/sequel/database/schema_methods.rb
922 def split_qualifiers(table_name)
923   schema_utility_dataset.split_qualifiers(table_name)
924 end
temporary_table_sql() click to toggle source

SQL fragment for temporary table

    # File lib/sequel/database/schema_methods.rb
927 def temporary_table_sql
928   'TEMPORARY '
929 end
type_literal(column) click to toggle source

SQL fragment specifying the type of a given column.

    # File lib/sequel/database/schema_methods.rb
932 def type_literal(column)
933   case column[:type]
934   when Class
935     type_literal_generic(column)
936   when :Bignum
937     type_literal_generic_bignum_symbol(column)
938   else
939     type_literal_specific(column)
940   end
941 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
945 def type_literal_generic(column)
946   meth = "type_literal_generic_#{column[:type].name.to_s.downcase}"
947   if respond_to?(meth, true)
948     # Allow calling private methods as per type literal generic methods are private
949     send(meth, column)
950   else
951     raise Error, "Unsupported ruby class used as database type: #{column[:type]}"
952   end
953 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
956 def type_literal_generic_bigdecimal(column)
957   type_literal_generic_numeric(column)
958 end
type_literal_generic_bignum_symbol(column) click to toggle source

Sequel uses the bigint type by default for :Bignum symbol.

    # File lib/sequel/database/schema_methods.rb
961 def type_literal_generic_bignum_symbol(column)
962   :bigint
963 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
966 def type_literal_generic_date(column)
967   :date
968 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
971 def type_literal_generic_datetime(column)
972   :timestamp
973 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
976 def type_literal_generic_falseclass(column)
977   type_literal_generic_trueclass(column)
978 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
981 def type_literal_generic_file(column)
982   :blob
983 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
986 def type_literal_generic_fixnum(column)
987   type_literal_generic_integer(column)
988 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
991 def type_literal_generic_float(column)
992   :"double precision"
993 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
996 def type_literal_generic_integer(column)
997   :integer
998 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
1003 def type_literal_generic_numeric(column)
1004   column[:size] ? "numeric(#{Array(column[:size]).join(', ')})" : :numeric
1005 end
type_literal_generic_only_time(column) click to toggle source

Use time by default for Time values if :only_time option is used.

     # File lib/sequel/database/schema_methods.rb
1032 def type_literal_generic_only_time(column)
1033   :time
1034 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
1011 def type_literal_generic_string(column)
1012   if column[:text]
1013     uses_clob_for_text? ? :clob : :text
1014   elsif column[:fixed]
1015     "char(#{column[:size]||default_string_column_size})"
1016   else
1017     "varchar(#{column[:size]||default_string_column_size})"
1018   end
1019 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
1023 def type_literal_generic_time(column)
1024   if column[:only_time]
1025     type_literal_generic_only_time(column)
1026   else
1027     type_literal_generic_datetime(column)
1028   end
1029 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
1037 def type_literal_generic_trueclass(column)
1038   :boolean
1039 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
1043 def type_literal_specific(column)
1044   type = column[:type]
1045   type = "double precision" if type.to_s == 'double'
1046   column[:size] ||= default_string_column_size if type.to_s == 'varchar'
1047   elements = column[:size] || column[:elements]
1048   "#{type}#{literal(Array(elements)) if elements}#{' UNSIGNED' if column[:unsigned]}"
1049 end
uses_clob_for_text?() click to toggle source

Whether clob should be used for String text: true columns.

     # File lib/sequel/database/schema_methods.rb
1052 def uses_clob_for_text?
1053   false
1054 end

3 - Methods that create datasets

↑ top

Public Instance Methods

[](*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
21 def [](*args)
22   args.first.is_a?(String) ? fetch(*args) : from(*args)
23 end
dataset() 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
29 def dataset
30   @dataset_class.new(self)
31 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

See caveats listed in Dataset#with_sql regarding datasets using custom SQL and the methods that can be called on them.

   # File lib/sequel/database/dataset.rb
49 def fetch(sql, *args, &block)
50   ds = @default_dataset.with_sql(sql, *args)
51   ds.each(&block) if block
52   ds
53 end
from(*args, &block) click to toggle source

Returns a new dataset with the from method invoked. If a block is given, it acts as a virtual row block

DB.from(:items) # SELECT * FROM items
DB.from{schema[:table]} # SELECT * FROM schema.table
   # File lib/sequel/database/dataset.rb
60 def from(*args, &block)
61   if block
62     @default_dataset.from(*args, &block)
63   elsif args.length == 1 && (table = args[0]).is_a?(Symbol)
64     @default_dataset.send(:cached_dataset, :"_from_#{table}_ds"){@default_dataset.from(table)}
65   else
66     @default_dataset.from(*args)
67   end
68 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.function} # SELECT server_version()
DB.select(:id).from(:items) # SELECT id FROM items
   # File lib/sequel/database/dataset.rb
75 def select(*args, &block)
76   @default_dataset.select(*args, &block)
77 end

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

↑ top

Constants

ADAPTERS

Array of supported database adapters

Attributes

pool[R]

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

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
16 def self.adapter_class(scheme)
17   scheme.is_a?(Class) ? scheme : load_adapter(scheme.to_sym)
18 end
adapter_scheme() click to toggle source

Returns the scheme symbol for the Database class.

   # File lib/sequel/database/connecting.rb
21 def self.adapter_scheme
22   @scheme
23 end
connect(conn_string, opts = OPTS) { |db| ... } click to toggle source

Connects to a database. See Sequel.connect.

   # File lib/sequel/database/connecting.rb
26 def self.connect(conn_string, opts = OPTS)
27   case conn_string
28   when String
29     if conn_string.start_with?('jdbc:')
30       c = adapter_class(:jdbc)
31       opts = opts.merge(:orig_opts=>opts.dup)
32       opts = {:uri=>conn_string}.merge!(opts)
33     else
34       uri = URI.parse(conn_string)
35       scheme = uri.scheme
36       c = adapter_class(scheme)
37       uri_options = c.send(:uri_to_options, uri)
38       uri.query.split('&').map{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v if k && !k.empty?} unless uri.query.to_s.strip.empty?
39       uri_options.to_a.each{|k,v| uri_options[k] = (defined?(URI::DEFAULT_PARSER) ? URI::DEFAULT_PARSER : URI).unescape(v) if v.is_a?(String)}
40       opts = uri_options.merge(opts).merge!(:orig_opts=>opts.dup, :uri=>conn_string, :adapter=>scheme)
41     end
42   when Hash
43     opts = conn_string.merge(opts)
44     opts = opts.merge(:orig_opts=>opts.dup)
45     c = adapter_class(opts[:adapter_class] || opts[:adapter] || opts['adapter'])
46   else
47     raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}"
48   end
49 
50   opts = opts.inject({}) do |m, (k,v)|
51     k = :user if k.to_s == 'username'
52     m[k.to_sym] = v
53     m
54   end
55 
56   begin
57     db = c.new(opts)
58     db.test_connection if db.send(:typecast_value_boolean, opts.fetch(:test, true))
59     if block_given?
60       return yield(db)
61     end
62   ensure
63     if block_given?
64       db.disconnect if db
65       Sequel.synchronize{::Sequel::DATABASES.delete(db)}
66     end
67   end
68   db
69 end
load_adapter(scheme, opts=OPTS) click to toggle source

Load the adapter from the file system. Raises Sequel::AdapterNotFound if the adapter cannot be loaded, or if the adapter isn't registered correctly after being loaded. Options:

:map

The Hash in which to look for an already loaded adapter (defaults to ADAPTER_MAP).

:subdir

The subdirectory of sequel/adapters to look in, only to be used for loading subadapters.

    # File lib/sequel/database/connecting.rb
 77 def self.load_adapter(scheme, opts=OPTS)
 78   map = opts[:map] || ADAPTER_MAP
 79   if subdir = opts[:subdir]
 80     file = "#{subdir}/#{scheme}"
 81   else
 82     file = scheme
 83   end
 84   
 85   unless obj = Sequel.synchronize{map[scheme]}
 86     # attempt to load the adapter file
 87     begin
 88       require "sequel/adapters/#{file}"
 89     rescue LoadError => e
 90       # If subadapter file doesn't exist, just return,
 91       # using the main adapter class without database customizations.
 92       return if subdir
 93       raise Sequel.convert_exception_class(e, AdapterNotFound)
 94     end
 95     
 96     # make sure we actually loaded the adapter
 97     unless obj = Sequel.synchronize{map[scheme]}
 98       raise AdapterNotFound, "Could not load #{file} adapter: adapter class not registered in ADAPTER_MAP"
 99     end
100   end
101 
102   obj
103 end
set_shared_adapter_scheme(scheme, mod) click to toggle source

Sets the given module as the shared adapter module for the given scheme. Used to register shared adapters for use by the mock adapter. Example:

# in file sequel/adapters/shared/mydb.rb
module Sequel::MyDB
  Sequel::Database.set_shared_adapter_scheme :mydb, self

  def self.mock_adapter_setup(db)
    # ...
  end

  module DatabaseMethods
    # ...
  end

  module DatasetMethods
    # ...
  end
end

would allow the mock adapter to return a Database instance that supports the MyDB syntax via:

Sequel.connect('mock://mydb')
    # File lib/sequel/database/connecting.rb
147 def self.set_shared_adapter_scheme(scheme, mod)
148   Sequel.synchronize{SHARED_ADAPTER_MAP[scheme] = mod}
149 end

Public Instance Methods

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
162 def adapter_scheme
163   self.class.adapter_scheme
164 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. Only usable when using a sharded connection pool.

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
174 def add_servers(servers)
175   unless sharded?
176     raise Error, "cannot call Database#add_servers on a Database instance that does not use a sharded connection pool"
177   end
178 
179   h = @opts[:servers]
180   Sequel.synchronize{h.merge!(servers)}
181   @pool.add_servers(servers.keys)
182 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.

Sequel.connect('jdbc:postgres://...').database_type
# => :postgres
    # File lib/sequel/database/connecting.rb
193 def database_type
194   adapter_scheme
195 end
disconnect(opts = OPTS) click to toggle source

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

:server

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(server: :server1) # Single server
DB.disconnect(server: [:server1, :server2]) # Multiple servers
    # File lib/sequel/database/connecting.rb
207 def disconnect(opts = OPTS)
208   pool.disconnect(opts)
209 end
disconnect_connection(conn) click to toggle source

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

    # File lib/sequel/database/connecting.rb
214 def disconnect_connection(conn)
215   conn.close
216 end
remove_servers(*servers) click to toggle source

Dynamically remove existing servers from the connection pool. Only usable when using a sharded connection pool

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
227 def remove_servers(*servers)
228   unless sharded?
229     raise Error, "cannot call Database#remove_servers on a Database instance that does not use a sharded connection pool"
230   end
231 
232   h = @opts[:servers]
233   servers.flatten.each{|s| Sequel.synchronize{h.delete(s)}}
234   @pool.remove_servers(servers)
235 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
241 def servers
242   pool.servers
243 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
246 def single_threaded?
247   @single_threaded
248 end
synchronize(server=nil) { |conn| ... } click to toggle source

:nocov:

    # File lib/sequel/database/connecting.rb
252 def synchronize(server=nil)
253   @pool.hold(server || :default){|conn| yield conn}
254 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
278 def test_connection(server=nil)
279   synchronize(server){|conn|}
280   true
281 end
valid_connection?(conn) click to toggle source

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

    # File lib/sequel/database/connecting.rb
287 def valid_connection?(conn)
288   sql = valid_connection_sql
289   begin
290     log_connection_execute(conn, sql)
291   rescue Sequel::DatabaseError, *database_error_classes
292     false
293   else
294     true
295   end
296 end

Private Instance Methods

connection_pool_default_options() click to toggle source

The default options for the connection pool.

    # File lib/sequel/database/connecting.rb
301 def connection_pool_default_options
302   {}
303 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
308 def server_opts(server)
309   opts = if @opts[:servers] and server_options = @opts[:servers][server]
310     case server_options
311     when Hash
312       @opts.merge(server_options)
313     when Proc
314       @opts.merge(server_options.call(self))
315     else
316       raise Error, 'Server opts should be a hash or proc'
317     end
318   elsif server.is_a?(Hash)
319     @opts.merge(server)
320   else
321     @opts.dup
322   end
323   opts.delete(:servers)
324   opts
325 end
valid_connection_sql() click to toggle source

The SQL query to issue to check if a connection is valid.

    # File lib/sequel/database/connecting.rb
328 def valid_connection_sql
329   @valid_connection_sql ||= select(nil).sql
330 end

5 - Methods that set defaults for created datasets

↑ top

Attributes

dataset_class[R]

The class to use for creating datasets. Should respond to new with the Database argument as the first argument, and an optional options hash.

Public Instance Methods

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
18 def dataset_class=(c)
19   unless @dataset_modules.empty?
20     c = Class.new(c)
21     @dataset_modules.each{|m| c.send(:include, m)}
22   end
23   @dataset_class = c
24   reset_default_dataset
25 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.

If a block is given, a Dataset::DatasetModule instance is created, allowing for the easy creation of named dataset methods that will do caching.

Examples:

# Introspect 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

# Add some named dataset methods
DB.extend_datasets do
  order :by_id, :id
  select :with_id_and_name, :id, :name
  where :active, :active
end

DB[:table].active.with_id_and_name.by_id
# SELECT id, name FROM table WHERE active ORDER BY id
   # File lib/sequel/database/dataset_defaults.rb
62 def extend_datasets(mod=nil, &block)
63   raise(Error, "must provide either mod or block, not both") if mod && block
64   mod = Dataset::DatasetModule.new(&block) if block
65   if @dataset_modules.empty?
66    @dataset_modules = [mod]
67    @dataset_class = Class.new(@dataset_class)
68   else
69    @dataset_modules << mod
70   end
71   @dataset_class.send(:include, mod)
72   reset_default_dataset
73 end

Private Instance Methods

dataset_class_default() click to toggle source

The default dataset class to use for the database

   # File lib/sequel/database/dataset_defaults.rb
78 def dataset_class_default
79   Sequel::Dataset
80 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
89 def quote_identifiers_default
90   true
91 end
reset_default_dataset() click to toggle source

Reset the default dataset used by most Database methods that create datasets.

   # File lib/sequel/database/dataset_defaults.rb
83 def reset_default_dataset
84   Sequel.synchronize{@symbol_literal_cache.clear}
85   @default_dataset = dataset
86 end

6 - Methods relating to logging

↑ top

Attributes

log_connection_info[RW]

Whether to include information about the connection in use when logging queries.

log_warn_duration[RW]

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

loggers[RW]

Array of SQL loggers to use for this database.

sql_log_level[RW]

Log level at which to log SQL queries. This is actually the method sent to the logger, so it should be the method name symbol. The default is :info, it can be set to :debug to log at DEBUG level.

Public Instance Methods

log_connection_yield(sql, conn, 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
37 def log_connection_yield(sql, conn, args=nil)
38   return yield if skip_logging?
39   sql = "#{connection_info(conn) if conn && log_connection_info}#{sql}#{"; #{args.inspect}" if args}"
40   timer = Sequel.start_timer
41 
42   begin
43     yield
44   rescue => e
45     log_exception(e, sql)
46     raise
47   ensure
48     log_duration(Sequel.elapsed_seconds_since(timer), sql) unless e
49   end
50 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
26 def log_exception(exception, message)
27   log_each(:error, "#{exception.class}: #{exception.message.strip if exception.message}: #{message}")
28 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
31 def log_info(message, args=nil)
32   log_each(:info, args ? "#{message}; #{args.inspect}" : message)
33 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
55 def logger=(logger)
56   @loggers = Array(logger)
57 end

Private Instance Methods

connection_info(conn) click to toggle source

String including information about the connection, for use when logging connection info.

   # File lib/sequel/database/logging.rb
69 def connection_info(conn)
70   "(conn: #{conn.__id__}) "
71 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
75 def log_connection_execute(conn, sql)
76   log_connection_yield(sql, conn){conn.public_send(connection_execute_method, sql)}
77 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
81 def log_duration(duration, message)
82   log_each((lwd = log_warn_duration and duration >= lwd) ? :warn : sql_log_level, "(#{sprintf('%0.6fs', duration)}) #{message}")
83 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
87 def log_each(level, message)
88   @loggers.each{|logger| logger.public_send(level, message)}
89 end
skip_logging?() click to toggle source

Determine if logging should be skipped. Defaults to true if no loggers have been specified.

   # File lib/sequel/database/logging.rb
63 def skip_logging?
64   @loggers.empty?
65 end

7 - Miscellaneous methods

↑ top

Constants

CHECK_CONSTRAINT_SQLSTATES
DEFAULT_DATABASE_ERROR_REGEXPS

Empty exception regexp to class map, used by default if Sequel doesn't have specific support for the database in use.

DEFAULT_STRING_COLUMN_SIZE

The general default size for string columns for all Sequel::Database instances.

EXTENSIONS

Hash of extension name symbols to callable objects to load the extension into the Database object (usually by extending it with a module defined in the extension).

FOREIGN_KEY_CONSTRAINT_SQLSTATES
NOT_NULL_CONSTRAINT_SQLSTATES
SCHEMA_TYPE_CLASSES

Mapping of schema type symbols to class or arrays of classes for that symbol.

SERIALIZATION_CONSTRAINT_SQLSTATES
UNIQUE_CONSTRAINT_SQLSTATES

Attributes

default_string_column_size[RW]

The specific default size of string columns for this Sequel::Database, usually 255 by default.

opts[R]

The options hash for this database

timezone[W]

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

Public Class Methods

after_initialize(&block) click to toggle source

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

   # File lib/sequel/database/misc.rb
34 def self.after_initialize(&block)
35   raise Error, "must provide block to after_initialize" unless block
36   Sequel.synchronize do
37     previous = @initialize_hook
38     @initialize_hook = proc do |db|
39       previous.call(db)
40       block.call(db)
41     end
42   end
43 end
extension(*extensions) click to toggle source

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

   # File lib/sequel/database/misc.rb
46 def self.extension(*extensions)
47   after_initialize{|db| db.extension(*extensions)}
48 end
new(opts = OPTS) click to toggle source

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

Accepts the following options:

:cache_schema

Whether schema should be cached for this Database instance

:default_string_column_size

The default size of string columns, 255 by default.

:extensions

Extensions to load into this Database instance. Can be a symbol, array of symbols, or string with extensions separated by columns. These extensions are loaded after connections are made by the :preconnect option.

:keep_reference

Whether to keep a reference to this instance in Sequel::DATABASES, true by default.

:logger

A specific logger to use.

:loggers

An array of loggers to use.

:log_connection_info

Whether connection information should be logged when logging queries.

:log_warn_duration

The number of elapsed seconds after which queries should be logged at warn level.

:name

A name to use for the Database object, displayed in PoolTimeout .

:preconnect

Automatically create the maximum number of connections, so that they don't need to be created as needed. This is useful when connecting takes a long time and you want to avoid possible latency during runtime. Set to :concurrently to create the connections in separate threads. Otherwise they'll be created sequentially.

:preconnect_extensions

Similar to the :extensions option, but loads the extensions before the connections are made by the :preconnect option.

: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. Additional options respected by the connection pool are :after_connect, :connect_sqls, :max_connections, :pool_timeout, :servers, and :servers_hash. See the connection pool documentation for details.

    # File lib/sequel/database/misc.rb
124 def initialize(opts = OPTS)
125   @opts ||= opts
126   @opts = connection_pool_default_options.merge(@opts)
127   @loggers = Array(@opts[:logger]) + Array(@opts[:loggers])
128   @opts[:servers] = {} if @opts[:servers].is_a?(String)
129   @sharded = !!@opts[:servers]
130   @opts[:adapter_class] = self.class
131   @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, Sequel.single_threaded))
132   @default_string_column_size = @opts[:default_string_column_size] || DEFAULT_STRING_COLUMN_SIZE
133 
134   @schemas = {}
135   @prepared_statements = {}
136   @transactions = {}
137   @symbol_literal_cache = {}
138 
139   @timezone = nil
140 
141   @dataset_class = dataset_class_default
142   @cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true))
143   @dataset_modules = []
144   @loaded_extensions = []
145   @schema_type_classes = SCHEMA_TYPE_CLASSES.dup
146 
147   self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info
148   self.log_warn_duration = @opts[:log_warn_duration]
149   self.log_connection_info = typecast_value_boolean(@opts[:log_connection_info])
150 
151   @pool = ConnectionPool.get_pool(self, @opts)
152 
153   reset_default_dataset
154   adapter_initialize
155 
156   unless typecast_value_boolean(@opts[:keep_reference]) == false
157     Sequel.synchronize{::Sequel::DATABASES.push(self)}
158   end
159   Sequel::Database.run_after_initialize(self)
160 
161   initialize_load_extensions(:preconnect_extensions)
162 
163   if typecast_value_boolean(@opts[:preconnect]) && @pool.respond_to?(:preconnect, true)
164     concurrent = typecast_value_string(@opts[:preconnect]) == "concurrently"
165     @pool.send(:preconnect, concurrent)
166   end
167 
168   initialize_load_extensions(:extensions)
169 end
register_extension(ext, mod=nil, &block) click to toggle source

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

   # File lib/sequel/database/misc.rb
55 def self.register_extension(ext, mod=nil, &block)
56   if mod
57     raise(Error, "cannot provide both mod and block to Database.register_extension") if block
58     if mod.is_a?(Module)
59       block = proc{|db| db.extend(mod)}
60     else
61       block = mod
62     end
63   end
64   Sequel.synchronize{EXTENSIONS[ext] = block}
65 end
run_after_initialize(instance) click to toggle source

Run the after_initialize hook for the given instance.

   # File lib/sequel/database/misc.rb
68 def self.run_after_initialize(instance)
69   @initialize_hook.call(instance)
70 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
74 def self.uri_to_options(uri)
75   {
76     :user => uri.user,
77     :password => uri.password,
78     :port => uri.port,
79     :host => uri.hostname,
80     :database => (m = /\/(.*)/.match(uri.path)) && (m[1])
81   }
82 end

Public Instance Methods

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
196 def cast_type_literal(type)
197   type_literal(:type=>type)
198 end
extension(*exts) click to toggle source

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

    # File lib/sequel/database/misc.rb
205 def extension(*exts)
206   Sequel.extension(*exts)
207   exts.each do |ext|
208     if pr = Sequel.synchronize{EXTENSIONS[ext]}
209       unless Sequel.synchronize{@loaded_extensions.include?(ext)}
210         Sequel.synchronize{@loaded_extensions << ext}
211         pr.call(self)
212       end
213     else
214       raise(Error, "Extension #{ext} does not have specific support handling individual databases (try: Sequel.extension #{ext.inspect})")
215     end
216   end
217   self
218 end
freeze() click to toggle source

Freeze internal data structures for the Database instance.

Calls superclass method
    # File lib/sequel/database/misc.rb
172 def freeze
173   valid_connection_sql
174   metadata_dataset
175   @opts.freeze
176   @loggers.freeze
177   @pool.freeze
178   @dataset_class.freeze
179   @dataset_modules.freeze
180   @schema_type_classes.freeze
181   @loaded_extensions.freeze
182   metadata_dataset
183   super
184 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
223 def from_application_timestamp(v)
224   Sequel.convert_output_timestamp(v, timezone)
225 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
229 def inspect
230   a = []
231   a << uri.inspect if uri
232   if (oo = opts[:orig_opts]) && !oo.empty?
233     a << oo.inspect
234   end
235   "#<#{self.class}: #{a.join(' ')}>"
236 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
243 def literal(v)
244   schema_utility_dataset.literal(v)
245 end
literal_symbol(sym) click to toggle source

Return the literalized version of the symbol if cached, or nil if it is not cached.

    # File lib/sequel/database/misc.rb
249 def literal_symbol(sym)
250   Sequel.synchronize{@symbol_literal_cache[sym]}
251 end
literal_symbol_set(sym, lit) click to toggle source

Set the cached value of the literal symbol.

    # File lib/sequel/database/misc.rb
254 def literal_symbol_set(sym, lit)
255   Sequel.synchronize{@symbol_literal_cache[sym] = lit}
256 end
prepared_statement(name) click to toggle source

Synchronize access to the prepared statements cache.

    # File lib/sequel/database/misc.rb
259 def prepared_statement(name)
260   Sequel.synchronize{prepared_statements[name]}
261 end
quote_identifier(v) click to toggle source

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

    # File lib/sequel/database/misc.rb
266 def quote_identifier(v)
267   schema_utility_dataset.quote_identifier(v)
268 end
schema_type_class(type) click to toggle source

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

    # File lib/sequel/database/misc.rb
271 def schema_type_class(type)
272   @schema_type_classes[type]
273 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
276 def serial_primary_key_options
277   {:primary_key => true, :type => Integer, :auto_increment => true}
278 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
281 def set_prepared_statement(name, ps)
282   Sequel.synchronize{prepared_statements[name] = ps}
283 end
sharded?() click to toggle source

Whether this database instance uses multiple servers, either for sharding or for primary/replica configurations.

    # File lib/sequel/database/misc.rb
287 def sharded?
288   @sharded
289 end
timezone() click to toggle source

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

    # File lib/sequel/database/misc.rb
292 def timezone
293   @timezone || Sequel.database_timezone
294 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
299 def to_application_timestamp(v)
300   Sequel.convert_timestamp(v, timezone)
301 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
308 def typecast_value(column_type, value)
309   return nil if value.nil?
310   meth = "typecast_value_#{column_type}"
311   begin
312     # Allow calling private methods as per-type typecasting methods are private
313     respond_to?(meth, true) ? send(meth, value) : value
314   rescue ArgumentError, TypeError => e
315     raise Sequel.convert_exception_class(e, InvalidValue)
316   end
317 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
321 def uri
322   opts[:uri]
323 end
url() click to toggle source

Explicit alias of uri for easier subclassing.

    # File lib/sequel/database/misc.rb
326 def url
327   uri
328 end

Private Instance Methods

_typecast_value_string_to_decimal(value) click to toggle source

:nocov:

    # File lib/sequel/database/misc.rb
484 def _typecast_value_string_to_decimal(value)
485   d = BigDecimal(value)
486   if d.zero?
487     # BigDecimal parsing is loose by default, returning a 0 value for
488     # invalid input.  If a zero value is received, use Float to check
489     # for validity.
490     begin
491       Float(value)
492     rescue ArgumentError
493       raise InvalidValue, "invalid value for BigDecimal: #{value.inspect}"
494     end
495   end
496   d
497 end
adapter_initialize() click to toggle source

Per adapter initialization method, empty by default.

    # File lib/sequel/database/misc.rb
333 def adapter_initialize
334 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
340 def blank_object?(obj)
341   return obj.blank? if obj.respond_to?(:blank?)
342   case obj
343   when NilClass, FalseClass
344     true
345   when Numeric, TrueClass
346     false
347   when String
348     obj.strip.empty?
349   else
350     obj.respond_to?(:empty?) ? obj.empty? : false
351   end
352 end
database_error_class(exception, opts) click to toggle source

Return the Sequel::DatabaseError subclass to wrap the given exception in.

    # File lib/sequel/database/misc.rb
363 def database_error_class(exception, opts)
364   database_specific_error_class(exception, opts) || DatabaseError
365 end
database_error_regexps() click to toggle source

An enumerable yielding pairs of regexps and exception classes, used to match against underlying driver exception messages in order to raise a more specific Sequel::DatabaseError subclass.

    # File lib/sequel/database/misc.rb
357 def database_error_regexps
358   DEFAULT_DATABASE_ERROR_REGEXPS
359 end
database_exception_sqlstate(exception, opts) click to toggle source

Return the SQLState for the given exception, if one can be determined

    # File lib/sequel/database/misc.rb
368 def database_exception_sqlstate(exception, opts)
369   nil
370 end
database_specific_error_class(exception, opts) click to toggle source

Return a specific Sequel::DatabaseError exception class if one is appropriate for the underlying exception, or nil if there is no specific exception class.

    # File lib/sequel/database/misc.rb
375 def database_specific_error_class(exception, opts)
376   return DatabaseDisconnectError if disconnect_error?(exception, opts)
377 
378   if sqlstate = database_exception_sqlstate(exception, opts)
379     if klass = database_specific_error_class_from_sqlstate(sqlstate)
380       return klass
381     end
382   else
383     database_error_regexps.each do |regexp, klss|
384       return klss if exception.message =~ regexp
385     end
386   end
387 
388   nil
389 end
database_specific_error_class_from_sqlstate(sqlstate) click to toggle source

Given the SQLState, return the appropriate DatabaseError subclass.

    # File lib/sequel/database/misc.rb
397 def database_specific_error_class_from_sqlstate(sqlstate)
398   case sqlstate
399   when *NOT_NULL_CONSTRAINT_SQLSTATES
400     NotNullConstraintViolation
401   when *FOREIGN_KEY_CONSTRAINT_SQLSTATES
402     ForeignKeyConstraintViolation
403   when *UNIQUE_CONSTRAINT_SQLSTATES
404     UniqueConstraintViolation
405   when *CHECK_CONSTRAINT_SQLSTATES
406     CheckConstraintViolation
407   when *SERIALIZATION_CONSTRAINT_SQLSTATES
408     SerializationFailure
409   end
410 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
413 def disconnect_error?(exception, opts)
414   opts[:disconnect]
415 end
initialize_load_extensions(key) click to toggle source

Load extensions during initialization from the given key in opts.

    # File lib/sequel/database/misc.rb
418 def initialize_load_extensions(key)
419   case exts = @opts[key]
420   when String
421     extension(*exts.split(',').map(&:to_sym))
422   when Array
423     extension(*exts)
424   when Symbol
425     extension(exts)
426   when nil
427     # nothing
428   else
429     raise Error, "unsupported Database #{key.inspect} option: #{@opts[key].inspect}"
430   end
431 end
raise_error(exception, opts=OPTS) click to toggle source

Convert the given exception to an appropriate Sequel::DatabaseError subclass, keeping message and backtrace.

    # File lib/sequel/database/misc.rb
435 def raise_error(exception, opts=OPTS)
436   if !opts[:classes] || Array(opts[:classes]).any?{|c| exception.is_a?(c)}
437     raise Sequel.convert_exception_class(exception, database_error_class(exception, opts))
438   else
439     raise exception
440   end
441 end
typecast_value_blob(value) click to toggle source

Typecast the value to an SQL::Blob

    # File lib/sequel/database/misc.rb
444 def typecast_value_blob(value)
445   value.is_a?(Sequel::SQL::Blob) ? value : Sequel::SQL::Blob.new(value)
446 end
typecast_value_boolean(value) click to toggle source

Typecast the value to true, false, or nil

    # File lib/sequel/database/misc.rb
449 def typecast_value_boolean(value)
450   case value
451   when false, 0, "0", /\Af(alse)?\z/i, /\Ano?\z/i
452     false
453   else
454     blank_object?(value) ? nil : true
455   end
456 end
typecast_value_date(value) click to toggle source

Typecast the value to a Date

    # File lib/sequel/database/misc.rb
459 def typecast_value_date(value)
460   case value
461   when DateTime, Time
462     Date.new(value.year, value.month, value.day)
463   when Date
464     value
465   when String
466     Sequel.string_to_date(value)
467   when Hash
468     Date.new(*[:year, :month, :day].map{|x| (value[x] || value[x.to_s]).to_i})
469   else
470     raise InvalidValue, "invalid value for Date: #{value.inspect}"
471   end
472 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
475 def typecast_value_datetime(value)
476   Sequel.typecast_to_application_timestamp(value)
477 end
typecast_value_decimal(value) click to toggle source

Typecast the value to a BigDecimal

    # File lib/sequel/database/misc.rb
502 def typecast_value_decimal(value)
503   case value
504   when BigDecimal
505     value
506   when Numeric
507     BigDecimal(value.to_s)
508   when String
509     _typecast_value_string_to_decimal(value)
510   else
511     raise InvalidValue, "invalid value for BigDecimal: #{value.inspect}"
512   end
513 end
typecast_value_integer(value) click to toggle source

Typecast the value to an Integer

    # File lib/sequel/database/misc.rb
519 def typecast_value_integer(value)
520   (value.is_a?(String) && value =~ /\A0+(\d)/) ? Integer(value, 10) : Integer(value)
521 end
typecast_value_string(value) click to toggle source

Typecast the value to a String

    # File lib/sequel/database/misc.rb
524 def typecast_value_string(value)
525   case value
526   when Hash, Array
527     raise Sequel::InvalidValue, "invalid value for String: #{value.inspect}"
528   else
529     value.to_s
530   end
531 end
typecast_value_time(value) click to toggle source

Typecast the value to a Time

    # File lib/sequel/database/misc.rb
534 def typecast_value_time(value)
535   case value
536   when Time
537     if value.is_a?(SQLTime)
538       value
539     else
540       SQLTime.create(value.hour, value.min, value.sec, value.nsec/1000.0)
541     end
542   when String
543     Sequel.string_to_time(value)
544   when Hash
545     SQLTime.create(*[:hour, :minute, :second].map{|x| (value[x] || value[x.to_s]).to_i})
546   else
547     raise Sequel::InvalidValue, "invalid value for Time: #{value.inspect}"
548   end
549 end

8 - Methods related to database transactions

↑ top

Constants

TRANSACTION_ISOLATION_LEVELS

Attributes

transaction_isolation_level[RW]

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

Public Instance Methods

after_commit(opts=OPTS) { || ... } 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:

:savepoint

If currently inside a savepoint, only run this hook on transaction commit if all enclosing savepoints have been released.

:server

The server/shard to use.

   # File lib/sequel/database/transactions.rb
31 def after_commit(opts=OPTS, &block)
32   raise Error, "must provide block to after_commit" unless block
33   synchronize(opts[:server]) do |conn|
34     if h = _trans(conn)
35       raise Error, "cannot call after_commit in a prepared transaction" if h[:prepare]
36       if opts[:savepoint] && in_savepoint?(conn)
37         add_savepoint_hook(conn, :after_commit, block)
38       else
39         add_transaction_hook(conn, :after_commit, block)
40       end
41     else
42       yield
43     end
44   end
45 end
after_rollback(opts=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:

:savepoint

If currently inside a savepoint, run this hook immediately when any enclosing savepoint is rolled back, which may be before the transaction commits or rollsback.

:server

The server/shard to use.

   # File lib/sequel/database/transactions.rb
55 def after_rollback(opts=OPTS, &block)
56   raise Error, "must provide block to after_rollback" unless block
57   synchronize(opts[:server]) do |conn|
58     if h = _trans(conn)
59       raise Error, "cannot call after_rollback in a prepared transaction" if h[:prepare]
60       if opts[:savepoint] && in_savepoint?(conn)
61         add_savepoint_hook(conn, :after_rollback, block)
62       else
63         add_transaction_hook(conn, :after_rollback, block)
64       end
65     end
66   end
67 end
in_transaction?(opts=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/transactions.rb
113 def in_transaction?(opts=OPTS)
114   synchronize(opts[:server]){|conn| !!_trans(conn)}
115 end
rollback_checker(opts=OPTS) click to toggle source

Returns a proc that you can call to check if the transaction has been rolled back. The proc will return nil if the transaction is still in progress, true if the transaction was rolled back, and false if it was committed. Raises an Error if called outside a transaction. Respects the :server option for selecting a shard.

    # File lib/sequel/database/transactions.rb
123 def rollback_checker(opts=OPTS)
124   synchronize(opts[:server]) do |conn|
125     raise Error, "not in a transaction" unless t = _trans(conn)
126     t[:rollback_checker] ||= proc{Sequel.synchronize{t[:rolled_back]}}
127   end
128 end
rollback_on_exit(opts=OPTS) click to toggle source

When exiting the transaction block through methods other than an exception (e.g. normal exit, non-local return, or throw), set the current transaction to rollback instead of committing. This is designed for use in cases where you want to preform a non-local return but also want to rollback instead of committing. Options:

:cancel

Cancel the current rollback_on_exit setting, so exiting will commit instead of rolling back.

:savepoint

Rollback only the current savepoint if inside a savepoint. Can also be an positive integer value to rollback that number of enclosing savepoints, up to and including the transaction itself. If the database does not support savepoints, this option is ignored and the entire transaction is affected.

:server

The server/shard the transaction is being executed on.

    # File lib/sequel/database/transactions.rb
 83 def rollback_on_exit(opts=OPTS)
 84   synchronize(opts[:server]) do |conn|
 85     raise Error, "Cannot call Sequel:: Database#rollback_on_exit! unless inside a transaction" unless h = _trans(conn)
 86     rollback = !opts[:cancel]
 87 
 88     if supports_savepoints?
 89       savepoints = h[:savepoints]
 90 
 91       if level = opts[:savepoint]
 92         level = 1 if level == true
 93         raise Error, "invalid :savepoint option to Database#rollback_on_exit: #{level.inspect}" unless level.is_a?(Integer)
 94         raise Error, "cannot pass nonpositive integer (#{level.inspect}) as :savepoint option to Database#rollback_on_exit" if level < 1
 95         level.times do |i|
 96           break unless savepoint = savepoints[-1 - i]
 97           savepoint[:rollback_on_exit] = rollback
 98         end
 99       else
100         savepoints[0][:rollback_on_exit] = rollback
101       end
102     else
103       h[:rollback_on_exit] = rollback
104     end
105   end
106 
107   nil
108 end
transaction(opts=OPTS) { |conn| ... } 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 tables do not support transactions.

The following general options are respected:

:auto_savepoint

Automatically use a savepoint for Database#transaction calls inside this transaction block.

:isolation

The transaction isolation level to use for this transaction, should be :uncommitted, :committed, :repeatable, or :serializable, used if given and the database/adapter supports customizable transaction isolation levels.

:num_retries

The number of times to retry if the :retry_on option is used. The default is 5 times. Can be set to nil to retry indefinitely, but that is not recommended.

:before_retry

Proc to execute before rertrying if the :retry_on option is used. Called with two arguments: the number of retry attempts (counting the current one) and the error the last attempt failed with.

:prepare

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

:retry_on

An exception class or array of exception classes for which to automatically retry the transaction. Can only be set if not inside an existing transaction. Note that this should not be used unless the entire transaction block is idempotent, as otherwise it can cause non-idempotent behavior to execute multiple times.

:rollback

Can the set to :reraise to reraise any Sequel::Rollback exceptions raised, or :always to always rollback even if no exceptions occur (useful for testing).

:server

The server to use for the transaction. Set to :default, :read_only, or whatever symbol you used in the connect string when naming your servers.

: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. If the surrounding transaction uses :auto_savepoint, you can set this to false to not use a savepoint. If the value given for this option is :only, it will only create a savepoint if it is inside a transaction.

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/transactions.rb
177 def transaction(opts=OPTS, &block)
178   opts = Hash[opts]
179   if retry_on = opts[:retry_on]
180     tot_retries = opts.fetch(:num_retries, 5)
181     num_retries = 0 unless tot_retries.nil?
182     begin
183       opts[:retry_on] = nil
184       opts[:retrying] = true
185       transaction(opts, &block)
186     rescue *retry_on => e
187       if num_retries
188         num_retries += 1
189         if num_retries <= tot_retries
190           opts[:before_retry].call(num_retries, e) if opts[:before_retry]
191           retry
192         end
193       else
194         retry
195       end
196       raise
197     end
198   else
199     synchronize(opts[:server]) do |conn|
200       if opts[:savepoint] == :only
201         if supports_savepoints?
202           if _trans(conn)
203             opts[:savepoint] = true
204           else
205             return yield(conn)
206           end
207         else
208           opts[:savepoint] = false
209         end
210       end
211 
212       if already_in_transaction?(conn, opts)
213         if opts[:rollback] == :always && !opts.has_key?(:savepoint)
214           if supports_savepoints? 
215             opts[:savepoint] = true
216           else
217             raise Sequel::Error, "cannot set :rollback=>:always transaction option if already inside a transaction"
218           end
219         end
220 
221         if opts[:savepoint] != false && (stack = _trans(conn)[:savepoints]) && stack.last[:auto_savepoint]
222           opts[:savepoint] = true
223         end
224 
225         unless opts[:savepoint]
226           if opts[:retrying]
227             raise Sequel::Error, "cannot set :retry_on options if you are already inside a transaction"
228           end
229           return yield(conn)
230         end
231       end
232 
233       _transaction(conn, opts, &block)
234     end
235   end
236 end

Private Instance Methods

_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/transactions.rb
289 def _trans(conn)
290   Sequel.synchronize{@transactions[conn]}
291 end
_transaction(conn, opts=OPTS) { |conn| ... } 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/transactions.rb
244 def _transaction(conn, opts=OPTS)
245   rollback = opts[:rollback]
246   begin
247     add_transaction(conn, opts)
248     begin_transaction(conn, opts)
249     if rollback == :always
250       begin
251         ret = yield(conn)
252       rescue Exception => e1
253         raise e1
254       ensure
255         raise ::Sequel::Rollback unless e1
256       end
257     else
258       yield(conn)
259     end
260   rescue Exception => e
261     begin
262       rollback_transaction(conn, opts)
263     rescue Exception => e3
264     end
265     transaction_error(e, :conn=>conn, :rollback=>rollback)
266     raise e3 if e3
267     ret
268   ensure
269     begin
270       committed = commit_or_rollback_transaction(e, conn, opts)
271     rescue Exception => e2
272       begin
273         raise_error(e2, :classes=>database_error_classes, :conn=>conn)
274       rescue Sequel::DatabaseError => e4
275         begin
276           rollback_transaction(conn, opts)
277         ensure
278           raise e4
279         end
280       end
281     ensure
282       remove_transaction(conn, committed)
283     end
284   end
285 end
add_savepoint_hook(conn, type, block) click to toggle source

Set the given callable as a hook to be called. Type should be either :after_commit or :after_rollback.

    # File lib/sequel/database/transactions.rb
316 def add_savepoint_hook(conn, type, block)
317   savepoint = _trans(conn)[:savepoints].last
318   (savepoint[type] ||= []) << block
319 end
add_transaction(conn, opts) click to toggle source

Add the current thread to the list of active transactions

    # File lib/sequel/database/transactions.rb
294 def add_transaction(conn, opts)
295   hash = transaction_options(conn, opts)
296 
297   if supports_savepoints?
298     if t = _trans(conn)
299       t[:savepoints].push({:auto_savepoint=>opts[:auto_savepoint]})
300       return
301     else
302       hash[:savepoints] = [{:auto_savepoint=>opts[:auto_savepoint]}]
303       if (prep = opts[:prepare]) && supports_prepared_transactions?
304         hash[:prepare] = prep
305       end
306     end
307   elsif (prep = opts[:prepare]) && supports_prepared_transactions?
308     hash[:prepare] = prep
309   end
310 
311   Sequel.synchronize{@transactions[conn] = hash}
312 end
add_transaction_hook(conn, type, block) click to toggle source

Set the given callable as a hook to be called. Type should be either :after_commit or :after_rollback.

    # File lib/sequel/database/transactions.rb
323 def add_transaction_hook(conn, type, block)
324   hooks = _trans(conn)[type] ||= []
325   hooks << block
326 end
already_in_transaction?(conn, opts) click to toggle source

Whether the given connection is already inside a transaction

    # File lib/sequel/database/transactions.rb
329 def already_in_transaction?(conn, opts)
330   _trans(conn) && (!supports_savepoints? || !opts[:savepoint])
331 end
begin_new_transaction(conn, opts) click to toggle source

Start a new database transaction on the given connection

    # File lib/sequel/database/transactions.rb
350 def begin_new_transaction(conn, opts)
351   log_connection_execute(conn, begin_transaction_sql)
352   set_transaction_isolation(conn, opts)
353 end
begin_savepoint(conn, opts) click to toggle source

Issue query to begin a new savepoint.

    # File lib/sequel/database/transactions.rb
340 def begin_savepoint(conn, opts)
341   log_connection_execute(conn, begin_savepoint_sql(savepoint_level(conn)-1))
342 end
begin_savepoint_sql(depth) click to toggle source

SQL to start a new savepoint

    # File lib/sequel/database/transactions.rb
345 def begin_savepoint_sql(depth)
346   "SAVEPOINT autopoint_#{depth}"
347 end
begin_transaction(conn, opts=OPTS) click to toggle source

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

    # File lib/sequel/database/transactions.rb
356 def begin_transaction(conn, opts=OPTS)
357   if in_savepoint?(conn)
358     begin_savepoint(conn, opts)
359   else
360     begin_new_transaction(conn, opts)
361   end
362 end
begin_transaction_sql() click to toggle source

SQL to BEGIN a transaction.

    # File lib/sequel/database/transactions.rb
365 def begin_transaction_sql
366   'BEGIN'
367 end
commit_or_rollback_transaction(exception, conn, opts) click to toggle source

Whether to commit the current transaction. Thread.current.status is checked because Thread#kill skips rescue blocks (so exception would be nil), but the transaction should still be rolled back. On Ruby 1.9 (but not 2.0+), the thread status will still be “run”, so Thread#kill will erroneously commit the transaction, and there isn't a workaround.

    # File lib/sequel/database/transactions.rb
374 def commit_or_rollback_transaction(exception, conn, opts)
375   if exception
376     false
377   else
378     if rollback_on_transaction_exit?(conn, opts)
379       rollback_transaction(conn, opts)
380       false
381     else
382       commit_transaction(conn, opts)
383       true
384     end
385   end
386 end
commit_savepoint_sql(depth) click to toggle source

SQL to commit a savepoint

    # File lib/sequel/database/transactions.rb
389 def commit_savepoint_sql(depth)
390   "RELEASE SAVEPOINT autopoint_#{depth}"
391 end
commit_transaction(conn, opts=OPTS) click to toggle source

Commit the active transaction on the connection

    # File lib/sequel/database/transactions.rb
394 def commit_transaction(conn, opts=OPTS)
395   if supports_savepoints?
396     depth = savepoint_level(conn)
397     log_connection_execute(conn, depth > 1 ? commit_savepoint_sql(depth-1) : commit_transaction_sql)
398   else
399     log_connection_execute(conn, commit_transaction_sql)
400   end
401 end
commit_transaction_sql() click to toggle source

SQL to COMMIT a transaction.

    # File lib/sequel/database/transactions.rb
404 def commit_transaction_sql
405   'COMMIT'
406 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/transactions.rb
410 def connection_execute_method
411   :execute
412 end
database_error_classes() click to toggle source

Which transaction errors to translate, blank by default.

    # File lib/sequel/database/transactions.rb
415 def database_error_classes
416   []
417 end
in_savepoint?(conn) click to toggle source

Whether the connection is currently inside a savepoint.

    # File lib/sequel/database/transactions.rb
420 def in_savepoint?(conn)
421   supports_savepoints? && savepoint_level(conn) > 1
422 end
remove_transaction(conn, committed) click to toggle source

Remove the current thread from the list of active transactions

    # File lib/sequel/database/transactions.rb
441 def remove_transaction(conn, committed)
442   if in_savepoint?(conn)
443     savepoint_callbacks = savepoint_hooks(conn, committed)
444     if committed
445       savepoint_rollback_callbacks = savepoint_hooks(conn, false)
446     end
447   else
448     callbacks = transaction_hooks(conn, committed)
449   end
450 
451   if transaction_finished?(conn)
452     h = _trans(conn)
453     rolled_back = !committed
454     Sequel.synchronize{h[:rolled_back] = rolled_back}
455     Sequel.synchronize{@transactions.delete(conn)}
456     callbacks.each(&:call) if callbacks
457   elsif savepoint_callbacks || savepoint_rollback_callbacks
458     if committed
459       meth = in_savepoint?(conn) ? :add_savepoint_hook : :add_transaction_hook 
460 
461       if savepoint_callbacks
462         savepoint_callbacks.each do |block|
463           send(meth, conn, :after_commit, block)
464         end
465       end
466       
467       if savepoint_rollback_callbacks
468         savepoint_rollback_callbacks.each do |block|
469           send(meth, conn, :after_rollback, block)
470         end
471       end
472     else
473       savepoint_callbacks.each(&:call)
474     end
475   end
476 end
rollback_on_transaction_exit?(conn, opts) click to toggle source

Whether to rollback the transaction when exiting the transaction.

    # File lib/sequel/database/transactions.rb
484 def rollback_on_transaction_exit?(conn, opts)
485   return true if Thread.current.status == 'aborting'
486   h = _trans(conn)
487   if supports_savepoints?
488     h[:savepoints].last[:rollback_on_exit]
489   else
490     h[:rollback_on_exit]
491   end
492 end
rollback_savepoint_sql(depth) click to toggle source

SQL to rollback to a savepoint

    # File lib/sequel/database/transactions.rb
479 def rollback_savepoint_sql(depth)
480   "ROLLBACK TO SAVEPOINT autopoint_#{depth}"
481 end
rollback_transaction(conn, opts=OPTS) click to toggle source

Rollback the active transaction on the connection

    # File lib/sequel/database/transactions.rb
495 def rollback_transaction(conn, opts=OPTS)
496   if supports_savepoints?
497     depth = savepoint_level(conn)
498     log_connection_execute(conn, depth > 1 ? rollback_savepoint_sql(depth-1) : rollback_transaction_sql)
499   else
500     log_connection_execute(conn, rollback_transaction_sql)
501   end
502 end
rollback_transaction_sql() click to toggle source

SQL to ROLLBACK a transaction.

    # File lib/sequel/database/transactions.rb
505 def rollback_transaction_sql
506   'ROLLBACK'
507 end
savepoint_hooks(conn, committed) click to toggle source

Retrieve the savepoint hooks that should be run for the given connection and commit status.

    # File lib/sequel/database/transactions.rb
426 def savepoint_hooks(conn, committed)
427   if in_savepoint?(conn)
428     _trans(conn)[:savepoints].last[committed ? :after_commit : :after_rollback]
429   end
430 end
savepoint_level(conn) click to toggle source

Current savepoint level.

    # File lib/sequel/database/transactions.rb
522 def savepoint_level(conn)
523   _trans(conn)[:savepoints].length
524 end
set_transaction_isolation(conn, opts) click to toggle source

Set the transaction isolation level on the given connection

    # File lib/sequel/database/transactions.rb
510 def set_transaction_isolation(conn, opts)
511   if supports_transaction_isolation_levels? and level = opts.fetch(:isolation, transaction_isolation_level)
512     log_connection_execute(conn, set_transaction_isolation_sql(level))
513   end
514 end
set_transaction_isolation_sql(level) click to toggle source

SQL to set the transaction isolation level

    # File lib/sequel/database/transactions.rb
517 def set_transaction_isolation_sql(level)
518   "SET TRANSACTION ISOLATION LEVEL #{TRANSACTION_ISOLATION_LEVELS[level]}"
519 end
transaction_error(e, opts=OPTS) click to toggle source

Raise a database error unless the exception is an Rollback.

    # File lib/sequel/database/transactions.rb
527 def transaction_error(e, opts=OPTS)
528   if e.is_a?(Rollback)
529     raise e if opts[:rollback] == :reraise
530   else
531     raise_error(e, opts.merge(:classes=>database_error_classes))
532   end
533 end
transaction_finished?(conn) click to toggle source

Finish a subtransaction. If savepoints are supported, pops the current tansaction off the savepoint stack.

    # File lib/sequel/database/transactions.rb
537 def transaction_finished?(conn)
538   if supports_savepoints?
539     stack = _trans(conn)[:savepoints]
540     stack.pop
541     stack.empty?
542   else
543     true
544   end
545 end
transaction_hooks(conn, committed) click to toggle source

Retrieve the transaction hooks that should be run for the given connection and commit status.

    # File lib/sequel/database/transactions.rb
434 def transaction_hooks(conn, committed)
435   unless in_savepoint?(conn)
436     _trans(conn)[committed ? :after_commit : :after_rollback]
437   end
438 end
transaction_options(conn, opts) click to toggle source

Derive the transaction hash from the options passed to the transaction. Meant to be overridden.

    # File lib/sequel/database/transactions.rb
335 def transaction_options(conn, opts)
336   {}
337 end

9 - Methods that describe what the database supports

↑ top

Public Instance Methods

global_index_namespace?() click to toggle source

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

   # File lib/sequel/database/features.rb
13 def global_index_namespace?
14   true
15 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/features.rb
19 def supports_create_table_if_not_exists?
20   false
21 end
supports_deferrable_constraints?() click to toggle source

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

   # File lib/sequel/database/features.rb
25 def supports_deferrable_constraints?
26   false
27 end
supports_deferrable_foreign_key_constraints?() click to toggle source

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

   # File lib/sequel/database/features.rb
31 def supports_deferrable_foreign_key_constraints?
32   supports_deferrable_constraints?
33 end
supports_drop_table_if_exists?() click to toggle source

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

   # File lib/sequel/database/features.rb
37 def supports_drop_table_if_exists?
38   supports_create_table_if_not_exists?
39 end
supports_foreign_key_parsing?() click to toggle source

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

   # File lib/sequel/database/features.rb
43 def supports_foreign_key_parsing?
44   respond_to?(:foreign_key_list)
45 end
supports_index_parsing?() click to toggle source

Whether the database supports Database#indexes for parsing indexes.

   # File lib/sequel/database/features.rb
48 def supports_index_parsing?
49   respond_to?(:indexes)
50 end
supports_partial_indexes?() click to toggle source

Whether the database supports partial indexes (indexes on a subset of a table), false by default.

   # File lib/sequel/database/features.rb
54 def supports_partial_indexes?
55   false
56 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/features.rb
60 def supports_prepared_transactions?
61   false
62 end
supports_savepoints?() click to toggle source

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

   # File lib/sequel/database/features.rb
65 def supports_savepoints?
66   false
67 end
supports_savepoints_in_prepared_transactions?() click to toggle source

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

   # File lib/sequel/database/features.rb
71 def supports_savepoints_in_prepared_transactions?
72   supports_prepared_transactions? && supports_savepoints?
73 end
supports_schema_parsing?() click to toggle source

Whether the database supports schema parsing via Database#schema.

   # File lib/sequel/database/features.rb
76 def supports_schema_parsing?
77   respond_to?(:schema_parse_table, true)
78 end
supports_table_listing?() click to toggle source

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

   # File lib/sequel/database/features.rb
81 def supports_table_listing?
82   respond_to?(:tables)
83 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/features.rb
91 def supports_transaction_isolation_levels?
92   false
93 end
supports_transactional_ddl?() click to toggle source

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

   # File lib/sequel/database/features.rb
96 def supports_transactional_ddl?
97   false
98 end
supports_view_listing?() click to toggle source

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

   # File lib/sequel/database/features.rb
86 def supports_view_listing?
87   respond_to?(:views)
88 end
supports_views_with_check_option?() click to toggle source

Whether CREATE VIEW … WITH CHECK OPTION is supported, false by default.

    # File lib/sequel/database/features.rb
101 def supports_views_with_check_option?
102   !!view_with_check_option_support
103 end
supports_views_with_local_check_option?() click to toggle source

Whether CREATE VIEW … WITH LOCAL CHECK OPTION is supported, false by default.

    # File lib/sequel/database/features.rb
106 def supports_views_with_local_check_option?
107   view_with_check_option_support == :local
108 end

Private Instance Methods

can_add_primary_key_constraint_on_nullable_columns?() click to toggle source

Whether the database supports adding primary key constraints on NULLable columns, automatically making them NOT NULL. If false, the columns must be set NOT NULL before the primary key constraint is added.

    # File lib/sequel/database/features.rb
115 def can_add_primary_key_constraint_on_nullable_columns?
116   true
117 end
folds_unquoted_identifiers_to_uppercase?() click to toggle source

Whether this dataset considers unquoted identifiers as uppercase. True by default as that is the SQL standard

    # File lib/sequel/database/features.rb
121 def folds_unquoted_identifiers_to_uppercase?
122   true
123 end
supports_combining_alter_table_ops?() click to toggle source

Whether the database supports combining multiple alter table operations into a single query, false by default.

    # File lib/sequel/database/features.rb
127 def supports_combining_alter_table_ops?
128   false
129 end
supports_create_or_replace_view?() click to toggle source

Whether the database supports CREATE OR REPLACE VIEW. If not, support will be emulated by dropping the view first. false by default.

    # File lib/sequel/database/features.rb
133 def supports_create_or_replace_view?
134   false
135 end
supports_named_column_constraints?() click to toggle source

Whether the database supports named column constraints. True by default. Those that don't support named column constraints have to have column constraints converted to table constraints if the column constraints have names.

    # File lib/sequel/database/features.rb
141 def supports_named_column_constraints?
142   true
143 end
view_with_check_option_support() click to toggle source

Don't advertise support for WITH CHECK OPTION by default.

    # File lib/sequel/database/features.rb
146 def view_with_check_option_support
147   nil
148 end