class Sequel::Database

  1. lib/sequel/database.rb
  2. lib/sequel/database/connecting.rb
  3. lib/sequel/database/dataset.rb
  4. lib/sequel/database/dataset_defaults.rb
  5. lib/sequel/database/features.rb
  6. lib/sequel/database/logging.rb
  7. lib/sequel/database/misc.rb
  8. lib/sequel/database/query.rb
  9. lib/sequel/database/schema_methods.rb
  10. lib/sequel/database/transactions.rb
  11. show all
Superclass: Object

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


Public Class

  1. adapter_class
  2. adapter_scheme
  3. after_initialize
  4. connect
  5. extension
  6. load_adapter
  7. new
  8. register_extension
  9. run_after_initialize
  10. set_shared_adapter_scheme

Public Instance

  1. <<
  2. []
  3. adapter_scheme
  4. add_column
  5. add_index
  6. add_servers
  7. after_commit
  8. after_rollback
  9. alter_table
  10. alter_table_generator
  11. cache_schema
  12. call
  13. cast_type_literal
  14. check_string_typecast_bytesize
  15. create_join_table
  16. create_join_table!
  17. create_join_table?
  18. create_or_replace_view
  19. create_table
  20. create_table!
  21. create_table?
  22. create_table_generator
  23. create_view
  24. database_type
  25. dataset
  26. dataset_class
  27. dataset_class=
  28. default_string_column_size
  29. disconnect
  30. disconnect_connection
  31. drop_column
  32. drop_index
  33. drop_join_table
  34. drop_table
  35. drop_table?
  36. drop_view
  37. execute_ddl
  38. execute_dui
  39. execute_insert
  40. extend_datasets
  41. extension
  42. fetch
  43. freeze
  44. from
  45. from_application_timestamp
  46. get
  47. global_index_namespace?
  48. in_transaction?
  49. inspect
  50. literal
  51. literal_symbol
  52. literal_symbol_set
  53. log_connection_info
  54. log_connection_yield
  55. log_exception
  56. log_info
  57. log_warn_duration
  58. logger=
  59. loggers
  60. new_connection
  61. opts
  62. pool
  63. prepared_statement
  64. prepared_statements
  65. quote_identifier
  66. remove_servers
  67. rename_column
  68. rename_table
  69. rollback_checker
  70. rollback_on_exit
  71. run
  72. schema
  73. schema_type_class
  74. select
  75. serial_primary_key_options
  76. servers
  77. set_column_default
  78. set_column_type
  79. set_prepared_statement
  80. sharded?
  81. single_threaded?
  82. sql_log_level
  83. supports_create_table_if_not_exists?
  84. supports_deferrable_constraints?
  85. supports_deferrable_foreign_key_constraints?
  86. supports_drop_table_if_exists?
  87. supports_foreign_key_parsing?
  88. supports_index_parsing?
  89. supports_partial_indexes?
  90. supports_prepared_transactions?
  91. supports_savepoints?
  92. supports_savepoints_in_prepared_transactions?
  93. supports_schema_parsing?
  94. supports_table_listing?
  95. supports_transaction_isolation_levels?
  96. supports_transactional_ddl?
  97. supports_view_listing?
  98. supports_views_with_check_option?
  99. supports_views_with_local_check_option?
  100. synchronize
  101. table_exists?
  102. test_connection
  103. timezone
  104. timezone
  105. to_application_timestamp
  106. transaction
  107. transaction_isolation_level
  108. typecast_value
  109. uri
  110. url
  111. valid_connection?


OPTS = Sequel::OPTS  

1 - Methods that execute queries and/or return results


COLUMN_SCHEMA_DATETIME_TYPES = [:date, :datetime].freeze  
COLUMN_SCHEMA_STRING_TYPES = [:string, :blob, :date, :datetime, :time, :enum, :set, :interval].freeze  
INTEGER1_MIN_MAX = [-128, 127].freeze  
INTEGER2_MIN_MAX = [-32768, 32767].freeze  
INTEGER3_MIN_MAX = [-8388608, 8388607].freeze  
INTEGER4_MIN_MAX = [-2147483648, 2147483647].freeze  
INTEGER8_MIN_MAX = [-9223372036854775808, 9223372036854775807].freeze  
UNSIGNED_INTEGER1_MIN_MAX = [0, 255].freeze  
UNSIGNED_INTEGER2_MIN_MAX = [0, 65535].freeze  
UNSIGNED_INTEGER3_MIN_MAX = [0, 16777215].freeze  
UNSIGNED_INTEGER4_MIN_MAX = [0, 4294967295].freeze  
UNSIGNED_INTEGER8_MIN_MAX = [0, 18446744073709551615].freeze  


