Class Sequel::Database
In: lib/sequel/extensions/query.rb
lib/sequel/adapters/do.rb
lib/sequel/adapters/jdbc.rb
lib/sequel/adapters/shared/mysql.rb
lib/sequel/database.rb
lib/sequel/database/schema_methods.rb
lib/sequel/database/schema_sql.rb
lib/sequel/deprecated.rb
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.

Methods

Included Modules

Metaprogramming

Constants

ADAPTERS = %w'ado 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_ROLLBACK = 'ROLLBACK'.freeze
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
TYPES = Hash.new {|h, k| k}
UNDERSCORE = '_'.freeze
UNIQUE = ' UNIQUE'.freeze
UNSIGNED = ' UNSIGNED'.freeze

External Aliases

column_references_sql -> default_column_references_sql
  Keep default column_references_sql for add_foreign_key support

Attributes

converted_exceptions  [RW]  Convert the given exceptions to Sequel:Errors, necessary because DO raises errors specific to database types in certain cases.
database_type  [R]  The type of database we are connecting to
default_schema  [RW]  The default schema to use, generally should be nil.
loggers  [RW]  Array of SQL loggers to use for this database
opts  [R]  The options for this database
pool  [R]  The connection pool for this database
prepared_statements  [R]  The prepared statement objects for this database, keyed by name

Public Class methods

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

[Source]

     # File lib/sequel/database.rb, line 97
 97:     def self.adapter_class(scheme)
 98:       scheme = scheme.to_s.gsub('-', '_').to_sym
 99:       
100:       unless klass = ADAPTER_MAP[scheme]
101:         # attempt to load the adapter file
102:         begin
103:           Sequel.require "adapters/#{scheme}"
104:         rescue LoadError => e
105:           raise AdapterNotFound, "Could not load #{scheme} adapter:\n  #{e.message}"
106:         end
107:         
108:         # make sure we actually loaded the adapter
109:         unless klass = ADAPTER_MAP[scheme]
110:           raise AdapterNotFound, "Could not load #{scheme} adapter"
111:         end
112:       end
113:       klass
114:     end

Returns the scheme for the Database class.

[Source]

     # File lib/sequel/database.rb, line 117
117:     def self.adapter_scheme
118:       @scheme
119:     end

Connects to a database. See Sequel.connect.

[Source]

     # File lib/sequel/database.rb, line 122
122:     def self.connect(conn_string, opts = {}, &block)
123:       if conn_string.is_a?(String)
124:         if match = /\A(jdbc|do):/o.match(conn_string)
125:           c = adapter_class(match[1].to_sym)
126:           opts = {:uri=>conn_string}.merge(opts)
127:         else
128:           uri = URI.parse(conn_string)
129:           scheme = uri.scheme
130:           scheme = :dbi if scheme =~ /\Adbi-/
131:           c = adapter_class(scheme)
132:           uri_options = {}
133:           uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v} unless uri.query.to_s.strip.empty?
134:           opts = c.send(:uri_to_options, uri).merge(uri_options).merge(opts)
135:         end
136:       else
137:         opts = conn_string.merge(opts)
138:         c = adapter_class(opts[:adapter] || opts['adapter'])
139:       end
140:       # process opts a bit
141:       opts = opts.inject({}) do |m, kv| k, v = *kv
142:         k = :user if k.to_s == 'username'
143:         m[k.to_sym] = v
144:         m
145:       end
146:       if block
147:         begin
148:           yield(db = c.new(opts))
149:         ensure
150:           db.disconnect if db
151:           ::Sequel::DATABASES.delete(db)
152:         end
153:         nil
154:       else
155:         c.new(opts)
156:       end
157:     end

The method to call on identifiers going into the database

[Source]

     # File lib/sequel/database.rb, line 160
160:     def self.identifier_input_method
161:       @@identifier_input_method
162:     end

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

[Source]

     # File lib/sequel/database.rb, line 166
166:     def self.identifier_input_method=(v)
167:       @@identifier_input_method = v || ""
168:     end

The method to call on identifiers coming from the database

[Source]

     # File lib/sequel/database.rb, line 171
171:     def self.identifier_output_method
172:       @@identifier_output_method
173:     end

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

[Source]

     # File lib/sequel/database.rb, line 177
177:     def self.identifier_output_method=(v)
178:       @@identifier_output_method = v || ""
179:     end

