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.
ADAPTERS | = | %w'ado amalgalite db2 dbi do firebird ibmdb informix jdbc mock mysql mysql2 odbc openbase oracle postgres sqlite swift tinytds'.collect{|x| x.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 17 17: def self.adapter_class(scheme) 18: return scheme if scheme.is_a?(Class) 19: 20: scheme = scheme.to_s.gsub('-', '_').to_sym 21: 22: unless klass = ADAPTER_MAP[scheme] 23: # attempt to load the adapter file 24: begin 25: Sequel.tsk_require "sequel/adapters/#{scheme}" 26: rescue LoadError => e 27: raise Sequel.convert_exception_class(e, AdapterNotFound) 28: end 29: 30: # make sure we actually loaded the adapter 31: unless klass = ADAPTER_MAP[scheme] 32: raise AdapterNotFound, "Could not load #{scheme} adapter: adapter class not registered in ADAPTER_MAP" 33: end 34: end 35: klass 36: end
Connects to a database. See Sequel.connect.
# File lib/sequel/database/connecting.rb, line 44 44: def self.connect(conn_string, opts = {}) 45: case conn_string 46: when String 47: if match = /\A(jdbc|do):/o.match(conn_string) 48: c = adapter_class(match[1].to_sym) 49: opts = {:uri=>conn_string}.merge(opts) 50: else 51: uri = URI.parse(conn_string) 52: scheme = uri.scheme 53: scheme = :dbi if scheme =~ /\Adbi-/ 54: c = adapter_class(scheme) 55: uri_options = c.send(:uri_to_options, uri) 56: 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? 57: uri_options.to_a.each{|k,v| uri_options[k] = URI.unescape(v) if v.is_a?(String)} 58: opts = uri_options.merge(opts) 59: opts[:adapter] = scheme 60: end 61: when Hash 62: opts = conn_string.merge(opts) 63: c = adapter_class(opts[:adapter_class] || opts[:adapter] || opts['adapter']) 64: else 65: raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" 66: end 67: # process opts a bit 68: opts = opts.inject({}) do |m, (k,v)| 69: k = :user if k.to_s == 'username' 70: m[k.to_sym] = v 71: m 72: end 73: begin 74: db = c.new(opts) 75: db.test_connection if opts[:test] && db.send(:typecast_value_boolean, opts[:test]) 76: result = yield(db) if block_given? 77: ensure 78: if block_given? 79: db.disconnect if db 80: ::Sequel::DATABASES.delete(db) 81: end 82: end 83: block_given? ? result : db 84: 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 120 120: def adapter_scheme 121: self.class.adapter_scheme 122: 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 133 133: def add_servers(servers) 134: @opts[:servers] = @opts[:servers] ? @opts[:servers].merge(servers) : servers 135: @pool.add_servers(servers.keys) 136: end
Connects to the database. This method should be overridden by descendants.
# File lib/sequel/database/connecting.rb, line 139 139: def connect(server) 140: raise NotImplemented, "#connect should be overridden by adapters" 141: 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 152 152: def database_type 153: adapter_scheme 154: 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 166 166: def disconnect(opts = {}) 167: pool.disconnect(opts) 168: 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 175 175: def each_server(&block) 176: servers.each{|s| self.class.connect(server_opts(s), &block)} 177: 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 189 189: def remove_servers(*servers) 190: if @opts[:servers] && !@opts[:servers].empty? 191: servs = @opts[:servers].dup 192: servers.flatten! 193: servers.each{|s| servs.delete(s)} 194: @opts[:servers] = servs 195: @pool.remove_servers(servers) 196: end 197: end
Returns true if the database is using a single-threaded connection pool.
# File lib/sequel/database/connecting.rb, line 208 208: def single_threaded? 209: @single_threaded 210: 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 224 224: def synchronize(server=nil, &block) 225: @pool.hold(server || :default, &block) 226: 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 232 232: def test_connection(server=nil) 233: synchronize(server){|conn|} 234: true 235: end
AUTOINCREMENT | = | 'AUTOINCREMENT'.freeze | ||
CASCADE | = | 'CASCADE'.freeze | ||
COMMA_SEPARATOR | = | ', '.freeze | ||
NO_ACTION | = | 'NO ACTION'.freeze | ||
NOT_NULL | = | ' NOT NULL'.freeze | ||
NULL | = | ' NULL'.freeze | ||
PRIMARY_KEY | = | ' PRIMARY KEY'.freeze | ||
RESTRICT | = | 'RESTRICT'.freeze | ||
SET_DEFAULT | = | 'SET DEFAULT'.freeze | ||
SET_NULL | = | 'SET NULL'.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. |
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 33 33: def add_column(table, *args) 34: alter_table(table) {add_column(*args)} 35: 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 |
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 46 46: def add_index(table, columns, options={}) 47: e = options[:ignore_errors] 48: begin 49: alter_table(table){add_index(columns, options)} 50: rescue DatabaseError 51: raise unless e 52: end 53: 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 72 72: def alter_table(name, generator=nil, &block) 73: generator ||= Schema::AlterTableGenerator.new(self, &block) 74: remove_cached_schema(name) 75: apply_alter_table(name, generator.operations) 76: nil 77: end
Creates a view, replacing it if it already exists:
DB.create_or_replace_view(:cheap_items, "SELECT * FROM items WHERE price < 100") DB.create_or_replace_view(:ruby_items, DB[:items].filter(:category => 'ruby'))
# File lib/sequel/database/schema_methods.rb, line 130 130: def create_or_replace_view(name, source) 131: source = source.sql if source.is_a?(Dataset) 132: execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}") 133: remove_cached_schema(name) 134: nil 135: 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
Options:
:temp : | Create the table as a temporary table. |
:ignore_index_errors : | Ignore any errors when creating indexes. |
See Schema::Generator and the "Migrations and Schema Modification" guide.
# File lib/sequel/database/schema_methods.rb, line 93 93: def create_table(name, options={}, &block) 94: remove_cached_schema(name) 95: options = {:generator=>options} if options.is_a?(Schema::Generator) 96: generator = options[:generator] || Schema::Generator.new(self, &block) 97: create_table_from_generator(name, generator, options) 98: create_table_indexes_from_generator(name, generator, options) 99: nil 100: end
Forcibly create a table, attempting to drop it if it already exists, then creating it.
DB.create_table!(:a){Integer :a} # SELECT * FROM a LIMIT a -- check existence # DROP TABLE a -- drop table if already exists # CREATE TABLE a (a integer)
# File lib/sequel/database/schema_methods.rb, line 108 108: def create_table!(name, options={}, &block) 109: drop_table(name) if table_exists?(name) 110: create_table(name, options, &block) 111: end
Creates the table unless the table already exists.
DB.create_table?(:a){Integer :a} # SELECT * FROM a LIMIT a -- check existence # CREATE TABLE a (a integer) -- if it doesn't already exist
# File lib/sequel/database/schema_methods.rb, line 118 118: def create_table?(name, options={}, &block) 119: if supports_create_table_if_not_exists? 120: create_table(name, options.merge(:if_not_exists=>true), &block) 121: elsif !table_exists?(name) 122: create_table(name, options, &block) 123: end 124: end
Creates a view based on a dataset or an SQL string:
DB.create_view(:cheap_items, "SELECT * FROM items WHERE price < 100") DB.create_view(:ruby_items, DB[:items].filter(:category => 'ruby'))
# File lib/sequel/database/schema_methods.rb, line 141 141: def create_view(name, source) 142: source = source.sql if source.is_a?(Dataset) 143: execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}") 144: end
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 151 151: def drop_column(table, *args) 152: alter_table(table) {drop_column(*args)} 153: 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 161 161: def drop_index(table, columns, options={}) 162: alter_table(table){drop_index(columns, options)} 163: end
Drops one or more tables corresponding to the given names:
DB.drop_table(:posts) DB.drop_table(:posts, :comments) DB.drop_table(:posts, :comments, :cascade=>true)
# File lib/sequel/database/schema_methods.rb, line 170 170: def drop_table(*names) 171: options = names.last.is_a?(Hash) ? names.pop : {} 172: names.each do |n| 173: execute_ddl(drop_table_sql(n, options)) 174: remove_cached_schema(n) 175: end 176: nil 177: 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)
# File lib/sequel/database/schema_methods.rb, line 184 184: def drop_view(*names) 185: options = names.last.is_a?(Hash) ? names.pop : {} 186: names.each do |n| 187: execute_ddl(drop_view_sql(n, options)) 188: remove_cached_schema(n) 189: end 190: nil 191: 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 210 210: def rename_column(table, *args) 211: alter_table(table) {rename_column(*args)} 212: 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 198 198: def rename_table(name, new_name) 199: execute_ddl(rename_table_sql(name, new_name)) 200: remove_cached_schema(name) 201: nil 202: 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 219 219: def set_column_default(table, *args) 220: alter_table(table) {set_column_default(*args)} 221: 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 228 228: def set_column_type(table, *args) 229: alter_table(table) {set_column_type(*args)} 230: end
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} |
POSTGRES_DEFAULT_RE | = | /\A(?:B?('.*')::[^']+|\((-?\d+(?:\.\d+)?)\))\z/ |
MSSQL_DEFAULT_RE | = | /\A(?:\(N?('.*')\)|\(\((-?\d+(?:\.\d+)?)\)\))\z/ |
MYSQL_TIMESTAMP_RE | = | /\ACURRENT_(?:DATE|TIMESTAMP)?\z/ |
STRING_DEFAULT_RE | = | /\A'(.*)'\z/ |
prepared_statements | [R] | The prepared statement object hash for this database, keyed by name symbol |
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. |
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 53 53: def call(ps_name, hash={}) 54: prepared_statements[ps_name].call(hash) 55: end
Executes the given SQL on the database. This method should be overridden in descendants. This method should not be called directly by user code.
# File lib/sequel/database/query.rb, line 59 59: def execute(sql, opts={}) 60: raise NotImplemented, "#execute should be overridden by adapters" 61: 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 66 66: def execute_ddl(sql, opts={}, &block) 67: execute_dui(sql, opts, &block) 68: 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 80 80: def execute_insert(sql, opts={}, &block) 81: execute_dui(sql, opts, &block) 82: end
Return a hash containing index information for the table. Hash keys are index name symbols. Values are subhashes with two keys, :columns and :unique. The value of :columns is an array of symbols of column names. The value of :unique is true or false depending on if the index is unique.
Should not include the primary key index, functional indexes, or partial indexes.
DB.indexes(:artists) # => {:artists_name_ukey=>{:columns=>[:name], :unique=>true}}
# File lib/sequel/database/query.rb, line 102 102: def indexes(table, opts={}) 103: raise NotImplemented, "#indexes should be overridden by adapters" 104: 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 should hash at least contain 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. |
: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 156 156: def schema(table, opts={}) 157: raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true) 158: 159: opts = opts.dup 160: if table.is_a?(Dataset) 161: o = table.opts 162: from = o[:from] 163: 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) 164: tab = table.first_source_table 165: sch, table_name = schema_and_table(tab) 166: quoted_name = table.literal(tab) 167: opts[:dataset] = table 168: else 169: sch, table_name = schema_and_table(table) 170: quoted_name = quote_schema_table(table) 171: end 172: opts[:schema] = sch if sch && !opts.include?(:schema) 173: 174: @schemas.delete(quoted_name) if opts[:reload] 175: return @schemas[quoted_name] if @schemas[quoted_name] 176: 177: cols = schema_parse_table(table_name, opts) 178: raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty? 179: cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} 180: @schemas[quoted_name] = cols 181: end
Returns true if a table with the given name exists. This requires a query to the database.
DB.table_exists?(:foo) # => false # SELECT * FROM foo LIMIT 1
# File lib/sequel/database/query.rb, line 188 188: def table_exists?(name) 189: sch, table_name = schema_and_table(name) 190: name = SQL::QualifiedIdentifier.new(sch, table_name) if sch 191: from(name).first 192: true 193: rescue 194: false 195: 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 tabels do not support transactions.
The following options are respected:
: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. |
:prepare : | A string to use as the transaction identifier for a prepared transaction (two-phase commit), if the database/adapter supports prepared transactions. |
: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. |
: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. |
# File lib/sequel/database/query.rb, line 225 225: def transaction(opts={}, &block) 226: synchronize(opts[:server]) do |conn| 227: return yield(conn) if already_in_transaction?(conn, opts) 228: _transaction(conn, opts, &block) 229: end 230: 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 19 19: def [](*args) 20: (String === args.first) ? fetch(*args) : from(*args) 21: 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 44 44: def fetch(sql, *args, &block) 45: ds = dataset.with_sql(sql, *args) 46: ds.each(&block) if block 47: ds 48: 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 55 55: def from(*args, &block) 56: ds = dataset.from(*args) 57: block ? ds.filter(&block) : ds 58: 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 65 65: def select(*args, &block) 66: dataset.select(*args, &block) 67: end
These methods don‘t fit neatly into another category.
opts | [R] | The options hash for this database |
timezone | [W] | Set the timezone to use for this database, overridding Sequel.database_timezone. |
Constructs a new instance of a database connection with the specified options hash.
Accepts the following options:
:default_schema : | The default schema to use, should generally be nil |
:disconnection_proc : | A proc used to disconnect the connection |
: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 |
: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. If a block is given, it is used as the connection_proc for the ConnectionPool.
# File lib/sequel/database/misc.rb, line 42 42: def initialize(opts = {}, &block) 43: @opts ||= opts 44: @opts = connection_pool_default_options.merge(@opts) 45: @loggers = Array(@opts[:logger]) + Array(@opts[:loggers]) 46: self.log_warn_duration = @opts[:log_warn_duration] 47: @opts[:disconnection_proc] ||= proc{|conn| disconnect_connection(conn)} 48: block ||= proc{|server| connect(server)} 49: @opts[:servers] = {} if @opts[:servers].is_a?(String) 50: @opts[:adapter_class] = self.class 51: 52: @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, @@single_threaded)) 53: @schemas = {} 54: @default_schema = @opts.fetch(:default_schema, default_schema_default) 55: @prepared_statements = {} 56: @transactions = {} 57: @identifier_input_method = nil 58: @identifier_output_method = nil 59: @quote_identifiers = nil 60: @timezone = nil 61: @dataset_class = dataset_class_default 62: @dataset_modules = [] 63: self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info 64: @pool = ConnectionPool.get_pool(@opts, &block) 65: 66: ::Sequel::DATABASES.push(self) 67: end
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/misc.rb, line 74 74: def after_commit(opts={}, &block) 75: raise Error, "must provide block to after_commit" unless block 76: synchronize(opts[:server]) do |conn| 77: if h = @transactions[conn] 78: raise Error, "cannot call after_commit in a prepared transaction" if h[:prepare] 79: (h[:after_commit] ||= []) << block 80: else 81: yield 82: end 83: end 84: 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/misc.rb, line 91 91: def after_rollback(opts={}, &block) 92: raise Error, "must provide block to after_rollback" unless block 93: synchronize(opts[:server]) do |conn| 94: if h = @transactions[conn] 95: raise Error, "cannot call after_rollback in a prepared transaction" if h[:prepare] 96: (h[:after_rollback] ||= []) << block 97: end 98: end 99: 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 112 112: def from_application_timestamp(v) 113: Sequel.convert_output_timestamp(v, timezone) 114: 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/misc.rb, line 119 119: def in_transaction?(opts={}) 120: synchronize(opts[:server]){|conn| !!@transactions[conn]} 121: end
Returns a string representation of the database object including the class name and the connection URI (or the opts if the URI cannot be constructed).
# File lib/sequel/database/misc.rb, line 126 126: def inspect 127: "#<#{self.class}: #{(uri rescue opts).inspect}>" 128: end
Default serial primary key options, used by the table creation code.
# File lib/sequel/database/misc.rb, line 141 141: def serial_primary_key_options 142: {:primary_key => true, :type => Integer, :auto_increment => true} 143: end
Whether the database supports CREATE TABLE IF NOT EXISTS syntax, false by default.
# File lib/sequel/database/misc.rb, line 147 147: def supports_create_table_if_not_exists? 148: false 149: end
Whether the database and adapter support prepared transactions (two-phase commit), false by default.
# File lib/sequel/database/misc.rb, line 153 153: def supports_prepared_transactions? 154: false 155: end
Whether the database and adapter support savepoints, false by default.
# File lib/sequel/database/misc.rb, line 158 158: def supports_savepoints? 159: false 160: end
Whether the database and adapter support transaction isolation levels, false by default.
# File lib/sequel/database/misc.rb, line 163 163: def supports_transaction_isolation_levels? 164: false 165: 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 184 184: def typecast_value(column_type, value) 185: return nil if value.nil? 186: meth = "typecast_value_#{column_type}" 187: begin 188: respond_to?(meth, true) ? send(meth, value) : value 189: rescue ArgumentError, TypeError => e 190: raise Sequel.convert_exception_class(e, InvalidValue) 191: end 192: end
Returns the URI identifying the database, which may not be the same as the URI used when connecting. This method can raise an error if the database used options instead of a connection string, and will not include uri parameters.
Sequel.connect('postgres://localhost/db?user=billg').url # => "postgres://billg@localhost/db"
# File lib/sequel/database/misc.rb, line 202 202: def uri 203: uri = URI::Generic.new( 204: adapter_scheme.to_s, 205: nil, 206: @opts[:host], 207: @opts[:port], 208: nil, 209: "/#{@opts[:database]}", 210: nil, 211: nil, 212: nil 213: ) 214: uri.user = @opts[:user] 215: uri.password = @opts[:password] if uri.user 216: uri.to_s 217: end
This methods affect relating to the logging of executed SQL.
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. |
Log a message at level info to all loggers.
# File lib/sequel/database/logging.rb, line 21 21: def log_info(message, args=nil) 22: log_each(:info, args ? "#{message}; #{args.inspect}" : message) 23: 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 27 27: def log_yield(sql, args=nil) 28: return yield if @loggers.empty? 29: sql = "#{sql}; #{args.inspect}" if args 30: start = Time.now 31: begin 32: yield 33: rescue => e 34: log_each(:error, "#{e.class}: #{e.message.strip}: #{sql}") 35: raise 36: ensure 37: log_duration(Time.now - start, sql) unless e 38: end 39: end
This methods change the default behavior of this database‘s datasets.
DatasetClass | = | Sequel::Dataset | The default class to use for datasets | |
MYSQL_DATABASE_DISCONNECT_ERRORS | = | /\A(Commands out of sync; you can't run this command now|Can't connect to local MySQL server through socket|MySQL server has gone away|Lost connection to MySQL server during query)/ | Mysql::Error messages that indicate the current connection should be disconnected | |
DISCONNECT_ERROR_RE | = | /terminating connection due to administrator command/ |
conversion_procs | [R] | A hash of conversion procs, keyed by type integer (oid) and having callable values for the conversion proc for that type. |
conversion_procs | [R] | The conversion procs to use for this database |
conversion_procs | [R] | Hash of conversion procs for the current database |
convert_invalid_date_time | [R] | By default, Sequel raises an exception if in invalid date or time is used. However, if this is set to nil or :nil, the adapter treats dates like 0000-00-00 and times like 838:00:00 as nil values. If set to :string, it returns the strings as is. |
convert_tinyint_to_bool | [R] | Whether to convert tinyint columns to bool for the current database |
convert_types | [RW] | Whether to convert some Java types to ruby types when retrieving rows. True by default, can be set to false to roughly double performance when fetching rows. |
database_type | [R] | The type of database we are connecting to |
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. |
default_schema | [RW] | The default schema to use, generally should be nil. |
driver | [R] | The Java database driver we are using |
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. |
Call the DATABASE_SETUP proc directly after initialization, so the object always uses sub adapter specific code. Also, raise an error immediately if the connection doesn‘t have a uri, since JDBC requires one.
# File lib/sequel/adapters/jdbc.rb, line 151 151: def initialize(opts) 152: super 153: @convert_types = typecast_value_boolean(@opts.fetch(:convert_types, true)) 154: raise(Error, "No connection string specified") unless uri 155: 156: resolved_uri = jndi? ? get_uri_from_jndi : uri 157: 158: if match = /\Ajdbc:([^:]+)/.match(resolved_uri) and prok = DATABASE_SETUP[match[1].to_sym] 159: @driver = prok.call(self) 160: end 161: end
# File lib/sequel/adapters/sqlite.rb, line 53 53: def initialize(opts={}) 54: super 55: @conversion_procs = SQLITE_TYPES.dup 56: @conversion_procs['timestamp'] = method(:to_application_timestamp) 57: @conversion_procs['datetime'] = method(:to_application_timestamp) 58: end
Call the DATABASE_SETUP proc directly after initialization, so the object always uses sub adapter specific code. Also, raise an error immediately if the connection doesn‘t have a uri, since DataObjects requires one.
# File lib/sequel/adapters/do.rb, line 50 50: def initialize(opts) 51: super 52: raise(Error, "No connection string specified") unless uri 53: if prok = DATABASE_SETUP[subadapter.to_sym] 54: prok.call(self) 55: end 56: end
Call the DATABASE_SETUP proc directly after initialization, so the object always uses sub adapter specific code. Also, raise an error immediately if the connection doesn‘t have a db_type specified, since one is required to include the correct subadapter.
# File lib/sequel/adapters/swift.rb, line 47 47: def initialize(opts) 48: super 49: if db_type = opts[:db_type] and !db_type.to_s.empty? 50: if prok = DATABASE_SETUP[db_type.to_s.to_sym] 51: prok.call(self) 52: else 53: raise(Error, "No :db_type option specified") 54: end 55: else 56: raise(Error, ":db_type option not valid, should be postgres, mysql, or sqlite") 57: end 58: end
# File lib/sequel/adapters/mysql.rb, line 58 58: def initialize(opts={}) 59: super 60: @conversion_procs = MYSQL_TYPES.dup 61: self.convert_tinyint_to_bool = Sequel::MySQL.convert_tinyint_to_bool 62: self.convert_invalid_date_time = Sequel::MySQL.convert_invalid_date_time 63: end
Execute the given stored procedure with the give name. If a block is given, the stored procedure should return rows.
# File lib/sequel/adapters/jdbc.rb, line 165 165: def call_sproc(name, opts = {}) 166: args = opts[:args] || [] 167: sql = "{call #{name}(#{args.map{'?'}.join(',')})}" 168: synchronize(opts[:server]) do |conn| 169: cps = conn.prepareCall(sql) 170: 171: i = 0 172: args.each{|arg| set_ps_arg(cps, arg, i+=1)} 173: 174: begin 175: if block_given? 176: yield log_yield(sql){cps.executeQuery} 177: else 178: case opts[:type] 179: when :insert 180: log_yield(sql){cps.executeUpdate} 181: last_insert_id(conn, opts) 182: else 183: log_yield(sql){cps.executeUpdate} 184: end 185: end 186: rescue NativeException, JavaSQL::SQLException => e 187: raise_error(e) 188: ensure 189: cps.close 190: end 191: end 192: end
Connect to the database. Since SQLite is a file based database, the only options available are :database (to specify the database name), and :timeout, to specify 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 64 64: def connect(server) 65: opts = server_opts(server) 66: opts[:database] = ':memory:' if blank_object?(opts[:database]) 67: db = ::SQLite3::Database.new(opts[:database]) 68: db.busy_timeout(opts.fetch(:timeout, 5000)) 69: 70: connection_pragmas.each{|s| log_yield(s){db.execute_batch(s)}} 71: 72: class << db 73: attr_reader :prepared_statements 74: end 75: db.instance_variable_set(:@prepared_statements, {}) 76: 77: db 78: end
Connect to the database. In addition to the usual database options, the following options have effect:
# 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 = [] 115: # Set encoding a slightly different way after connecting, 116: # in case the READ_DEFAULT_GROUP overrode the provided encoding. 117: # Doesn't work across implicit reconnects, but Sequel doesn't turn on 118: # that feature. 119: sqls << "SET NAMES #{literal(encoding.to_s)}" if encoding 120: 121: # Increase timeout so mysql server doesn't disconnect us 122: # Value used by default is maximum allowed value on Windows. 123: sqls << "SET @@wait_timeout = #{opts[:timeout] || 2147483}" 124: 125: # By default, MySQL 'where id is null' selects the last inserted id 126: sqls << "SET SQL_AUTO_IS_NULL=0" unless opts[:auto_is_null] 127: 128: sqls.each{|sql| log_yield(sql){conn.query(sql)}} 129: 130: add_prepared_statements_cache(conn) 131: conn 132: end
Connect to the database using JavaSQL::DriverManager.getConnection.
# File lib/sequel/adapters/jdbc.rb, line 195 195: def connect(server) 196: opts = server_opts(server) 197: conn = if jndi? 198: get_connection_from_jndi 199: else 200: args = [uri(opts)] 201: args.concat([opts[:user], opts[:password]]) if opts[:user] && opts[:password] 202: begin 203: JavaSQL::DriverManager.setLoginTimeout(opts[:login_timeout]) if opts[:login_timeout] 204: JavaSQL::DriverManager.getConnection(*args) 205: rescue => e 206: raise e unless driver 207: # If the DriverManager can't get the connection - use the connect 208: # method of the driver. (This happens under Tomcat for instance) 209: props = java.util.Properties.new 210: if opts && opts[:user] && opts[:password] 211: props.setProperty("user", opts[:user]) 212: props.setProperty("password", opts[:password]) 213: end 214: opts[:jdbc_properties].each{|k,v| props.setProperty(k.to_s, v)} if opts[:jdbc_properties] 215: begin 216: driver.new.connect(args[0], props) 217: rescue => e2 218: e.message << "\n#{e2.class.name}: #{e2.message}" 219: raise e 220: end 221: end 222: end 223: setup_connection(conn) 224: end
Setup a DataObjects::Connection to the database.
# File lib/sequel/adapters/do.rb, line 59 59: def connect(server) 60: setup_connection(::DataObjects::Connection.new(uri(server_opts(server)))) 61: end
Create an instance of swift_class for the given options.
# File lib/sequel/adapters/swift.rb, line 61 61: def connect(server) 62: setup_connection(swift_class.new(server_opts(server))) 63: end
Connects to the database. In addition to the standard database options, using the :encoding or :charset option changes the client encoding for the connection.
# File lib/sequel/adapters/postgres.rb, line 219 219: def connect(server) 220: opts = server_opts(server) 221: conn = if SEQUEL_POSTGRES_USES_PG 222: connection_params = { 223: :host => opts[:host], 224: :port => opts[:port] || 5432, 225: :tty => '', 226: :dbname => opts[:database], 227: :user => opts[:user], 228: :password => opts[:password], 229: :connect_timeout => opts[:connect_timeout] || 20 230: }.delete_if { |key, value| blank_object?(value) } 231: Adapter.connect(connection_params) 232: else 233: Adapter.connect( 234: (opts[:host] unless blank_object?(opts[:host])), 235: opts[:port] || 5432, 236: nil, '', 237: opts[:database], 238: opts[:user], 239: opts[:password] 240: ) 241: end 242: if encoding = opts[:encoding] || opts[:charset] 243: if conn.respond_to?(:set_client_encoding) 244: conn.set_client_encoding(encoding) 245: else 246: conn.async_exec("set client_encoding to '#{encoding}'") 247: end 248: end 249: conn.db = self 250: conn.apply_connection_settings 251: @conversion_procs ||= get_conversion_procs(conn) 252: conn 253: end
Modify the type translators for the date, time, and timestamp types depending on the value given.
# File lib/sequel/adapters/mysql.rb, line 136 136: def convert_invalid_date_time=(v) 137: m0 = ::Sequel.method(:string_to_time) 138: @conversion_procs[11] = (v != false) ? lambda{|v| convert_date_time(v, &m0)} : m0 139: m1 = ::Sequel.method(:string_to_date) 140: m = (v != false) ? lambda{|v| convert_date_time(v, &m1)} : m1 141: [10, 14].each{|i| @conversion_procs[i] = m} 142: m2 = method(:to_application_timestamp) 143: m = (v != false) ? lambda{|v| convert_date_time(v, &m2)} : m2 144: [7, 12].each{|i| @conversion_procs[i] = m} 145: @convert_invalid_date_time = v 146: end
Modify the type translator used for the tinyint type based on the value given.
# File lib/sequel/adapters/mysql.rb, line 150 150: def convert_tinyint_to_bool=(v) 151: @conversion_procs[1] = TYPE_TRANSLATOR.method(v ? :boolean : :integer) 152: @convert_tinyint_to_bool = v 153: end
copy_table uses PostgreSQL‘s COPY SQL statement to return formatted results directly to the caller. This method is only supported if pg is the underlying ruby driver. This method should only be called if you want results returned to the client. If you are using +COPY FROM+ or +COPY TO+ with a filename, you should just use run instead of this method. This method does not currently support +COPY FROM STDIN+, but that may be supported in the future.
The table argument supports the following types:
String : | Uses the first argument directly as literal SQL. If you are using a version of PostgreSQL before 9.0, you will probably want to use a string if you are using any options at all, as the syntax Sequel uses for options is only compatible with PostgreSQL 9.0+. |
Dataset : | Uses a query instead of a table name when copying. |
other : | Uses a table name (usually a symbol) when copying. |
The following options are respected:
:format : | The format to use. text is the default, so this should be :csv or :binary. |
:options : | An options SQL string to use, which should contain comma separated options. |
:server : | The server on which to run the query. |
If a block is provided, the method continually yields to the block, one yield per row. If a block is not provided, a single string is returned with all of the data.
# File lib/sequel/adapters/postgres.rb, line 302 302: def copy_table(table, opts={}) 303: sql = if table.is_a?(String) 304: sql = table 305: else 306: if opts[:options] || opts[:format] 307: options = " (" 308: options << "FORMAT #{opts[:format]}" if opts[:format] 309: options << "#{', ' if opts[:format]}#{opts[:options]}" if opts[:options] 310: options << ')' 311: end 312: table = if table.is_a?(::Sequel::Dataset) 313: "(#{table.sql})" 314: else 315: literal(table) 316: end 317: sql = "COPY #{table} TO STDOUT#{options}" 318: end 319: synchronize(opts[:server]) do |conn| 320: conn.execute(sql) 321: begin 322: if block_given? 323: while buf = conn.get_copy_data 324: yield buf 325: end 326: nil 327: else 328: b = '' 329: b << buf while buf = conn.get_copy_data 330: b 331: end 332: ensure 333: raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state" if buf 334: end 335: end 336: 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 59 59: def dataset_class=(c) 60: unless @dataset_modules.empty? 61: c = Class.new(c) 62: @dataset_modules.each{|m| c.send(:include, m)} 63: end 64: @dataset_class = c 65: end
Dump indexes for all tables as a migration. This complements the :indexes=>false option to dump_schema_migration. Options:
# File lib/sequel/extensions/schema_dumper.rb, line 13 13: def dump_indexes_migration(options={}) 14: ts = tables(options) 15: "Sequel.migration do\n up do\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :add_index, options)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, ' ')}\n end\n \n down do\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :drop_index, options)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, ' ')}\n end\nend\n" 16: end
Return a string that contains a Sequel::Migration subclass that when run would recreate the database structure. Options:
# File lib/sequel/extensions/schema_dumper.rb, line 38 38: def dump_schema_migration(options={}) 39: ts = tables(options) 40: "Sequel.migration do\n up do\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_schema(t, options)}.join(\"\\n\\n\").gsub(/^/o, ' ')}\n end\n \n down do\n drop_table(\#{ts.sort_by{|t| t.to_s}.inspect[1...-1]})\n end\nend\n" 41: end
Return a string with a create table block that will recreate the given table‘s schema. Takes the same options as dump_schema_migration.
# File lib/sequel/extensions/schema_dumper.rb, line 56 56: def dump_table_schema(table, options={}) 57: table = table.value.to_s if table.is_a?(SQL::Identifier) 58: raise(Error, "must provide table as a Symbol, String, or Sequel::SQL::Identifier") unless [String, Symbol].any?{|c| table.is_a?(c)} 59: s = schema(table).dup 60: pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first} 61: options = options.merge(:single_pk=>true) if pks.length == 1 62: m = method(:column_schema_to_generator_opts) 63: im = method(:index_to_generator_opts) 64: begin 65: indexes = indexes(table).sort_by{|k,v| k.to_s} if options[:indexes] != false 66: rescue Sequel::NotImplemented 67: nil 68: end 69: gen = Schema::Generator.new(self) do 70: s.each{|name, info| send(*m.call(name, info, options))} 71: primary_key(pks) if !@primary_key && pks.length > 0 72: indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts))} if indexes 73: end 74: commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n") 75: "create_table(#{table.inspect}#{', :ignore_index_errors=>true' if !options[:same_db] && options[:indexes] != false && indexes && !indexes.empty?}) do\n#{commands.gsub(/^/o, ' ')}\nend" 76: end
Execute the given SQL. If a block is given, the DataObjects::Reader created is yielded to it. A block should not be provided unless a a SELECT statement is being used (or something else that returns rows). Otherwise, the return value is the insert id if opts[:type] is :insert, or the number of affected rows, otherwise.
# File lib/sequel/adapters/do.rb, line 68 68: def execute(sql, opts={}) 69: synchronize(opts[:server]) do |conn| 70: begin 71: command = conn.create_command(sql) 72: res = log_yield(sql){block_given? ? command.execute_reader : command.execute_non_query} 73: rescue ::DataObjects::Error => e 74: raise_error(e) 75: end 76: if block_given? 77: begin 78: yield(res) 79: ensure 80: res.close if res 81: end 82: elsif opts[:type] == :insert 83: res.insert_id 84: else 85: res.affected_rows 86: end 87: end 88: end
Execute the given SQL. If a block is given, if should be a SELECT statement or something else that returns rows.
# File lib/sequel/adapters/jdbc.rb, line 228 228: def execute(sql, opts={}, &block) 229: return call_sproc(sql, opts, &block) if opts[:sproc] 230: return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)} 231: synchronize(opts[:server]) do |conn| 232: statement(conn) do |stmt| 233: if block 234: yield log_yield(sql){stmt.executeQuery(sql)} 235: else 236: case opts[:type] 237: when :ddl 238: log_yield(sql){stmt.execute(sql)} 239: when :insert 240: log_yield(sql) do 241: if requires_return_generated_keys? 242: stmt.executeUpdate(sql, JavaSQL::Statement.RETURN_GENERATED_KEYS) 243: else 244: stmt.executeUpdate(sql) 245: end 246: end 247: last_insert_id(conn, opts.merge(:stmt=>stmt)) 248: else 249: log_yield(sql){stmt.executeUpdate(sql)} 250: end 251: end 252: end 253: end 254: end
Execute the given SQL, yielding a Swift::Result if a block is given.
# File lib/sequel/adapters/swift.rb, line 66 66: def execute(sql, opts={}) 67: synchronize(opts[:server]) do |conn| 68: begin 69: res = log_yield(sql){conn.execute(sql)} 70: yield res if block_given? 71: nil 72: rescue SwiftError => e 73: raise_error(e) 74: end 75: end 76: end
Execute the given SQL with the given args on an available connection.
# File lib/sequel/adapters/postgres.rb, line 256 256: def execute(sql, opts={}, &block) 257: check_database_errors do 258: return execute_prepared_statement(sql, opts, &block) if Symbol === sql 259: synchronize(opts[:server]){|conn| conn.execute(sql, opts[:arguments], &block)} 260: end 261: 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 93 93: def execute_ddl(sql, opts={}) 94: synchronize(opts[:server]) do |conn| 95: conn.prepared_statements.values.each{|cps, s| cps.close} 96: conn.prepared_statements.clear 97: super 98: end 99: end
Execute the SQL on the this database, returning the number of affected rows.
# File lib/sequel/adapters/swift.rb, line 80 80: def execute_dui(sql, opts={}) 81: synchronize(opts[:server]) do |conn| 82: begin 83: log_yield(sql){conn.execute(sql).rows} 84: rescue SwiftError => e 85: raise_error(e) 86: end 87: end 88: end
Insert the values into the table and return the primary key (if automatically generated).
# File lib/sequel/adapters/postgres.rb, line 265 265: def execute_insert(sql, opts={}) 266: return execute(sql, opts) if Symbol === sql 267: check_database_errors do 268: synchronize(opts[:server]) do |conn| 269: conn.execute(sql, opts[:arguments]) 270: insert_result(conn, opts[:table], opts[:values]) 271: end 272: end 273: end
Execute the SQL on this database, returning the primary key of the table being inserted to.
# File lib/sequel/adapters/swift.rb, line 92 92: def execute_insert(sql, opts={}) 93: synchronize(opts[:server]) do |conn| 94: begin 95: log_yield(sql){conn.execute(sql).insert_id} 96: rescue SwiftError => e 97: raise_error(e) 98: end 99: end 100: 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 89 89: def extend_datasets(mod=nil, &block) 90: raise(Error, "must provide either mod or block, not both") if mod && block 91: mod = Module.new(&block) if block 92: if @dataset_modules.empty? 93: @dataset_modules = [mod] 94: @dataset_class = Class.new(@dataset_class) 95: else 96: @dataset_modules << mod 97: end 98: @dataset_class.send(:include, mod) 99: end
The method to call on identifiers going into the database
# File lib/sequel/database/dataset_defaults.rb, line 102 102: def identifier_input_method 103: case @identifier_input_method 104: when nil 105: @identifier_input_method = @opts.fetch(:identifier_input_method, (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method)) 106: @identifier_input_method == "" ? nil : @identifier_input_method 107: when "" 108: nil 109: else 110: @identifier_input_method 111: end 112: 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 119 119: def identifier_input_method=(v) 120: reset_schema_utility_dataset 121: @identifier_input_method = v || "" 122: end
The method to call on identifiers coming from the database
# File lib/sequel/database/dataset_defaults.rb, line 125 125: def identifier_output_method 126: case @identifier_output_method 127: when nil 128: @identifier_output_method = @opts.fetch(:identifier_output_method, (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method)) 129: @identifier_output_method == "" ? nil : @identifier_output_method 130: when "" 131: nil 132: else 133: @identifier_output_method 134: end 135: 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 142 142: def identifier_output_method=(v) 143: reset_schema_utility_dataset 144: @identifier_output_method = v || "" 145: end
Use the JDBC metadata to get the index information for the table.
# File lib/sequel/adapters/jdbc.rb, line 270 270: def indexes(table, opts={}) 271: m = output_identifier_meth 272: im = input_identifier_meth 273: schema, table = schema_and_table(table) 274: schema ||= opts[:schema] 275: schema = im.call(schema) if schema 276: table = im.call(table) 277: indexes = {} 278: metadata(:getIndexInfo, nil, schema, table, false, true) do |r| 279: next unless name = r[:column_name] 280: next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re 281: i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>[false, 0].include?(r[:non_unique])} 282: i[:columns] << m.call(name) 283: end 284: indexes 285: end
Whether or not JNDI is being used for this connection.
# File lib/sequel/adapters/jdbc.rb, line 288 288: def jndi? 289: !!(uri =~ JNDI_URI_REGEXP) 290: end
Listens on the given channel (or multiple channels if channel is an array), waiting for notifications. After a notification is received, or the timeout has passed, stops listening to the channel. Options:
:after_listen : | An object that responds to call that is called with the underlying connection after the LISTEN statement is sent, but before the connection starts waiting for notifications. |
:loop : | Whether to continually wait for notifications, instead of just waiting for a single notification. If this option is given, a block must be provided. If this object responds to call, it is called with the underlying connection after each notification is received (after the block is called). If a :timeout option is used, and a callable object is given, the object will also be called if the timeout expires. If :loop is used and you want to stop listening, you can either break from inside the block given to listen, or you can throw :stop from inside the :loop object‘s call method or the block. |
:server : | The server on which to listen, if the sharding support is being used. |
:timeout : | How long to wait for a notification, in seconds (can provide a float value for fractional seconds). If not given or nil, waits indefinitely. |
This method is only supported if pg is used as the underlying ruby driver. It returns the channel the notification was sent to (as a string), unless :loop was used, in which case it returns nil. If a block is given, it is yielded 3 arguments:
# File lib/sequel/adapters/postgres.rb, line 359 359: def listen(channels, opts={}, &block) 360: check_database_errors do 361: synchronize(opts[:server]) do |conn| 362: begin 363: channels = Array(channels) 364: channels.each{|channel| conn.execute("LISTEN #{channel}")} 365: opts[:after_listen].call(conn) if opts[:after_listen] 366: timeout = opts[:timeout] ? [opts[:timeout]] : [] 367: if l = opts[:loop] 368: raise Error, 'calling #listen with :loop requires a block' unless block 369: loop_call = l.respond_to?(:call) 370: catch(:stop) do 371: loop do 372: conn.wait_for_notify(*timeout, &block) 373: l.call(conn) if loop_call 374: end 375: end 376: nil 377: else 378: conn.wait_for_notify(*timeout, &block) 379: end 380: ensure 381: conn.execute("UNLISTEN *") 382: end 383: end 384: end 385: 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 152 152: def quote_identifiers=(v) 153: reset_schema_utility_dataset 154: @quote_identifiers = v 155: end
Returns true if the database quotes identifiers.
# File lib/sequel/database/dataset_defaults.rb, line 158 158: def quote_identifiers? 159: return @quote_identifiers unless @quote_identifiers.nil? 160: @quote_identifiers = @opts.fetch(:quote_identifiers, (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers)) 161: end
Return the subadapter type for this database, i.e. sqlite3 for do:sqlite3::memory:.
# File lib/sequel/adapters/do.rb, line 104 104: def subadapter 105: uri.split(":").first 106: end
Return the DataObjects URI for the Sequel URI, removing the do: prefix.
# File lib/sequel/adapters/do.rb, line 110 110: def uri(opts={}) 111: opts = @opts.merge(opts) 112: (opts[:uri] || opts[:url]).sub(/\Ado:/, '') 113: end
The uri for this connection. You can specify the uri using the :uri, :url, or :database options. You don‘t need to worry about this if you use Sequel.connect with the JDBC connectrion strings.
# File lib/sequel/adapters/jdbc.rb, line 301 301: def uri(opts={}) 302: opts = @opts.merge(opts) 303: ur = opts[:uri] || opts[:url] || opts[:database] 304: ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}" 305: end
This methods involve the Database‘s connection pool.