cache_schema [RW]

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

prepared_statements [R]

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

Public Instance methods


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

DB << "UPDATE albums SET artist_id = NULL" << "DROP TABLE artists"
[show source]
   # File lib/sequel/database/query.rb
25 def <<(sql)
26   run(sql)
27   self
28 end
call(ps_name, hash=OPTS, &block)

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

DB[:items].where(id: 1).prepare(:first, :sa) # SELECT * FROM items WHERE id = 1
[show source]
   # 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)

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.

[show source]
   # 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)

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.

[show source]
   # 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)

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.

[show source]
   # 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)

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

DB.get(1) # SELECT 1
# => 1
DB.get{server_version.function} # SELECT server_version()
[show source]
   # File lib/sequel/database/query.rb
65 def get(*args, &block)
66   @default_dataset.get(*args, &block)
67 end
run(sql, opts=OPTS)

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


The server to run the SQL on."SET some_server_variable = 42")
[show source]
   # 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)

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:


Ignore any cached results, and get fresh information from the database.


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:


Whether NULL is an allowed value for the column.


The database type for the column, as a database specific string.


The database default for the column, as a database specific string, or nil if there is no default value.


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.


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.


A symbol specifying the type, such as :integer or :string.


# [[: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}]]
[show source]
    # 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?
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
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
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
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)
154   Sequel.synchronize{@schemas.delete(quoted_name)} if opts[:reload]
155   if v = Sequel.synchronize{@schemas[quoted_name]}
156     return v
157   end
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?
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
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     if !c[:max_value] && !c[:min_value]
179       min_max = case c[:type]
180       when :integer
181         column_schema_integer_min_max_values(c)
182       when :decimal
183         column_schema_decimal_min_max_values(c)
184       end
185       c[:min_value], c[:max_value] = min_max if min_max
186     end
187   end
188   schema_post_process(cols)
190   Sequel.synchronize{@schemas[quoted_name] = cols} if cache_schema
191   cols
192 end

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

DB.table_exists?(:foo) # => false

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.

[show source]
    # File lib/sequel/database/query.rb
202 def table_exists?(name)
203   sch, table_name = schema_and_table(name)
204   name =, table_name) if sch
205   ds = from(name)
206   transaction(:savepoint=>:only){_table_exists?(ds)}
207   true
208 rescue DatabaseError
209   false
210 end

2 - Methods that modify the database schema


COLUMN_DEFINITION_ORDER = [:collate, :default, :null, :unique, :primary_key, :auto_increment, :references].freeze  

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

COMBINABLE_ALTER_TABLE_OPS = [:add_column, :drop_column, :rename_column, :set_column_type, :set_column_default, :set_column_null, :add_constraint, :drop_constraint].freeze  

The alter table operations that are combinable.

Public Instance methods

add_column(table, *args)

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

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

See alter_table.

[show source]
   # 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)

Adds an index to a table for the given columns:

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



Ignore any DatabaseErrors that are raised


Name to use for index instead of default

See alter_table.

[show source]
   # 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)

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]

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

[show source]
   # 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

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

[show source]
   # File lib/sequel/database/schema_methods.rb
76 def alter_table_generator(&block)
77, &block)
78 end
create_join_table(hash, options=OPTS)

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:


The options to pass to the index


The name of the table to create


Set to true not to create the second index.


Set to true to not create the primary key.

[show source]
    # 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)

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

[show source]
    # 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)

Creates the join table unless it already exists.

[show source]
    # 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)

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.

[show source]
    # File lib/sequel/database/schema_methods.rb
254 def create_or_replace_view(name, source, options = OPTS)
255   if supports_create_or_replace_view? && !options[:materialized]
256     options = options.merge(:replace=>true)
257   else
258     swallow_database_error{drop_view(name, options)}
259   end
261   create_view(name, source, options)
262   nil
263 end
create_table(name, options=OPTS, &block)

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

General options:


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 any errors when creating indexes.


Create the table as a temporary table.

MySQL specific options:


The character set to use for the table.


The collation to use for the table.


The table engine to use for the table.

PostgreSQL specific options:


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


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


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


Create the table as an unlogged table.


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.


The tablespace to use for the table.

SQLite specific options:


Create a STRICT table, which checks that the values for the columns are the correct type (similar to all other SQL databases). Note that when using this option, all column types used should be one of the following: int, integer, real, text, blob, and any. The any type is treated like a SQLite column in a non-strict table, allowing any type of data to be stored. This option is supported on SQLite 3.37.0+.


Create a WITHOUT ROWID table. Every row in SQLite has a special ‘rowid’ column, that uniquely identifies that row within the table. If this option is used, the ‘rowid’ column is omitted, which can sometimes provide some space and speed advantages. Note that you must then provide an explicit primary key when you create the table. This option is supported on SQLite 3.8.2+.

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

[show source]
    # File lib/sequel/database/schema_methods.rb
202 def create_table(name, options=OPTS, &block)
203   remove_cached_schema(name)
204   if sql = options[:as]
205     raise(Error, "can't provide both :as option and block to create_table") if block
206     create_table_as(name, sql, options)
207   else
208     generator = options[:generator] || create_table_generator(&block)
209     create_table_from_generator(name, generator, options)
210     create_table_indexes_from_generator(name, generator, options)
211   end
212   nil
213 end
create_table!(name, options=OPTS, &block)

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)
[show source]
    # File lib/sequel/database/schema_methods.rb
221 def create_table!(name, options=OPTS, &block)
222   drop_table?(name)
223   create_table(name, options, &block)
224 end
create_table?(name, options=OPTS, &block)

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
[show source]
    # File lib/sequel/database/schema_methods.rb
231 def create_table?(name, options=OPTS, &block)
232   options = options.dup
233   generator = options[:generator] ||= create_table_generator(&block)
234   if generator.indexes.empty? && supports_create_table_if_not_exists?
235     create_table(name, options.merge!(:if_not_exists=>true))
236   elsif !table_exists?(name)
237     create_table(name, options)
238   end
239 end

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

[show source]
    # File lib/sequel/database/schema_methods.rb
243 def create_table_generator(&block)
244, &block)
245 end
create_view(name, source, options = OPTS)

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

DB.create_view(:bar_items, DB[:items].select(:foo), columns: [:bar])
# CREATE VIEW bar_items (bar) AS
# SELECT foo FROM items



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


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:


Create a temporary view, automatically dropped on disconnect.

PostgreSQL specific options:


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


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.


Set the security_invoker property on the view, making the access to the view use the current user’s permissions, instead of the view owner’s permissions.


The tablespace to use for materialized views.

[show source]
    # File lib/sequel/database/schema_methods.rb
308 def create_view(name, source, options = OPTS)
309   execute_ddl(create_view_sql(name, source, options))
310   remove_cached_schema(name)
311   nil
312 end
drop_column(table, *args)

Removes a column from the specified table:

DB.drop_column :items, :category

See alter_table.

[show source]
    # File lib/sequel/database/schema_methods.rb
319 def drop_column(table, *args)
320   alter_table(table) {drop_column(*args)}
321 end
drop_index(table, columns, options=OPTS)

Removes an index for the given table and column(s):

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

See alter_table.

[show source]
    # File lib/sequel/database/schema_methods.rb
329 def drop_index(table, columns, options=OPTS)
330   alter_table(table){drop_index(columns, options)}
331 end
drop_join_table(hash, options=OPTS)

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
[show source]
    # File lib/sequel/database/schema_methods.rb
338 def drop_join_table(hash, options=OPTS)
339   drop_table(join_table_name(hash, options), options)
340 end

Drops one or more tables corresponding to the given names:

DB.drop_table(:posts) # DROP TABLE posts
DB.drop_table(:posts, :comments)
DB.drop_table(:posts, :comments, cascade: true)
[show source]
    # File lib/sequel/database/schema_methods.rb
347 def drop_table(*names)
348   options = names.last.is_a?(Hash) ? names.pop : OPTS 
349   names.each do |n|
350     execute_ddl(drop_table_sql(n, options))
351     remove_cached_schema(n)
352   end
353   nil
354 end

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

# SELECT NULL FROM a LIMIT 1 -- check existence
# DROP TABLE a -- if it already exists
[show source]
    # File lib/sequel/database/schema_methods.rb
362 def drop_table?(*names)
363   options = names.last.is_a?(Hash) ? names.pop : OPTS
364   if supports_drop_table_if_exists?
365     options = options.merge(:if_exists=>true)
366     names.each do |name|
367       drop_table(name, options)
368     end
369   else
370     names.each do |name|
371       drop_table(name, options) if table_exists?(name)
372     end
373   end
374   nil
375 end

Drops one or more views corresponding to the given names:

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)