Call the DATABASE_SETUP proc directly after initialization, so the object always uses sub adapter specific code. Also, raise an error immediately if the connection doesn‘t have a uri, since JDBC requires one.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 95
 95:       def initialize(opts)
 96:         @opts = opts
 97:         raise(Error, "No connection string specified") unless uri
 98:         if match = /\Ajdbc:([^:]+)/.match(uri) and prok = DATABASE_SETUP[match[1].to_sym]
 99:           prok.call(self)
100:         end
101:         super(opts)
102:       end

Constructs a new instance of a database connection with the specified options hash.

Sequel::Database is an abstract class that is not useful by itself.

Takes the following options:

  • :default_schema : The default schema to use, should generally be nil
  • :disconnection_proc: A proc used to disconnect the connection.
  • :identifier_input_method: A string method symbol to call on identifiers going into the database
  • :identifier_output_method: A string method symbol to call on identifiers coming from the database
  • :loggers : An array of loggers to use.
  • :quote_identifiers : Whether to quote identifiers
  • :single_threaded : Whether to use a single-threaded connection pool

All options given are also passed to the ConnectionPool. If a block is given, it is used as the connection_proc for the ConnectionPool.

[Source]

    # File lib/sequel/database.rb, line 69
69:     def initialize(opts = {}, &block)
70:       @opts ||= opts
71:       
72:       @single_threaded = opts.include?(:single_threaded) ? opts[:single_threaded] : @@single_threaded
73:       @schemas = nil
74:       @default_schema = opts.include?(:default_schema) ? opts[:default_schema] : default_schema_default
75:       @prepared_statements = {}
76:       @transactions = []
77:       @identifier_input_method = nil
78:       @identifier_output_method = nil
79:       @quote_identifiers = nil
80:       if opts.include?(:upcase_identifiers)
81:         Deprecation.deprecate('The :upcase_identifiers Database option', 'Use the :identifier_input_method => :upcase option instead')
82:         @identifier_input_method = opts[:upcase_identifiers] ? :upcase : ""
83:       end
84:       @pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(connection_pool_default_options.merge(opts), &block)
85:       @pool.connection_proc = proc{|server| connect(server)} unless block
86:       @pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc]
87: 
88:       @loggers = Array(opts[:logger]) + Array(opts[:loggers])
89:       ::Sequel::DATABASES.push(self)
90:     end

Call the DATABASE_SETUP proc directly after initialization, so the object always uses sub adapter specific code. Also, raise an error immediately if the connection doesn‘t have a uri, since DataObjects requires one.

[Source]

    # File lib/sequel/adapters/do.rb, line 53
53:       def initialize(opts)
54:         @opts = opts
55:         @converted_exceptions = []
56:         raise(Error, "No connection string specified") unless uri
57:         if prok = DATABASE_SETUP[subadapter.to_sym]
58:           prok.call(self)
59:         end
60:         super(opts)
61:       end

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

[Source]

     # File lib/sequel/database.rb, line 183
183:     def self.quote_identifiers=(value)
184:       @@quote_identifiers = value
185:     end

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

[Source]

     # File lib/sequel/database.rb, line 189
189:     def self.single_threaded=(value)
190:       @@single_threaded = value
191:     end

[Source]

    # File lib/sequel/deprecated.rb, line 66
66:     def self.upcase_identifiers=(value)
67:       Deprecation.deprecate('Sequel::Database.upcase_identifiers=', 'Use Sequel::Database.identifier_input_method = :upcase or nil')
68:       self.identifier_input_method = value ? :upcase : nil
69:     end

Public Instance methods

Executes the supplied SQL statement string.

[Source]

     # File lib/sequel/database.rb, line 227
227:     def <<(sql)
228:       Deprecation.deprecate('Passing an array argument to Database#<<', 'Use array.each{|x| database << x}') if Array === sql
229:       execute_ddl((Array === sql) ? sql.to_sql : sql)
230:     end

[Source]

    # File lib/sequel/deprecated.rb, line 81
81:     def >>(*args, &block)
82:       Deprecation.deprecate('Sequel::Database#>>', 'Use Sequel::Database#fetch')
83:       fetch(*args, &block)
84:     end

Returns a dataset from the database. If the first argument is a string, the method acts as an alias for Database#fetch, returning a dataset for arbitrary SQL:

  DB['SELECT * FROM items WHERE name = ?', my_name].all

