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.
STRING_DEFAULT_RE | = | /\A'(.*)'\z/ |
CURRENT_TIMESTAMP_RE | = | /now|today|CURRENT|getdate|\ADate\(\)\z/io |
COLUMN_SCHEMA_DATETIME_TYPES | = | [:date, :datetime] |
COLUMN_SCHEMA_STRING_TYPES | = | [:string, :blob, :date, :datetime, :time, :enum, :set, :interval] |
Call the prepared statement with the given name with the given hash of arguments.
DB[:items].filter(:id=>1).prepare(:first, :sa) DB.call(:sa) # SELECT * FROM items WHERE id = 1
# File lib/sequel/database/query.rb, line 37 37: def call(ps_name, hash={}, &block) 38: prepared_statement(ps_name).call(hash, &block) 39: 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 44 44: def execute_ddl(sql, opts=OPTS, &block) 45: execute_dui(sql, opts, &block) 46: 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 58 58: def execute_insert(sql, opts=OPTS, &block) 59: execute_dui(sql, opts, &block) 60: 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 76 76: def run(sql, opts=OPTS) 77: sql = literal(sql) if sql.is_a?(SQL::PlaceholderLiteralString) 78: execute_ddl(sql, opts) 79: nil 80: 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 123 123: def schema(table, opts=OPTS) 124: raise(Error, 'schema parsing is not implemented on this database') unless supports_schema_parsing? 125: 126: opts = opts.dup 127: tab = if table.is_a?(Dataset) 128: o = table.opts 129: from = o[:from] 130: 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) 131: table.first_source_table 132: else 133: table 134: end 135: 136: qualifiers = split_qualifiers(tab) 137: table_name = qualifiers.pop 138: sch = qualifiers.pop 139: information_schema_schema = case qualifiers.length 140: when 1 141: Sequel.identifier(*qualifiers) 142: when 2 143: Sequel.qualify(*qualifiers) 144: end 145: 146: if table.is_a?(Dataset) 147: quoted_name = table.literal(tab) 148: opts[:dataset] = table 149: else 150: quoted_name = schema_utility_dataset.literal(table) 151: end 152: 153: opts[:schema] = sch if sch && !opts.include?(:schema) 154: opts[:information_schema_schema] = information_schema_schema if information_schema_schema && !opts.include?(:information_schema_schema) 155: 156: Sequel.synchronize{@schemas.delete(quoted_name)} if opts[:reload] 157: if v = Sequel.synchronize{@schemas[quoted_name]} 158: return v 159: end 160: 161: cols = schema_parse_table(table_name, opts) 162: raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty? 163: 164: primary_keys = 0 165: auto_increment_set = false 166: cols.each do |_,c| 167: auto_increment_set = true if c.has_key?(:auto_increment) 168: primary_keys += 1 if c[:primary_key] 169: end 170: 171: cols.each do |_,c| 172: c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type]) unless c.has_key?(:ruby_default) 173: if c[:primary_key] && !auto_increment_set 174: # If adapter didn't set it, assume that integer primary keys are auto incrementing 175: c[:auto_increment] = primary_keys == 1 && !!(c[:db_type] =~ /int/io) 176: end 177: if !c[:max_length] && c[:type] == :string && (max_length = column_schema_max_length(c[:db_type])) 178: c[:max_length] = max_length 179: end 180: end 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
This methods change the default behavior of this database‘s datasets.
DatasetClass | = | Sequel::Dataset | The default class to use for datasets |
dataset_class | [R] | The class to use for creating datasets. Should respond to new with the Database argument as the first argument, and an optional options hash. |
identifier_input_method | [R] | The identifier input method to use by default for all databases (default: adapter default) |
identifier_input_method | [R] | The identifier input method to use by default for this database (default: adapter default) |
identifier_output_method | [R] | The identifier output method to use by default for all databases (default: adapter default) |
identifier_output_method | [R] | The identifier output method to use by default for this database (default: adapter default) |
quote_identifiers | [RW] | Whether to quote identifiers (columns and tables) by default for all databases (default: adapter default) |
Change the default identifier input method to use for all databases,
# File lib/sequel/database/dataset_defaults.rb, line 29 29: def self.identifier_input_method=(v) 30: @identifier_input_method = v.nil? ? false : v 31: end
Change the default identifier output method to use for all databases,
# File lib/sequel/database/dataset_defaults.rb, line 34 34: def self.identifier_output_method=(v) 35: @identifier_output_method = v.nil? ? false : v 36: 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 52 52: def dataset_class=(c) 53: unless @dataset_modules.empty? 54: c = Class.new(c) 55: @dataset_modules.each{|m| c.send(:include, m)} 56: end 57: @dataset_class = c 58: reset_default_dataset 59: 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 83 83: def extend_datasets(mod=nil, &block) 84: raise(Error, "must provide either mod or block, not both") if mod && block 85: mod = Module.new(&block) if block 86: if @dataset_modules.empty? 87: @dataset_modules = [mod] 88: @dataset_class = Class.new(@dataset_class) 89: else 90: @dataset_modules << mod 91: end 92: @dataset_class.send(:include, mod) 93: reset_default_dataset 94: end
Set the method to call on identifiers going into the database:
DB[:items] # SELECT * FROM items DB.identifier_input_method = :upcase DB[:items] # SELECT * FROM ITEMS
# File lib/sequel/database/dataset_defaults.rb, line 101 101: def identifier_input_method=(v) 102: reset_default_dataset 103: @identifier_input_method = v 104: end
Set the method to call on identifiers coming from the database:
DB[:items].first # {:id=>1, :name=>'foo'} DB.identifier_output_method = :upcase DB[:items].first # {:ID=>1, :NAME=>'foo'}
# File lib/sequel/database/dataset_defaults.rb, line 111 111: def identifier_output_method=(v) 112: reset_default_dataset 113: @identifier_output_method = v 114: end
Set whether to quote identifiers (columns and tables) for this database:
DB[:items] # SELECT * FROM items DB.quote_identifiers = true DB[:items] # SELECT * FROM "items"
# File lib/sequel/database/dataset_defaults.rb, line 121 121: def quote_identifiers=(v) 122: reset_default_dataset 123: @quote_identifiers = v 124: end
This methods involve the Database‘s connection pool.
ADAPTERS | = | %w'ado amalgalite cubrid do ibmdb jdbc mock mysql mysql2 odbc oracle postgres sqlanywhere sqlite swift tinytds'.collect(&:to_sym) | 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 23 23: def self.adapter_class(scheme) 24: return scheme if scheme.is_a?(Class) 25: 26: scheme = scheme.to_s.gsub('-', '_').to_sym 27: 28: load_adapter(scheme) 29: end
Connects to a database. See Sequel.connect.
# File lib/sequel/database/connecting.rb, line 37 37: def self.connect(conn_string, opts = OPTS) 38: case conn_string 39: when String 40: if match = /\A(jdbc|do):/o.match(conn_string) 41: c = adapter_class(match[1].to_sym) 42: opts = opts.merge(:orig_opts=>opts.dup) 43: opts = {:uri=>conn_string}.merge!(opts) 44: else 45: uri = URI.parse(conn_string) 46: scheme = uri.scheme 47: c = adapter_class(scheme) 48: uri_options = c.send(:uri_to_options, uri) 49: 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? 50: 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)} 51: opts = uri_options.merge(opts).merge!(:orig_opts=>opts.dup, :uri=>conn_string, :adapter=>scheme) 52: end 53: when Hash 54: opts = conn_string.merge(opts) 55: opts = opts.merge(:orig_opts=>opts.dup) 56: c = adapter_class(opts[:adapter_class] || opts[:adapter] || opts['adapter']) 57: else 58: raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" 59: end 60: # process opts a bit 61: opts = opts.inject({}) do |m, (k,v)| 62: k = :user if k.to_s == 'username' 63: m[k.to_sym] = v 64: m 65: end 66: begin 67: db = c.new(opts) 68: db.test_connection if opts[:test] && db.send(:typecast_value_boolean, opts[:test]) 69: if block_given? 70: return yield(db) 71: end 72: ensure 73: if block_given? 74: db.disconnect if db 75: Sequel.synchronize{::Sequel::DATABASES.delete(db)} 76: end 77: end 78: db 79: 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 87 87: def self.load_adapter(scheme, opts=OPTS) 88: map = opts[:map] || ADAPTER_MAP 89: if subdir = opts[:subdir] 90: file = "#{subdir}/#{scheme}" 91: else 92: file = scheme 93: end 94: 95: unless obj = Sequel.synchronize{map[scheme]} 96: # attempt to load the adapter file 97: begin 98: require "sequel/adapters/#{file}" 99: rescue LoadError => e 100: # If subadapter file doesn't exist, just return, 101: # using the main adapter class without database customizations. 102: return if subdir 103: raise Sequel.convert_exception_class(e, AdapterNotFound) 104: end 105: 106: # make sure we actually loaded the adapter 107: unless obj = Sequel.synchronize{map[scheme]} 108: raise AdapterNotFound, "Could not load #{file} adapter: adapter class not registered in ADAPTER_MAP" 109: end 110: end 111: 112: obj 113: 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 157 157: def self.set_shared_adapter_scheme(scheme, mod) 158: Sequel.synchronize{SHARED_ADAPTER_MAP[scheme] = mod} 159: 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 171 171: def adapter_scheme 172: self.class.adapter_scheme 173: 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 184 184: def add_servers(servers) 185: if h = @opts[:servers] 186: Sequel.synchronize{h.merge!(servers)} 187: @pool.add_servers(servers.keys) 188: end 189: 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 (think JDBC or DataObjects).
Sequel.connect('jdbc:postgres://...').database_type # => :postgres
# File lib/sequel/database/connecting.rb, line 200 200: def database_type 201: adapter_scheme 202: end
Disconnects all available connections from the connection pool. Any connections currently in use will not be disconnected. Options:
:servers : | Should be a symbol specifing the server to disconnect from, or an array of symbols to specify multiple servers. |
Example:
DB.disconnect # All servers DB.disconnect(:servers=>:server1) # Single server DB.disconnect(:servers=>[:server1, :server2]) # Multiple servers
# File lib/sequel/database/connecting.rb, line 214 214: def disconnect(opts = OPTS) 215: pool.disconnect(opts) 216: 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 221 221: def disconnect_connection(conn) 222: conn.close 223: 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 230 230: def each_server(&block) 231: raise(Error, "Database#each_server must be passed a block") unless block 232: servers.each{|s| self.class.connect(server_opts(s), &block)} 233: 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 245 245: def remove_servers(*servers) 246: if h = @opts[:servers] 247: servers.flatten.each{|s| Sequel.synchronize{h.delete(s)}} 248: @pool.remove_servers(servers) 249: end 250: end
Returns true if the database is using a single-threaded connection pool.
# File lib/sequel/database/connecting.rb, line 261 261: def single_threaded? 262: @single_threaded 263: 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 278 278: def synchronize(server=nil) 279: @pool.hold(server || :default){|conn| yield conn} 280: end
:nocov:
# File lib/sequel/database/connecting.rb, line 283 283: def synchronize(server=nil, &block) 284: @pool.hold(server || :default, &block) 285: 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 293 293: def test_connection(server=nil) 294: synchronize(server){|conn|} 295: true 296: 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 302 302: def valid_connection?(conn) 303: sql = valid_connection_sql 304: begin 305: log_connection_execute(conn, sql) 306: rescue Sequel::DatabaseError, *database_error_classes 307: false 308: else 309: true 310: end 311: end
AUTOINCREMENT | = | 'AUTOINCREMENT'.freeze | ||
COMMA_SEPARATOR | = | ', '.freeze | ||
NOT_NULL | = | ' NOT NULL'.freeze | ||
NULL | = | ' NULL'.freeze | ||
PRIMARY_KEY | = | ' PRIMARY KEY'.freeze | ||
TEMPORARY | = | 'TEMPORARY '.freeze | ||
UNDERSCORE | = | '_'.freeze | ||
UNIQUE | = | ' UNIQUE'.freeze | ||
UNSIGNED | = | ' UNSIGNED'.freeze | ||
COLUMN_DEFINITION_ORDER | = | [:collate, :default, :null, :unique, :primary_key, :auto_increment, :references] | The order of column modifiers to use when defining a column. | |
DEFAULT_JOIN_TABLE_COLUMN_OPTIONS | = | {:null=>false} | The default options for join table columns. | |
COMBINABLE_ALTER_TABLE_OPS | = | [:add_column, :drop_column, :rename_column, :set_column_type, :set_column_default, :set_column_null, :add_constraint, :drop_constraint] | 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 38 38: def add_column(table, *args) 39: alter_table(table) {add_column(*args)} 40: 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 52 52: def add_index(table, columns, options=OPTS) 53: e = options[:ignore_errors] 54: begin 55: alter_table(table){add_index(columns, options)} 56: rescue DatabaseError 57: raise unless e 58: end 59: 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 78 78: def alter_table(name, generator=nil, &block) 79: generator ||= alter_table_generator(&block) 80: remove_cached_schema(name) 81: apply_alter_table_generator(name, generator) 82: nil 83: 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 87 87: def alter_table_generator(&block) 88: alter_table_generator_class.new(self, &block) 89: 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:
: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 123 123: def create_join_table(hash, options=OPTS) 124: keys = hash.keys.sort_by(&:to_s) 125: create_table(join_table_name(hash, options), options) do 126: keys.each do |key| 127: v = hash[key] 128: unless v.is_a?(Hash) 129: v = {:table=>v} 130: end 131: v = DEFAULT_JOIN_TABLE_COLUMN_OPTIONS.merge(v) 132: foreign_key(key, v) 133: end 134: primary_key(keys) unless options[:no_primary_key] 135: index(keys.reverse, options[:index_options] || {}) unless options[:no_index] 136: end 137: 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 140 140: def create_join_table!(hash, options=OPTS) 141: drop_table?(join_table_name(hash, options)) 142: create_join_table(hash, options) 143: end
Creates the join table unless it already exists.
# File lib/sequel/database/schema_methods.rb, line 146 146: def create_join_table?(hash, options=OPTS) 147: if supports_create_table_if_not_exists? && options[:no_index] 148: create_join_table(hash, options.merge(:if_not_exists=>true)) 149: elsif !table_exists?(join_table_name(hash, options)) 150: create_join_table(hash, options) 151: end 152: 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].filter(: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 242 242: def create_or_replace_view(name, source, options = OPTS) 243: if supports_create_or_replace_view? 244: options = options.merge(:replace=>true) 245: else 246: drop_view(name) rescue nil 247: end 248: 249: create_view(name, source, options) 250: 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:
: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::Generator and the "Schema Modification" guide.
# File lib/sequel/database/schema_methods.rb, line 189 189: def create_table(name, options=OPTS, &block) 190: remove_cached_schema(name) 191: options = {:generator=>options} if options.is_a?(Schema::CreateTableGenerator) 192: if sql = options[:as] 193: raise(Error, "can't provide both :as option and block to create_table") if block 194: create_table_as(name, sql, options) 195: else 196: generator = options[:generator] || create_table_generator(&block) 197: create_table_from_generator(name, generator, options) 198: create_table_indexes_from_generator(name, generator, options) 199: nil 200: end 201: 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 209 209: def create_table!(name, options=OPTS, &block) 210: drop_table?(name) 211: create_table(name, options, &block) 212: 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 219 219: def create_table?(name, options=OPTS, &block) 220: options = options.dup 221: generator = options[:generator] ||= create_table_generator(&block) 222: if generator.indexes.empty? && supports_create_table_if_not_exists? 223: create_table(name, options.merge!(:if_not_exists=>true)) 224: elsif !table_exists?(name) 225: create_table(name, options) 226: end 227: 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 231 231: def create_table_generator(&block) 232: create_table_generator_class.new(self, &block) 233: 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 287 287: def create_view(name, source, options = OPTS) 288: execute_ddl(create_view_sql(name, source, options)) 289: remove_cached_schema(name) 290: nil 291: end
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 298 298: def drop_column(table, *args) 299: alter_table(table) {drop_column(*args)} 300: 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 308 308: def drop_index(table, columns, options=OPTS) 309: alter_table(table){drop_index(columns, options)} 310: 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 317 317: def drop_join_table(hash, options=OPTS) 318: drop_table(join_table_name(hash, options), options) 319: 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 326 326: def drop_table(*names) 327: options = names.last.is_a?(Hash) ? names.pop : {} 328: names.each do |n| 329: execute_ddl(drop_table_sql(n, options)) 330: remove_cached_schema(n) 331: end 332: nil 333: 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 341 341: def drop_table?(*names) 342: options = names.last.is_a?(Hash) ? names.pop : {} 343: if supports_drop_table_if_exists? 344: options = options.merge(:if_exists=>true) 345: names.each do |name| 346: drop_table(name, options) 347: end 348: else 349: names.each do |name| 350: drop_table(name, options) if table_exists?(name) 351: end 352: end 353: 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 368 368: def drop_view(*names) 369: options = names.last.is_a?(Hash) ? names.pop : {} 370: names.each do |n| 371: execute_ddl(drop_view_sql(n, options)) 372: remove_cached_schema(n) 373: end 374: nil 375: 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 394 394: def rename_column(table, *args) 395: alter_table(table) {rename_column(*args)} 396: 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 382 382: def rename_table(name, new_name) 383: execute_ddl(rename_table_sql(name, new_name)) 384: remove_cached_schema(name) 385: nil 386: end
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 403 403: def set_column_default(table, *args) 404: alter_table(table) {set_column_default(*args)} 405: 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 412 412: def set_column_type(table, *args) 413: alter_table(table) {set_column_type(*args)} 414: end
Database transactions make multiple queries atomic, so that either all of the queries take effect or none of them do.
SQL_BEGIN | = | 'BEGIN'.freeze |
SQL_COMMIT | = | 'COMMIT'.freeze |
SQL_RELEASE_SAVEPOINT | = | 'RELEASE SAVEPOINT autopoint_%d'.freeze |
SQL_ROLLBACK | = | 'ROLLBACK'.freeze |
SQL_ROLLBACK_TO_SAVEPOINT | = | 'ROLLBACK TO SAVEPOINT autopoint_%d'.freeze |
SQL_SAVEPOINT | = | 'SAVEPOINT autopoint_%d'.freeze |
TRANSACTION_BEGIN | = | 'Transaction.begin'.freeze |
TRANSACTION_COMMIT | = | 'Transaction.commit'.freeze |
TRANSACTION_ROLLBACK | = | 'Transaction.rollback'.freeze |
TRANSACTION_ISOLATION_LEVELS | = | {:uncommitted=>'READ UNCOMMITTED'.freeze, :committed=>'READ COMMITTED'.freeze, :repeatable=>'REPEATABLE READ'.freeze, :serializable=>'SERIALIZABLE'.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 40 40: def after_commit(opts=OPTS, &block) 41: raise Error, "must provide block to after_commit" unless block 42: synchronize(opts[:server]) do |conn| 43: if h = _trans(conn) 44: raise Error, "cannot call after_commit in a prepared transaction" if h[:prepare] 45: add_transaction_hook(conn, :after_commit, block) 46: else 47: yield 48: end 49: end 50: 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 57 57: def after_rollback(opts=OPTS, &block) 58: raise Error, "must provide block to after_rollback" unless block 59: synchronize(opts[:server]) do |conn| 60: if h = _trans(conn) 61: raise Error, "cannot call after_rollback in a prepared transaction" if h[:prepare] 62: add_transaction_hook(conn, :after_rollback, block) 63: end 64: end 65: 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 70 70: def in_transaction?(opts=OPTS) 71: synchronize(opts[:server]){|conn| !!_trans(conn)} 72: 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 80 80: def rollback_checker(opts=OPTS) 81: synchronize(opts[:server]) do |conn| 82: raise Error, "not in a transaction" unless t = _trans(conn) 83: t[:rollback_checker] ||= proc{t[:rolled_back]} 84: end 85: 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 transacation. |
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 134 134: def transaction(opts=OPTS, &block) 135: opts = Hash[opts] 136: if retry_on = opts[:retry_on] 137: tot_retries = opts.fetch(:num_retries, 5) 138: num_retries = 0 unless tot_retries.nil? 139: begin 140: opts[:retry_on] = nil 141: opts[:retrying] = true 142: transaction(opts, &block) 143: rescue *retry_on => e 144: if num_retries 145: num_retries += 1 146: if num_retries <= tot_retries 147: opts[:before_retry].call(num_retries, e) if opts[:before_retry] 148: retry 149: end 150: else 151: retry 152: end 153: raise 154: end 155: else 156: synchronize(opts[:server]) do |conn| 157: if opts[:savepoint] == :only 158: if supports_savepoints? 159: if _trans(conn) 160: opts[:savepoint] = true 161: else 162: return yield(conn) 163: end 164: else 165: opts[:savepoint] = false 166: end 167: end 168: 169: if already_in_transaction?(conn, opts) 170: if opts[:rollback] == :always && !opts.has_key?(:savepoint) 171: if supports_savepoints? 172: opts[:savepoint] = true 173: else 174: raise Sequel::Error, "cannot set :rollback=>:always transaction option if already inside a transaction" 175: end 176: end 177: 178: if opts[:savepoint] != false && (stack = _trans(conn)[:savepoints]) && stack.last 179: opts[:savepoint] = true 180: end 181: 182: unless opts[:savepoint] 183: if opts[:retrying] 184: raise Sequel::Error, "cannot set :retry_on options if you are already inside a transaction" 185: end 186: return yield(conn) 187: end 188: end 189: 190: _transaction(conn, opts, &block) 191: end 192: end 193: 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 43 43: def log_connection_yield(sql, conn, args=nil) 44: return yield if @loggers.empty? 45: sql = "#{connection_info(conn) if conn && log_connection_info}#{sql}#{"; #{args.inspect}" if args}" 46: start = Time.now 47: begin 48: yield 49: rescue => e 50: log_exception(e, sql) 51: raise 52: ensure 53: log_duration(Time.now - start, sql) unless e 54: end 55: 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
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_yield(sql, args=nil, &block) 38: log_connection_yield(sql, nil, args, &block) 39: 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 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, default is the same as supports_create_table_if_not_exists?.
# 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).
# File lib/sequel/database/features.rb, line 53 53: def supports_partial_indexes? 54: false 55: end
Whether the database and adapter support prepared transactions (two-phase commit), false by default.
# File lib/sequel/database/features.rb, line 59 59: def supports_prepared_transactions? 60: false 61: end
Whether the database and adapter support savepoints, false by default.
# File lib/sequel/database/features.rb, line 64 64: def supports_savepoints? 65: false 66: 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 70: def supports_savepoints_in_prepared_transactions? 71: supports_prepared_transactions? && supports_savepoints? 72: end
Whether the database supports schema parsing via Database#schema.
# File lib/sequel/database/features.rb, line 75 75: def supports_schema_parsing? 76: respond_to?(:schema_parse_table, true) 77: end
Whether the database supports Database#tables for getting list of tables.
# File lib/sequel/database/features.rb, line 80 80: def supports_table_listing? 81: respond_to?(:tables) 82: end
Whether the database and adapter support transaction isolation levels, false by default.
# File lib/sequel/database/features.rb, line 90 90: def supports_transaction_isolation_levels? 91: false 92: end
Whether DDL statements work correctly in transactions, false by default.
# File lib/sequel/database/features.rb, line 95 95: def supports_transactional_ddl? 96: false 97: end
Whether the database supports Database#views for getting list of views.
# File lib/sequel/database/features.rb, line 85 85: def supports_view_listing? 86: respond_to?(:views) 87: end
Whether CREATE VIEW … WITH CHECK OPTION is supported, false by default.
# File lib/sequel/database/features.rb, line 100 100: def supports_views_with_check_option? 101: !!view_with_check_option_support 102: 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
# File lib/sequel/database/dataset.rb, line 46 46: def fetch(sql, *args, &block) 47: ds = @default_dataset.with_sql(sql, *args) 48: ds.each(&block) if block 49: ds 50: 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 57 57: def from(*args, &block) 58: ds = @default_dataset.from(*args) 59: block ? ds.filter(&block) : ds 60: 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 67 67: def select(*args, &block) 68: @default_dataset.select(*args, &block) 69: end
These methods don‘t fit neatly into another category.
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) | ||
LEADING_ZERO_RE | = | /\A0+(\d)/.freeze | Used for checking/removing leading zeroes from strings so they don‘t get interpreted as octal. | |
LEADING_ZERO_REP | = | "\\1".freeze | :nocov: Replacement string when replacing leading zeroes. | |
AFFECTED_ROWS_RE | = | /Rows matched:\s+(\d+)\s+Changed:\s+\d+\s+Warnings:\s+\d+/.freeze | Regular expression used for getting accurate number of rows matched by an update statement. | |
DEFAULT_CONFIG | = | { :user => 'dba', :password => 'sql' } | ||
LAST_INSERT_ID | = | 'SELECT @@IDENTITY'.freeze | ||
OPTS | = | Sequel::OPTS |
api | [RW] | |
conversion_procs | [R] | Hash of conversion procs for the current database |
conversion_procs | [R] | The conversion procs to use for this 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 |
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 |
swift_class | [RW] | The Swift adapter class being used by this database. Connections in this database‘s connection pool will be instances of this class. |
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 42 42: def self.after_initialize(&block) 43: raise Error, "must provide block to after_initialize" unless block 44: Sequel.synchronize do 45: previous = @initialize_hook 46: @initialize_hook = Proc.new do |db| 47: previous.call(db) 48: block.call(db) 49: end 50: end 51: end
# File lib/sequel/adapters/swift.rb, line 39 39: def initialize(opts=OPTS) 40: Sequel.require "adapters/swift/#{opts[:db_type]}" if %w'postgres mysql sqlite'.include?(opts[:db_type].to_s) 41: super 42: end
Constructs a new instance of a database connection with the specified options hash.
Accepts the following options:
:default_string_column_size : | The default size of string columns, 255 by default. |
:identifier_input_method : | A string method symbol to call on identifiers going into the database. |
:identifier_output_method : | A string method symbol to call on identifiers coming from the database. |
:logger : | A specific logger to use. |
:loggers : | An array of loggers to use. |
:name : | A name to use for the Database object. |
:preconnect : | Whether to automatically connect to the maximum number of servers. |
: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 119 119: def initialize(opts = OPTS) 120: @opts ||= opts 121: @opts = connection_pool_default_options.merge(@opts) 122: @loggers = Array(@opts[:logger]) + Array(@opts[:loggers]) 123: @opts[:servers] = {} if @opts[:servers].is_a?(String) 124: @sharded = !!@opts[:servers] 125: @opts[:adapter_class] = self.class 126: @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, Database.single_threaded)) 127: @default_string_column_size = @opts[:default_string_column_size] || DEFAULT_STRING_COLUMN_SIZE 128: 129: @schemas = {} 130: @prepared_statements = {} 131: @transactions = {} 132: @symbol_literal_cache = {} 133: 134: @identifier_input_method = nil 135: @identifier_output_method = nil 136: @quote_identifiers = nil 137: @timezone = nil 138: 139: @dataset_class = dataset_class_default 140: @cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true)) 141: @dataset_modules = [] 142: @schema_type_classes = SCHEMA_TYPE_CLASSES.dup 143: 144: self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info 145: self.log_warn_duration = @opts[:log_warn_duration] 146: self.log_connection_info = typecast_value_boolean(@opts[:log_connection_info]) 147: 148: @pool = ConnectionPool.get_pool(self, @opts) 149: 150: reset_identifier_mangling 151: adapter_initialize 152: 153: unless typecast_value_boolean(@opts[:keep_reference]) == false 154: Sequel.synchronize{::Sequel::DATABASES.push(self)} 155: end 156: Sequel::Database.run_after_initialize(self) 157: if typecast_value_boolean(@opts[:preconnect]) && @pool.respond_to?(:preconnect, true) 158: concurrent = typecast_value_string(@opts[:preconnect]) == "concurrently" 159: @pool.send(:preconnect, concurrent) 160: end 161: 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 63 63: def self.register_extension(ext, mod=nil, &block) 64: if mod 65: raise(Error, "cannot provide both mod and block to Database.register_extension") if block 66: if mod.is_a?(Module) 67: block = proc{|db| db.extend(mod)} 68: else 69: block = mod 70: end 71: end 72: Sequel.synchronize{EXTENSIONS[ext] = block} 73: end
Run the after_initialize hook for the given instance.
# File lib/sequel/database/misc.rb, line 76 76: def self.run_after_initialize(instance) 77: @initialize_hook.call(instance) 78: end
# File lib/sequel/adapters/sqlanywhere.rb, line 51 51: def connect(server) 52: opts = server_opts(server) 53: unless conn_string = opts[:conn_string] 54: conn_string = [] 55: conn_string << "Host=#{opts[:host]}#{":#{opts[:port]}" if opts[:port]}" if opts[:host] 56: conn_string << "DBN=#{opts[:database]}" if opts[:database] 57: conn_string << "UID=#{opts[:user]}" if opts[:user] 58: conn_string << "Password=#{opts[:password]}" if opts[:password] 59: conn_string << "CommLinks=#{opts[:commlinks]}" if opts[:commlinks] 60: conn_string << "ConnectionName=#{opts[:connection_name]}" if opts[:connection_name] 61: conn_string << "CharSet=#{opts[:encoding]}" if opts[:encoding] 62: conn_string << "Idle=0" # Prevent the server from disconnecting us if we're idle for >240mins (by default) 63: conn_string << nil 64: conn_string = conn_string.join(';') 65: end 66: 67: conn = @api.sqlany_new_connection 68: raise LoadError, "Could not connect" unless conn && @api.sqlany_connect(conn, conn_string) == 1 69: 70: if Sequel.application_timezone == :utc 71: @api.sqlany_execute_immediate(conn, "SET TEMPORARY OPTION time_zone_adjustment=0") 72: end 73: 74: conn 75: end
Connect to the database. Since SQLite is a file based database, available options are limited:
:database : | database name (filename or ’:memory:’ or file: URI) |
:readonly : | open database in read-only mode; useful for reading static data that you do not want to modify |
:timeout : | how long to wait for the database to be available if it is locked, given in milliseconds (default is 5000) |
# File lib/sequel/adapters/sqlite.rb, line 104 104: def connect(server) 105: opts = server_opts(server) 106: opts[:database] = ':memory:' if blank_object?(opts[:database]) 107: sqlite3_opts = {} 108: sqlite3_opts[:readonly] = typecast_value_boolean(opts[:readonly]) if opts.has_key?(:readonly) 109: db = ::SQLite3::Database.new(opts[:database].to_s, sqlite3_opts) 110: db.busy_timeout(opts.fetch(:timeout, 5000)) 111: 112: connection_pragmas.each{|s| log_connection_yield(s, db){db.execute_batch(s)}} 113: 114: class << db 115: attr_reader :prepared_statements 116: end 117: db.instance_variable_set(:@prepared_statements, {}) 118: 119: db 120: 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 86 86: def connect(server) 87: opts = server_opts(server) 88: conn = Mysql.init 89: conn.options(Mysql::READ_DEFAULT_GROUP, opts[:config_default_group] || "client") 90: conn.options(Mysql::OPT_LOCAL_INFILE, opts[:config_local_infile]) if opts.has_key?(:config_local_infile) 91: conn.ssl_set(opts[:sslkey], opts[:sslcert], opts[:sslca], opts[:sslcapath], opts[:sslcipher]) if opts[:sslca] || opts[:sslkey] 92: if encoding = opts[:encoding] || opts[:charset] 93: # Set encoding before connecting so that the mysql driver knows what 94: # encoding we want to use, but this can be overridden by READ_DEFAULT_GROUP. 95: conn.options(Mysql::SET_CHARSET_NAME, encoding) 96: end 97: if read_timeout = opts[:read_timeout] and defined? Mysql::OPT_READ_TIMEOUT 98: conn.options(Mysql::OPT_READ_TIMEOUT, read_timeout) 99: end 100: if connect_timeout = opts[:connect_timeout] and defined? Mysql::OPT_CONNECT_TIMEOUT 101: conn.options(Mysql::OPT_CONNECT_TIMEOUT, connect_timeout) 102: end 103: conn.real_connect( 104: opts[:host] || 'localhost', 105: opts[:user], 106: opts[:password], 107: opts[:database], 108: (opts[:port].to_i if opts[:port]), 109: opts[:socket], 110: Mysql::CLIENT_MULTI_RESULTS + 111: Mysql::CLIENT_MULTI_STATEMENTS + 112: (opts[:compress] == false ? 0 : Mysql::CLIENT_COMPRESS) 113: ) 114: sqls = mysql_connection_setting_sqls 115: 116: # Set encoding a slightly different way after connecting, 117: # in case the READ_DEFAULT_GROUP overrode the provided encoding. 118: # Doesn't work across implicit reconnects, but Sequel doesn't turn on 119: # that feature. 120: sqls.unshift("SET NAMES #{literal(encoding.to_s)}") if encoding 121: 122: sqls.each{|sql| log_connection_yield(sql, conn){conn.query(sql)}} 123: 124: add_prepared_statements_cache(conn) 125: conn 126: 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) |
: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 39 39: def connect(server) 40: opts = server_opts(server) 41: opts[:host] ||= 'localhost' 42: opts[:username] ||= opts.delete(:user) 43: opts[:flags] ||= 0 44: opts[:flags] |= ::Mysql2::Client::FOUND_ROWS if ::Mysql2::Client.const_defined?(:FOUND_ROWS) 45: opts[:encoding] ||= opts[:charset] 46: conn = ::Mysql2::Client.new(opts) 47: conn.query_options.merge!(:symbolize_keys=>true, :cache_rows=>false) 48: 49: if NativePreparedStatements 50: @default_query_options ||= conn.query_options.dup 51: end 52: 53: sqls = mysql_connection_setting_sqls 54: 55: # Set encoding a slightly different way after connecting, 56: # in case the READ_DEFAULT_GROUP overrode the provided encoding. 57: # Doesn't work across implicit reconnects, but Sequel doesn't turn on 58: # that feature. 59: if encoding = opts[:encoding] 60: sqls.unshift("SET NAMES #{conn.escape(encoding.to_s)}") 61: end 62: 63: sqls.each{|sql| log_connection_yield(sql, conn){conn.query(sql)}} 64: 65: add_prepared_statements_cache(conn) 66: conn 67: end
Create an instance of swift_class for the given options.
# File lib/sequel/adapters/swift.rb, line 45 45: def connect(server) 46: opts = server_opts(server) 47: opts[:pass] = opts[:password] 48: setup_connection(swift_class.new(opts)) 49: end
Modify the type translators for the date, time, and timestamp types depending on the value given.
# File lib/sequel/adapters/mysql.rb, line 137 137: def convert_invalid_date_time=(v) 138: m0 = ::Sequel.method(:string_to_time) 139: @conversion_procs[11] = (v != false) ? lambda{|val| convert_date_time(val, &m0)} : m0 140: m1 = ::Sequel.method(:string_to_date) 141: m = (v != false) ? lambda{|val| convert_date_time(val, &m1)} : m1 142: [10, 14].each{|i| @conversion_procs[i] = m} 143: m2 = method(:to_application_timestamp) 144: m = (v != false) ? lambda{|val| convert_date_time(val, &m2)} : m2 145: [7, 12].each{|i| @conversion_procs[i] = m} 146: @convert_invalid_date_time = v 147: end
Modify the type translator used for the tinyint type based on the value given.
# File lib/sequel/adapters/mysql.rb, line 151 151: def convert_tinyint_to_bool=(v) 152: @conversion_procs[1] = TYPE_TRANSLATOR.method(v ? :boolean : :integer) 153: @convert_tinyint_to_bool = v 154: end
Closes given database connection.
# File lib/sequel/adapters/sqlanywhere.rb, line 78 78: def disconnect_connection(c) 79: @api.sqlany_disconnect(c) 80: end
Closes given database connection.
# File lib/sequel/adapters/mysql.rb, line 129 129: def disconnect_connection(c) 130: c.close 131: rescue Mysql::Error 132: nil 133: end
Execute the given SQL, yielding a Swift::Result if a block is given.
# File lib/sequel/adapters/swift.rb, line 52 52: def execute(sql, opts=OPTS) 53: synchronize(opts[:server]) do |conn| 54: begin 55: res = log_connection_yield(sql, conn){conn.execute(sql)} 56: yield res if block_given? 57: nil 58: rescue ::Swift::Error => e 59: raise_error(e) 60: end 61: end 62: end
# File lib/sequel/adapters/sqlanywhere.rb, line 89 89: def execute(sql, opts=OPTS, &block) 90: synchronize(opts[:server]) do |conn| 91: _execute(conn, :select, sql, opts, &block) 92: end 93: end
Drop any prepared statements on the connection when executing DDL. This is because prepared statements lock the table in such a way that you can‘t drop or alter the table while a prepared statement that references it still exists.
# File lib/sequel/adapters/sqlite.rb, line 141 141: def execute_ddl(sql, opts=OPTS) 142: synchronize(opts[:server]) do |conn| 143: conn.prepared_statements.values.each{|cps, s| cps.close} 144: conn.prepared_statements.clear 145: super 146: end 147: end
Returns number of rows affected
# File lib/sequel/adapters/sqlanywhere.rb, line 83 83: def execute_dui(sql, opts=OPTS) 84: synchronize(opts[:server]) do |conn| 85: _execute(conn, :rows, sql, opts) 86: end 87: end
Return the number of matched rows when executing a delete/update statement.
# File lib/sequel/adapters/mysql2.rb, line 70 70: def execute_dui(sql, opts=OPTS) 71: execute(sql, opts){|c| return c.affected_rows} 72: end
Execute the SQL on the this database, returning the number of affected rows.
# File lib/sequel/adapters/swift.rb, line 66 66: def execute_dui(sql, opts=OPTS) 67: synchronize(opts[:server]) do |conn| 68: begin 69: log_connection_yield(sql, conn){conn.execute(sql).affected_rows} 70: rescue ::Swift::Error => e 71: raise_error(e) 72: end 73: end 74: end
Return the number of matched rows when executing a delete/update statement.
# File lib/sequel/adapters/mysql.rb, line 157 157: def execute_dui(sql, opts=OPTS) 158: execute(sql, opts){|c| return affected_rows(c)} 159: end
Execute the SQL on this database, returning the primary key of the table being inserted to.
# File lib/sequel/adapters/swift.rb, line 78 78: def execute_insert(sql, opts=OPTS) 79: synchronize(opts[:server]) do |conn| 80: begin 81: log_connection_yield(sql, conn){conn.execute(sql).insert_id} 82: rescue ::Swift::Error => e 83: raise_error(e) 84: end 85: end 86: end
# File lib/sequel/adapters/sqlanywhere.rb, line 95 95: def execute_insert(sql, opts=OPTS) 96: synchronize(opts[:server]) do |conn| 97: _execute(conn, :insert, sql, opts) 98: end 99: end
Return the last inserted id when executing an insert statement.
# File lib/sequel/adapters/mysql.rb, line 162 162: def execute_insert(sql, opts=OPTS) 163: execute(sql, opts){|c| return c.insert_id} 164: end
Return the last inserted id when executing an insert statement.
# File lib/sequel/adapters/mysql2.rb, line 75 75: def execute_insert(sql, opts=OPTS) 76: execute(sql, opts){|c| return c.last_id} 77: 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 176 176: def extension(*exts) 177: Sequel.extension(*exts) 178: exts.each do |ext| 179: if pr = Sequel.synchronize{EXTENSIONS[ext]} 180: pr.call(self) 181: else 182: raise(Error, "Extension #{ext} does not have specific support handling individual databases (try: Sequel.extension #{ext.inspect})") 183: end 184: end 185: self 186: 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 191 191: def from_application_timestamp(v) 192: Sequel.convert_output_timestamp(v, timezone) 193: 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 197 197: def inspect 198: a = [] 199: a << uri.inspect if uri 200: if (oo = opts[:orig_opts]) && !oo.empty? 201: a << oo.inspect 202: end 203: "#<#{self.class}: #{a.join(' ')}>" 204: end
Return the literalized version of the symbol if cached, or nil if it is not cached.
# File lib/sequel/database/misc.rb, line 217 217: def literal_symbol(sym) 218: Sequel.synchronize{@symbol_literal_cache[sym]} 219: end
Synchronize access to the prepared statements cache.
# File lib/sequel/database/misc.rb, line 227 227: def prepared_statement(name) 228: Sequel.synchronize{prepared_statements[name]} 229: 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 234 234: def quote_identifier(v) 235: schema_utility_dataset.quote_identifier(v) 236: end
Return ruby class or array of classes for the given type symbol.
# File lib/sequel/database/misc.rb, line 239 239: def schema_type_class(type) 240: @schema_type_classes[type] 241: end
Default serial primary key options, used by the table creation code.
# File lib/sequel/database/misc.rb, line 245 245: def serial_primary_key_options 246: {:primary_key => true, :type => Integer, :auto_increment => true} 247: end
Cache the prepared statement object at the given name.
# File lib/sequel/database/misc.rb, line 250 250: def set_prepared_statement(name, ps) 251: ps.prepared_sql 252: Sequel.synchronize{prepared_statements[name] = ps} 253: end
Handle Integer and Float arguments, since SQLite can store timestamps as integers and floats.
# File lib/sequel/adapters/sqlite.rb, line 155 155: def to_application_timestamp(s) 156: case s 157: when String 158: super 159: when Integer 160: super(Time.at(s).to_s) 161: when Float 162: super(DateTime.jd(s).to_s) 163: else 164: raise Sequel::Error, "unhandled type when converting to : #{s.inspect} (#{s.class.inspect})" 165: end 166: 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 278 278: def typecast_value(column_type, value) 279: return nil if value.nil? 280: meth = "typecast_value_#{column_type}" 281: begin 282: respond_to?(meth, true) ? send(meth, value) : value 283: rescue ArgumentError, TypeError => e 284: raise Sequel.convert_exception_class(e, InvalidValue) 285: end 286: end
This methods generally execute SQL code on the database server.