Also drop objects depending on this view.


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

PostgreSQL specific options:


Drop a materialized view.

[show source]
    # File lib/sequel/database/schema_methods.rb
390 def drop_view(*names)
391   options = names.last.is_a?(Hash) ? names.pop : OPTS
392   names.each do |n|
393     execute_ddl(drop_view_sql(n, options))
394     remove_cached_schema(n)
395   end
396   nil
397 end
rename_column(table, *args)

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

DB.rename_column :items, :cntr, :counter

See alter_table.

[show source]
    # File lib/sequel/database/schema_methods.rb
416 def rename_column(table, *args)
417   alter_table(table) {rename_column(*args)}
418 end
rename_table(name, new_name)

Renames a table:

DB.tables #=> [:items]
DB.rename_table :items, :old_items
DB.tables #=> [:old_items]
[show source]
    # File lib/sequel/database/schema_methods.rb
404 def rename_table(name, new_name)
405   execute_ddl(rename_table_sql(name, new_name))
406   remove_cached_schema(name)
407   nil
408 end
set_column_default(table, *args)

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

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

See alter_table.

[show source]
    # File lib/sequel/database/schema_methods.rb
425 def set_column_default(table, *args)
426   alter_table(table) {set_column_default(*args)}
427 end
set_column_type(table, *args)

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

DB.set_column_type :items, :price, :float

See alter_table.

[show source]
    # File lib/sequel/database/schema_methods.rb
434 def set_column_type(table, *args)
435   alter_table(table) {set_column_type(*args)}
436 end

3 - Methods that create datasets

Public Instance methods


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

DB['SELECT * FROM items'].all
DB['SELECT * FROM items WHERE name = ?', my_name].all

Otherwise, acts as an alias for Database#from, setting the primary table for the dataset:

DB[:items].sql #=> "SELECT * FROM items"
[show source]
   # File lib/sequel/database/dataset.rb
21 def [](*args)
22   args.first.is_a?(String) ? fetch(*args) : from(*args)
23 end

Returns a blank dataset for this database.

DB.dataset # SELECT *
DB.dataset.from(:items) # SELECT * FROM items
[show source]
   # File lib/sequel/database/dataset.rb
29 def dataset
31 end
fetch(sql, *args, &block)

Returns a dataset instance for the given SQL string:

ds = DB.fetch('SELECT * FROM items')

You can then call methods on the dataset to retrieve results:

# SELECT * FROM items
# => [{:column=>value, ...}, ...]

If a block is given, it is passed to each on the resulting dataset to iterate over the records returned by the query:

DB.fetch('SELECT * FROM items'){|r| p r}
# {:column=>value, ...}
# ...

fetch can also perform parameterized queries for protection against SQL injection:

ds = DB.fetch('SELECT * FROM items WHERE name = ?', "my name")
# SELECT * FROM items WHERE name = 'my name'

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

[show source]
   # File lib/sequel/database/dataset.rb
59 def fetch(sql, *args, &block)
60   ds = @default_dataset.with_sql(sql, *args)
61   ds.each(&block) if block
62   ds
63 end
from(*args, &block)

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
[show source]
   # File lib/sequel/database/dataset.rb
70 def from(*args, &block)
71   if block
72     @default_dataset.from(*args, &block)
73   elsif args.length == 1 && (table = args[0]).is_a?(Symbol)
74     @default_dataset.send(:cached_dataset, :"_from_#{table}_ds"){@default_dataset.from(table)}
75   else
76     @default_dataset.from(*args)
77   end
78 end
select(*args, &block)

Returns a new dataset with the select method invoked. # SELECT 1{server_version.function} # SELECT server_version() # SELECT id FROM items
[show source]
   # File lib/sequel/database/dataset.rb
85 def select(*args, &block)
86*args, &block)
87 end

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


ADAPTERS = %w'ado amalgalite ibmdb jdbc mock mysql mysql2 odbc oracle postgres sqlanywhere sqlite tinytds trilogy'.map(&:to_sym)  

Array of supported database adapters


pool [R]

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

Public Class methods


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

[show source]
   # 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

Returns the scheme symbol for the Database class.

[show source]
   # File lib/sequel/database/connecting.rb
21 def self.adapter_scheme
22   @scheme
23 end
connect(conn_string, opts = OPTS)

Connects to a database. See Sequel.connect.