Otherwise, acts as an alias for Database#from, setting the primary table for the dataset:

  DB[:items].sql #=> "SELECT * FROM items"

[Source]

     # File lib/sequel/database.rb, line 242
242:     def [](*args)
243:       (String === args.first) ? fetch(*args) : from(*args)
244:     end

Adds a column to the specified table. This method expects a column name, a datatype and optionally a hash with additional constraints and options:

  DB.add_column :items, :name, :text, :unique => true, :null => false
  DB.add_column :items, :category, :text, :default => 'ruby'

See alter_table.

[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

Adds an index to a table for the given columns:

  DB.add_index :posts, :title
  DB.add_index :posts, [:author, :title], :unique => true

See alter_table.

[Source]

    # File lib/sequel/database/schema_methods.rb, line 20
20:     def add_index(table, *args)
21:       alter_table(table) {add_index(*args)}
22:     end

Alters the given table with the specified block. Example:

  DB.alter_table :items do
    add_column :category, :text, :default => 'ruby'
    drop_column :category
    rename_column :cntr, :counter
    set_column_type :value, :float
    set_column_default :value, :float
    add_index [:group, :category]
    drop_index [:group, :category]
  end

Note that add_column accepts all the options available for column definitions using create_table, and add_index accepts all the options available for index definition.

See Schema::AlterTableGenerator.

[Source]

    # File lib/sequel/database/schema_methods.rb, line 41
41:     def alter_table(name, generator=nil, &block)
42:       remove_cached_schema(name)
43:       generator ||= Schema::AlterTableGenerator.new(self, &block)
44:       alter_table_sql_list(name, generator.operations).flatten.each {|sql| execute_ddl(sql)}
45:     end

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

[Source]

     # File lib/sequel/database.rb, line 248
248:     def call(ps_name, hash={})
249:       prepared_statements[ps_name].call(hash)
250:     end

Execute the given stored procedure with the give name. If a block is given, the stored procedure should return rows.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 106
106:       def call_sproc(name, opts = {})
107:         args = opts[:args] || []
108:         sql = "{call #{name}(#{args.map{'?'}.join(',')})}"
109:         synchronize(opts[:server]) do |conn|
110:           cps = conn.prepareCall(sql)
111: 
112:           i = 0
113:           args.each{|arg| set_ps_arg(cps, arg, i+=1)}
114: 
115:           begin
116:             if block_given?
117:               yield cps.executeQuery
118:             else
119:               case opts[:type]
120:               when :insert
121:                 cps.executeUpdate
122:                 last_insert_id(conn, opts)
123:               else
124:                 cps.executeUpdate
125:               end
126:             end
127:           rescue NativeException, JavaSQL::SQLException => e
128:             raise_error(e)
129:           ensure
130:             cps.close
131:           end
132:         end
133:       end

Setup a DataObjects::Connection to the database.

[Source]

    # File lib/sequel/adapters/do.rb, line 64
64:       def connect(server)
65:         setup_connection(::DataObjects::Connection.new(uri(server_opts(server))))
66:       end

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

[Source]

     # File lib/sequel/database.rb, line 253
253:     def connect
254:       raise NotImplementedError, "#connect should be overridden by adapters"
255:     end

Connect to the database using JavaSQL::DriverManager.getConnection.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 136
136:       def connect(server)
137:         setup_connection(JavaSQL::DriverManager.getConnection(uri(server_opts(server))))
138:       end

Creates a view, replacing it if it already exists:

  DB.create_or_replace_view(:cheap_items, "SELECT * FROM items WHERE price < 100")
  DB.create_or_replace_view(:ruby_items, DB[:items].filter(:category => 'ruby'))

[Source]

    # File lib/sequel/database/schema_methods.rb, line 72
72:     def create_or_replace_view(name, source)
73:       remove_cached_schema(name)
74:       source = source.sql if source.is_a?(Dataset)
75:       execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}")
76:     end

Creates a table with the columns given in the provided block:

  DB.create_table :posts do
    primary_key :id
    column :title, :text
    String :content
    index :title
  end

See Schema::Generator.

[Source]

    # File lib/sequel/database/schema_methods.rb, line 57
57:     def create_table(name, options={}, &block)
58:       options = {:generator=>options} if options.is_a?(Schema::Generator)
59:       create_table_sql_list(name, *((options[:generator] || Schema::Generator.new(self, &block)).create_info << options)).flatten.each {|sql| execute_ddl(sql)}
60:     end

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

