Class Sequel::Database

  1. lib/sequel/database.rb
  2. lib/sequel/database/schema_methods.rb
  3. lib/sequel/database/schema_sql.rb
  4. show all
Parent: Object

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.

Included modules

  1. Metaprogramming

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

adapter_class (scheme)

The Database subclass for the given adapter scheme. Raises Sequel::AdapterNotFound if the adapter could not be loaded.

[show source]
     # 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
adapter_scheme ()

Returns the scheme for the Database class.

[show source]
     # File lib/sequel/database.rb, line 127
127:     def self.adapter_scheme
128:       @scheme
129:     end
connect (conn_string, opts = {}) {|db = c.new(opts)| ...}

Connects to a database. See Sequel.connect.

[show source]
     # 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
identifier_input_method ()

The method to call on identifiers going into the database

[show source]
     # File lib/sequel/database.rb, line 174
174:     def self.identifier_input_method
175:       @@identifier_input_method
176:     end
identifier_input_method= (v)

Set the method to call on identifiers going into the database See Sequel.identifier_input_method=.

[show source]
     # File lib/sequel/database.rb, line 180
180:     def self.identifier_input_method=(v)
181:       @@identifier_input_method = v || ""
182:     end
identifier_output_method ()

The method to call on identifiers coming from the database

[show source]
     # File lib/sequel/database.rb, line 185
185:     def self.identifier_output_method
186:       @@identifier_output_method
187:     end
identifier_output_method= (v)

Set the method to call on identifiers coming from the database See Sequel.identifier_output_method=.

[show source]
     # File lib/sequel/database.rb, line 191
191:     def self.identifier_output_method=(v)
192:       @@identifier_output_method = v || ""
193:     end
new (opts = {}, &block)

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.

[show source]
     # 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
quote_identifiers= (value)

Sets the default quote_identifiers mode for new databases. See Sequel.quote_identifiers=.

[show source]
     # File lib/sequel/database.rb, line 197
197:     def self.quote_identifiers=(value)
198:       @@quote_identifiers = value
199:     end
single_threaded= (value)

Sets the default single_threaded mode for new databases. See Sequel.single_threaded=.

[show source]
     # File lib/sequel/database.rb, line 203
203:     def self.single_threaded=(value)
204:       @@single_threaded = value
205:     end

Public instance methods

<< (sql)

Runs the supplied SQL statement string on the database server. Alias for run.

[show source]
     # File lib/sequel/database.rb, line 242
242:     def <<(sql)
243:       run(sql)
244:     end
[] (*args)

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"
[show source]
     # File lib/sequel/database.rb, line 256
256:     def [](*args)
257:       (String === args.first) ? fetch(*args) : from(*args)
258:     end
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.

[show source]
    # File lib/sequel/database/schema_methods.rb, line 10
10:     def add_column(table, *args)
11:       alter_table(table) {add_column(*args)}
12:     end
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.

[show source]
    # 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
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"})
[show source]
     # 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
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.

[show source]
    # 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 (ps_name, hash={})

Call the prepared statement with the given name with the given hash of arguments.

[show source]
     # File lib/sequel/database.rb, line 276
276:     def call(ps_name, hash={})
277:       prepared_statements[ps_name].call(hash)
278:     end
cast_type_literal (type)

Cast the given type to a literal type

[show source]
     # File lib/sequel/database.rb, line 281
281:     def cast_type_literal(type)
282:       type_literal(:type=>type)
283:     end
connect (server)

Connects to the database. This method should be overridden by descendants.

[show source]
     # File lib/sequel/database.rb, line 286
286:     def connect(server)
287:       raise NotImplementedError, "#connect should be overridden by adapters"
288:     end
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'))
[show source]
    # 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
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.

[show source]
    # 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
create_table! (name, options={}, &block)

Forcibly creates a table, attempting to drop it unconditionally (and catching any errors), then creating it.

[show source]
    # 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
create_table? (name, options={}, &block)

Creates the table unless the table already exists

[show source]
    # 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
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'))
[show source]
     # 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
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).

[show source]
     # File lib/sequel/database.rb, line 297
297:     def database_type
298:       self.class.adapter_scheme
299:     end
dataset ()

Returns a blank dataset for this database

[show source]
     # File lib/sequel/database.rb, line 302
302:     def dataset
303:       ds = Sequel::Dataset.new(self)
304:     end
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.
[show source]
     # File lib/sequel/database.rb, line 310
310:     def disconnect(opts = {})
311:       pool.disconnect(opts)
312:     end
drop_column (table, *args)

Removes a column from the specified table:

  DB.drop_column :items, :category

See alter_table.

[show source]
     # File lib/sequel/database/schema_methods.rb, line 112
112:     def drop_column(table, *args)
113:       alter_table(table) {drop_column(*args)}
114:     end
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.

[show source]
     # 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
drop_table (*names)

Drops one or more tables corresponding to the given names:

  DB.drop_table(:posts, :comments)
[show source]
     # 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
drop_view (*names)

Drops one or more views corresponding to the given names:

  DB.drop_view(:cheap_items)
[show source]
     # 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
each_server (&block)

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}}
[show source]
     # 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
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.

[show source]
     # File lib/sequel/database.rb, line 325