[show source]
   # 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] = URI::DEFAULT_PARSER.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
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
56   begin
57     db =
58     if defined?(yield)
59       return yield(db)
60     end
61   ensure
62     if defined?(yield)
63       db.disconnect if db
64       Sequel.synchronize{::Sequel::DATABASES.delete(db)}
65     end
66   end
67   db
68 end
load_adapter(scheme, opts=OPTS)

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:


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


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

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

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

  module DatabaseMethods
    # ...

  module DatasetMethods
    # ...

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

[show source]
    # File lib/sequel/database/connecting.rb
146 def self.set_shared_adapter_scheme(scheme, mod)
147   Sequel.synchronize{SHARED_ADAPTER_MAP[scheme] = mod}
148 end

Public Instance methods


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

# => :jdbc
[show source]
    # File lib/sequel/database/connecting.rb
161 def adapter_scheme
162   self.class.adapter_scheme
163 end

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

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

# => :postgres
[show source]
    # File lib/sequel/database/connecting.rb
192 def database_type
193   adapter_scheme
194 end
disconnect(opts = OPTS)

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


Should be a symbol specifing the server to disconnect from,

or an array of symbols to specify multiple servers.


DB.disconnect # All servers
DB.disconnect(server: :server1) # Single server
DB.disconnect(server: [:server1, :server2]) # Multiple servers
[show source]
    # File lib/sequel/database/connecting.rb
206 def disconnect(opts = OPTS)
207   pool.disconnect(opts)
208 end

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

[show source]
    # File lib/sequel/database/connecting.rb
213 def disconnect_connection(conn)
214   conn.close
215 end

Connect to the given server/shard. Handles database-generic post-connection setup not handled by connect, using the :after_connect and :connect_sqls options.

[show source]
    # File lib/sequel/database/connecting.rb
247 def new_connection(server)
248   conn = connect(server)
249   opts = server_opts(server)
251   if ac = opts[:after_connect]
252     if ac.arity == 2
253, server)
254     else
256     end
257   end
259   if cs = opts[:connect_sqls]
260     cs.each do |sql|
261       log_connection_execute(conn, sql)
262     end
263   end
265   conn
266 end

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)
[show source]
    # File lib/sequel/database/connecting.rb
226 def remove_servers(*servers)
227   unless sharded?
228     raise Error, "cannot call Database#remove_servers on a Database instance that does not use a sharded connection pool"
229   end
231   h = @opts[:servers]
232   servers.flatten.each{|s| Sequel.synchronize{h.delete(s)}}
233   @pool.remove_servers(servers)
234 end

An array of servers/shards for this Database object.

DB.servers # Unsharded: => [:default]
DB.servers # Sharded:   => [:default, :server1, :server2]
[show source]
    # File lib/sequel/database/connecting.rb
240 def servers
241   pool.servers
242 end

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

[show source]
    # File lib/sequel/database/connecting.rb
269 def single_threaded?
270   @single_threaded
271 end


[show source]
    # File lib/sequel/database/connecting.rb
275 def synchronize(server=nil)
276   @pool.hold(server || :default){|conn| yield conn}
277 end

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

[show source]
    # File lib/sequel/database/connecting.rb
301 def test_connection(server=nil)
302   synchronize(server){|conn|}
303   true
304 end

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

[show source]
    # File lib/sequel/database/connecting.rb
310 def valid_connection?(conn)
311   sql = valid_connection_sql
312   begin
313     log_connection_execute(conn, sql)
314   rescue Sequel::DatabaseError, *database_error_classes
315     false
316   else
317     true
318   end
319 end

5 - Methods that set defaults for created datasets


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


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.

[show source]
   # File lib/sequel/database/dataset_defaults.rb
18 def dataset_class=(c)
19   unless @dataset_modules.empty?
20     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)

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.


# Introspect columns for all of DB's datasets

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

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

# SELECT id, name FROM table WHERE active ORDER BY id
[show source]
   # 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 = if block
65   if @dataset_modules.empty?
66    @dataset_modules = [mod]
67    @dataset_class =
68   else
69    @dataset_modules << mod
70   end
71   @dataset_class.send(:include, mod)
72   reset_default_dataset
73 end

6 - Methods relating to logging


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)

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.

[show source]
   # 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
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)

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

[show source]
   # 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)

Log a message at level info to all loggers.

[show source]
   # File lib/sequel/database/logging.rb
31 def log_info(message, args=nil)
32   log_each(:info, args ? "#{message}; #{args.inspect}" : message)
33 end

Remove any existing loggers and just use the given logger:

DB.logger =$stdout)
[show source]
   # File lib/sequel/database/logging.rb