[Source]

    # File lib/sequel/database/schema_methods.rb, line 63
63:     def create_table!(name, options={}, &block)
64:       drop_table(name) rescue nil
65:       create_table(name, options, &block)
66:     end

Creates a view based on a dataset or an SQL string:

  DB.create_view(:cheap_items, "SELECT * FROM items WHERE price < 100")
  DB.create_view(:ruby_items, DB[:items].filter(:category => 'ruby'))

[Source]

    # File lib/sequel/database/schema_methods.rb, line 82
82:     def create_view(name, source)
83:       source = source.sql if source.is_a?(Dataset)
84:       execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}")
85:     end

Return instances of JDBC::Dataset with the given opts.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 141
141:       def dataset(opts = nil)
142:         JDBC::Dataset.new(self, opts)
143:       end

Return a Sequel::DataObjects::Dataset object for this database.

[Source]

    # File lib/sequel/adapters/do.rb, line 69
69:       def dataset(opts = nil)
70:         DataObjects::Dataset.new(self, opts)
71:       end

Returns a blank dataset for this database

[Source]

     # File lib/sequel/database.rb, line 258
258:     def dataset
259:       ds = Sequel::Dataset.new(self)
260:     end

Disconnects all available connections from the connection pool. Any connections currently in use will not be disconnected.

[Source]

     # File lib/sequel/database.rb, line 264
264:     def disconnect
265:       pool.disconnect
266:     end

Removes a column from the specified table:

  DB.drop_column :items, :category

See alter_table.

[Source]

    # File lib/sequel/database/schema_methods.rb, line 92
92:     def drop_column(table, *args)
93:       alter_table(table) {drop_column(*args)}
94:     end

Removes an index for the given table and column/s:

  DB.drop_index :posts, :title
  DB.drop_index :posts, [:author, :title]

See alter_table.

[Source]

     # File lib/sequel/database/schema_methods.rb, line 102
102:     def drop_index(table, columns)
103:       alter_table(table) {drop_index(columns)}
104:     end

Drops one or more tables corresponding to the given names:

  DB.drop_table(:posts, :comments)

[Source]

     # File lib/sequel/database/schema_methods.rb, line 109
109:     def drop_table(*names)
110:       names.each do |n|
111:         remove_cached_schema(n)
112:         execute_ddl(drop_table_sql(n))
113:       end
114:     end

Drops one or more views corresponding to the given names:

  DB.drop_view(:cheap_items)

[Source]

     # File lib/sequel/database/schema_methods.rb, line 119
119:     def drop_view(*names)
120:       names.each do |n|
121:         remove_cached_schema(n)
122:         execute_ddl("DROP VIEW #{quote_schema_table(n)}")
123:       end
124:     end

Execute the given SQL. If a block is given, the DataObjects::Reader created is yielded to it. A block should not be provided unless a a SELECT statement is being used (or something else that returns rows). Otherwise, the return value is the insert id if opts[:type] is :insert, or the number of affected rows, otherwise.

[Source]

    # File lib/sequel/adapters/do.rb, line 78
78:       def execute(sql, opts={})
79:         log_info(sql)
80:         synchronize(opts[:server]) do |conn|
81:           begin
82:             command = conn.create_command(sql)
83:             res = block_given? ? command.execute_reader : command.execute_non_query
84:           rescue Exception => e
85:             raise_error(e, :classes=>@converted_exceptions)
86:           end
87:           if block_given?
88:             begin
89:               yield(res)
90:             ensure
91:              res.close if res
92:             end
93:           elsif opts[:type] == :insert
94:             res.insert_id
95:           else
96:             res.affected_rows
97:           end
98:         end
99:       end

Executes the given SQL on the database. This method should be overridden in descendants. This method should not be called directly by user code.

[Source]

     # File lib/sequel/database.rb, line 270
270:     def execute(sql, opts={})
271:       raise NotImplementedError, "#execute should be overridden by adapters"
272:     end