325:     def execute(sql, opts={})
326:       raise NotImplementedError, "#execute should be overridden by adapters"
327:     end
execute_ddl (sql, opts={}, &block)

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.

[show source]
     # File lib/sequel/database.rb, line 332
332:     def execute_ddl(sql, opts={}, &block)
333:       execute_dui(sql, opts, &block)
334:     end
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.

[show source]
     # File lib/sequel/database.rb, line 339
339:     def execute_dui(sql, opts={}, &block)
340:       execute(sql, opts, &block)
341:     end
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.

[show source]
     # File lib/sequel/database.rb, line 346
346:     def execute_insert(sql, opts={}, &block)
347:       execute_dui(sql, opts, &block)
348:     end
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 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
[show source]
     # 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
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.

[show source]
     # 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
get (*args, &block)

Returns a single value from the database, e.g.:

  # SELECT 1
  DB.get(1) #=> 1

  # SELECT version()
  DB.get(:version.sql_function) #=> ...
[show source]
     # File lib/sequel/database.rb, line 383
383:     def get(*args, &block)
384:       dataset.get(*args, &block)
385:     end
identifier_input_method ()

The method to call on identifiers going into the database

[show source]
     # 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
identifier_input_method= (v)

Set the method to call on identifiers going into the database

[show source]
     # 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
identifier_output_method ()

The method to call on identifiers coming from the database

[show source]
     # 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
identifier_output_method= (v)

Set the method to call on identifiers coming from the database

[show source]
     # 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
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).

[show source]
     # File lib/sequel/database.rb, line 428
428:     def inspect
429:       "#<#{self.class}: #{(uri rescue opts).inspect}>" 
430:     end
literal (v)

Proxy the literal call to the dataset, used for default values.

[show source]
     # File lib/sequel/database.rb, line 433
433:     def literal(v)
434:       schema_utility_dataset.literal(v)
435:     end
log_info (message, args=nil)

Log a message at level info to all loggers. All SQL logging goes through this method.

[show source]
     # 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
logger= (logger)

Remove any existing loggers and just use the given logger.

[show source]
     # File lib/sequel/database.rb, line 445
445:     def logger=(logger)
446:       @loggers = Array(logger)
447:     end
quote_identifiers= (v)

Whether to quote identifiers (columns and tables) for this database

[show source]
     # File lib/sequel/database.rb, line 450
450:     def quote_identifiers=(v)
451:       reset_schema_utility_dataset
452:       @quote_identifiers = v
453:     end
quote_identifiers? ()

Returns true if the database quotes identifiers.

[show source]
     # 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
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)
[show source]
     # 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
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.

[show source]
     # File lib/sequel/database/schema_methods.rb, line 162
162:     def rename_column(table, *args)
163:       alter_table(table) {rename_column(*args)}
164:     end
rename_table (name, new_name)

Renames a table:

  DB.tables #=> [:items]
  DB.rename_table :items, :old_items
  DB.tables #=> [:old_items]
[show source]
     # 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
run (sql, opts={})

Runs the supplied SQL statement string on the database server. Returns nil. Options:

  • :server - The server to run the SQL on.
[show source]
     # File lib/sequel/database.rb, line 484
484:     def run(sql, opts={})
485:       execute_ddl(sql, opts)
486:       nil
487:     end
schema (table, opts={})

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.
[show source]
     # 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
select (*args, &block)

Returns a new dataset with the select method invoked.

[show source]
     # File lib/sequel/database.rb, line 518
518:     def select(*args, &block)
519:       dataset.select(*args, &block)
520:     end
serial_primary_key_options ()

Default serial primary key options.

[show source]
    # 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
servers ()

An array of servers/shards for this Database object.

[show source]
     # File lib/sequel/database.rb, line 523
523:     def servers
524:       pool.servers
525:     end
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.

[show source]
     # 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_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.

[show source]
     # 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
single_threaded? ()

Returns true if the database is using a single-threaded connection pool.

[show source]
     # File lib/sequel/database.rb, line 528
528:     def single_threaded?
529:       @single_threaded
530:     end
supports_savepoints? ()

Whether the database and adapter support savepoints, false by default

[show source]
     # File lib/sequel/database.rb, line 538
538:     def supports_savepoints?
539:       false
540:     end
synchronize (server=nil, &block)

Acquires a database connection, yielding it to the passed block.

[show source]
     # File lib/sequel/database.rb, line 533
533:     def synchronize(server=nil, &block)
534:       @pool.hold(server || :default, &block)
535:     end
table_exists? (name)

Returns true if a table with the given name exists. This requires a query to the database.

[show source]
     # 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
test_connection (server=nil)

Attempts to acquire a database connection. Returns true if successful. Will probably raise an error if unsuccessful.

[show source]
     # File lib/sequel/database.rb, line 555
555:     def test_connection(server=nil)
556:       synchronize(server){|conn|}
557:       true
558:     end
transaction (opts={}) {|conn| ...}

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.
[show source]
     # 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_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.

[show source]
     # 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
uri ()

Returns the URI identifying the database. This method can raise an error if the database used options instead of a connection string.

[show source]
     # 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
url ()

Explicit alias of uri for easier subclassing.

[show source]
     # File lib/sequel/database.rb, line 614
614:     def url
615:       uri
616:     end