55 def logger=(logger)
56   @loggers = Array(logger)
57 end

7 - Miscellaneous methods


CHECK_CONSTRAINT_SQLSTATES = %w'23513 23514'.freeze.each(&:freeze)  

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


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


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 = %w'23503 23506 23504'.freeze.each(&:freeze)  
NOT_NULL_CONSTRAINT_SQLSTATES = %w'23502'.freeze.each(&:freeze)  
SCHEMA_TYPE_CLASSES = {:string=>String, :integer=>Integer, :date=>Date, :datetime=>[Time, DateTime].freeze, :time=>Sequel::SQLTime, :boolean=>[TrueClass, FalseClass].freeze, :float=>Float, :decimal=>BigDecimal, :blob=>Sequel::SQL::Blob}.freeze  

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

SERIALIZATION_CONSTRAINT_SQLSTATES = %w'40001'.freeze.each(&:freeze)  
UNIQUE_CONSTRAINT_SQLSTATES = %w'23505'.freeze.each(&:freeze)  


check_string_typecast_bytesize [RW]

Whether to check the bytesize of strings before typecasting (to avoid typecasting strings that would be too long for the given type), true by default. Strings that are too long will raise a typecasting error.

default_string_column_size [RW]

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

opts [R]

The options hash for this database

timezone [W]

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

Public Class methods


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

[show source]
   # 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|
41     end
42   end
43 end

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

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

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

Accepts the following options:


A callable object called after each new connection is made, with the connection object (and server argument if the callable accepts 2 arguments), useful for customizations that you want to apply to all connections.


Callable that runs after extensions from :preconnect_extensions are loaded, but before any connections are created.


Whether schema should be cached for this Database instance


Whether to check the bytesize of strings before typecasting.


An array of sql strings to execute on each new connection, after :after_connect runs.


The default size of string columns, 255 by default.


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.


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


A specific logger to use.


An array of loggers to use.


Whether connection information should be logged when logging queries.


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


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


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.


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


Whether to quote identifiers.


A hash specifying a server/shard specific options, keyed by shard symbol.


Whether to use a single-threaded connection pool.


Method to use to log SQL to a logger, :info by default.

For sharded connection pools, :after_connect and :connect_sqls can be specified per-shard.

All options given are also passed to the connection pool. Additional options respected by the connection pool are :max_connections, :pool_timeout, :servers, and :servers_hash. See the connection pool documentation for details.

[show source]
    # File lib/sequel/database/misc.rb
138 def initialize(opts = OPTS)
139   @opts ||= opts
140   @opts = connection_pool_default_options.merge(@opts)
141   @loggers = Array(@opts[:logger]) + Array(@opts[:loggers])
142   @opts[:servers] = {} if @opts[:servers].is_a?(String)
143   @sharded = !!@opts[:servers]
144   @opts[:adapter_class] = self.class
145   @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, Sequel.single_threaded))
146   @default_string_column_size = @opts[:default_string_column_size] || DEFAULT_STRING_COLUMN_SIZE
147   @check_string_typecast_bytesize = typecast_value_boolean(@opts.fetch(:check_string_typecast_bytesize, true))
149   @schemas = {}
150   @prepared_statements = {}
151   @transactions = {}
152   @transactions.compare_by_identity
153   @symbol_literal_cache = {}
155   @timezone = nil
157   @dataset_class = dataset_class_default
158   @cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true))
159   @dataset_modules = []
160   @loaded_extensions = []
161   @schema_type_classes = SCHEMA_TYPE_CLASSES.dup
163   self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info
164   self.log_warn_duration = @opts[:log_warn_duration]
165   self.log_connection_info = typecast_value_boolean(@opts[:log_connection_info])
167   @pool = ConnectionPool.get_pool(self, @opts)
169   reset_default_dataset
170   adapter_initialize
172   keep_reference = typecast_value_boolean(@opts[:keep_reference]) != false
173   begin
174     Sequel.synchronize{::Sequel::DATABASES.push(self)} if keep_reference
175     Sequel::Database.run_after_initialize(self)
177     initialize_load_extensions(:preconnect_extensions)
179     if before_preconnect = @opts[:before_preconnect]
181     end
183     if typecast_value_boolean(@opts[:preconnect]) && @pool.respond_to?(:preconnect, true)
184       concurrent = typecast_value_string(@opts[:preconnect]) == "concurrently"
185       @pool.send(:preconnect, concurrent)
186     end
188     initialize_load_extensions(:extensions)
189     test_connection if typecast_value_boolean(@opts.fetch(:test, true)) && respond_to?(:connect, true)
190   rescue
191     Sequel.synchronize{::Sequel::DATABASES.delete(self)} if keep_reference
192     raise
193   end
194 end
register_extension(ext, mod=nil, &block)

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.

