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.
Methods
public class
- adapter_class
- adapter_scheme
- connect
- identifier_input_method
- identifier_input_method=
- identifier_output_method
- identifier_output_method=
- new
- quote_identifiers=
- single_threaded=
public instance
- <<
- []
- add_column
- add_index
- add_servers
- alter_table
- call
- cast_type_literal
- connect
- create_or_replace_view
- create_table
- create_table!
- create_table?
- create_view
- database_type
- dataset
- disconnect
- drop_column
- drop_index
- drop_table
- drop_view
- each_server
- execute
- execute_ddl
- execute_dui
- execute_insert
- fetch
- from
- get
- identifier_input_method
- identifier_input_method=
- identifier_output_method
- identifier_output_method=
- inspect
- literal
- log_info
- logger=
- quote_identifiers=
- quote_identifiers?
- remove_servers
- rename_column
- rename_table
- run
- schema
- select
- serial_primary_key_options
- servers
- set_column_default
- set_column_type
- single_threaded?
- supports_savepoints?
- synchronize
- table_exists?
- test_connection
- transaction
- typecast_value
- uri
- url
Included modules
Constants
| ADAPTERS | = | %w'ado amalgalite db2 dbi do firebird informix jdbc mysql odbc openbase oracle postgres sqlite'.collect{|x| x.to_sym} | Array of supported database adapters | |
| 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 | ||
| 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/ | ||
| 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 |
Attributes
| default_schema | [RW] | The default schema to use, generally should be nil. |
| loggers | [RW] | Array of SQL loggers to use for this database |
| opts | [R] | The options for this database |
| pool | [R] | The connection pool for this database |
| prepared_statements | [R] | The prepared statement objects for this database, keyed by name |
Public class methods
The Database subclass for the given adapter scheme. Raises Sequel::AdapterNotFound if the adapter could not be loaded.
# File lib/sequel/database.rb, line 107 107: def self.adapter_class(scheme) 108: scheme = scheme.to_s.gsub('-', '_').to_sym 109: 110: unless klass = ADAPTER_MAP[scheme] 111: # attempt to load the adapter file 112: begin 113: Sequel.tsk_require "sequel/adapters/#{scheme}" 114: rescue LoadError => e 115: raise Sequel.convert_exception_class(e, AdapterNotFound) 116: end 117: 118: # make sure we actually loaded the adapter 119: unless klass = ADAPTER_MAP[scheme] 120: raise AdapterNotFound, "Could not load #{scheme} adapter" 121: end 122: end 123: klass 124: end
Returns the scheme for the Database class.
# File lib/sequel/database.rb, line 127 127: def self.adapter_scheme 128: @scheme 129: end
Connects to a database. See Sequel.connect.
# File lib/sequel/database.rb, line 132 132: def self.connect(conn_string, opts = {}, &block) 133: case conn_string 134: when String 135: if match = /\A(jdbc|do):/o.match(conn_string) 136: c = adapter_class(match[1].to_sym) 137: opts = {:uri=>conn_string}.merge(opts) 138: else 139: uri = URI.parse(conn_string) 140: scheme = uri.scheme 141: scheme = :dbi if scheme =~ /\Adbi-/ 142: c = adapter_class(scheme) 143: uri_options = c.send(:uri_to_options, uri) 144: 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? 145: uri_options.entries.each{|k,v| uri_options[k] = URI.unescape(v) if v.is_a?(String)} 146: opts = uri_options.merge(opts) 147: end 148: when Hash 149: opts = conn_string.merge(opts) 150: c = adapter_class(opts[:adapter] || opts['adapter']) 151: else 152: raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" 153: end 154: # process opts a bit 155: opts = opts.inject({}) do |m, kv| k, v = *kv 156: k = :user if k.to_s == 'username' 157: m[k.to_sym] = v 158: m 159: end 160: if block 161: begin 162: yield(db = c.new(opts)) 163: ensure 164: db.disconnect if db 165: ::Sequel::DATABASES.delete(db) 166: end 167: nil 168: else 169: c.new(opts) 170: end 171: end
The method to call on identifiers going into the database
# File lib/sequel/database.rb, line 174 174: def self.identifier_input_method 175: @@identifier_input_method 176: end
Set the method to call on identifiers going into the database See Sequel.identifier_input_method=.
# File lib/sequel/database.rb, line 180 180: def self.identifier_input_method=(v) 181: @@identifier_input_method = v || "" 182: end
The method to call on identifiers coming from the database
# File lib/sequel/database.rb, line 185 185: def self.identifier_output_method 186: @@identifier_output_method 187: end
Set the method to call on identifiers coming from the database See Sequel.identifier_output_method=.
# File lib/sequel/database.rb, line 191 191: def self.identifier_output_method=(v) 192: @@identifier_output_method = v || "" 193: end
Constructs a new instance of a database connection with the specified options hash.
Sequel::Database is an abstract class that is not useful by itself.
Takes 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
- :loggers : An array of loggers to use.
- :quote_identifiers : Whether to quote identifiers
- :single_threaded : Whether to use a single-threaded connection pool
All options given are also passed to the ConnectionPool. If a block is given, it is used as the connection_proc for the ConnectionPool.
# File lib/sequel/database.rb, line 81 81: def initialize(opts = {}, &block) 82: @opts ||= opts 83: @opts = connection_pool_default_options.merge(@opts) 84: @loggers = Array(@opts[:logger]) + Array(@opts[:loggers]) 85: @opts[:disconnection_proc] ||= proc{|conn| disconnect_connection(conn)} 86: block ||= proc{|server| connect(server)} 87: @opts[:servers] = {} if @opts[:servers].is_a?(String) 88: 89: @opts[:single_threaded] = @single_threaded = @opts.include?(:single_threaded) ? typecast_value_boolean(@opts[:single_threaded]) : @@single_threaded 90: @schemas = {} 91: @default_schema = opts.include?(:default_schema) ? @opts[:default_schema] : default_schema_default 92: @prepared_statements = {} 93: @transactions = [] 94: @identifier_input_method = nil 95: @identifier_output_method = nil 96: @quote_identifiers = nil 97: @pool = ConnectionPool.get_pool(@opts, &block) 98: 99: ::Sequel::DATABASES.push(self) 100: end
Sets the default quote_identifiers mode for new databases. See Sequel.quote_identifiers=.
# File lib/sequel/database.rb, line 197 197: def self.quote_identifiers=(value) 198: @@quote_identifiers = value 199: end
Sets the default single_threaded mode for new databases. See Sequel.single_threaded=.
# File lib/sequel/database.rb, line 203 203: def self.single_threaded=(value) 204: @@single_threaded = value 205: end
Public instance methods
Runs the supplied SQL statement string on the database server. Alias for run.
# File lib/sequel/database.rb, line 242 242: def <<(sql) 243: run(sql) 244: end
Returns a dataset from the database. If the first argument is a string, the method acts as an alias for Database#fetch, returning a dataset for arbitrary SQL:
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.rb, line 256 256: def [](*args) 257: (String === args.first) ? fetch(*args) : from(*args) 258: end
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 10 10: def add_column(table, *args) 11: alter_table(table) {add_column(*args)} 12: 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 24 24: def add_index(table, columns, options={}) 25: e = options[:ignore_errors] 26: begin 27: alter_table(table){add_index(columns, options)} 28: rescue DatabaseError 29: raise unless e 30: end 31: 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.rb, line 269 269: def add_servers(servers) 270: @opts[:servers] = @opts[:servers] ? @opts[:servers].merge(servers) : servers 271: @pool.add_servers(servers.keys) 272: 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.
# File lib/sequel/database/schema_methods.rb, line 50 50: def alter_table(name, generator=nil, &block) 51: remove_cached_schema(name) 52: generator ||= Schema::AlterTableGenerator.new(self, &block) 53: alter_table_sql_list(name, generator.operations).flatten.each {|sql| execute_ddl(sql)} 54: end
Call the prepared statement with the given name with the given hash of arguments.
# File lib/sequel/database.rb, line 276 276: def call(ps_name, hash={}) 277: prepared_statements[ps_name].call(hash) 278: end
Cast the given type to a literal type
# File lib/sequel/database.rb, line 281 281: def cast_type_literal(type) 282: type_literal(:type=>type) 283: end
Connects to the database. This method should be overridden by descendants.
# File lib/sequel/database.rb, line 286 286: def connect(server) 287: raise NotImplementedError, "#connect should be overridden by adapters" 288: 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 92 92: def create_or_replace_view(name, source) 93: remove_cached_schema(name) 94: source = source.sql if source.is_a?(Dataset) 95: execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}") 96: 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.
# File lib/sequel/database/schema_methods.rb, line 70 70: def create_table(name, options={}, &block) 71: options = {:generator=>options} if options.is_a?(Schema::Generator) 72: generator = options[:generator] || Schema::Generator.new(self, &block) 73: create_table_from_generator(name, generator, options) 74: create_table_indexes_from_generator(name, generator, options) 75: end
Forcibly creates a table, attempting to drop it unconditionally (and catching any errors), then creating it.
# File lib/sequel/database/schema_methods.rb, line 78 78: def create_table!(name, options={}, &block) 79: drop_table(name) rescue nil 80: create_table(name, options, &block) 81: end
Creates the table unless the table already exists
# File lib/sequel/database/schema_methods.rb, line 84 84: def create_table?(name, options={}, &block) 85: create_table(name, options, &block) unless table_exists?(name) 86: 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 102 102: def create_view(name, source) 103: source = source.sql if source.is_a?(Dataset) 104: execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}") 105: 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).
# File lib/sequel/database.rb, line 297 297: def database_type 298: self.class.adapter_scheme 299: end
Returns a blank dataset for this database
# File lib/sequel/database.rb, line 302 302: def dataset 303: ds = Sequel::Dataset.new(self) 304: 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.
# File lib/sequel/database.rb, line 310 310: def disconnect(opts = {}) 311: pool.disconnect(opts) 312: end
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 112 112: def drop_column(table, *args) 113: alter_table(table) {drop_column(*args)} 114: 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 122 122: def drop_index(table, columns, options={}) 123: alter_table(table){drop_index(columns, options)} 124: end
Drops one or more tables corresponding to the given names:
DB.drop_table(:posts, :comments)
# File lib/sequel/database/schema_methods.rb, line 129 129: def drop_table(*names) 130: names.each do |n| 131: remove_cached_schema(n) 132: execute_ddl(drop_table_sql(n)) 133: end 134: end
Drops one or more views corresponding to the given names:
DB.drop_view(:cheap_items)
# File lib/sequel/database/schema_methods.rb, line 139 139: def drop_view(*names) 140: names.each do |n| 141: remove_cached_schema(n) 142: execute_ddl("DROP VIEW #{quote_schema_table(n)}") 143: end 144: end
Yield a new database object 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.rb, line 319 319: def each_server(&block) 320: servers.each{|s| self.class.connect(server_opts(s), &block)} 321: 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.rb, line 325 325: def execute(sql, opts={}) 326: raise NotImplementedError, "#execute should be overridden by adapters" 327: end
Method that should be used when submitting any DDL (Data Definition Language) SQL. By default, calls execute_dui. This method should not be called directly by user code.
# File lib/sequel/database.rb, line 332 332: def execute_ddl(sql, opts={}, &block) 333: execute_dui(sql, opts, &block) 334: end
Method that should be used when issuing a DELETE, UPDATE, or INSERT statement. By default, calls execute. This method should not be called directly by user code.
# File lib/sequel/database.rb, line 339 339: def execute_dui(sql, opts={}, &block) 340: execute(sql, opts, &block) 341: 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.rb, line 346 346: def execute_insert(sql, opts={}, &block) 347: execute_dui(sql, opts, &block) 348: 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 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.rb, line 363 363: def fetch(sql, *args, &block) 364: ds = dataset.with_sql(sql, *args) 365: ds.each(&block) if block 366: ds 367: end
Returns a new dataset with the from method invoked. If a block is given, it is used as a filter on the dataset.
# File lib/sequel/database.rb, line 371 371: def from(*args, &block) 372: ds = dataset.from(*args) 373: block ? ds.filter(&block) : ds 374: end
Returns a single value from the database, e.g.:
# SELECT 1 DB.get(1) #=> 1 # SELECT version() DB.get(:version.sql_function) #=> ...
# File lib/sequel/database.rb, line 383 383: def get(*args, &block) 384: dataset.get(*args, &block) 385: end
The method to call on identifiers going into the database
# File lib/sequel/database.rb, line 388 388: def identifier_input_method 389: case @identifier_input_method 390: when nil 391: @identifier_input_method = @opts.include?(:identifier_input_method) ? @opts[:identifier_input_method] : (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method) 392: @identifier_input_method == "" ? nil : @identifier_input_method 393: when "" 394: nil 395: else 396: @identifier_input_method 397: end 398: end
Set the method to call on identifiers going into the database
# File lib/sequel/database.rb, line 401 401: def identifier_input_method=(v) 402: reset_schema_utility_dataset 403: @identifier_input_method = v || "" 404: end
The method to call on identifiers coming from the database
# File lib/sequel/database.rb, line 407 407: def identifier_output_method 408: case @identifier_output_method 409: when nil 410: @identifier_output_method = @opts.include?(:identifier_output_method) ? @opts[:identifier_output_method] : (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method) 411: @identifier_output_method == "" ? nil : @identifier_output_method 412: when "" 413: nil 414: else 415: @identifier_output_method 416: end 417: end
Set the method to call on identifiers coming from the database
# File lib/sequel/database.rb, line 420 420: def identifier_output_method=(v) 421: reset_schema_utility_dataset 422: @identifier_output_method = v || "" 423: 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.rb, line 428 428: def inspect 429: "#<#{self.class}: #{(uri rescue opts).inspect}>" 430: end
Proxy the literal call to the dataset, used for default values.
# File lib/sequel/database.rb, line 433 433: def literal(v) 434: schema_utility_dataset.literal(v) 435: end
Log a message at level info to all loggers. All SQL logging goes through this method.
# File lib/sequel/database.rb, line 439 439: def log_info(message, args=nil) 440: message = "#{message}; #{args.inspect}" if args 441: @loggers.each{|logger| logger.info(message)} 442: end
Remove any existing loggers and just use the given logger.
# File lib/sequel/database.rb, line 445 445: def logger=(logger) 446: @loggers = Array(logger) 447: end
Whether to quote identifiers (columns and tables) for this database
# File lib/sequel/database.rb, line 450 450: def quote_identifiers=(v) 451: reset_schema_utility_dataset 452: @quote_identifiers = v 453: end
Returns true if the database quotes identifiers.
# File lib/sequel/database.rb, line 456 456: def quote_identifiers? 457: return @quote_identifiers unless @quote_identifiers.nil? 458: @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers) 459: 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.rb, line 471 471: def remove_servers(*servers) 472: if @opts[:servers] && !@opts[:servers].empty? 473: servs = @opts[:servers].dup 474: servers.flatten! 475: servers.each{|s| servs.delete(s)} 476: @opts[:servers] = servs 477: @pool.remove_servers(servers) 478: end 479: 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 162 162: def rename_column(table, *args) 163: alter_table(table) {rename_column(*args)} 164: 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 151 151: def rename_table(name, new_name) 152: remove_cached_schema(name) 153: execute_ddl(rename_table_sql(name, new_name)) 154: end
Runs the supplied SQL statement string on the database server. Returns nil. Options:
- :server - The server to run the SQL on.
# File lib/sequel/database.rb, line 484 484: def run(sql, opts={}) 485: execute_ddl(sql, opts) 486: nil 487: end
Parse the schema from the database. 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. Available options are:
- :reload - Get fresh information from the database, instead of using cached information. If table_name is blank, :reload should be used unless you are sure that schema has not been called before with a table_name, otherwise you may only getting the schemas for tables that have been requested explicitly.
- :schema - An explicit schema to use. It may also be implicitly provided via the table name.
# File lib/sequel/database.rb, line 501 501: def schema(table, opts={}) 502: raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true) 503: 504: sch, table_name = schema_and_table(table) 505: quoted_name = quote_schema_table(table) 506: opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema) 507: 508: @schemas.delete(quoted_name) if opts[:reload] 509: return @schemas[quoted_name] if @schemas[quoted_name] 510: 511: cols = schema_parse_table(table_name, opts) 512: raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty? 513: cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} 514: @schemas[quoted_name] = cols 515: end
Returns a new dataset with the select method invoked.
# File lib/sequel/database.rb, line 518 518: def select(*args, &block) 519: dataset.select(*args, &block) 520: end
Default serial primary key options.
# File lib/sequel/database/schema_sql.rb, line 19 19: def serial_primary_key_options 20: {:primary_key => true, :type => Integer, :auto_increment => true} 21: end
An array of servers/shards for this Database object.
# File lib/sequel/database.rb, line 523 523: def servers 524: pool.servers 525: 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 171 171: def set_column_default(table, *args) 172: alter_table(table) {set_column_default(*args)} 173: 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 180 180: def set_column_type(table, *args) 181: alter_table(table) {set_column_type(*args)} 182: end
Returns true if the database is using a single-threaded connection pool.
# File lib/sequel/database.rb, line 528 528: def single_threaded? 529: @single_threaded 530: end
Whether the database and adapter support savepoints, false by default
# File lib/sequel/database.rb, line 538 538: def supports_savepoints? 539: false 540: end
Acquires a database connection, yielding it to the passed block.
# File lib/sequel/database.rb, line 533 533: def synchronize(server=nil, &block) 534: @pool.hold(server || :default, &block) 535: end
Returns true if a table with the given name exists. This requires a query to the database.
# File lib/sequel/database.rb, line 544 544: def table_exists?(name) 545: begin 546: from(name).first 547: true 548: rescue 549: false 550: end 551: end
Attempts to acquire a database connection. Returns true if successful. Will probably raise an error if unsuccessful.
# File lib/sequel/database.rb, line 555 555: def test_connection(server=nil) 556: synchronize(server){|conn|} 557: true 558: 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:
- :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.rb, line 571 571: def transaction(opts={}, &block) 572: synchronize(opts[:server]) do |conn| 573: return yield(conn) if already_in_transaction?(conn, opts) 574: _transaction(conn, &block) 575: end 576: 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.rb, line 583 583: def typecast_value(column_type, value) 584: return nil if value.nil? 585: meth = "typecast_value_#{column_type}" 586: begin 587: respond_to?(meth, true) ? send(meth, value) : value 588: rescue ArgumentError, TypeError => e 589: raise Sequel.convert_exception_class(e, InvalidValue) 590: end 591: end
Returns the URI identifying the database. This method can raise an error if the database used options instead of a connection string.
# File lib/sequel/database.rb, line 596 596: def uri 597: uri = URI::Generic.new( 598: self.class.adapter_scheme.to_s, 599: nil, 600: @opts[:host], 601: @opts[:port], 602: nil, 603: "/#{@opts[:database]}", 604: nil, 605: nil, 606: nil 607: ) 608: uri.user = @opts[:user] 609: uri.password = @opts[:password] if uri.user 610: uri.to_s 611: end
Explicit alias of uri for easier subclassing.
# File lib/sequel/database.rb, line 614 614: def url 615: uri 616: end