Execute the given SQL. If a block is given, if should be a SELECT statement or something else that returns rows.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 147
147:       def execute(sql, opts={}, &block)
148:         return call_sproc(sql, opts, &block) if opts[:sproc]
149:         return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)}
150:         log_info(sql)
151:         synchronize(opts[:server]) do |conn|
152:           stmt = conn.createStatement
153:           begin
154:             if block_given?
155:               yield stmt.executeQuery(sql)
156:             else
157:               case opts[:type]
158:               when :ddl
159:                 stmt.execute(sql)
160:               when :insert
161:                 stmt.executeUpdate(sql)
162:                 last_insert_id(conn, opts)
163:               else
164:                 stmt.executeUpdate(sql)
165:               end
166:             end
167:           rescue NativeException, JavaSQL::SQLException => e
168:             raise_error(e)
169:           ensure
170:             stmt.close
171:           end
172:         end
173:       end

Execute the given DDL SQL, which should not return any values or rows.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 178
178:       def execute_ddl(sql, opts={})
179:         execute(sql, {:type=>:ddl}.merge(opts))
180:       end

Method that should be used when submitting any DDL (Data Definition Language) SQL. By default, calls execute_dui. This method should not be called directly by user code.

[Source]

     # File lib/sequel/database.rb, line 277
277:     def execute_ddl(sql, opts={}, &block)
278:       execute_dui(sql, opts, &block)
279:     end
execute_dui(sql, opts={})

Alias for execute

Execute the SQL on the this database, returning the number of affected rows.

[Source]

     # File lib/sequel/adapters/do.rb, line 103
103:       def execute_dui(sql, opts={})
104:         execute(sql, opts)
105:       end

Method that should be used when issuing a DELETE, UPDATE, or INSERT statement. By default, calls execute. This method should not be called directly by user code.

[Source]

     # File lib/sequel/database.rb, line 284
284:     def execute_dui(sql, opts={}, &block)
285:       execute(sql, opts, &block)
286:     end

Execute the given INSERT SQL, returning the last inserted row id.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 184
184:       def execute_insert(sql, opts={})
185:         execute(sql, {:type=>:insert}.merge(opts))
186:       end

Execute the SQL on this database, returning the primary key of the table being inserted to.

[Source]

     # File lib/sequel/adapters/do.rb, line 109
109:       def execute_insert(sql, opts={})
110:         execute(sql, opts.merge(:type=>:insert))
111:       end

Method that should be used when issuing a INSERT statement. By default, calls execute_dui. This method should not be called directly by user code.

[Source]

     # File lib/sequel/database.rb, line 291
291:     def execute_insert(sql, opts={}, &block)
292:       execute_dui(sql, opts, &block)
293:     end

Fetches records for an arbitrary SQL statement. If a block is given, it is used to iterate over the records:

  DB.fetch('SELECT * FROM items'){|r| p r}

The method returns a dataset instance:

  DB.fetch('SELECT * FROM items').all

Fetch can also perform parameterized queries for protection against SQL injection:

  DB.fetch('SELECT * FROM items WHERE name = ?', my_name).all

[Source]

     # File lib/sequel/database.rb, line 308
308:     def fetch(sql, *args, &block)
309:       ds = dataset.with_sql(sql, *args)
310:       ds.each(&block) if block
311:       ds
312:     end

Returns a new dataset with the from method invoked. If a block is given, it is used as a filter on the dataset.

[Source]

     # File lib/sequel/database.rb, line 316
316:     def from(*args, &block)
317:       ds = dataset.from(*args)
318:       block ? ds.filter(&block) : ds
319:     end

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

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

  # SELECT version()
  DB.get(:version.sql_function) #=> ...

[Source]

     # File lib/sequel/database.rb, line 328
328:     def get(*args, &block)
329:       dataset.get(*args, &block)
330:     end

The method to call on identifiers going into the database

[Source]

     # File lib/sequel/database.rb, line 333
333:     def identifier_input_method
334:       case @identifier_input_method
335:       when nil
336:         @identifier_input_method = @opts.include?(:identifier_input_method) ? @opts[:identifier_input_method] : (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method)
337:         @identifier_input_method == "" ? nil : @identifier_input_method
338:       when ""
339:         nil
340:       else
341:         @identifier_input_method
342:       end
343:     end

Set the method to call on identifiers going into the database

[Source]

     # File lib/sequel/database.rb, line 346
346:     def identifier_input_method=(v)
347:       reset_schema_utility_dataset
348:       @identifier_input_method = v || ""
349:     end

The method to call on identifiers coming from the database

[Source]

     # File lib/sequel/database.rb, line 352