[show source]
   # 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 the after_initialize hook for the given instance.

[show source]
   # File lib/sequel/database/misc.rb
68 def self.run_after_initialize(instance)
70 end

Public Instance methods


Cast the given type to a literal type

DB.cast_type_literal(Float) # double precision
DB.cast_type_literal(:foo)  # foo
[show source]
    # File lib/sequel/database/misc.rb
223 def cast_type_literal(type)
224   type_literal(:type=>type)
225 end

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

[show source]
    # File lib/sequel/database/misc.rb
232 def extension(*exts)
233   Sequel.extension(*exts)
234   exts.each do |ext|
235     if pr = Sequel.synchronize{EXTENSIONS[ext]}
236       if Sequel.synchronize{@loaded_extensions.include?(ext) ? false : (@loaded_extensions << ext)}
238       end
239     else
240       raise(Error, "Extension #{ext} does not have specific support handling individual databases (try: Sequel.extension #{ext.inspect})")
241     end
242   end
243   self
244 end

Freeze internal data structures for the Database instance.

[show source]
    # File lib/sequel/database/misc.rb
197 def freeze
198   valid_connection_sql
199   metadata_dataset
200   @opts.freeze
201   @loggers.freeze
202   @pool.freeze
203   @dataset_class.freeze
204   @dataset_modules.freeze
205   @schema_type_classes.freeze
206   @loaded_extensions.freeze
207   metadata_dataset
208   super
209 end

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

[show source]
    # File lib/sequel/database/misc.rb
249 def from_application_timestamp(v)
250   Sequel.convert_output_timestamp(v, timezone)
251 end

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

[show source]
    # File lib/sequel/database/misc.rb
255 def inspect
256   a = []
257   a << uri.inspect if uri
258   if (oo = opts[:orig_opts]) && !oo.empty?
259     a << oo.inspect
260   end
261   "#<#{self.class}: #{a.join(' ')}>"
262 end

Proxy the literal call to the dataset.

DB.literal(1)   # 1
DB.literal(:a)  # "a" # or `a`, [a], or a, depending on identifier quoting
DB.literal("a") # 'a'
[show source]
    # File lib/sequel/database/misc.rb
269 def literal(v)
270   schema_utility_dataset.literal(v)
271 end

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

[show source]
    # File lib/sequel/database/misc.rb
275 def literal_symbol(sym)
276   Sequel.synchronize{@symbol_literal_cache[sym]}
277 end
literal_symbol_set(sym, lit)

Set the cached value of the literal symbol.

[show source]
    # File lib/sequel/database/misc.rb
280 def literal_symbol_set(sym, lit)
281   Sequel.synchronize{@symbol_literal_cache[sym] = lit}
282 end

Synchronize access to the prepared statements cache.

[show source]
    # File lib/sequel/database/misc.rb
285 def prepared_statement(name)
286   Sequel.synchronize{prepared_statements[name]}
287 end

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

[show source]
    # File lib/sequel/database/misc.rb
292 def quote_identifier(v)
293   schema_utility_dataset.quote_identifier(v)
294 end

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

[show source]
    # File lib/sequel/database/misc.rb
297 def schema_type_class(type)
298   @schema_type_classes[type]
299 end

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

[show source]
    # File lib/sequel/database/misc.rb
302 def serial_primary_key_options
303   {:primary_key => true, :type => Integer, :auto_increment => true}
304 end
set_prepared_statement(name, ps)

Cache the prepared statement object at the given name.

[show source]
    # File lib/sequel/database/misc.rb
307 def set_prepared_statement(name, ps)
308   Sequel.synchronize{prepared_statements[name] = ps}
309 end

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

[show source]
    # File lib/sequel/database/misc.rb
313 def sharded?
314   @sharded
315 end

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

[show source]
    # File lib/sequel/database/misc.rb
318 def timezone
319   @timezone || Sequel.database_timezone
320 end

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

[show source]
    # File lib/sequel/database/misc.rb
325 def to_application_timestamp(v)
326   Sequel.convert_timestamp(v, timezone)
327 end
typecast_value(column_type, value)

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

[show source]
    # File lib/sequel/database/misc.rb
