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.
| OPTS | = | Sequel::OPTS |
| EXTENSIONS | = | {} | Hash of extension name symbols to callable objects to load the extension into the Database object (usually by extending it with a module defined in the extension). | |
| DEFAULT_STRING_COLUMN_SIZE | = | 255 | The general default size for string columns for all Sequel::Database instances. | |
| DEFAULT_DATABASE_ERROR_REGEXPS | = | {}.freeze | Empty exception regexp to class map, used by default if Sequel doesn‘t have specific support for the database in use. | |
| SCHEMA_TYPE_CLASSES | = | {:string=>String, :integer=>Integer, :date=>Date, :datetime=>[Time, DateTime].freeze, :time=>Sequel::SQLTime, :boolean=>[TrueClass, FalseClass].freeze, :float=>Float, :decimal=>BigDecimal, :blob=>Sequel::SQL::Blob}.freeze | Mapping of schema type symbols to class or arrays of classes for that symbol. | |
| NOT_NULL_CONSTRAINT_SQLSTATES | = | %w'23502'.freeze.each(&:freeze) | ||
| FOREIGN_KEY_CONSTRAINT_SQLSTATES | = | %w'23503 23506 23504'.freeze.each(&:freeze) | ||
| UNIQUE_CONSTRAINT_SQLSTATES | = | %w'23505'.freeze.each(&:freeze) | ||
| CHECK_CONSTRAINT_SQLSTATES | = | %w'23513 23514'.freeze.each(&:freeze) | ||
| SERIALIZATION_CONSTRAINT_SQLSTATES | = | %w'40001'.freeze.each(&:freeze) |
| 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. |
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, line 34
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.new do |db|
39: previous.call(db)
40: block.call(db)
41: end
42: end
43: end
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. |
| :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. |
| :preconnect : | Whether to automatically connect to the maximum number of servers. Can use a valid of ‘concurrently’ to preconnect in separate threads. |
| :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.
# File lib/sequel/database/misc.rb, line 114
114: def initialize(opts = OPTS)
115: @opts ||= opts
116: @opts = connection_pool_default_options.merge(@opts)
117: @loggers = Array(@opts[:logger]) + Array(@opts[:loggers])
118: @opts[:servers] = {} if @opts[:servers].is_a?(String)
119: @sharded = !!@opts[:servers]
120: @opts[:adapter_class] = self.class
121: @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, Sequel.single_threaded))
122: @default_string_column_size = @opts[:default_string_column_size] || DEFAULT_STRING_COLUMN_SIZE
123:
124: @schemas = {}
125: @prepared_statements = {}
126: @transactions = {}
127: @symbol_literal_cache = {}
128:
129: @timezone = nil
130:
131: @dataset_class = dataset_class_default
132: @cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true))
133: @dataset_modules = []
134: @loaded_extensions = []
135: @schema_type_classes = SCHEMA_TYPE_CLASSES.dup
136:
137: self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info
138: self.log_warn_duration = @opts[:log_warn_duration]
139: self.log_connection_info = typecast_value_boolean(@opts[:log_connection_info])
140:
141: @pool = ConnectionPool.get_pool(self, @opts)
142:
143: reset_default_dataset
144: adapter_initialize
145:
146: unless typecast_value_boolean(@opts[:keep_reference]) == false
147: Sequel.synchronize{::Sequel::DATABASES.push(self)}
148: end
149: Sequel::Database.run_after_initialize(self)
150: if typecast_value_boolean(@opts[:preconnect]) && @pool.respond_to?(:preconnect, true)
151: concurrent = typecast_value_string(@opts[:preconnect]) == "concurrently"
152: @pool.send(:preconnect, concurrent)
153: end
154:
155: case exts = @opts[:extensions]
156: when String
157: extension(*exts.split(',').map(&:to_sym))
158: when Array
159: extension(*exts)
160: when Symbol
161: extension(exts)
162: when nil
163: # nothing
164: else
165: raise Error, "unsupported Database :extensions option: #{@opts[:extensions].inspect}"
166: end
167: end
Register an extension callback for Database objects. ext should be the extension name symbol, and mod should either be a Module that the database is extended with, or a callable object called with the database object. If mod is not provided, a block can be provided and is treated as the mod object.
# File lib/sequel/database/misc.rb, line 55
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.
# File lib/sequel/database/misc.rb, line 68
68: def self.run_after_initialize(instance)
69: @initialize_hook.call(instance)
70: 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.
# File lib/sequel/database/misc.rb, line 203
203: def extension(*exts)
204: Sequel.extension(*exts)
205: exts.each do |ext|
206: if pr = Sequel.synchronize{EXTENSIONS[ext]}
207: unless Sequel.synchronize{@loaded_extensions.include?(ext)}
208: Sequel.synchronize{@loaded_extensions << ext}
209: pr.call(self)
210: end
211: else
212: raise(Error, "Extension #{ext} does not have specific support handling individual databases (try: Sequel.extension #{ext.inspect})")
213: end
214: end
215: self
216: end
Freeze internal data structures for the Database instance.
# File lib/sequel/database/misc.rb, line 170
170: def freeze
171: valid_connection_sql
172: metadata_dataset
173: @opts.freeze
174: @loggers.freeze
175: @pool.freeze
176: @dataset_class.freeze
177: @dataset_modules.freeze
178: @schema_type_classes.freeze
179: @loaded_extensions.freeze
180: metadata_dataset
181: super
182: 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.
# File lib/sequel/database/misc.rb, line 221
221: def from_application_timestamp(v)
222: Sequel.convert_output_timestamp(v, timezone)
223: end
Returns a string representation of the database object including the class name and connection URI and options used when connecting (if any).
# File lib/sequel/database/misc.rb, line 227
227: def inspect
228: a = []
229: a << uri.inspect if uri
230: if (oo = opts[:orig_opts]) && !oo.empty?
231: a << oo.inspect
232: end
233: "#<#{self.class}: #{a.join(' ')}>"
234: end
Return the literalized version of the symbol if cached, or nil if it is not cached.
# File lib/sequel/database/misc.rb, line 247
247: def literal_symbol(sym)
248: Sequel.synchronize{@symbol_literal_cache[sym]}
249: end
Synchronize access to the prepared statements cache.
# File lib/sequel/database/misc.rb, line 257
257: def prepared_statement(name)
258: Sequel.synchronize{prepared_statements[name]}
259: end
Proxy the quote_identifier method to the dataset, useful for quoting unqualified identifiers for use outside of datasets.
# File lib/sequel/database/misc.rb, line 264
264: def quote_identifier(v)
265: schema_utility_dataset.quote_identifier(v)
266: end
Return ruby class or array of classes for the given type symbol.
# File lib/sequel/database/misc.rb, line 269
269: def schema_type_class(type)
270: @schema_type_classes[type]
271: end
Default serial primary key options, used by the table creation code.
# File lib/sequel/database/misc.rb, line 274
274: def serial_primary_key_options
275: {:primary_key => true, :type => Integer, :auto_increment => true}
276: end
Cache the prepared statement object at the given name.
# File lib/sequel/database/misc.rb, line 279
279: def set_prepared_statement(name, ps)
280: Sequel.synchronize{prepared_statements[name] = ps}
281: end
Typecast the value to the given column_type. Calls typecast_value_#{column_type} if the method exists, otherwise returns the value. This method should raise Sequel::InvalidValue if assigned value is invalid.
# File lib/sequel/database/misc.rb, line 306
306: def typecast_value(column_type, value)
307: return nil if value.nil?
308: meth = "typecast_value_#{column_type}"
309: begin
310: # Allow calling private methods as per-type typecasting methods are private
311: respond_to?(meth, true) ? send(meth, value) : value
312: rescue ArgumentError, TypeError => e
313: raise Sequel.convert_exception_class(e, InvalidValue)
314: end
315: end
These methods execute code on the database that modifies the database‘s 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. |
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, line 25
25: def add_column(table, *args)
26: alter_table(table) {add_column(*args)}
27: end
Adds an index to a table for the given columns:
DB.add_index :posts, :title DB.add_index :posts, [:author, :title], unique: true
Options:
| :ignore_errors : | Ignore any DatabaseErrors that are raised |
| :name : | Name to use for index instead of default |
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 40
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
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, line 67
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.
# File lib/sequel/database/schema_methods.rb, line 76
76: def alter_table_generator(&block)
77: alter_table_generator_class.new(self, &block)
78: end
Create a join table using a hash of foreign keys to referenced table names. Example:
create_join_table(cat_id: :cats, dog_id: :dogs) # CREATE TABLE cats_dogs ( # cat_id integer NOT NULL REFERENCES cats, # dog_id integer NOT NULL REFERENCES dogs, # PRIMARY KEY (cat_id, dog_id) # ) # CREATE INDEX cats_dogs_dog_id_cat_id_index ON cats_dogs(dog_id, cat_id)
The primary key and index are used so that almost all operations on the table can benefit from one of the two indexes, and the primary key ensures that entries in the table are unique, which is the typical desire for a join table.
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, line 119
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
Forcibly create a join table, attempting to drop it if it already exists, then creating it.
# File lib/sequel/database/schema_methods.rb, line 137
137: def create_join_table!(hash, options=OPTS)
138: drop_table?(join_table_name(hash, options))
139: create_join_table(hash, options)
140: end
Creates the join table unless it already exists.
# File lib/sequel/database/schema_methods.rb, line 143
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
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, line 238
238: def create_or_replace_view(name, source, options = OPTS)
239: if supports_create_or_replace_view?
240: options = options.merge(:replace=>true)
241: else
242: drop_view(name) rescue nil
243: end
244:
245: create_view(name, source, options)
246: nil
247: end
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. |
See Schema::CreateTableGenerator and the "Schema Modification" guide.
# File lib/sequel/database/schema_methods.rb, line 186
186: def create_table(name, options=OPTS, &block)
187: remove_cached_schema(name)
188: if sql = options[:as]
189: raise(Error, "can't provide both :as option and block to create_table") if block
190: create_table_as(name, sql, options)
191: else
192: generator = options[:generator] || create_table_generator(&block)
193: create_table_from_generator(name, generator, options)
194: create_table_indexes_from_generator(name, generator, options)
195: end
196: nil
197: end
Forcibly create a table, attempting to drop it if it already exists, then creating it.
DB.create_table!(:a){Integer :a}
# SELECT NULL FROM a LIMIT 1 -- check existence
# DROP TABLE a -- drop table if already exists
# CREATE TABLE a (a integer)
# File lib/sequel/database/schema_methods.rb, line 205
205: def create_table!(name, options=OPTS, &block)
206: drop_table?(name)
207: create_table(name, options, &block)
208: end
Creates the table unless the table already exists.
DB.create_table?(:a){Integer :a}
# SELECT NULL FROM a LIMIT 1 -- check existence
# CREATE TABLE a (a integer) -- if it doesn't already exist
# File lib/sequel/database/schema_methods.rb, line 215
215: def create_table?(name, options=OPTS, &block)
216: options = options.dup
217: generator = options[:generator] ||= create_table_generator(&block)
218: if generator.indexes.empty? && supports_create_table_if_not_exists?
219: create_table(name, options.merge!(:if_not_exists=>true))
220: elsif !table_exists?(name)
221: create_table(name, options)
222: end
223: end
Return a new Schema::CreateTableGenerator instance with the receiver as the database and the given block.
# File lib/sequel/database/schema_methods.rb, line 227
227: def create_table_generator(&block)
228: create_table_generator_class.new(self, &block)
229: end
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. |
# File lib/sequel/database/schema_methods.rb, line 284
284: def create_view(name, source, options = OPTS)
285: execute_ddl(create_view_sql(name, source, options))
286: remove_cached_schema(name)
287: nil
288: end
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 295
295: def drop_column(table, *args)
296: alter_table(table) {drop_column(*args)}
297: end
Removes an index for the given table and column(s):
DB.drop_index :posts, :title DB.drop_index :posts, [:author, :title]
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 305
305: def drop_index(table, columns, options=OPTS)
306: alter_table(table){drop_index(columns, options)}
307: end
Drop the join table that would have been created with the same arguments to create_join_table:
drop_join_table(cat_id: :cats, dog_id: :dogs) # DROP TABLE cats_dogs
# File lib/sequel/database/schema_methods.rb, line 314
314: def drop_join_table(hash, options=OPTS)
315: drop_table(join_table_name(hash, options), options)
316: 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)
# File lib/sequel/database/schema_methods.rb, line 323
323: def drop_table(*names)
324: options = names.last.is_a?(Hash) ? names.pop : OPTS
325: names.each do |n|
326: execute_ddl(drop_table_sql(n, options))
327: remove_cached_schema(n)
328: end
329: nil
330: end
Drops the table if it already exists. If it doesn‘t exist, does nothing.
DB.drop_table?(:a) # SELECT NULL FROM a LIMIT 1 -- check existence # DROP TABLE a -- if it already exists
# File lib/sequel/database/schema_methods.rb, line 338
338: def drop_table?(*names)
339: options = names.last.is_a?(Hash) ? names.pop : OPTS
340: if supports_drop_table_if_exists?
341: options = options.merge(:if_exists=>true)
342: names.each do |name|
343: drop_table(name, options)
344: end
345: else
346: names.each do |name|
347: drop_table(name, options) if table_exists?(name)
348: end
349: end
350: nil
351: end
Drops one or more views corresponding to the given names:
DB.drop_view(:cheap_items) DB.drop_view(:cheap_items, :pricey_items) DB.drop_view(:cheap_items, :pricey_items, cascade: true) 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, line 366
366: def drop_view(*names)
367: options = names.last.is_a?(Hash) ? names.pop : OPTS
368: names.each do |n|
369: execute_ddl(drop_view_sql(n, options))
370: remove_cached_schema(n)
371: end
372: nil
373: end
Renames a column in the specified table. This method expects the current column name and the new column name:
DB.rename_column :items, :cntr, :counter
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 392
392: def rename_column(table, *args)
393: alter_table(table) {rename_column(*args)}
394: end
Renames a table:
DB.tables #=> [:items] DB.rename_table :items, :old_items DB.tables #=> [:old_items]
# File lib/sequel/database/schema_methods.rb, line 380
380: def rename_table(name, new_name)
381: execute_ddl(rename_table_sql(name, new_name))
382: remove_cached_schema(name)
383: nil
384: end
Sets the default value for the given column in the given table:
DB.set_column_default :items, :category, 'perl!'
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 401
401: def set_column_default(table, *args)
402: alter_table(table) {set_column_default(*args)}
403: end
Set the data type for the given column in the given table:
DB.set_column_type :items, :price, :float
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 410
410: def set_column_type(table, *args)
411: alter_table(table) {set_column_type(*args)}
412: end
These methods all return instances of this database‘s dataset class.
Returns a dataset for the database. If the first argument is a string, the method acts as an alias for Database#fetch, returning a dataset for arbitrary SQL, with or without placeholders:
DB['SELECT * FROM items'].all DB['SELECT * FROM items WHERE name = ?', my_name].all
Otherwise, acts as an alias for Database#from, setting the primary table for the dataset:
DB[:items].sql #=> "SELECT * FROM items"
# File lib/sequel/database/dataset.rb, line 21
21: def [](*args)
22: args.first.is_a?(String) ? fetch(*args) : from(*args)
23: end
Fetches records for an arbitrary SQL statement. If a block is given, it is used to iterate over the records:
DB.fetch('SELECT * FROM items'){|r| p r}
The fetch method returns a dataset instance:
DB.fetch('SELECT * FROM items').all
fetch can also perform parameterized queries for protection against SQL injection:
DB.fetch('SELECT * FROM items WHERE name = ?', my_name).all
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, line 49
49: def fetch(sql, *args, &block)
50: ds = @default_dataset.with_sql(sql, *args)
51: ds.each(&block) if block
52: ds
53: end
Returns a new dataset with the from method invoked. If a block is given, it 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, line 60
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""_from_#{table}_ds"){@default_dataset.from(table)}
65: else
66: @default_dataset.from(*args)
67: end
68: end
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, line 75
75: def select(*args, &block)
76: @default_dataset.select(*args, &block)
77: end
This methods change the default behavior of this database‘s datasets.
If the database has any dataset modules associated with it, use a subclass of the given class that includes the modules as the dataset class.
# File lib/sequel/database/dataset_defaults.rb, line 18
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
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, line 62
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
This methods affect relating to the logging of executed SQL.
| 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. |
Yield to the block, logging any errors at error level to all loggers, and all other queries with the duration at warn or info level.
# File lib/sequel/database/logging.rb, line 37
37: def log_connection_yield(sql, conn, args=nil)
38: return yield if @loggers.empty?
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 a message at error level, with information about the exception.
# File lib/sequel/database/logging.rb, line 26
26: def log_exception(exception, message)
27: log_each(:error, "#{exception.class}: #{exception.message.strip if exception.message}: #{message}")
28: end
Log a message at level info to all loggers.
# File lib/sequel/database/logging.rb, line 31
31: def log_info(message, args=nil)
32: log_each(:info, args ? "#{message}; #{args.inspect}" : message)
33: end
This methods involve the Database‘s connection pool.
| ADAPTERS | = | %w'ado amalgalite ibmdb jdbc mock mysql mysql2 odbc oracle postgres sqlanywhere sqlite tinytds'.map(&:to_sym) | Array of supported database adapters |
Connects to a database. See Sequel.connect.
# File lib/sequel/database/connecting.rb, line 26
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 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, line 77
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
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, line 147
147: def self.set_shared_adapter_scheme(scheme, mod)
148: Sequel.synchronize{SHARED_ADAPTER_MAP[scheme] = mod}
149: end
Returns the scheme symbol for this instance‘s class, which reflects which adapter is being used. In some cases, this can be the same as the database_type (for native adapters), in others (i.e. adapters with subadapters), it will be different.
Sequel.connect('jdbc:postgres://...').adapter_scheme
# => :jdbc
# File lib/sequel/database/connecting.rb, line 162
162: def adapter_scheme
163: self.class.adapter_scheme
164: 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"})
# File lib/sequel/database/connecting.rb, line 174
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
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, line 193
193: def database_type
194: adapter_scheme
195: end
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, line 207
207: def disconnect(opts = OPTS)
208: pool.disconnect(opts)
209: 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.
# File lib/sequel/database/connecting.rb, line 214
214: def disconnect_connection(conn)
215: conn.close
216: 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)
# File lib/sequel/database/connecting.rb, line 227
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
Returns true if the database is using a single-threaded connection pool.
# File lib/sequel/database/connecting.rb, line 246
246: def single_threaded?
247: @single_threaded
248: end
:nocov:
# File lib/sequel/database/connecting.rb, line 252
252: def synchronize(server=nil)
253: @pool.hold(server || :default){|conn| yield conn}
254: end
Acquires a database connection, yielding it to the passed block. This is useful if you want to make sure the same connection is used for all database queries in the block. It is also useful if you want to gain direct access to the underlying connection object if you need to do something Sequel does not natively support.
If a server option is given, acquires a connection for that specific server, instead of the :default server.
DB.synchronize do |conn|
# ...
end
# File lib/sequel/database/connecting.rb, line 269
269: def synchronize(server=nil, &block)
270: @pool.hold(server || :default, &block)
271: 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.
# File lib/sequel/database/connecting.rb, line 278
278: def test_connection(server=nil)
279: synchronize(server){|conn|}
280: true
281: 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.
# File lib/sequel/database/connecting.rb, line 287
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
This methods generally execute SQL code on the database server.
| COLUMN_SCHEMA_DATETIME_TYPES | = | [:date, :datetime].freeze |
| COLUMN_SCHEMA_STRING_TYPES | = | [:string, :blob, :date, :datetime, :time, :enum, :set, :interval].freeze |
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, line 35
35: def call(ps_name, hash=OPTS, &block)
36: prepared_statement(ps_name).call(hash, &block)
37: end
Method that should be used when submitting any DDL (Data Definition Language) SQL, such as create_table. By default, calls execute_dui. This method should not be called directly by user code.
# File lib/sequel/database/query.rb, line 42
42: def execute_ddl(sql, opts=OPTS, &block)
43: execute_dui(sql, opts, &block)
44: end
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, line 49
49: def execute_dui(sql, opts=OPTS, &block)
50: execute(sql, opts, &block)
51: end
Method that should be used when issuing a INSERT statement. By default, calls execute_dui. This method should not be called directly by user code.
# File lib/sequel/database/query.rb, line 56
56: def execute_insert(sql, opts=OPTS, &block)
57: execute_dui(sql, opts, &block)
58: end
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, line 65
65: def get(*args, &block)
66: @default_dataset.get(*args, &block)
67: end
Runs the supplied SQL statement string on the database server. Returns nil. Options:
| :server : | The server to run the SQL on. |
DB.run("SET some_server_variable = 42")
# File lib/sequel/database/query.rb, line 74
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
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, line 121
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
Returns true if a table with the given name exists. This requires a query to the database.
DB.table_exists?(:foo) # => false # SELECT NULL FROM foo LIMIT 1
Note that since this does a SELECT from the table, it can give false negatives if you don‘t have permission to SELECT from the table.
# File lib/sequel/database/query.rb, line 193
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
Database transactions make multiple queries atomic, so that either all of the queries take effect or none of them do.
| 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. |
If a transaction is not currently in process, yield to the block immediately. Otherwise, add the block to the list of blocks to call after the currently in progress transaction commits (and only if it commits). Options:
| :server : | The server/shard to use. |
# File lib/sequel/database/transactions.rb, line 29
29: def after_commit(opts=OPTS, &block)
30: raise Error, "must provide block to after_commit" unless block
31: synchronize(opts[:server]) do |conn|
32: if h = _trans(conn)
33: raise Error, "cannot call after_commit in a prepared transaction" if h[:prepare]
34: add_transaction_hook(conn, :after_commit, block)
35: else
36: yield
37: end
38: end
39: end
If a transaction is not currently in progress, ignore the block. Otherwise, add the block to the list of the blocks to call after the currently in progress transaction rolls back (and only if it rolls back). Options:
| :server : | The server/shard to use. |
# File lib/sequel/database/transactions.rb, line 46
46: def after_rollback(opts=OPTS, &block)
47: raise Error, "must provide block to after_rollback" unless block
48: synchronize(opts[:server]) do |conn|
49: if h = _trans(conn)
50: raise Error, "cannot call after_rollback in a prepared transaction" if h[:prepare]
51: add_transaction_hook(conn, :after_rollback, block)
52: end
53: end
54: end
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, line 59
59: def in_transaction?(opts=OPTS)
60: synchronize(opts[:server]){|conn| !!_trans(conn)}
61: 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.
# File lib/sequel/database/transactions.rb, line 69
69: def rollback_checker(opts=OPTS)
70: synchronize(opts[:server]) do |conn|
71: raise Error, "not in a transaction" unless t = _trans(conn)
72: t[:rollback_checker] ||= proc{Sequel.synchronize{t[:rolled_back]}}
73: end
74: end
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, line 123
123: def transaction(opts=OPTS, &block)
124: opts = Hash[opts]
125: if retry_on = opts[:retry_on]
126: tot_retries = opts.fetch(:num_retries, 5)
127: num_retries = 0 unless tot_retries.nil?
128: begin
129: opts[:retry_on] = nil
130: opts[:retrying] = true
131: transaction(opts, &block)
132: rescue *retry_on => e
133: if num_retries
134: num_retries += 1
135: if num_retries <= tot_retries
136: opts[:before_retry].call(num_retries, e) if opts[:before_retry]
137: retry
138: end
139: else
140: retry
141: end
142: raise
143: end
144: else
145: synchronize(opts[:server]) do |conn|
146: if opts[:savepoint] == :only
147: if supports_savepoints?
148: if _trans(conn)
149: opts[:savepoint] = true
150: else
151: return yield(conn)
152: end
153: else
154: opts[:savepoint] = false
155: end
156: end
157:
158: if already_in_transaction?(conn, opts)
159: if opts[:rollback] == :always && !opts.has_key?(:savepoint)
160: if supports_savepoints?
161: opts[:savepoint] = true
162: else
163: raise Sequel::Error, "cannot set :rollback=>:always transaction option if already inside a transaction"
164: end
165: end
166:
167: if opts[:savepoint] != false && (stack = _trans(conn)[:savepoints]) && stack.last
168: opts[:savepoint] = true
169: end
170:
171: unless opts[:savepoint]
172: if opts[:retrying]
173: raise Sequel::Error, "cannot set :retry_on options if you are already inside a transaction"
174: end
175: return yield(conn)
176: end
177: end
178:
179: _transaction(conn, opts, &block)
180: end
181: end
182: end
These methods all return booleans, with most describing whether or not the database supprots a given feature.
| conversion_procs | [R] | Hash of conversion procs for the current database |
| convert_invalid_date_time | [R] | By default, Sequel raises an exception if in invalid date or time is used. However, if this is set to nil or :nil, the adapter treats dates like 0000-00-00 and times like 838:00:00 as nil values. If set to :string, it returns the strings as is. |
| convert_tinyint_to_bool | [R] | Whether to convert tinyint columns to bool for the current database |
| convert_tinyint_to_bool | [RW] | Whether to convert tinyint columns to bool for this database |
Connect to the database. In addition to the usual database options, the following options have effect:
| :auto_is_null : | Set to true to use MySQL default behavior of having a filter for an autoincrement column equals NULL to return the last inserted row. |
| :charset : | Same as :encoding (:encoding takes precendence) |
| :encoding : | Set all the related character sets for this connection (connection, client, database, server, and results). |
The options hash is also passed to mysql2, and can include mysql2 options such as :local_infile.
# File lib/sequel/adapters/mysql2.rb, line 37
37: def connect(server)
38: opts = server_opts(server)
39: opts[:host] ||= 'localhost'
40: opts[:username] ||= opts.delete(:user)
41: opts[:flags] ||= 0
42: opts[:flags] |= ::Mysql2::Client::FOUND_ROWS if ::Mysql2::Client.const_defined?(:FOUND_ROWS)
43: opts[:encoding] ||= opts[:charset]
44: conn = ::Mysql2::Client.new(opts)
45: conn.query_options.merge!(:symbolize_keys=>true, :cache_rows=>false)
46:
47: if NativePreparedStatements
48: conn.instance_variable_set(:@sequel_default_query_options, conn.query_options.dup)
49: end
50:
51: sqls = mysql_connection_setting_sqls
52:
53: # Set encoding a slightly different way after connecting,
54: # in case the READ_DEFAULT_GROUP overrode the provided encoding.
55: # Doesn't work across implicit reconnects, but Sequel doesn't turn on
56: # that feature.
57: if encoding = opts[:encoding]
58: sqls.unshift("SET NAMES #{conn.escape(encoding.to_s)}")
59: end
60:
61: sqls.each{|sql| log_connection_yield(sql, conn){conn.query(sql)}}
62:
63: add_prepared_statements_cache(conn)
64: conn
65: end
Connect to the database. In addition to the usual database options, the following options have effect:
| :auto_is_null : | Set to true to use MySQL default behavior of having a filter for an autoincrement column equals NULL to return the last inserted row. |
| :charset : | Same as :encoding (:encoding takes precendence) |
| :compress : | Set to false to not compress results from the server |
| :config_default_group : | The default group to read from the in the MySQL config file. |
| :config_local_infile : | If provided, sets the Mysql::OPT_LOCAL_INFILE option on the connection with the given value. |
| :connect_timeout : | Set the timeout in seconds before a connection attempt is abandoned. |
| :encoding : | Set all the related character sets for this connection (connection, client, database, server, and results). |
| :read_timeout : | Set the timeout in seconds for reading back results to a query. |
| :socket : | Use a unix socket file instead of connecting via TCP/IP. |
| :timeout : | Set the timeout in seconds before the server will disconnect this connection (a.k.a @@wait_timeout). |
# File lib/sequel/adapters/mysql.rb, line 73
73: def connect(server)
74: opts = server_opts(server)
75: conn = Mysql.init
76: conn.options(Mysql::READ_DEFAULT_GROUP, opts[:config_default_group] || "client")
77: conn.options(Mysql::OPT_LOCAL_INFILE, opts[:config_local_infile]) if opts.has_key?(:config_local_infile)
78: conn.ssl_set(opts[:sslkey], opts[:sslcert], opts[:sslca], opts[:sslcapath], opts[:sslcipher]) if opts[:sslca] || opts[:sslkey]
79: if encoding = opts[:encoding] || opts[:charset]
80: # Set encoding before connecting so that the mysql driver knows what
81: # encoding we want to use, but this can be overridden by READ_DEFAULT_GROUP.
82: conn.options(Mysql::SET_CHARSET_NAME, encoding)
83: end
84: if read_timeout = opts[:read_timeout] and defined? Mysql::OPT_READ_TIMEOUT
85: conn.options(Mysql::OPT_READ_TIMEOUT, read_timeout)
86: end
87: if connect_timeout = opts[:connect_timeout] and defined? Mysql::OPT_CONNECT_TIMEOUT
88: conn.options(Mysql::OPT_CONNECT_TIMEOUT, connect_timeout)
89: end
90: conn.real_connect(
91: opts[:host] || 'localhost',
92: opts[:user],
93: opts[:password],
94: opts[:database],
95: (opts[:port].to_i if opts[:port]),
96: opts[:socket],
97: Mysql::CLIENT_MULTI_RESULTS +
98: Mysql::CLIENT_MULTI_STATEMENTS +
99: (opts[:compress] == false ? 0 : Mysql::CLIENT_COMPRESS)
100: )
101: sqls = mysql_connection_setting_sqls
102:
103: # Set encoding a slightly different way after connecting,
104: # in case the READ_DEFAULT_GROUP overrode the provided encoding.
105: # Doesn't work across implicit reconnects, but Sequel doesn't turn on
106: # that feature.
107: sqls.unshift("SET NAMES #{literal(encoding.to_s)}") if encoding
108:
109: sqls.each{|sql| log_connection_yield(sql, conn){conn.query(sql)}}
110:
111: add_prepared_statements_cache(conn)
112: conn
113: end
Modify the type translators for the date, time, and timestamp types depending on the value given.
# File lib/sequel/adapters/mysql.rb, line 123
123: def convert_invalid_date_time=(v)
124: m0 = ::Sequel.method(:string_to_time)
125: @conversion_procs[11] = (v != false) ? lambda{|val| convert_date_time(val, &m0)} : m0
126: m1 = ::Sequel.method(:string_to_date)
127: m = (v != false) ? lambda{|val| convert_date_time(val, &m1)} : m1
128: [10, 14].each{|i| @conversion_procs[i] = m}
129: m2 = method(:to_application_timestamp)
130: m = (v != false) ? lambda{|val| convert_date_time(val, &m2)} : m2
131: [7, 12].each{|i| @conversion_procs[i] = m}
132: @convert_invalid_date_time = v
133: end
Modify the type translator used for the tinyint type based on the value given.
# File lib/sequel/adapters/mysql.rb, line 137
137: def convert_tinyint_to_bool=(v)
138: @conversion_procs[1] = TYPE_TRANSLATOR.method(v ? :boolean : :integer)
139: @convert_tinyint_to_bool = v
140: end
# File lib/sequel/adapters/mysql.rb, line 115
115: def disconnect_connection(c)
116: c.close
117: rescue Mysql::Error
118: nil
119: end
# File lib/sequel/adapters/mysql.rb, line 142
142: def execute_dui(sql, opts=OPTS)
143: execute(sql, opts){|c| return affected_rows(c)}
144: end
# File lib/sequel/adapters/mysql2.rb, line 67
67: def execute_dui(sql, opts=OPTS)
68: execute(sql, opts){|c| return c.affected_rows}
69: end
# File lib/sequel/adapters/mysql.rb, line 146
146: def execute_insert(sql, opts=OPTS)
147: execute(sql, opts){|c| return c.insert_id}
148: end
# File lib/sequel/adapters/mysql2.rb, line 71
71: def execute_insert(sql, opts=OPTS)
72: execute(sql, opts){|c| return c.last_id}
73: end
# File lib/sequel/adapters/mysql.rb, line 150
150: def freeze
151: server_version
152: @conversion_procs.freeze
153: super
154: end
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, line 13
13: def global_index_namespace?
14: true
15: end
Whether the database supports CREATE TABLE IF NOT EXISTS syntax, false by default.
# File lib/sequel/database/features.rb, line 19
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.
# File lib/sequel/database/features.rb, line 25
25: def supports_deferrable_constraints?
26: false
27: end
Whether the database supports deferrable foreign key constraints, false by default as few databases do.
# File lib/sequel/database/features.rb, line 31
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.
# File lib/sequel/database/features.rb, line 37
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.
# File lib/sequel/database/features.rb, line 43
43: def supports_foreign_key_parsing?
44: respond_to?(:foreign_key_list)
45: end
Whether the database supports Database#indexes for parsing indexes.
# File lib/sequel/database/features.rb, line 48
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.
# File lib/sequel/database/features.rb, line 54
54: def supports_partial_indexes?
55: false
56: end
Whether the database and adapter support prepared transactions (two-phase commit), false by default.
# File lib/sequel/database/features.rb, line 60
60: def supports_prepared_transactions?
61: false
62: end
Whether the database and adapter support savepoints, false by default.
# File lib/sequel/database/features.rb, line 65
65: def supports_savepoints?
66: false
67: end
Whether the database and adapter support savepoints inside prepared transactions (two-phase commit), false by default.
# File lib/sequel/database/features.rb, line 71
71: def supports_savepoints_in_prepared_transactions?
72: supports_prepared_transactions? && supports_savepoints?
73: end
Whether the database supports schema parsing via Database#schema.
# File lib/sequel/database/features.rb, line 76
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.
# File lib/sequel/database/features.rb, line 81
81: def supports_table_listing?
82: respond_to?(:tables)
83: end
Whether the database and adapter support transaction isolation levels, false by default.
# File lib/sequel/database/features.rb, line 91
91: def supports_transaction_isolation_levels?
92: false
93: end
Whether DDL statements work correctly in transactions, false by default.
# File lib/sequel/database/features.rb, line 96
96: def supports_transactional_ddl?
97: false
98: end
Whether the database supports Database#views for getting list of views.
# File lib/sequel/database/features.rb, line 86
86: def supports_view_listing?
87: respond_to?(:views)
88: end
Whether CREATE VIEW … WITH CHECK OPTION is supported, false by default.
# File lib/sequel/database/features.rb, line 101
101: def supports_views_with_check_option?
102: !!view_with_check_option_support
103: end
These methods don‘t fit neatly into another category.