352:     def identifier_output_method
353:       case @identifier_output_method
354:       when nil
355:         @identifier_output_method = @opts.include?(:identifier_output_method) ? @opts[:identifier_output_method] : (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method)
356:         @identifier_output_method == "" ? nil : @identifier_output_method
357:       when ""
358:         nil
359:       else
360:         @identifier_output_method
361:       end
362:     end

Set the method to call on identifiers coming from the database

[Source]

     # File lib/sequel/database.rb, line 365
365:     def identifier_output_method=(v)
366:       reset_schema_utility_dataset
367:       @identifier_output_method = v || ""
368:     end

Returns a string representation of the database object including the class name and the connection URI (or the opts if the URI cannot be constructed).

[Source]

     # File lib/sequel/database.rb, line 373
373:     def inspect
374:       "#<#{self.class}: #{(uri rescue opts).inspect}>" 
375:     end

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

[Source]

     # File lib/sequel/database.rb, line 378
378:     def literal(v)
379:       schema_utility_dataset.literal(v)
380:     end

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

[Source]

     # File lib/sequel/database.rb, line 384
384:     def log_info(message, args=nil)
385:       message = "#{message}; #{args.inspect}" if args
386:       @loggers.each{|logger| logger.info(message)}
387:     end

[Source]

    # File lib/sequel/deprecated.rb, line 91
91:     def logger
92:       Deprecation.deprecate('Sequel::Database#logger', 'Use Sequel::Database#loggers')
93:       @loggers.first
94:     end

Remove any existing loggers and just use the given logger.

[Source]

     # File lib/sequel/database.rb, line 390
390:     def logger=(logger)
391:       @loggers = Array(logger)
392:     end

[Source]

    # File lib/sequel/deprecated.rb, line 96
96:     def multi_threaded?
97:       Deprecation.deprecate('Sequel::Database#multi_threaded?', 'Use !database.single_threaded?')
98:       !@single_threaded
99:     end

[Source]

    # File lib/sequel/deprecated.rb, line 86
86:     def query(&block)
87:       Deprecation.deprecate('Sequel::Database#query', 'require "sequel/extensions/query" first')
88:       dataset.query(&block)
89:     end

Return a dataset modified by the query block

[Source]

   # File lib/sequel/extensions/query.rb, line 4
4:     def query(&block)
5:       dataset.query(&block)
6:     end

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

[Source]

     # File lib/sequel/database.rb, line 395
395:     def quote_identifiers=(v)
396:       reset_schema_utility_dataset
397:       @quote_identifiers = v
398:     end

Returns true if the database quotes identifiers.

[Source]

     # File lib/sequel/database.rb, line 401
401:     def quote_identifiers?
402:       return @quote_identifiers unless @quote_identifiers.nil?
403:       @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers)
404:     end

Renames a column in the specified table. This method expects the current column name and the new column name:

  DB.rename_column :items, :cntr, :counter

See alter_table.

[Source]

     # File lib/sequel/database/schema_methods.rb, line 142
142:     def rename_column(table, *args)
143:       alter_table(table) {rename_column(*args)}
144:     end

Renames a table:

  DB.tables #=> [:items]
  DB.rename_table :items, :old_items
  DB.tables #=> [:old_items]

[Source]

     # File lib/sequel/database/schema_methods.rb, line 131
131:     def rename_table(name, new_name)
132:       remove_cached_schema(name)
133:       execute_ddl(rename_table_sql(name, new_name))
134:     end

Parse the schema from the database. If the table_name is not given, returns the schema for all tables as a hash. If the table_name is given, returns the schema for a single table as an array with all members being arrays of length 2. 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.

[Source]

     # File lib/sequel/database.rb, line 423
423:     def schema(table = nil, opts={})
424:       Deprecation.deprecate('Calling Database#schema without a table argument', 'Use database.tables.inject({}){|h, m| h[m] = database.schema(m); h}') unless table
425:       raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true)
426: 
427:       if table
428:         sch, table_name = schema_and_table(table)
429:         quoted_name = quote_schema_table(table)
430:       end
431:       opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema)
432:       if opts[:reload] && @schemas
433:         if table_name
434:           @schemas.delete(quoted_name)
435:         else
436:           @schemas = nil
437:         end
438:       end
439: 
440:       if @schemas
441:         if table_name
442:           return @schemas[quoted_name] if @schemas[quoted_name]
443:         else
444:           return @schemas
445:         end
446:       end
447: 
448:       raise(Error, '#tables does not exist, you must provide a specific table to #schema') if table.nil? && !respond_to?(:tables, true)
449: 
450:       @schemas ||= Hash.new do |h,k|
451:         quote_name = quote_schema_table(k)
452:         h[quote_name] if h.include?(quote_name)
453:       end
454: 
455:       if table_name
456:         cols = schema_parse_table(table_name, opts)
457:         raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty?
458:         @schemas[quoted_name] = cols
459:       else
460:         tables.each{|t| @schemas[quote_schema_table(t)] = schema_parse_table(t.to_s, opts)}
461:         @schemas
462:       end
463:     end