334 def typecast_value(column_type, value)
335   return nil if value.nil?
336   meth = "typecast_value_#{column_type}"
337   begin
338     # Allow calling private methods as per-type typecasting methods are private
339     respond_to?(meth, true) ? send(meth, value) : value
340   rescue ArgumentError, TypeError => e
341     raise Sequel.convert_exception_class(e, InvalidValue)
342   end
343 end

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

[show source]
    # File lib/sequel/database/misc.rb
347 def uri
348   opts[:uri]
349 end

Explicit alias of uri for easier subclassing.

[show source]
    # File lib/sequel/database/misc.rb
352 def url
353   uri
354 end

8 - Methods related to database transactions


TRANSACTION_ISOLATION_LEVELS = {:uncommitted=>'READ UNCOMMITTED'.freeze, :committed=>'READ COMMITTED'.freeze, :repeatable=>'REPEATABLE READ'.freeze, :serializable=>'SERIALIZABLE'.freeze}.freeze  


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, &block)

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:


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


The server/shard to use.

[show source]
   # 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)

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:


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.


The server/shard to use.

[show source]
   # 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

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

[show source]
    # File lib/sequel/database/transactions.rb
113 def in_transaction?(opts=OPTS)
114   synchronize(opts[:server]){|conn| !!_trans(conn)}
115 end

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.

[show source]
    # 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

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 the current rollback_on_exit setting, so exiting will commit instead of rolling back.


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.


The server/shard the transaction is being executed on.

[show source]
    # 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]
 88     if supports_savepoints?
 89       savepoints = h[:savepoints]
 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
107   nil
108 end
transaction(opts=OPTS, &block)

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:


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


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.


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.


Proc to execute before retrying 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.


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


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.


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


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.


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.


If set, do not actually open a transaction or savepoint, just checkout a connection and yield it.

PostgreSQL specific options:


(9.1+) If present, set to DEFERRABLE if true or NOT DEFERRABLE if false.


If present, set to READ ONLY if true or READ WRITE if false.


if non-nil, set synchronous_commit appropriately. Valid values true, :on, false, :off, :local (9.1+), and :remote_write (9.2+).

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

9 - Methods that describe what the database supports

Public Instance methods


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

[show source]
   # File lib/sequel/database/features.rb
13 def global_index_namespace?
14   true
15 end

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

[show source]
   # File lib/sequel/database/features.rb
19 def supports_create_table_if_not_exists?
20   false
21 end

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

[show source]
   # File lib/sequel/database/features.rb
25 def supports_deferrable_constraints?
26   false
27 end

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

[show source]
   # File lib/sequel/database/features.rb
31 def supports_deferrable_foreign_key_constraints?
32   supports_deferrable_constraints?
33 end

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

[show source]
   # File lib/sequel/database/features.rb
37 def supports_drop_table_if_exists?
38   supports_create_table_if_not_exists?
39 end

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

[show source]
   # File lib/sequel/database/features.rb
43 def supports_foreign_key_parsing?
44   respond_to?(:foreign_key_list)
45 end

Whether the database supports Database#indexes for parsing indexes.

[show source]
   # File lib/sequel/database/features.rb
48 def supports_index_parsing?
49   respond_to?(:indexes)
50 end

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

[show source]
   # File lib/sequel/database/features.rb
54 def supports_partial_indexes?
55   false
56 end

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

[show source]
   # File lib/sequel/database/features.rb
60 def supports_prepared_transactions?
61   false
62 end

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

[show source]
   # File lib/sequel/database/features.rb
65 def supports_savepoints?
66   false
67 end

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

[show source]
   # File lib/sequel/database/features.rb
71 def supports_savepoints_in_prepared_transactions?
72   supports_prepared_transactions? && supports_savepoints?
73 end

Whether the database supports schema parsing via Database#schema.

[show source]
   # File lib/sequel/database/features.rb
76 def supports_schema_parsing?
77   respond_to?(:schema_parse_table, true)
78 end

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

[show source]
   # File lib/sequel/database/features.rb
81 def supports_table_listing?
82   respond_to?(:tables)
83 end

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

[show source]
   # File lib/sequel/database/features.rb
91 def supports_transaction_isolation_levels?
92   false
93 end

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

[show source]
   # File lib/sequel/database/features.rb
96 def supports_transactional_ddl?
97   false
98 end

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

[show source]
   # File lib/sequel/database/features.rb
86 def supports_view_listing?
87   respond_to?(:views)
88 end

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

[show source]
    # File lib/sequel/database/features.rb
101 def supports_views_with_check_option?
102   !!view_with_check_option_support
103 end

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

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