Class: Sequel::Database
- Inherits:
-
Object
- Object
- Sequel::Database
- Extended by:
- Metaprogramming
- Includes:
- Metaprogramming
- Defined in:
- lib/sequel/database.rb,
lib/sequel/database/misc.rb,
lib/sequel/database/query.rb,
lib/sequel/database/logging.rb,
lib/sequel/database/dataset.rb,
lib/sequel/extensions/query.rb,
lib/sequel/database/connecting.rb,
lib/sequel/database/schema_methods.rb,
lib/sequel/extensions/schema_dumper.rb,
lib/sequel/database/dataset_defaults.rb
Overview
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.
Direct Known Subclasses
ADO::Database, Amalgalite::Database, Sequel::DB2::Database, Sequel::DBI::Database, Sequel::DataObjects::Database, Firebird::Database, IBMDB::Database, Informix::Database, JDBC::Database, Mock::Database, MySQL::Database, Mysql2::Database, ODBC::Database, OpenBase::Database, Oracle::Database, Postgres::Database, SQLite::Database, Swift::Database, TinyTDS::Database
Constant Summary
- LEADING_ZERO_RE =
Used for checking/removing leading zeroes from strings so they don't get interpreted as octal.
/\A0+(\d)/.freeze
- LEADING_ZERO_REP =
Replacement string when replacing leading zeroes.
"\\1".freeze
- SQL_BEGIN =
:section: 1 - Methods that execute queries and/or return results This methods generally execute SQL code on the database server.
'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/- ADAPTERS =
Array of supported database 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}
- AUTOINCREMENT =
:section: 2 - Methods that modify the database schema These methods execute code on the database that modifies the database's schema.
'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 =
The order of column modifiers to use when defining a column.
[:collate, :default, :null, :unique, :primary_key, :auto_increment, :references]
- DatasetClass =
The default class to use for datasets
Sequel::Dataset
- @@single_threaded =
Whether to use the single threaded connection pool by default
false- @@identifier_input_method =
The identifier input method to use by default
nil- @@identifier_output_method =
The identifier output method to use by default
nil- @@quote_identifiers =
Whether to quote identifiers (columns and tables) by default
nil
Instance Attribute Summary (collapse)
-
- (Object) dataset_class
The class to use for creating datasets.
-
- (Object) default_schema
The default schema to use, generally should be nil.
-
- (Object) log_warn_duration
Numeric specifying the duration beyond which queries are logged at warn level instead of info level.
-
- (Object) loggers
Array of SQL loggers to use for this database.
-
- (Object) opts
readonly
The options hash for this database.
-
- (Object) pool
readonly
The connection pool for this Database instance.
-
- (Object) prepared_statements
readonly
The prepared statement object hash for this database, keyed by name symbol.
-
- (Object) sql_log_level
Log level at which to log SQL queries.
-
- (Object) timezone
The timezone to use for this database, defaulting to Sequel.database_timezone.
-
- (Object) transaction_isolation_level
The default transaction isolation level for this database, used for all future transactions.
Class Method Summary (collapse)
-
+ (Object) adapter_class(scheme)
The Database subclass for the given adapter scheme.
-
+ (Object) adapter_scheme
Returns the scheme symbol for the Database class.
-
+ (Object) connect(conn_string, opts = {})
Connects to a database.
-
+ (Object) identifier_input_method
The method to call on identifiers going into the database.
-
+ (Object) identifier_input_method=(v)
Set the method to call on identifiers going into the database See Sequel.identifier_input_method=.
-
+ (Object) identifier_output_method
The method to call on identifiers coming from the database.
-
+ (Object) identifier_output_method=(v)
Set the method to call on identifiers coming from the database See Sequel.identifier_output_method=.
-
+ (Object) quote_identifiers=(value)
Sets the default quote_identifiers mode for new databases.
-
+ (Object) set_adapter_scheme(scheme)
Sets the adapter scheme for the Database class.
-
+ (Object) single_threaded=(value)
Sets the default single_threaded mode for new databases.
-
+ (Object) uri_to_options(uri)
Converts a uri to an options hash.
Instance Method Summary (collapse)
-
- (Object) <<(sql)
Runs the supplied SQL statement string on the database server.
-
- (Object) [](*args)
Returns a dataset for the database.
-
- (Object) adapter_scheme
Returns the scheme symbol for this instance's class, which reflects which adapter is being used.
-
- (Object) add_column(table, *args)
Adds a column to the specified table.
-
- (Object) add_index(table, columns, options = {})
Adds an index to a table for the given columns:.
-
- (Object) add_servers(servers)
Dynamically add new servers or modify server options at runtime.
-
- (Object) after_commit(opts = {}, &block)
If a transaction is not currently in process, yield to the block immediately.
-
- (Object) after_rollback(opts = {}, &block)
If a transaction is not currently in progress, ignore the block.
-
- (Object) alter_table(name, generator = nil, &block)
Alters the given table with the specified block.
-
- (Object) call(ps_name, hash = {})
Call the prepared statement with the given name with the given hash of arguments.
-
- (Object) cast_type_literal(type)
Cast the given type to a literal type.
-
- (Object) commit_or_rollback_transaction(exception, conn, opts)
Whether to commit the current transaction.
-
- (Object) connect(server)
Connects to the database.
-
- (Object) create_or_replace_view(name, source)
Creates a view, replacing it if it already exists:.
-
- (Object) create_table(name, options = {}, &block)
Creates a table with the columns given in the provided block:.
-
- (Object) create_table!(name, options = {}, &block)
Forcibly create a table, attempting to drop it if it already exists, then creating it.
-
- (Boolean) create_table?(name, options = {}, &block)
Creates the table unless the table already exists.
-
- (Object) create_view(name, source)
Creates a view based on a dataset or an SQL string:.
-
- (Object) database_type
The database type for this database object, the same as the adapter scheme by default.
-
- (Object) dataset(opts = nil)
Returns a blank dataset for this database.
-
- (Object) disconnect(opts = {})
Disconnects all available connections from the connection pool.
-
- (Object) drop_column(table, *args)
Removes a column from the specified table:.
-
- (Object) drop_index(table, columns, options = {})
Removes an index for the given table and column/s:.
-
- (Object) drop_table(*names)
Drops one or more tables corresponding to the given names:.
-
- (Boolean) drop_table?(*names)
Drops the table if it already exists.
-
- (Object) drop_view(*names)
Drops one or more views corresponding to the given names:.
-
- (Object) dump_indexes_migration(options = {})
Dump indexes for all tables as a migration.
-
- (Object) dump_schema_migration(options = {})
Return a string that contains a Sequel::Migration subclass that when run would recreate the database structure.
-
- (Object) dump_table_schema(table, options = {})
Return a string with a create table block that will recreate the given table's schema.
-
- (Object) each_server(&block)
Yield a new Database instance for every server in the connection pool.
-
- (Object) execute(sql, opts = {})
Executes the given SQL on the database.
-
- (Object) execute_ddl(sql, opts = {}, &block)
Method that should be used when submitting any DDL (Data Definition Language) SQL, such as create_table.
-
- (Object) execute_dui(sql, opts = {}, &block)
Method that should be used when issuing a DELETE, UPDATE, or INSERT statement.
-
- (Object) execute_insert(sql, opts = {}, &block)
Method that should be used when issuing a INSERT statement.
-
- (Object) extend_datasets(mod = nil, &block)
Equivalent to extending all datasets produced by the database with a module.
-
- (Object) fetch(sql, *args, &block)
Fetches records for an arbitrary SQL statement.
-
- (Object) from(*args, &block)
Returns a new dataset with the from method invoked.
-
- (Object) from_application_timestamp(v)
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.
-
- (Object) get(*args, &block)
Returns a single value from the database, e.g.:.
-
- (Object) identifier_input_method
The method to call on identifiers going into the database.
-
- (Object) identifier_input_method=(v)
Set the method to call on identifiers going into the database:.
-
- (Object) identifier_output_method
The method to call on identifiers coming from the database.
-
- (Object) identifier_output_method=(v)
Set the method to call on identifiers coming from the database:.
-
- (Boolean) in_transaction?(opts = {})
Return true if already in a transaction given the options, false otherwise.
-
- (Object) indexes(table, opts = {})
Return a hash containing index information for the table.
-
- (Database) initialize(opts = {}, &block)
constructor
Constructs a new instance of a database connection with the specified options hash.
-
- (Object) inspect
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).
-
- (Object) literal(v)
Proxy the literal call to the dataset.
-
- (Object) log_info(message, args = nil)
Log a message at level info to all loggers.
-
- (Object) log_yield(sql, args = nil)
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.
-
- (Object) logger=(logger)
Remove any existing loggers and just use the given logger:.
-
- (Object) query(&block)
Return a dataset modified by the query block.
-
- (Object) quote_identifiers=(v)
Set whether to quote identifiers (columns and tables) for this database:.
-
- (Boolean) quote_identifiers?
Returns true if the database quotes identifiers.
-
- (Object) remove_servers(*servers)
Dynamically remove existing servers from the connection pool.
-
- (Object) rename_column(table, *args)
Renames a column in the specified table.
-
- (Object) rename_table(name, new_name)
Renames a table:.
-
- (Object) run(sql, opts = {})
Runs the supplied SQL statement string on the database server.
-
- (Object) schema(table, opts = {})
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.
-
- (Object) select(*args, &block)
Returns a new dataset with the select method invoked.
-
- (Object) serial_primary_key_options
Default serial primary key options, used by the table creation code.
-
- (Object) servers
An array of servers/shards for this Database object.
-
- (Object) set_column_default(table, *args)
Sets the default value for the given column in the given table:.
-
- (Object) set_column_type(table, *args)
Set the data type for the given column in the given table:.
-
- (Boolean) single_threaded?
Returns true if the database is using a single-threaded connection pool.
-
- (Boolean) supports_create_table_if_not_exists?
Whether the database supports CREATE TABLE IF NOT EXISTS syntax, false by default.
-
- (Boolean) supports_drop_table_if_exists?
Whether the database supports DROP TABLE IF EXISTS syntax, default is the same as #supports_create_table_if_not_exists?.
-
- (Boolean) supports_prepared_transactions?
Whether the database and adapter support prepared transactions (two-phase commit), false by default.
-
- (Boolean) supports_savepoints?
Whether the database and adapter support savepoints, false by default.
-
- (Boolean) supports_savepoints_in_prepared_transactions?
Whether the database and adapter support savepoints inside prepared transactions (two-phase commit), default is false.
-
- (Boolean) supports_transaction_isolation_levels?
Whether the database and adapter support transaction isolation levels, false by default.
-
- (Object) synchronize(server = nil, &block)
Acquires a database connection, yielding it to the passed block.
-
- (Boolean) table_exists?(name)
Returns true if a table with the given name exists.
-
- (Object) tables(opts = {})
Return all tables in the database as an array of symbols.
-
- (Object) test_connection(server = nil)
Attempts to acquire a database connection.
-
- (Object) to_application_timestamp(v)
Convert the given timestamp to the application's timezone, from the databases's timezone or the default database timezone if the database does not have a timezone.
-
- (Object) transaction(opts = {}, &block)
Starts a database transaction.
-
- (Object) typecast_value(column_type, value)
Typecast the value to the given column_type.
-
- (Object) typecast_value_integer(value)
Typecast the value to an Integer.
-
- (Object) uri
Returns the URI identifying the database, which may not be the same as the URI used when connecting.
-
- (Object) url
Explicit alias of uri for easier subclassing.
-
- (Object) views(opts = {})
Return all views in the database as an array of symbols.
Methods included from Metaprogramming
Constructor Details
- (Database) initialize(opts = {}, &block)
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.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/sequel/database/misc.rb', line 42 def initialize(opts = {}, &block) @opts ||= opts @opts = .merge(@opts) @loggers = Array(@opts[:logger]) + Array(@opts[:loggers]) self.log_warn_duration = @opts[:log_warn_duration] @opts[:disconnection_proc] ||= proc{|conn| disconnect_connection(conn)} block ||= proc{|server| connect(server)} @opts[:servers] = {} if @opts[:servers].is_a?(String) @opts[:adapter_class] = self.class @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, @@single_threaded)) @schemas = {} @default_schema = @opts.fetch(:default_schema, default_schema_default) @prepared_statements = {} @transactions = {} @identifier_input_method = nil @identifier_output_method = nil @quote_identifiers = nil @timezone = nil @dataset_class = dataset_class_default @dataset_modules = [] self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info @pool = ConnectionPool.get_pool(@opts, &block) ::Sequel::DATABASES.push(self) end |
Instance Attribute Details
- (Object) dataset_class
The class to use for creating datasets. Should respond to new with the Database argument as the first argument, and an optional options hash.
51 52 53 |
# File 'lib/sequel/database/dataset_defaults.rb', line 51 def dataset_class @dataset_class end |
- (Object) default_schema
The default schema to use, generally should be nil.
54 55 56 |
# File 'lib/sequel/database/dataset_defaults.rb', line 54 def default_schema @default_schema end |
- (Object) log_warn_duration
Numeric specifying the duration beyond which queries are logged at warn level instead of info level.
10 11 12 |
# File 'lib/sequel/database/logging.rb', line 10 def log_warn_duration @log_warn_duration end |
- (Object) loggers
Array of SQL loggers to use for this database.
13 14 15 |
# File 'lib/sequel/database/logging.rb', line 13 def loggers @loggers end |
- (Object) opts (readonly)
The options hash for this database
20 21 22 |
# File 'lib/sequel/database/misc.rb', line 20 def opts @opts end |
- (Object) pool (readonly)
The connection pool for this Database instance. All Database instances have their own connection pools.
112 113 114 |
# File 'lib/sequel/database/connecting.rb', line 112 def pool @pool end |
- (Object) prepared_statements (readonly)
The prepared statement object hash for this database, keyed by name symbol
30 31 32 |
# File 'lib/sequel/database/query.rb', line 30 def prepared_statements @prepared_statements end |
- (Object) sql_log_level
Log level at which to log SQL queries. This is actually the method sent to the logger, so it should be the method name symbol. The default is :info, it can be set to :debug to log at DEBUG level.
18 19 20 |
# File 'lib/sequel/database/logging.rb', line 18 def sql_log_level @sql_log_level end |
- (Object) timezone
The timezone to use for this database, defaulting to Sequel.database_timezone.
180 181 182 |
# File 'lib/sequel/database/misc.rb', line 180 def timezone @timezone || Sequel.database_timezone end |
- (Object) transaction_isolation_level
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.
37 38 39 |
# File 'lib/sequel/database/query.rb', line 37 def transaction_isolation_level @transaction_isolation_level end |
Class Method Details
+ (Object) adapter_class(scheme)
The Database subclass for the given adapter scheme. Raises Sequel::AdapterNotFound if the adapter could not be loaded.
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/sequel/database/connecting.rb', line 17 def self.adapter_class(scheme) return scheme if scheme.is_a?(Class) scheme = scheme.to_s.gsub('-', '_').to_sym unless klass = ADAPTER_MAP[scheme] # attempt to load the adapter file begin Sequel.tsk_require "sequel/adapters/#{scheme}" rescue LoadError => e raise Sequel.convert_exception_class(e, AdapterNotFound) end # make sure we actually loaded the adapter unless klass = ADAPTER_MAP[scheme] raise AdapterNotFound, "Could not load #{scheme} adapter: adapter class not registered in ADAPTER_MAP" end end klass end |
+ (Object) adapter_scheme
Returns the scheme symbol for the Database class.
39 40 41 |
# File 'lib/sequel/database/connecting.rb', line 39 def self.adapter_scheme @scheme end |
+ (Object) connect(conn_string, opts = {})
Connects to a database. See Sequel.connect.
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/sequel/database/connecting.rb', line 44 def self.connect(conn_string, opts = {}) case conn_string when String if match = /\A(jdbc|do):/o.match(conn_string) c = adapter_class(match[1].to_sym) opts = {:uri=>conn_string}.merge(opts) else uri = URI.parse(conn_string) scheme = uri.scheme scheme = :dbi if scheme =~ /\Adbi-/ c = adapter_class(scheme) = c.send(:uri_to_options, uri) uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| [k.to_sym] = v if k && !k.empty?} unless uri.query.to_s.strip.empty? .to_a.each{|k,v| [k] = URI.unescape(v) if v.is_a?(String)} opts = .merge(opts) opts[:adapter] = scheme end when Hash opts = conn_string.merge(opts) c = adapter_class(opts[:adapter_class] || opts[:adapter] || opts['adapter']) else raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" end # process opts a bit opts = opts.inject({}) do |m, (k,v)| k = :user if k.to_s == 'username' m[k.to_sym] = v m end begin db = c.new(opts) db.test_connection if opts[:test] && db.send(:typecast_value_boolean, opts[:test]) result = yield(db) if block_given? ensure if block_given? db.disconnect if db ::Sequel::DATABASES.delete(db) end end block_given? ? result : db end |
+ (Object) identifier_input_method
The method to call on identifiers going into the database
21 22 23 |
# File 'lib/sequel/database/dataset_defaults.rb', line 21 def self.identifier_input_method @@identifier_input_method end |
+ (Object) identifier_input_method=(v)
Set the method to call on identifiers going into the database See Sequel.identifier_input_method=.
27 28 29 |
# File 'lib/sequel/database/dataset_defaults.rb', line 27 def self.identifier_input_method=(v) @@identifier_input_method = v || "" end |
+ (Object) identifier_output_method
The method to call on identifiers coming from the database
32 33 34 |
# File 'lib/sequel/database/dataset_defaults.rb', line 32 def self.identifier_output_method @@identifier_output_method end |
+ (Object) identifier_output_method=(v)
Set the method to call on identifiers coming from the database See Sequel.identifier_output_method=.
38 39 40 |
# File 'lib/sequel/database/dataset_defaults.rb', line 38 def self.identifier_output_method=(v) @@identifier_output_method = v || "" end |
+ (Object) quote_identifiers=(value)
Sets the default quote_identifiers mode for new databases. See Sequel.quote_identifiers=.
44 45 46 |
# File 'lib/sequel/database/dataset_defaults.rb', line 44 def self.quote_identifiers=(value) @@quote_identifiers = value end |
+ (Object) set_adapter_scheme(scheme)
Sets the adapter scheme for the Database class. Call this method in descendants of Database to allow connection using a URL. For example the following:
class Sequel::MyDB::Database < Sequel::Database
set_adapter_scheme :mydb
...
end
would allow connection using:
Sequel.connect('mydb://user:password@dbserver/mydb')
104 105 106 107 |
# File 'lib/sequel/database/connecting.rb', line 104 def self.set_adapter_scheme(scheme) # :nodoc: @scheme = scheme ADAPTER_MAP[scheme.to_sym] = self end |
+ (Object) single_threaded=(value)
Sets the default single_threaded mode for new databases. See Sequel.single_threaded=.
88 89 90 |
# File 'lib/sequel/database/connecting.rb', line 88 def self.single_threaded=(value) @@single_threaded = value end |
+ (Object) uri_to_options(uri)
Converts a uri to an options hash. These options are then passed to a newly created database object.
10 11 12 13 14 15 16 |
# File 'lib/sequel/database/misc.rb', line 10 def self.(uri) { :user => uri.user, :password => uri.password, :host => uri.host, :port => uri.port, :database => (m = /\/(.*)/.match(uri.path)) && (m[1]) } end |
Instance Method Details
- (Object) <<(sql)
Runs the supplied SQL statement string on the database server. Returns self so it can be safely chained:
DB << "UPDATE albums SET artist_id = NULL" << "DROP TABLE artists"
43 44 45 46 |
# File 'lib/sequel/database/query.rb', line 43 def <<(sql) run(sql) self end |
- (Object) [](*args)
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"
19 20 21 |
# File 'lib/sequel/database/dataset.rb', line 19 def [](*args) (String === args.first) ? fetch(*args) : from(*args) end |
- (Object) adapter_scheme
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
120 121 122 |
# File 'lib/sequel/database/connecting.rb', line 120 def adapter_scheme self.class.adapter_scheme end |
- (Object) add_column(table, *args)
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.
33 34 35 |
# File 'lib/sequel/database/schema_methods.rb', line 33 def add_column(table, *args) alter_table(table) {add_column(*args)} end |
- (Object) add_index(table, columns, options = {})
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.
46 47 48 49 50 51 52 53 |
# File 'lib/sequel/database/schema_methods.rb', line 46 def add_index(table, columns, ={}) e = [:ignore_errors] begin alter_table(table){add_index(columns, )} rescue DatabaseError raise unless e end end |
- (Object) add_servers(servers)
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"})
133 134 135 136 |
# File 'lib/sequel/database/connecting.rb', line 133 def add_servers(servers) @opts[:servers] = @opts[:servers] ? @opts[:servers].merge(servers) : servers @pool.add_servers(servers.keys) end |
- (Object) after_commit(opts = {}, &block)
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. |
74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/sequel/database/misc.rb', line 74 def after_commit(opts={}, &block) raise Error, "must provide block to after_commit" unless block synchronize(opts[:server]) do |conn| if h = @transactions[conn] raise Error, "cannot call after_commit in a prepared transaction" if h[:prepare] (h[:after_commit] ||= []) << block else yield end end end |
- (Object) after_rollback(opts = {}, &block)
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. |
91 92 93 94 95 96 97 98 99 |
# File 'lib/sequel/database/misc.rb', line 91 def after_rollback(opts={}, &block) raise Error, "must provide block to after_rollback" unless block synchronize(opts[:server]) do |conn| if h = @transactions[conn] raise Error, "cannot call after_rollback in a prepared transaction" if h[:prepare] (h[:after_rollback] ||= []) << block end end end |
- (Object) alter_table(name, generator = nil, &block)
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.
72 73 74 75 76 77 |
# File 'lib/sequel/database/schema_methods.rb', line 72 def alter_table(name, generator=nil, &block) generator ||= Schema::AlterTableGenerator.new(self, &block) remove_cached_schema(name) apply_alter_table(name, generator.operations) nil end |
- (Object) call(ps_name, hash = {})
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
53 54 55 |
# File 'lib/sequel/database/query.rb', line 53 def call(ps_name, hash={}) prepared_statements[ps_name].call(hash) end |
- (Object) cast_type_literal(type)
Cast the given type to a literal type
DB.cast_type_literal(Float) # double precision
DB.cast_type_literal(:foo) # foo
105 106 107 |
# File 'lib/sequel/database/misc.rb', line 105 def cast_type_literal(type) type_literal(:type=>type) end |
- (Object) commit_or_rollback_transaction(exception, conn, opts)
Whether to commit the current transaction. On ruby 1.9 and JRuby, transactions will be committed if Thread#kill is used on an thread that has a transaction open, and there isn't a work around.
402 403 404 405 406 407 408 409 |
# File 'lib/sequel/database/query.rb', line 402 def commit_or_rollback_transaction(exception, conn, opts) if exception false else commit_transaction(conn, opts) true end end |
- (Object) connect(server)
Connects to the database. This method should be overridden by descendants.
139 140 141 |
# File 'lib/sequel/database/connecting.rb', line 139 def connect(server) raise NotImplemented, "#connect should be overridden by adapters" end |
- (Object) create_or_replace_view(name, source)
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'))
130 131 132 133 134 135 |
# File 'lib/sequel/database/schema_methods.rb', line 130 def create_or_replace_view(name, source) source = source.sql if source.is_a?(Dataset) execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}") remove_cached_schema(name) nil end |
- (Object) create_table(name, options = {}, &block)
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.
93 94 95 96 97 98 99 100 |
# File 'lib/sequel/database/schema_methods.rb', line 93 def create_table(name, ={}, &block) remove_cached_schema(name) = {:generator=>} if .is_a?(Schema::Generator) generator = [:generator] || Schema::Generator.new(self, &block) create_table_from_generator(name, generator, ) create_table_indexes_from_generator(name, generator, ) nil end |
- (Object) create_table!(name, options = {}, &block)
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)
108 109 110 111 |
# File 'lib/sequel/database/schema_methods.rb', line 108 def create_table!(name, ={}, &block) drop_table?(name) create_table(name, , &block) end |
- (Boolean) create_table?(name, options = {}, &block)
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
118 119 120 121 122 123 124 |
# File 'lib/sequel/database/schema_methods.rb', line 118 def create_table?(name, ={}, &block) if supports_create_table_if_not_exists? create_table(name, .merge(:if_not_exists=>true), &block) elsif !table_exists?(name) create_table(name, , &block) end end |
- (Object) create_view(name, source)
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'))
141 142 143 144 |
# File 'lib/sequel/database/schema_methods.rb', line 141 def create_view(name, source) source = source.sql if source.is_a?(Dataset) execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}") end |
- (Object) database_type
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
152 153 154 |
# File 'lib/sequel/database/connecting.rb', line 152 def database_type adapter_scheme end |
- (Object) dataset(opts = nil)
Returns a blank dataset for this database.
DB.dataset # SELECT *
DB.dataset.from(:items) # SELECT * FROM items
27 28 29 |
# File 'lib/sequel/database/dataset.rb', line 27 def dataset(opts=nil) @dataset_class.new(self, opts) end |
- (Object) disconnect(opts = {})
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
166 167 168 |
# File 'lib/sequel/database/connecting.rb', line 166 def disconnect(opts = {}) pool.disconnect(opts) end |
- (Object) drop_column(table, *args)
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table.
151 152 153 |
# File 'lib/sequel/database/schema_methods.rb', line 151 def drop_column(table, *args) alter_table(table) {drop_column(*args)} end |
- (Object) drop_index(table, columns, options = {})
Removes an index for the given table and column/s:
DB.drop_index :posts, :title
DB.drop_index :posts, [:author, :title]
See alter_table.
161 162 163 |
# File 'lib/sequel/database/schema_methods.rb', line 161 def drop_index(table, columns, ={}) alter_table(table){drop_index(columns, )} end |
- (Object) drop_table(*names)
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)
170 171 172 173 174 175 176 177 |
# File 'lib/sequel/database/schema_methods.rb', line 170 def drop_table(*names) = names.last.is_a?(Hash) ? names.pop : {} names.each do |n| execute_ddl(drop_table_sql(n, )) remove_cached_schema(n) end nil end |
- (Boolean) drop_table?(*names)
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
185 186 187 188 189 190 191 192 193 194 195 196 197 |
# File 'lib/sequel/database/schema_methods.rb', line 185 def drop_table?(*names) = names.last.is_a?(Hash) ? names.pop : {} if supports_drop_table_if_exists? = .merge(:if_exists=>true) names.each do |name| drop_table(name, ) end else names.each do |name| drop_table(name, ) if table_exists?(name) end end end |
- (Object) drop_view(*names)
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)
204 205 206 207 208 209 210 211 |
# File 'lib/sequel/database/schema_methods.rb', line 204 def drop_view(*names) = names.last.is_a?(Hash) ? names.pop : {} names.each do |n| execute_ddl(drop_view_sql(n, )) remove_cached_schema(n) end nil end |
- (Object) dump_indexes_migration(options = {})
Dump indexes for all tables as a migration. This complements the :indexes=>false option to dump_schema_migration. Options:
-
:same_db - Create a dump for the same database type, so don't ignore errors if the index statements fail.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/sequel/extensions/schema_dumper.rb', line 13 def dump_indexes_migration(={}) ts = tables() <<END_MIG Sequel.migration do up do #{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :add_index, )}.reject{|x| x == ''}.join("\n\n").gsub(/^/o, ' ')} end down do #{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :drop_index, )}.reject{|x| x == ''}.join("\n\n").gsub(/^/o, ' ')} end end END_MIG end |
- (Object) dump_schema_migration(options = {})
Return a string that contains a Sequel::Migration subclass that when run would recreate the database structure. Options:
-
:same_db - Don't attempt to translate database types to ruby types. If this isn't set to true, all database types will be translated to ruby types, but there is no guarantee that the migration generated will yield the same type. Without this set, types that aren't recognized will be translated to a string-like type.
-
:indexes - If set to false, don't dump indexes (they can be added later via dump_index_migration).
37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/sequel/extensions/schema_dumper.rb', line 37 def dump_schema_migration(={}) ts = tables() <<END_MIG Sequel.migration do up do #{ts.sort_by{|t| t.to_s}.map{|t| dump_table_schema(t, )}.join("\n\n").gsub(/^/o, ' ')} end down do drop_table(#{ts.sort_by{|t| t.to_s}.inspect[1...-1]}) end end END_MIG end |
- (Object) dump_table_schema(table, options = {})
Return a string with a create table block that will recreate the given table's schema. Takes the same options as dump_schema_migration.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/sequel/extensions/schema_dumper.rb', line 54 def dump_table_schema(table, ={}) table = table.value.to_s if table.is_a?(SQL::Identifier) raise(Error, "must provide table as a Symbol, String, or Sequel::SQL::Identifier") unless [String, Symbol].any?{|c| table.is_a?(c)} s = schema(table).dup pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first} = .merge(:single_pk=>true) if pks.length == 1 m = method(:column_schema_to_generator_opts) im = method(:index_to_generator_opts) begin indexes = indexes(table).sort_by{|k,v| k.to_s} if [:indexes] != false rescue Sequel::NotImplemented nil end gen = Schema::Generator.new(self) do s.each{|name, info| send(*m.call(name, info, ))} primary_key(pks) if !@primary_key && pks.length > 0 indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts))} if indexes end commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n") "create_table(#{table.inspect}#{', :ignore_index_errors=>true' if ![:same_db] && [:indexes] != false && indexes && !indexes.empty?}) do\n#{commands.gsub(/^/o, ' ')}\nend" end |
- (Object) each_server(&block)
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}}
175 176 177 |
# File 'lib/sequel/database/connecting.rb', line 175 def each_server(&block) servers.each{|s| self.class.connect(server_opts(s), &block)} end |
- (Object) execute(sql, opts = {})
Executes the given SQL on the database. This method should be overridden in descendants. This method should not be called directly by user code.
59 60 61 |
# File 'lib/sequel/database/query.rb', line 59 def execute(sql, opts={}) raise NotImplemented, "#execute should be overridden by adapters" end |
- (Object) execute_ddl(sql, opts = {}, &block)
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.
66 67 68 |
# File 'lib/sequel/database/query.rb', line 66 def execute_ddl(sql, opts={}, &block) execute_dui(sql, opts, &block) end |
- (Object) execute_dui(sql, opts = {}, &block)
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.
73 74 75 |
# File 'lib/sequel/database/query.rb', line 73 def execute_dui(sql, opts={}, &block) execute(sql, opts, &block) end |
- (Object) execute_insert(sql, opts = {}, &block)
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.
80 81 82 |
# File 'lib/sequel/database/query.rb', line 80 def execute_insert(sql, opts={}, &block) execute_dui(sql, opts, &block) end |
- (Object) extend_datasets(mod = nil, &block)
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
89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/sequel/database/dataset_defaults.rb', line 89 def extend_datasets(mod=nil, &block) raise(Error, "must provide either mod or block, not both") if mod && block reset_schema_utility_dataset mod = Module.new(&block) if block if @dataset_modules.empty? @dataset_modules = [mod] @dataset_class = Class.new(@dataset_class) else @dataset_modules << mod end @dataset_class.send(:include, mod) end |
- (Object) fetch(sql, *args, &block)
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
44 45 46 47 48 |
# File 'lib/sequel/database/dataset.rb', line 44 def fetch(sql, *args, &block) ds = dataset.with_sql(sql, *args) ds.each(&block) if block ds end |
- (Object) from(*args, &block)
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)
55 56 57 58 |
# File 'lib/sequel/database/dataset.rb', line 55 def from(*args, &block) ds = dataset.from(*args) block ? ds.filter(&block) : ds end |
- (Object) from_application_timestamp(v)
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.
112 113 114 |
# File 'lib/sequel/database/misc.rb', line 112 def (v) Sequel.(v, timezone) end |
- (Object) get(*args, &block)
Returns a single value from the database, e.g.:
DB.get(1) # SELECT 1
# => 1
DB.get{server_version{}} # SELECT server_version()
89 90 91 |
# File 'lib/sequel/database/query.rb', line 89 def get(*args, &block) dataset.get(*args, &block) end |
- (Object) identifier_input_method
The method to call on identifiers going into the database
103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/sequel/database/dataset_defaults.rb', line 103 def identifier_input_method case @identifier_input_method when nil @identifier_input_method = @opts.fetch(:identifier_input_method, (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method)) @identifier_input_method == "" ? nil : @identifier_input_method when "" nil else @identifier_input_method end end |
- (Object) identifier_input_method=(v)
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
120 121 122 123 |
# File 'lib/sequel/database/dataset_defaults.rb', line 120 def identifier_input_method=(v) reset_schema_utility_dataset @identifier_input_method = v || "" end |
- (Object) identifier_output_method
The method to call on identifiers coming from the database
126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/sequel/database/dataset_defaults.rb', line 126 def identifier_output_method case @identifier_output_method when nil @identifier_output_method = @opts.fetch(:identifier_output_method, (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method)) @identifier_output_method == "" ? nil : @identifier_output_method when "" nil else @identifier_output_method end end |
- (Object) identifier_output_method=(v)
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'}
143 144 145 146 |
# File 'lib/sequel/database/dataset_defaults.rb', line 143 def identifier_output_method=(v) reset_schema_utility_dataset @identifier_output_method = v || "" end |
- (Boolean) in_transaction?(opts = {})
Return true if already in a transaction given the options, false otherwise. Respects the :server option for selecting a shard.
119 120 121 |
# File 'lib/sequel/database/misc.rb', line 119 def in_transaction?(opts={}) synchronize(opts[:server]){|conn| !!@transactions[conn]} end |
- (Object) indexes(table, opts = {})
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}}
102 103 104 |
# File 'lib/sequel/database/query.rb', line 102 def indexes(table, opts={}) raise NotImplemented, "#indexes should be overridden by adapters" end |
- (Object) inspect
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).
126 127 128 |
# File 'lib/sequel/database/misc.rb', line 126 def inspect "#<#{self.class}: #{(uri rescue opts).inspect}>" end |
- (Object) literal(v)
Proxy the literal call to the dataset.
DB.literal(1) # 1
DB.literal(:a) # a
DB.literal('a') # 'a'
135 136 137 |
# File 'lib/sequel/database/misc.rb', line 135 def literal(v) schema_utility_dataset.literal(v) end |
- (Object) log_info(message, args = nil)
Log a message at level info to all loggers.
21 22 23 |
# File 'lib/sequel/database/logging.rb', line 21 def log_info(, args=nil) log_each(:info, args ? "#{}; #{args.inspect}" : ) end |
- (Object) log_yield(sql, args = nil)
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.
27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/sequel/database/logging.rb', line 27 def log_yield(sql, args=nil) return yield if @loggers.empty? sql = "#{sql}; #{args.inspect}" if args start = Time.now begin yield rescue => e log_each(:error, "#{e.class}: #{e..strip}: #{sql}") raise ensure log_duration(Time.now - start, sql) unless e end end |
- (Object) logger=(logger)
Remove any existing loggers and just use the given logger:
DB.logger = Logger.new($stdout)
44 45 46 |
# File 'lib/sequel/database/logging.rb', line 44 def logger=(logger) @loggers = Array(logger) end |
- (Object) query(&block)
Return a dataset modified by the query block
8 9 10 |
# File 'lib/sequel/extensions/query.rb', line 8 def query(&block) dataset.query(&block) end |
- (Object) quote_identifiers=(v)
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"
153 154 155 156 |
# File 'lib/sequel/database/dataset_defaults.rb', line 153 def quote_identifiers=(v) reset_schema_utility_dataset @quote_identifiers = v end |
- (Boolean) quote_identifiers?
Returns true if the database quotes identifiers.
159 160 161 162 |
# File 'lib/sequel/database/dataset_defaults.rb', line 159 def quote_identifiers? return @quote_identifiers unless @quote_identifiers.nil? @quote_identifiers = @opts.fetch(:quote_identifiers, (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers)) end |
- (Object) remove_servers(*servers)
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)
189 190 191 192 193 194 195 196 197 |
# File 'lib/sequel/database/connecting.rb', line 189 def remove_servers(*servers) if @opts[:servers] && !@opts[:servers].empty? servs = @opts[:servers].dup servers.flatten! servers.each{|s| servs.delete(s)} @opts[:servers] = servs @pool.remove_servers(servers) end end |
- (Object) rename_column(table, *args)
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.
230 231 232 |
# File 'lib/sequel/database/schema_methods.rb', line 230 def rename_column(table, *args) alter_table(table) {rename_column(*args)} end |
- (Object) rename_table(name, new_name)
Renames a table:
DB.tables #=> [:items]
DB.rename_table :items, :old_items
DB.tables #=> [:old_items]
218 219 220 221 222 |
# File 'lib/sequel/database/schema_methods.rb', line 218 def rename_table(name, new_name) execute_ddl(rename_table_sql(name, new_name)) remove_cached_schema(name) nil end |
- (Object) run(sql, opts = {})
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")
111 112 113 114 |
# File 'lib/sequel/database/query.rb', line 111 def run(sql, opts={}) execute_ddl(sql, opts) nil end |
- (Object) schema(table, opts = {})
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}]]
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/sequel/database/query.rb', line 156 def schema(table, opts={}) raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true) opts = opts.dup if table.is_a?(Dataset) o = table.opts from = o[:from] raise(Error, "can only parse the schema for a dataset with a single from table") unless from && from.length == 1 && !o.include?(:join) && !o.include?(:sql) tab = table.first_source_table sch, table_name = schema_and_table(tab) quoted_name = table.literal(tab) opts[:dataset] = table else sch, table_name = schema_and_table(table) quoted_name = quote_schema_table(table) end opts[:schema] = sch if sch && !opts.include?(:schema) @schemas.delete(quoted_name) if opts[:reload] return @schemas[quoted_name] if @schemas[quoted_name] cols = schema_parse_table(table_name, opts) raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty? cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} @schemas[quoted_name] = cols end |
- (Object) select(*args, &block)
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
65 66 67 |
# File 'lib/sequel/database/dataset.rb', line 65 def select(*args, &block) dataset.select(*args, &block) end |
- (Object) serial_primary_key_options
Default serial primary key options, used by the table creation code.
141 142 143 |
# File 'lib/sequel/database/misc.rb', line 141 def {:primary_key => true, :type => Integer, :auto_increment => true} end |
- (Object) servers
An array of servers/shards for this Database object.
DB.servers # Unsharded: => [:default]
DB.servers # Sharded: => [:default, :server1, :server2]
203 204 205 |
# File 'lib/sequel/database/connecting.rb', line 203 def servers pool.servers end |
- (Object) set_column_default(table, *args)
Sets the default value for the given column in the given table:
DB.set_column_default :items, :category, 'perl!'
See alter_table.
239 240 241 |
# File 'lib/sequel/database/schema_methods.rb', line 239 def set_column_default(table, *args) alter_table(table) {set_column_default(*args)} end |
- (Object) set_column_type(table, *args)
Set the data type for the given column in the given table:
DB.set_column_type :items, :price, :float
See alter_table.
248 249 250 |
# File 'lib/sequel/database/schema_methods.rb', line 248 def set_column_type(table, *args) alter_table(table) {set_column_type(*args)} end |
- (Boolean) single_threaded?
Returns true if the database is using a single-threaded connection pool.
208 209 210 |
# File 'lib/sequel/database/connecting.rb', line 208 def single_threaded? @single_threaded end |
- (Boolean) supports_create_table_if_not_exists?
Whether the database supports CREATE TABLE IF NOT EXISTS syntax, false by default.
147 148 149 |
# File 'lib/sequel/database/misc.rb', line 147 def supports_create_table_if_not_exists? false end |
- (Boolean) supports_drop_table_if_exists?
Whether the database supports DROP TABLE IF EXISTS syntax, default is the same as #supports_create_table_if_not_exists?.
153 154 155 |
# File 'lib/sequel/database/misc.rb', line 153 def supports_drop_table_if_exists? supports_create_table_if_not_exists? end |
- (Boolean) supports_prepared_transactions?
Whether the database and adapter support prepared transactions (two-phase commit), false by default.
159 160 161 |
# File 'lib/sequel/database/misc.rb', line 159 def supports_prepared_transactions? false end |
- (Boolean) supports_savepoints?
Whether the database and adapter support savepoints, false by default.
164 165 166 |
# File 'lib/sequel/database/misc.rb', line 164 def supports_savepoints? false end |
- (Boolean) supports_savepoints_in_prepared_transactions?
Whether the database and adapter support savepoints inside prepared transactions (two-phase commit), default is false.
170 171 172 |
# File 'lib/sequel/database/misc.rb', line 170 def supports_savepoints_in_prepared_transactions? supports_prepared_transactions? && supports_savepoints? end |
- (Boolean) supports_transaction_isolation_levels?
Whether the database and adapter support transaction isolation levels, false by default.
175 176 177 |
# File 'lib/sequel/database/misc.rb', line 175 def supports_transaction_isolation_levels? false end |
- (Object) synchronize(server = nil, &block)
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
224 225 226 |
# File 'lib/sequel/database/connecting.rb', line 224 def synchronize(server=nil, &block) @pool.hold(server || :default, &block) end |
- (Boolean) table_exists?(name)
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.
191 192 193 194 195 196 197 198 |
# File 'lib/sequel/database/query.rb', line 191 def table_exists?(name) sch, table_name = schema_and_table(name) name = SQL::QualifiedIdentifier.new(sch, table_name) if sch _table_exists?(from(name)) true rescue DatabaseError false end |
- (Object) tables(opts = {})
Return all tables in the database as an array of symbols.
DB.tables # => [:albums, :artists]
203 204 205 |
# File 'lib/sequel/database/query.rb', line 203 def tables(opts={}) raise NotImplemented, "#tables should be overridden by adapters" end |
- (Object) test_connection(server = nil)
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.
232 233 234 235 |
# File 'lib/sequel/database/connecting.rb', line 232 def test_connection(server=nil) synchronize(server){|conn|} true end |
- (Object) to_application_timestamp(v)
Convert the given timestamp to the application's timezone, from the databases's timezone or the default database timezone if the database does not have a timezone.
187 188 189 |
# File 'lib/sequel/database/misc.rb', line 187 def (v) Sequel.(v, timezone) end |
- (Object) transaction(opts = {}, &block)
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. |
228 229 230 231 232 233 |
# File 'lib/sequel/database/query.rb', line 228 def transaction(opts={}, &block) synchronize(opts[:server]) do |conn| return yield(conn) if already_in_transaction?(conn, opts) _transaction(conn, opts, &block) end end |
- (Object) typecast_value(column_type, value)
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.
196 197 198 199 200 201 202 203 204 |
# File 'lib/sequel/database/misc.rb', line 196 def typecast_value(column_type, value) return nil if value.nil? meth = "typecast_value_#{column_type}" begin respond_to?(meth, true) ? send(meth, value) : value rescue ArgumentError, TypeError => e raise Sequel.convert_exception_class(e, InvalidValue) end end |
- (Object) typecast_value_integer(value)
Typecast the value to an Integer
334 335 336 |
# File 'lib/sequel/database/misc.rb', line 334 def typecast_value_integer(value) Integer(value.is_a?(String) ? value.sub(LEADING_ZERO_RE, LEADING_ZERO_REP) : value) end |
- (Object) uri
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"
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
# File 'lib/sequel/database/misc.rb', line 214 def uri uri = URI::Generic.new( adapter_scheme.to_s, nil, @opts[:host], @opts[:port], nil, "/#{@opts[:database]}", nil, nil, nil ) uri.user = @opts[:user] uri.password = @opts[:password] if uri.user uri.to_s end |
- (Object) url
Explicit alias of uri for easier subclassing.
232 233 234 |
# File 'lib/sequel/database/misc.rb', line 232 def url uri end |
- (Object) views(opts = {})
Return all views in the database as an array of symbols.
DB.views # => [:gold_albums, :artists_with_many_albums]
238 239 240 |
# File 'lib/sequel/database/query.rb', line 238 def views(opts={}) raise NotImplemented, "#views should be overridden by adapters" end |