Returns a new dataset with the select method invoked.

[Source]

     # File lib/sequel/database.rb, line 407
407:     def select(*args, &block)
408:       dataset.select(*args, &block)
409:     end

Default serial primary key options.

[Source]

    # File lib/sequel/database/schema_sql.rb, line 24
24:     def serial_primary_key_options
25:       {:primary_key => true, :type => Integer, :auto_increment => true}
26:     end

Sets the default value for the given column in the given table:

  DB.set_column_default :items, :category, 'perl!'

See alter_table.

[Source]

     # File lib/sequel/database/schema_methods.rb, line 151
151:     def set_column_default(table, *args)
152:       alter_table(table) {set_column_default(*args)}
153:     end

Set the data type for the given column in the given table:

  DB.set_column_type :items, :price, :float

See alter_table.

[Source]

     # File lib/sequel/database/schema_methods.rb, line 160
160:     def set_column_type(table, *args)
161:       alter_table(table) {set_column_type(*args)}
162:     end

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

[Source]

     # File lib/sequel/database.rb, line 466
466:     def single_threaded?
467:       @single_threaded
468:     end

Return the subadapter type for this database, i.e. sqlite3 for do:sqlite3::memory:.

[Source]

     # File lib/sequel/adapters/do.rb, line 115
115:       def subadapter
116:         uri.split(":").first
117:       end

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

[Source]

     # File lib/sequel/database.rb, line 471
471:     def synchronize(server=nil, &block)
472:       @pool.hold(server || :default, &block)
473:     end

Returns true if a table with the given name exists. This requires a query to the database unless this database object already has the schema for the given table name.

[Source]

     # File lib/sequel/database.rb, line 478
478:     def table_exists?(name)
479:       if @schemas && @schemas[name]
480:         true
481:       else
482:         begin 
483:           from(name).first
484:           true
485:         rescue
486:           false
487:         end
488:       end
489:     end

All tables in this database

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 189
189:       def tables
190:         ts = []
191:         ds = dataset
192:         metadata(:getTables, nil, nil, nil, ['TABLE'].to_java(:string)){|h| ts << ds.send(:output_identifier, h[:table_name])}
193:         ts
194:       end

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

[Source]

     # File lib/sequel/database.rb, line 493
493:     def test_connection(server=nil)
494:       synchronize(server){|conn|}
495:       true
496:     end

Use DataObject‘s transaction support for transactions. This only supports single level transactions, and it always prepares transactions and commits them immediately after. It‘s wasteful, but required by DataObject‘s API.

[Source]

     # File lib/sequel/adapters/do.rb, line 123
123:       def transaction(opts={})
124:         unless opts.is_a?(Hash)
125:           Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})") 
126:           opts = {:server=>opts}
127:         end
128:         th = Thread.current
129:         synchronize(opts[:server]) do |conn|
130:           return yield(conn) if @transactions.include?(th)
131:           t = ::DataObjects::Transaction.create_for_uri(uri)
132:           t.instance_variable_get(:@connection).close
133:           t.instance_variable_set(:@connection, conn)
134:           begin
135:             log_info("Transaction.begin")
136:             t.begin
137:             @transactions << th
138:             yield(conn)
139:           rescue Exception => e
140:             log_info("Transaction.rollback")
141:             t.rollback
142:             transaction_error(e)
143:           ensure
144:             unless e
145:               log_info("Transaction.commit")
146:               t.prepare
147:               t.commit 
148:             end
149:             @transactions.delete(th)
150:           end
151:         end
152:       end

A simple implementation of SQL transactions. Nested transactions are not supported - calling transaction within a transaction will reuse the current transaction. Should be overridden for databases that support nested transactions.

[Source]

     # File lib/sequel/database.rb, line 502
