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.
This methods generally execute SQL code on the database server.
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.
The prepared statement object hash for this database, keyed by name symbol
Runs the supplied SQL statement string on the database server. Returns self so it can be safely chained:
DB << "UPDATE albums SET artist_id = NULL" << "DROP TABLE artists"
# File lib/sequel/database/query.rb, line 29 def <<(sql) run(sql) self end
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 39 def call(ps_name, hash={}, &block) prepared_statement(ps_name).call(hash, &block) 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 46 def execute_ddl(sql, opts=OPTS, &block) execute_dui(sql, opts, &block) end
Method that should be used when issuing a DELETE, UPDATE, or INSERT statement. By default, calls execute. This method should not be called directly by user code.
# File lib/sequel/database/query.rb, line 53 def execute_dui(sql, opts=OPTS, &block) execute(sql, opts, &block) 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 60 def execute_insert(sql, opts=OPTS, &block) execute_dui(sql, opts, &block) end
Returns a single value from the database, e.g.:
DB.get(1) # SELECT 1 # => 1 DB.get{server_version{}} # SELECT server_version()
# File lib/sequel/database/query.rb, line 69 def get(*args, &block) @default_dataset.get(*args, &block) end
Runs the supplied SQL statement string on the database server. Returns nil. Options:
The server to run the SQL on.
DB.run("SET some_server_variable = 42")
# File lib/sequel/database/query.rb, line 78 def run(sql, opts=OPTS) sql = literal(sql) if sql.is_a?(SQL::PlaceholderLiteralString) execute_ddl(sql, opts) nil 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:
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.
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 125 def schema(table, opts=OPTS) raise(Error, 'schema parsing is not implemented on this database') unless supports_schema_parsing? opts = opts.dup tab = if table.is_a?(Dataset) o = table.opts from = o[:from] 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) table.first_source_table else table end qualifiers = split_qualifiers(tab) table_name = qualifiers.pop sch = qualifiers.pop information_schema_schema = case qualifiers.length when 1 Sequel.identifier(*qualifiers) when 2 Sequel.qualify(*qualifiers) end if table.is_a?(Dataset) quoted_name = table.literal(tab) opts[:dataset] = table else quoted_name = schema_utility_dataset.literal(table) end opts[:schema] = sch if sch && !opts.include?(:schema) opts[:information_schema_schema] = information_schema_schema if information_schema_schema && !opts.include?(:information_schema_schema) Sequel.synchronize{@schemas.delete(quoted_name)} if opts[:reload] if v = Sequel.synchronize{@schemas[quoted_name]} return v end cols = schema_parse_table(table_name, opts) raise(Error, "schema parsing returned no columns, table #{table_name.inspect} probably doesn't exist") if cols.nil? || cols.empty? primary_keys = 0 auto_increment_set = false cols.each do |_,c| auto_increment_set = true if c.has_key?(:auto_increment) primary_keys += 1 if c[:primary_key] end cols.each do |_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type]) unless c.has_key?(:ruby_default) if c[:primary_key] && !auto_increment_set # If adapter didn't set it, assume that integer primary keys are auto incrementing c[:auto_increment] = primary_keys == 1 && !!(c[:db_type] =~ /int/o) end if !c[:max_length] && c[:type] == :string && (max_length = column_schema_max_length(c[:db_type])) c[:max_length] = max_length end end Sequel.synchronize{@schemas[quoted_name] = cols} if cache_schema cols 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 195 def table_exists?(name) sch, table_name = schema_and_table(name) name = SQL::QualifiedIdentifier.new(sch, table_name) if sch ds = from(name) transaction(:savepoint=>:only){_table_exists?(ds)} true rescue DatabaseError false end
These methods execute code on the database that modifies the database’s schema.
The order of column modifiers to use when defining a column.
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, :text, :unique => true, :null => false DB.add_column :items, :category, :text, :default => 'ruby'
See alter_table
.
# File lib/sequel/database/schema_methods.rb, line 46 def add_column(table, *args) alter_table(table) {add_column(*args)} 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 any DatabaseErrors that are raised
Name to use for index instead of default
See alter_table
.
# File lib/sequel/database/schema_methods.rb, line 60 def add_index(table, columns, options=OPTS) e = options[:ignore_errors] begin alter_table(table){add_index(columns, options)} rescue DatabaseError raise unless e end end
Alters the given table with the specified block. Example:
DB.alter_table :items do add_column :category, :text, :default => 'ruby' drop_column :category rename_column :cntr, :counter set_column_type :value, :float set_column_default :value, :float add_index [:group, :category] drop_index [:group, :category] end
Note that add_column
accepts all the options available for
column definitions using create_table
, and
add_index
accepts all the options available for index
definition.
See Schema::AlterTableGenerator
and the “Migrations and Schema Modification”
guide
# File lib/sequel/database/schema_methods.rb, line 86 def alter_table(name, generator=(arg_not_given=true; nil), &block) if generator Sequel::Deprecation.deprecate("Passing a Sequel::Schema::AlterTableGenerator instance as the second argument to Sequel::Database#alter_table ", "Pass a block to Sequel::Database#alter_table instead") else Sequel::Deprecation.deprecate("Passing a second argument to Sequel::Database#alter_table :generator option", "Pass only a single argument to the method") unless arg_not_given generator = alter_table_generator(&block) end remove_cached_schema(name) apply_alter_table_generator(name, generator) nil 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 100 def alter_table_generator(&block) alter_table_generator_class.new(self, &block) end
Create a join table using a hash of foreign keys to referenced table names. Example:
create_join_table(:cat_id=>:cats, :dog_id=>:dogs) # CREATE TABLE cats_dogs ( # cat_id integer NOT NULL REFERENCES cats, # dog_id integer NOT NULL REFERENCES dogs, # PRIMARY KEY (cat_id, dog_id) # ) # CREATE INDEX cats_dogs_dog_id_cat_id_index ON cats_dogs(dog_id, cat_id)
The primary key and index are used so that almost all operations on the table can benefit from one of the two indexes, and the primary key ensures that entries in the table are unique, which is the typical desire for a join table.
You can provide column options by making the values in the hash be option hashes, so long as the option hashes have a :table entry giving the table referenced:
create_join_table(:cat_id=>{:table=>:cats, :type=>:Bignum}, :dog_id=>:dogs)
You can provide a second argument which is a table options hash:
create_join_table({:cat_id=>:cats, :dog_id=>:dogs}, :temp=>true)
Some table options are handled specially:
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.
# File lib/sequel/database/schema_methods.rb, line 136 def create_join_table(hash, options=OPTS) keys = hash.keys.sort_by(&:to_s) create_table(join_table_name(hash, options), options) do keys.each do |key| v = hash[key] unless v.is_a?(Hash) v = {:table=>v} end v[:null] = false unless v.has_key?(:null) foreign_key(key, v) end primary_key(keys) unless options[:no_primary_key] index(keys.reverse, options[:index_options] || {}) unless options[:no_index] end 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 153 def create_join_table!(hash, options=OPTS) drop_table?(join_table_name(hash, options)) create_join_table(hash, options) end
Creates the join table unless it already exists.
# File lib/sequel/database/schema_methods.rb, line 159 def create_join_table?(hash, options=OPTS) if supports_create_table_if_not_exists? && options[:no_index] create_join_table(hash, options.merge(:if_not_exists=>true)) elsif !table_exists?(join_table_name(hash, options)) create_join_table(hash, options) end 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 258 def create_or_replace_view(name, source, options = OPTS) if supports_create_or_replace_view? options = options.merge(:replace=>true) else drop_view(name) rescue nil end create_view(name, source, options) end
Creates a table with the columns given in the provided block:
DB.create_table :posts do primary_key :id column :title, :text String :content index :title end
General options:
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.
See Schema::CreateTableGenerator
and the “Schema Modification”
guide
# File lib/sequel/database/schema_methods.rb, line 202 def create_table(name, options=OPTS, &block) remove_cached_schema(name) if options.is_a?(Schema::CreateTableGenerator) Sequel::Deprecation.deprecate("Passing a Sequel::Schema::CreateTableGenerator instance as the second argument to Sequel::Database#create_table", "Use the Sequel::Database#create_table :generator option instead") options = {:generator=>options} end if sql = options[:as] raise(Error, "can't provide both :as option and block to create_table") if block create_table_as(name, sql, options) else generator = options[:generator] || create_table_generator(&block) create_table_from_generator(name, generator, options) create_table_indexes_from_generator(name, generator, options) nil end 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 225 def create_table!(name, options=OPTS, &block) drop_table?(name) create_table(name, options, &block) 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 235 def create_table?(name, options=OPTS, &block) options = options.dup generator = options[:generator] ||= create_table_generator(&block) if generator.indexes.empty? && supports_create_table_if_not_exists? create_table(name, options.merge!(:if_not_exists=>true)) elsif !table_exists?(name) create_table(name, options) end 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 247 def create_table_generator(&block) create_table_generator_class.new(self, &block) 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:
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.
# File lib/sequel/database/schema_methods.rb, line 303 def create_view(name, source, options = OPTS) execute_ddl(create_view_sql(name, source, options)) remove_cached_schema(name) nil end
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table
.
# File lib/sequel/database/schema_methods.rb, line 314 def drop_column(table, *args) alter_table(table) {drop_column(*args)} 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 324 def drop_index(table, columns, options=OPTS) alter_table(table){drop_index(columns, options)} 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 333 def drop_join_table(hash, options=OPTS) drop_table(join_table_name(hash, options), options) 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 342 def drop_table(*names) options = names.last.is_a?(Hash) ? names.pop : {} names.each do |n| execute_ddl(drop_table_sql(n, options)) remove_cached_schema(n) end nil 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 357 def drop_table?(*names) options = names.last.is_a?(Hash) ? names.pop : {} if supports_drop_table_if_exists? options = options.merge(:if_exists=>true) names.each do |name| drop_table(name, options) end else names.each do |name| drop_table(name, options) if table_exists?(name) end end 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:
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.
# File lib/sequel/database/schema_methods.rb, line 384 def drop_view(*names) options = names.last.is_a?(Hash) ? names.pop : {} names.each do |n| execute_ddl(drop_view_sql(n, options)) remove_cached_schema(n) end nil 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 410 def rename_column(table, *args) alter_table(table) {rename_column(*args)} 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 398 def rename_table(name, new_name) execute_ddl(rename_table_sql(name, new_name)) remove_cached_schema(name) nil 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 419 def set_column_default(table, *args) alter_table(table) {set_column_default(*args)} 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 428 def set_column_type(table, *args) alter_table(table) {set_column_type(*args)} 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 #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 #from, setting the primary table for the dataset:
DB[:items].sql #=> "SELECT * FROM items"
# File lib/sequel/database/dataset.rb, line 21 def [](*args) args.first.is_a?(String) ? fetch(*args) : from(*args) end
Returns a blank dataset for this database.
DB.dataset # SELECT * DB.dataset.from(:items) # SELECT * FROM items
# File lib/sequel/database/dataset.rb, line 29 def dataset @dataset_class.new(self) 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 Sequel::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 def fetch(sql, *args, &block) ds = @default_dataset.with_sql(sql, *args) ds.each(&block) if block ds end
Returns a new dataset with the from
method invoked. If a block
is given, it is used as a filter on the dataset.
DB.from(:items) # SELECT * FROM items DB.from(:items){id > 2} # SELECT * FROM items WHERE (id > 2)
# File lib/sequel/database/dataset.rb, line 60 def from(*args, &block) ds = @default_dataset.from(*args) if block Sequel::Deprecation.deprecate("Sequel::Database#from with a block", "Use .from(*args).where(&block) instead") ds.where(&block) else ds end end
Returns a new dataset with the select method invoked.
DB.select(1) # SELECT 1 DB.select{server_version{}} # SELECT server_version() DB.select(:id).from(:items) # SELECT id FROM items
# File lib/sequel/database/dataset.rb, line 75 def select(*args, &block) @default_dataset.select(*args, &block) end
This methods involve the Database’s connection pool.
Array of supported database adapters
The Database subclass for the given adapter scheme. Raises Sequel::AdapterNotFound if the adapter could not be loaded.
# File lib/sequel/database/connecting.rb, line 27 def self.adapter_class(scheme) return scheme if scheme.is_a?(Class) if scheme.to_s.include?('-') # :nocov: Sequel::Deprecation.deprecate("Automatically converting '-' to '_' in adapter schemes", "Use '_' instead of '-' in the adapter scheme") # :nocov: end scheme = scheme.to_s.gsub('-', '_').to_sym # SEQUEL5: Remove # scheme = scheme.to_sym # SEQUEL5 load_adapter(scheme) end
Returns the scheme symbol for the Database class.
# File lib/sequel/database/connecting.rb, line 43 def self.adapter_scheme @scheme end
Connects to a database. See Sequel.connect.
# File lib/sequel/database/connecting.rb, line 48 def self.connect(conn_string, opts = OPTS) case conn_string when String # SEQUEL5: Remove do if match = /\A(jdbc|do):/.match(conn_string) c = adapter_class(match[1].to_sym) opts = opts.merge(:orig_opts=>opts.dup) opts = {:uri=>conn_string}.merge!(opts) else uri = URI.parse(conn_string) scheme = uri.scheme c = adapter_class(scheme) uri_options = c.send(:uri_to_options, uri) uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v if k && !k.empty?} unless uri.query.to_s.strip.empty? 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)} opts = uri_options.merge(opts).merge!(:orig_opts=>opts.dup, :uri=>conn_string, :adapter=>scheme) end when Hash opts = conn_string.merge(opts) opts = opts.merge(:orig_opts=>opts.dup) c = adapter_class(opts[:adapter_class] || opts[:adapter] || opts['adapter']) else raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" end # process opts a bit opts = opts.inject({}) do |m, (k,v)| k = :user if k.to_s == 'username' m[k.to_sym] = v m end begin db = c.new(opts) # SEQUEL5: Default opts[:test] to true db.test_connection if opts[:test] && db.send(:typecast_value_boolean, opts[:test]) if block_given? return yield(db) end ensure if block_given? db.disconnect if db Sequel.synchronize{::Sequel::DATABASES.delete(db)} end end db 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:
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.
# File lib/sequel/database/connecting.rb, line 100 def self.load_adapter(scheme, opts=OPTS) map = opts[:map] || ADAPTER_MAP if subdir = opts[:subdir] file = "#{subdir}/#{scheme}" else file = scheme end unless obj = Sequel.synchronize{map[scheme]} # attempt to load the adapter file begin require "sequel/adapters/#{file}" rescue LoadError => e # If subadapter file doesn't exist, just return, # using the main adapter class without database customizations. return if subdir raise Sequel.convert_exception_class(e, AdapterNotFound) end # make sure we actually loaded the adapter unless obj = Sequel.synchronize{map[scheme]} raise AdapterNotFound, "Could not load #{file} adapter: adapter class not registered in ADAPTER_MAP" end end obj end
SEQUEL5: Remove cubrid do swift
# File lib/sequel/database/connecting.rb, line 14 def self.single_threaded Sequel::Deprecation.deprecate("Sequel::Database.single_threaded", "Use Sequel.single_threaded instead") Sequel.single_threaded end
# File lib/sequel/database/connecting.rb, line 19 def self.single_threaded=(v) Sequel::Deprecation.deprecate("Sequel::Database.single_threaded=", "Use Sequel.single_threaded= instead") Sequel.single_threaded = v 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 185 def adapter_scheme self.class.adapter_scheme end
Dynamically add new servers or modify server options at runtime. Also adds new servers to the connection pool. Intended for use with master/slave or shard configurations where it is useful to add new server hosts at runtime.
servers argument should be a hash with server name symbol keys and hash or proc values. If a servers key is already in use, it’s value is overridden with the value provided.
DB.add_servers(:f=>{:host=>"hash_host_f"})
# File lib/sequel/database/connecting.rb, line 198 def add_servers(servers) unless h = @opts[:servers] Sequel::Deprecation.deprecate("Calling Database#add_servers on a database that does not use sharding", "This method should only be called if the database supports sharding.") # raise Error, "cannot call Database#add_servers on a Database instance that does not use a sharded connection pool" # SEQUEL5 return end Sequel.synchronize{h.merge!(servers)} @pool.add_servers(servers.keys) 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 217 def database_type adapter_scheme end
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.
Example:
DB.disconnect # All servers DB.disconnect(:servers=>:server1) # Single server DB.disconnect(:servers=>[:server1, :server2]) # Multiple servers
# File lib/sequel/database/connecting.rb, line 231 def disconnect(opts = OPTS) pool.disconnect(opts) 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 238 def disconnect_connection(conn) conn.close end
Yield a new Database instance for every server in the connection pool. Intended for use in sharded environments where there is a need to make schema modifications (DDL queries) on each shard.
DB.each_server{|db| db.create_table(:users){primary_key :id; String :name}}
# File lib/sequel/database/connecting.rb, line 247 def each_server(&block) Sequel::Deprecation.deprecate("Database#each_server", "Switching to using Dataset#servers and Database#with_server from the server_block extension: \"DB.servers.each{|s| DB.with_server(s){}}\"") raise(Error, "Database#each_server must be passed a block") unless block servers.each{|s| self.class.connect(server_opts(s), &block)} end
Dynamically remove existing servers from the connection pool. Intended for use with master/slave or shard configurations where it is useful to remove existing server hosts at runtime.
servers should be symbols or arrays of symbols. If a nonexistent server is specified, it is ignored. If no servers have been specified for this database, no changes are made. If you attempt to remove the :default server, an error will be raised.
DB.remove_servers(:f1, :f2)
# File lib/sequel/database/connecting.rb, line 263 def remove_servers(*servers) unless h = @opts[:servers] Sequel::Deprecation.deprecate("Calling Database#add_servers on a database that does not use sharding", "This method should only be called if the database supports sharding.") # raise Error, "cannot call Database#remove_servers on a Database instance that does not use a sharded connection pool" # SEQUEL5 return end servers.flatten.each{|s| Sequel.synchronize{h.delete(s)}} @pool.remove_servers(servers) end
An array of servers/shards for this Database object.
DB.servers # Unsharded: => [:default] DB.servers # Sharded: => [:default, :server1, :server2]
# File lib/sequel/database/connecting.rb, line 278 def servers pool.servers end
Returns true if the database is using a single-threaded connection pool.
# File lib/sequel/database/connecting.rb, line 283 def single_threaded? @single_threaded 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 300 def synchronize(server=nil) @pool.hold(server || :default){|conn| yield conn} 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 315 def test_connection(server=nil) synchronize(server){|conn|} true 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 324 def valid_connection?(conn) sql = valid_connection_sql begin log_connection_execute(conn, sql) rescue Sequel::DatabaseError, *database_error_classes false else true end end
This methods change the default behavior of this database’s datasets.
The default class to use for datasets
The identifier input method to use by default for all databases (default: adapter default)
The identifier output method to use by default for all databases (default: adapter default)
Whether to quote identifiers (columns and tables) by default for all databases (default: adapter default)
The class to use for creating datasets. Should respond to new with the Database argument as the first argument, and an optional options hash.
Change the default identifier input method to use for all databases,
# File lib/sequel/database/dataset_defaults.rb, line 30 def self.identifier_input_method=(v) Sequel::Deprecation.deprecate("Sequel.identifier_input_method= and Sequel::Database.identifier_input_method=", "Call Sequel::Database#identifier_input_method= instead") @identifier_input_method = v.nil? ? false : v end
Change the default identifier output method to use for all databases,
# File lib/sequel/database/dataset_defaults.rb, line 36 def self.identifier_output_method=(v) Sequel::Deprecation.deprecate("Sequel.identifier_output_method= and Sequel::Database.identifier_output_method=", "Call Sequel::Database#identifier_output_method= instead") @identifier_output_method = v.nil? ? false : v end
# File lib/sequel/database/dataset_defaults.rb, line 41 def self.quote_identifiers=(v) Sequel::Deprecation.deprecate("Sequel.quote_identifiers= and Sequel::Database.quote_identifiers=", "Call Sequel::Database#quote_identifiers= instead") @quote_identifiers = v end
If the database has any dataset modules associated with it, use a subclass of the given class that includes the modules as the dataset class.
# File lib/sequel/database/dataset_defaults.rb, line 54 def dataset_class=(c) unless @dataset_modules.empty? c = Class.new(c) @dataset_modules.each{|m| c.send(:include, m)} end @dataset_class = c reset_default_dataset end
Equivalent to extending all datasets produced by the database with a module. What it actually does is use a subclass of the current #dataset_class as the new #dataset_class, and include the module in the subclass. Instead of a module, you can provide a block that is used to create an anonymous module.
This allows you to override any of the dataset methods even if they are defined directly on the dataset class that this Database object uses.
Examples:
# Introspec columns for all of DB's datasets DB.extend_datasets(Sequel::ColumnsIntrospection) # Trace all SELECT queries by printing the SQL and the full backtrace DB.extend_datasets do def fetch_rows(sql) puts sql puts caller super end end
# File lib/sequel/database/dataset_defaults.rb, line 85 def extend_datasets(mod=nil, &block) raise(Error, "must provide either mod or block, not both") if mod && block mod = Module.new(&block) if block if @dataset_modules.empty? @dataset_modules = [mod] @dataset_class = Class.new(@dataset_class) else @dataset_modules << mod end @dataset_class.send(:include, mod) reset_default_dataset end
This methods affect relating to the logging of executed SQL.
Whether to include information about the connection in use when logging queries.
Numeric specifying the duration beyond which queries are logged at warn level instead of info level.
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 44 def log_connection_yield(sql, conn, args=nil) return yield if @loggers.empty? sql = "#{connection_info(conn) if conn && log_connection_info}#{sql}#{"; #{args.inspect}" if args}" start = Time.now begin yield rescue => e log_exception(e, sql) raise ensure log_duration(Time.now - start, sql) unless e end end
Log a message at error level, with information about the exception.
# File lib/sequel/database/logging.rb, line 26 def log_exception(exception, message) log_each(:error, "#{exception.class}: #{exception.message.strip if exception.message}: #{message}") end
Log a message at level info to all loggers.
# File lib/sequel/database/logging.rb, line 31 def log_info(message, args=nil) log_each(:info, args ? "#{message}; #{args.inspect}" : message) end
Yield to the block, logging any errors at error level to all loggers, and all other queries with the duration at warn or info level.
# File lib/sequel/database/logging.rb, line 37 def log_yield(sql, args=nil, &block) Sequel::Deprecation.deprecate("Sequel::Database#log_yield", "Update the adapter to use Sequel::Database#log_connection_yield") log_connection_yield(sql, nil, args, &block) end
Remove any existing loggers and just use the given logger:
DB.logger = Logger.new($stdout)
# File lib/sequel/database/logging.rb, line 61 def logger=(logger) @loggers = Array(logger) end
These methods don’t fit neatly into another category.
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).
Used for checking/removing leading zeroes from strings so they don’t get interpreted as octal.
:nocov: Replacement string when replacing leading zeroes.
Mapping of schema type symbols to class or arrays of classes for that symbol.
The specific default size of string columns for this Sequel::Database, usually 255 by default.
The options hash for this database
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 46 def self.after_initialize(&block) raise Error, "must provide block to after_initialize" unless block Sequel.synchronize do previous = @initialize_hook @initialize_hook = Proc.new do |db| previous.call(db) block.call(db) end end end
Apply an extension to all Database objects created in the future.
# File lib/sequel/database/misc.rb, line 58 def self.extension(*extensions) after_initialize{|db| db.extension(*extensions)} end
Constructs a new instance of a database connection with the specified options hash.
Accepts the following options:
The default size of string columns, 255 by default.
Whether to support non-default identifier mangling for the current database.
A specific logger to use.
An array of loggers to use.
A name to use for the Database object.
Whether to automatically connect to the maximum number of servers.
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.
All options given are also passed to the connection pool.
# File lib/sequel/database/misc.rb, line 122 def initialize(opts = OPTS) @opts ||= opts @opts = connection_pool_default_options.merge(@opts) @loggers = Array(@opts[:logger]) + Array(@opts[:loggers]) @opts[:servers] = {} if @opts[:servers].is_a?(String) @sharded = !!@opts[:servers] @opts[:adapter_class] = self.class @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, Sequel.single_threaded)) @default_string_column_size = @opts[:default_string_column_size] || DEFAULT_STRING_COLUMN_SIZE @schemas = {} @prepared_statements = {} @transactions = {} @symbol_literal_cache = {} @timezone = nil @dataset_class = dataset_class_default @cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true)) @dataset_modules = [] @loaded_extensions = [] @schema_type_classes = SCHEMA_TYPE_CLASSES.dup self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info self.log_warn_duration = @opts[:log_warn_duration] self.log_connection_info = typecast_value_boolean(@opts[:log_connection_info]) @pool = ConnectionPool.get_pool(self, @opts) reset_default_dataset adapter_initialize if typecast_value_boolean(@opts.fetch(:identifier_mangling, true)) # SEQUEL5: Remove extension(:_deprecated_identifier_mangling) end unless typecast_value_boolean(@opts[:keep_reference]) == false Sequel.synchronize{::Sequel::DATABASES.push(self)} end Sequel::Database.run_after_initialize(self) if typecast_value_boolean(@opts[:preconnect]) && @pool.respond_to?(:preconnect, true) concurrent = typecast_value_string(@opts[:preconnect]) == "concurrently" @pool.send(:preconnect, concurrent) end 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 67 def self.register_extension(ext, mod=nil, &block) if mod raise(Error, "cannot provide both mod and block to Database.register_extension") if block if mod.is_a?(Module) block = proc{|db| db.extend(mod)} else block = mod end end Sequel.synchronize{EXTENSIONS[ext] = block} end
Run the ::after_initialize hook
for the given instance
.
# File lib/sequel/database/misc.rb, line 80 def self.run_after_initialize(instance) @initialize_hook.call(instance) end
Cast the given type to a literal type
DB.cast_type_literal(Float) # double precision DB.cast_type_literal(:foo) # foo
# File lib/sequel/database/misc.rb, line 195 def cast_type_literal(type) type_literal(:type=>type) 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 204 def extension(*exts) Sequel.extension(*exts) exts.each do |ext| if pr = Sequel.synchronize{EXTENSIONS[ext]} unless Sequel.synchronize{@loaded_extensions.include?(ext)} Sequel.synchronize{@loaded_extensions << ext} pr.call(self) end else raise(Error, "Extension #{ext} does not have specific support handling individual databases (try: Sequel.extension #{ext.inspect})") end end self end
Freeze internal data structures for the Database instance.
# File lib/sequel/database/misc.rb, line 169 def freeze valid_connection_sql metadata_dataset @opts.freeze @loggers.freeze @pool.freeze @dataset_class.freeze @dataset_modules.freeze @schema_type_classes.freeze @loaded_extensions.freeze # SEQUEL5: Frozen by default, remove this @default_dataset.freeze metadata_dataset.freeze super 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 222 def from_application_timestamp(v) Sequel.convert_output_timestamp(v, timezone) end
# File lib/sequel/database/misc.rb, line 185 def initialize_copy(_) Sequel::Deprecation.deprecate("Database#dup and #clone", "Use Sequel.connect to create a new Database instance") # raise(Error, "cannot dup/clone a Sequel::Database instance") # SEQUEL5 super 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 228 def inspect a = [] a << uri.inspect if uri if (oo = opts[:orig_opts]) && !oo.empty? a << oo.inspect end "#<#{self.class}: #{a.join(' ')}>" end
Proxy the literal call to the dataset.
DB.literal(1) # 1 DB.literal(:a) # a DB.literal('a') # 'a'
# File lib/sequel/database/misc.rb, line 242 def literal(v) schema_utility_dataset.literal(v) end
Return the literalized version of the symbol if cached, or nil if it is not cached.
# File lib/sequel/database/misc.rb, line 248 def literal_symbol(sym) Sequel.synchronize{@symbol_literal_cache[sym]} end
Set the cached value of the literal symbol.
# File lib/sequel/database/misc.rb, line 253 def literal_symbol_set(sym, lit) Sequel.synchronize{@symbol_literal_cache[sym] = lit} end
Synchronize access to the prepared statements cache.
# File lib/sequel/database/misc.rb, line 258 def prepared_statement(name) Sequel.synchronize{prepared_statements[name]} 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 265 def quote_identifier(v) schema_utility_dataset.quote_identifier(v) end
Return ruby class or array of classes for the given type symbol.
# File lib/sequel/database/misc.rb, line 270 def schema_type_class(type) @schema_type_classes[type] end
Default serial primary key options, used by the table creation code.
# File lib/sequel/database/misc.rb, line 276 def serial_primary_key_options {:primary_key => true, :type => Integer, :auto_increment => true} end
Cache the prepared statement object at the given name.
# File lib/sequel/database/misc.rb, line 281 def set_prepared_statement(name, ps) Sequel.synchronize{prepared_statements[name] = ps} end
Whether this database instance uses multiple servers, either for sharding or for master/slave.
# File lib/sequel/database/misc.rb, line 287 def sharded? @sharded end
The timezone to use for this database, defaulting to
Sequel.database_timezone
.
# File lib/sequel/database/misc.rb, line 292 def timezone @timezone || Sequel.database_timezone 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.
# File lib/sequel/database/misc.rb, line 299 def to_application_timestamp(v) Sequel.convert_timestamp(v, timezone) 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 308 def typecast_value(column_type, value) return nil if value.nil? meth = "typecast_value_#{column_type}" begin respond_to?(meth, true) ? send(meth, value) : value rescue ArgumentError, TypeError => e raise Sequel.convert_exception_class(e, InvalidValue) end end
Returns the URI use to connect to the database. If a URI was not used when connecting, returns nil.
# File lib/sequel/database/misc.rb, line 320 def uri opts[:uri] end
Explicit alias of uri for easier subclassing.
# File lib/sequel/database/misc.rb, line 325 def url uri end
These methods all return booleans, with most describing whether or not the database supprots a given feature.
Whether the database uses a global namespace for the index. If false, the indexes are going to be namespaced per table.
# File lib/sequel/database/features.rb, line 13 def global_index_namespace? true end
Whether the database supports CREATE TABLE IF NOT EXISTS syntax, false by default.
# File lib/sequel/database/features.rb, line 19 def supports_create_table_if_not_exists? false end
Whether the database supports deferrable constraints, false by default as few databases do.
# File lib/sequel/database/features.rb, line 25 def supports_deferrable_constraints? false end
Whether the database supports deferrable foreign key constraints, false by default as few databases do.
# File lib/sequel/database/features.rb, line 31 def supports_deferrable_foreign_key_constraints? supports_deferrable_constraints? end
Whether the database supports DROP TABLE IF EXISTS syntax, default is the same as supports_create_table_if_not_exists?.
# File lib/sequel/database/features.rb, line 37 def supports_drop_table_if_exists? supports_create_table_if_not_exists? end
Whether the database supports Database#foreign_key_list for parsing foreign keys.
# File lib/sequel/database/features.rb, line 43 def supports_foreign_key_parsing? respond_to?(:foreign_key_list) end
Whether the database supports Database#indexes for parsing indexes.
# File lib/sequel/database/features.rb, line 48 def supports_index_parsing? respond_to?(:indexes) end
Whether the database supports partial indexes (indexes on a subset of a table).
# File lib/sequel/database/features.rb, line 53 def supports_partial_indexes? false end
Whether the database and adapter support prepared transactions (two-phase commit), false by default.
# File lib/sequel/database/features.rb, line 59 def supports_prepared_transactions? false end
Whether the database and adapter support savepoints, false by default.
# File lib/sequel/database/features.rb, line 64 def supports_savepoints? false end
Whether the database and adapter support savepoints inside prepared transactions (two-phase commit), default is false.
# File lib/sequel/database/features.rb, line 70 def supports_savepoints_in_prepared_transactions? supports_prepared_transactions? && supports_savepoints? end
Whether the database supports schema parsing via #schema.
# File lib/sequel/database/features.rb, line 75 def supports_schema_parsing? respond_to?(:schema_parse_table, true) end
Whether the database supports Database#tables for getting list of tables.
# File lib/sequel/database/features.rb, line 80 def supports_table_listing? respond_to?(:tables) end
Whether the database and adapter support transaction isolation levels, false by default.
# File lib/sequel/database/features.rb, line 90 def supports_transaction_isolation_levels? false end
Whether DDL statements work correctly in transactions, false by default.
# File lib/sequel/database/features.rb, line 95 def supports_transactional_ddl? false end
Whether the database supports Database#views for getting list of views.
# File lib/sequel/database/features.rb, line 85 def supports_view_listing? respond_to?(:views) end
Whether CREATE VIEW … WITH CHECK OPTION is supported, false by default.
# File lib/sequel/database/features.rb, line 100 def supports_views_with_check_option? !!view_with_check_option_support end
Whether CREATE VIEW … WITH LOCAL CHECK OPTION is supported, false by default.
# File lib/sequel/database/features.rb, line 105 def supports_views_with_local_check_option? view_with_check_option_support == :local end