502:     def transaction(opts={})
503:       unless opts.is_a?(Hash)
504:         Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})") 
505:         opts = {:server=>opts}
506:       end
507:       synchronize(opts[:server]) do |conn|
508:         return yield(conn) if @transactions.include?(Thread.current)
509:         log_info(begin_transaction_sql)
510:         conn.execute(begin_transaction_sql)
511:         begin
512:           @transactions << Thread.current
513:           yield(conn)
514:         rescue Exception => e
515:           log_info(rollback_transaction_sql)
516:           conn.execute(rollback_transaction_sql)
517:           transaction_error(e)
518:         ensure
519:           unless e
520:             log_info(commit_transaction_sql)
521:             conn.execute(commit_transaction_sql)
522:           end
523:           @transactions.delete(Thread.current)
524:         end
525:       end
526:     end

Default transaction method that should work on most JDBC databases. Does not use the JDBC transaction methods, uses SQL BEGIN/ROLLBACK/COMMIT statements instead.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 199
199:       def transaction(opts={})
200:         unless opts.is_a?(Hash)
201:           Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})") 
202:           opts = {:server=>opts}
203:         end
204:         synchronize(opts[:server]) do |conn|
205:           return yield(conn) if @transactions.include?(Thread.current)
206:           stmt = conn.createStatement
207:           begin
208:             log_info(begin_transaction_sql)
209:             stmt.execute(begin_transaction_sql)
210:             @transactions << Thread.current
211:             yield(conn)
212:           rescue Exception => e
213:             log_info(rollback_transaction_sql)
214:             stmt.execute(rollback_transaction_sql)
215:             transaction_error(e)
216:           ensure
217:             unless e
218:               log_info(commit_transaction_sql)
219:               stmt.execute(commit_transaction_sql)
220:             end
221:             stmt.close
222:             @transactions.delete(Thread.current)
223:           end
224:         end
225:       end

Typecast the value to the given column_type. Calls typecast_value_#{column_type} if the method exists, otherwise returns the value. This method should raise Sequel::InvalidValue if assigned value is invalid.

[Source]

     # File lib/sequel/database.rb, line 533
533:     def typecast_value(column_type, value)
534:       return nil if value.nil?
535:       meth = "typecast_value_#{column_type}"
536:       begin
537:         respond_to?(meth, true) ? send(meth, value) : value
538:       rescue ArgumentError, TypeError => exp
539:         e = Sequel::InvalidValue.new("#{exp.class} #{exp.message}")
540:         e.set_backtrace(exp.backtrace)
541:         raise e
542:       end
543:     end

[Source]

    # File lib/sequel/deprecated.rb, line 71
71:     def upcase_identifiers=(v)
72:       Deprecation.deprecate('Sequel::Database#upcase_identifiers=', 'Use Sequel::Database#identifier_input_method = :upcase or nil')
73:       self.identifier_input_method = v ? :upcase : nil
74:     end

[Source]

    # File lib/sequel/deprecated.rb, line 76
76:     def upcase_identifiers?
77:       Deprecation.deprecate('Sequel::Database#upcase_identifiers?', 'Use Sequel::Database#identifier_input_method == :upcase')
78:       identifier_input_method == :upcase
79:     end

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

[Source]

     # File lib/sequel/database.rb, line 548
548:     def uri
549:       uri = URI::Generic.new(
550:         self.class.adapter_scheme.to_s,
551:         nil,
552:         @opts[:host],
553:         @opts[:port],
554:         nil,
555:         "/#{@opts[:database]}",
556:         nil,
557:         nil,
558:         nil
559:       )
560:       uri.user = @opts[:user]
561:       uri.password = @opts[:password] if uri.user
562:       uri.to_s
563:     end

Return the DataObjects URI for the Sequel URI, removing the do: prefix.

[Source]

     # File lib/sequel/adapters/do.rb, line 156
156:       def uri(opts={})
157:         opts = @opts.merge(opts)
158:         (opts[:uri] || opts[:url]).sub(/\Ado:/, '')
159:       end

The uri for this connection. You can specify the uri using the :uri, :url, or :database options. You don‘t need to worry about this if you use Sequel.connect with the JDBC connectrion strings.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 231
231:       def uri(opts={})
232:         opts = @opts.merge(opts)
233:         ur = opts[:uri] || opts[:url] || opts[:database]
234:         ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}"
235:       end

Explicit alias of uri for easier subclassing.

[Source]

     # File lib/sequel/database.rb, line 566
566:     def url
567:       uri
568:     end

[Validate]