Class Sequel::Database
In: lib/sequel/adapters/do.rb
lib/sequel/adapters/jdbc.rb
lib/sequel/database.rb
lib/sequel/database/schema_methods.rb
lib/sequel/database/connecting.rb
lib/sequel/database/dataset.rb
lib/sequel/database/dataset_defaults.rb
lib/sequel/database/logging.rb
lib/sequel/database/misc.rb
lib/sequel/database/query.rb
lib/sequel/extensions/query.rb
lib/sequel/extensions/schema_dumper.rb
Parent: Sequel::Database

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

<<   []   adapter_class   adapter_scheme   add_column   add_index   add_servers   alter_table   call   call_sproc   cast_type_literal   connect   connect   connect   connect   create_or_replace_view   create_table   create_table!   create_table?   create_view   database_type   dataset   dataset   dataset   disconnect   drop_column   drop_index   drop_table   drop_view   dump_indexes_migration   dump_schema_migration   dump_table_schema   each_server   execute   execute   execute   execute_ddl   execute_ddl   execute_dui   execute_dui   execute_dui   execute_insert   execute_insert   execute_insert   fetch   from   get   identifier_input_method   identifier_input_method   identifier_input_method=   identifier_input_method=   identifier_output_method   identifier_output_method   identifier_output_method=   identifier_output_method=   indexes   indexes   inspect   jndi?   literal   log_info   log_yield   logger=   new   new   new   query   quote_identifiers=   quote_identifiers=   quote_identifiers?   remove_servers   rename_column   rename_table   run   schema   select   serial_primary_key_options   servers   set_column_default   set_column_type   single_threaded=   single_threaded?   subadapter   supports_prepared_transactions?   supports_savepoints?   supports_transaction_isolation_levels?   synchronize   table_exists?   tables   tables   test_connection   transaction   typecast_value   uri   uri   uri   url  

Included Modules

Attributes

convert_types  [RW]  Whether to convert some Java types to ruby types when retrieving rows. True by default, can be set to false to roughly double performance when fetching rows.
database_type  [R]  The type of database we are connecting to
driver  [R]  The Java database driver we are using

Public Class methods

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 109
109:       def initialize(opts)
110:         super
111:         @convert_types = typecast_value_boolean(@opts.fetch(:convert_types, true))
112:         raise(Error, "No connection string specified") unless uri
113:         
114:         resolved_uri = jndi? ? get_uri_from_jndi : uri
115: 
116:         if match = /\Ajdbc:([^:]+)/.match(resolved_uri) and prok = DATABASE_SETUP[match[1].to_sym]
117:           @driver = prok.call(self)
118:         end        
119:       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 45
45:       def initialize(opts)
46:         super
47:         raise(Error, "No connection string specified") unless uri
48:         if prok = DATABASE_SETUP[subadapter.to_sym]
49:           prok.call(self)
50:         end
51:       end

Public Instance methods

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 123
123:       def call_sproc(name, opts = {})
124:         args = opts[:args] || []
125:         sql = "{call #{name}(#{args.map{'?'}.join(',')})}"
126:         synchronize(opts[:server]) do |conn|
127:           cps = conn.prepareCall(sql)
128: 
129:           i = 0
130:           args.each{|arg| set_ps_arg(cps, arg, i+=1)}
131: 
132:           begin
133:             if block_given?
134:               yield log_yield(sql){cps.executeQuery}
135:             else
136:               case opts[:type]
137:               when :insert
138:                 log_yield(sql){cps.executeUpdate}
139:                 last_insert_id(conn, opts)
140:               else
141:                 log_yield(sql){cps.executeUpdate}
142:               end
143:             end
144:           rescue NativeException, JavaSQL::SQLException => e
145:             raise_error(e)
146:           ensure
147:             cps.close
148:           end
149:         end
150:       end

Setup a DataObjects::Connection to the database.

[Source]

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

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 153
153:       def connect(server)
154:         opts = server_opts(server)
155:         conn = if jndi?
156:           get_connection_from_jndi
157:         else
158:           args = [uri(opts)]
159:           args.concat([opts[:user], opts[:password]]) if opts[:user] && opts[:password]
160:           begin
161:             JavaSQL::DriverManager.getConnection(*args)
162:           rescue => e
163:             raise e unless driver
164:             # If the DriverManager can't get the connection - use the connect
165:             # method of the driver. (This happens under Tomcat for instance)
166:             props = java.util.Properties.new
167:             if opts && opts[:user] && opts[:password]
168:               props.setProperty("user", opts[:user])
169:               props.setProperty("password", opts[:password])
170:             end
171:             driver.new.connect(args[0], props) rescue (raise e)
172:           end
173:         end
174:         setup_connection(conn)
175:       end

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

[Source]

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

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

[Source]

    # File lib/sequel/adapters/do.rb, line 59
59:       def dataset(opts = nil)
60:         DataObjects::Dataset.new(self, opts)
61:       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 184
184:       def execute(sql, opts={}, &block)
185:         return call_sproc(sql, opts, &block) if opts[:sproc]
186:         return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)}
187:         synchronize(opts[:server]) do |conn|
188:           statement(conn) do |stmt|
189:             if block_given?
190:               yield log_yield(sql){stmt.executeQuery(sql)}
191:             else
192:               case opts[:type]
193:               when :ddl
194:                 log_yield(sql){stmt.execute(sql)}
195:               when :insert
196:                 log_yield(sql) do
197:                   if requires_return_generated_keys?
198:                     stmt.executeUpdate(sql, JavaSQL::Statement.RETURN_GENERATED_KEYS)
199:                   else
200:                     stmt.executeUpdate(sql)
201:                   end
202:                 end
203:                 last_insert_id(conn, opts.merge(:stmt=>stmt))
204:               else
205:                 log_yield(sql){stmt.executeUpdate(sql)}
206:               end
207:             end
208:           end
209:         end
210:       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 68
68:       def execute(sql, opts={})
69:         synchronize(opts[:server]) do |conn|
70:           begin
71:             command = conn.create_command(sql)
72:             res = log_yield(sql){block_given? ? command.execute_reader : command.execute_non_query}
73:           rescue ::DataObjects::Error => e
74:             raise_error(e)
75:           end
76:           if block_given?
77:             begin
78:               yield(res)
79:             ensure
80:              res.close if res
81:             end
82:           elsif opts[:type] == :insert
83:             res.insert_id
84:           else
85:             res.affected_rows
86:           end
87:         end
88:       end

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 215
215:       def execute_ddl(sql, opts={})
216:         execute(sql, {:type=>:ddl}.merge(opts))
217:       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 92
92:       def execute_dui(sql, opts={})
93:         execute(sql, opts)
94:       end

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 221
221:       def execute_insert(sql, opts={})
222:         execute(sql, {:type=>:insert}.merge(opts))
223:       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 98
 98:       def execute_insert(sql, opts={})
 99:         execute(sql, opts.merge(:type=>:insert))
100:       end

Use the JDBC metadata to get the index information for the table.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 226
226:       def indexes(table, opts={})
227:         m = output_identifier_meth
228:         im = input_identifier_meth
229:         schema, table = schema_and_table(table)
230:         schema ||= opts[:schema]
231:         schema = im.call(schema) if schema
232:         table = im.call(table)
233:         indexes = {}
234:         metadata(:getIndexInfo, nil, schema, table, false, true) do |r|
235:           next unless name = r[:column_name]
236:           next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re 
237:           i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>[false, 0].include?(r[:non_unique])}
238:           i[:columns] << m.call(name)
239:         end
240:         indexes
241:       end

Whether or not JNDI is being used for this connection.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 262
262:       def jndi?
263:         !!(uri =~ JNDI_URI_REGEXP)
264:       end

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

[Source]

     # File lib/sequel/adapters/do.rb, line 104
104:       def subadapter
105:         uri.split(":").first
106:       end

All tables in this database

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 244
244:       def tables(opts={})
245:         ts = []
246:         m = output_identifier_meth
247:         metadata(:getTables, nil, nil, nil, ['TABLE'].to_java(:string)){|h| ts << m.call(h[:table_name])}
248:         ts
249:       end

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

[Source]

     # File lib/sequel/adapters/do.rb, line 110
110:       def uri(opts={})
111:         opts = @opts.merge(opts)
112:         (opts[:uri] || opts[:url]).sub(/\Ado:/, '')
113:       end

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 255
255:       def uri(opts={})
256:         opts = @opts.merge(opts)
257:         ur = opts[:uri] || opts[:url] || opts[:database]
258:         ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}"
259:       end

Methods that modify the database schema

These methods execute code on the database that modifies the database‘s schema.

Constants

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

Public Instance methods

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 30
30:     def add_column(table, *args)
31:       alter_table(table) {add_column(*args)}
32:     end

Adds an index to a table for the given columns:

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

Options:

  • :ignore_errors - Ignore any DatabaseErrors that are raised

See alter_table.

[Source]

    # File lib/sequel/database/schema_methods.rb, line 44
44:     def add_index(table, columns, options={})
45:       e = options[:ignore_errors]
46:       begin
47:         alter_table(table){add_index(columns, options)}
48:       rescue DatabaseError
49:         raise unless e
50:       end
51:     end

Alters the given table with the specified block. Example:

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

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

See Schema::AlterTableGenerator and the "Migrations and Schema Modification" guide.

[Source]

    # File lib/sequel/database/schema_methods.rb, line 70
70:     def alter_table(name, generator=nil, &block)
71:       generator ||= Schema::AlterTableGenerator.new(self, &block)
72:       alter_table_sql_list(name, generator.operations).flatten.each {|sql| execute_ddl(sql)}
73:       remove_cached_schema(name)
74:       nil
75:     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 115
115:     def create_or_replace_view(name, source)
116:       source = source.sql if source.is_a?(Dataset)
117:       execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}")
118:       remove_cached_schema(name)
119:       nil
120:     end

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

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

Options:

  • :temp - Create the table as a temporary table.
  • :ignore_index_errors - Ignore any errors when creating indexes.

See Schema::Generator and the "Migrations and Schema Modification" guide.

[Source]

    # File lib/sequel/database/schema_methods.rb, line 91
91:     def create_table(name, options={}, &block)
92:       remove_cached_schema(name)
93:       options = {:generator=>options} if options.is_a?(Schema::Generator)
94:       generator = options[:generator] || Schema::Generator.new(self, &block)
95:       create_table_from_generator(name, generator, options)
96:       create_table_indexes_from_generator(name, generator, options)
97:       nil
98:     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 101
101:     def create_table!(name, options={}, &block)
102:       drop_table(name) rescue nil
103:       create_table(name, options, &block)
104:     end

Creates the table unless the table already exists

[Source]

     # File lib/sequel/database/schema_methods.rb, line 107
107:     def create_table?(name, options={}, &block)
108:       create_table(name, options, &block) unless table_exists?(name)
109:     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 126
126:     def create_view(name, source)
127:       source = source.sql if source.is_a?(Dataset)
128:       execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}")
129:     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 136
136:     def drop_column(table, *args)
137:       alter_table(table) {drop_column(*args)}
138:     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 146
146:     def drop_index(table, columns, options={})
147:       alter_table(table){drop_index(columns, options)}
148:     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 153
153:     def drop_table(*names)
154:       names.each do |n|
155:         execute_ddl(drop_table_sql(n))
156:         remove_cached_schema(n)
157:       end
158:       nil
159:     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 164
164:     def drop_view(*names)
165:       names.each do |n|
166:         execute_ddl("DROP VIEW #{quote_schema_table(n)}")
167:         remove_cached_schema(n)
168:       end
169:       nil
170:     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 189
189:     def rename_column(table, *args)
190:       alter_table(table) {rename_column(*args)}
191:     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 177
177:     def rename_table(name, new_name)
178:       execute_ddl(rename_table_sql(name, new_name))
179:       remove_cached_schema(name)
180:       nil
181:     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 198
198:     def set_column_default(table, *args)
199:       alter_table(table) {set_column_default(*args)}
200:     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 207
207:     def set_column_type(table, *args)
208:       alter_table(table) {set_column_type(*args)}
209:     end

Methods relating to adapters, connecting, disconnecting, and sharding

This methods involve the Database‘s connection pool.

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

Attributes

pool  [R]  The connection pool for this database

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/connecting.rb, line 17
17:     def self.adapter_class(scheme)
18:       scheme = scheme.to_s.gsub('-', '_').to_sym
19:       
20:       unless klass = ADAPTER_MAP[scheme]
21:         # attempt to load the adapter file
22:         begin
23:           Sequel.tsk_require "sequel/adapters/#{scheme}"
24:         rescue LoadError => e
25:           raise Sequel.convert_exception_class(e, AdapterNotFound)
26:         end
27:         
28:         # make sure we actually loaded the adapter
29:         unless klass = ADAPTER_MAP[scheme]
30:           raise AdapterNotFound, "Could not load #{scheme} adapter"
31:         end
32:       end
33:       klass
34:     end

Returns the scheme for the Database class.

[Source]

    # File lib/sequel/database/connecting.rb, line 37
37:     def self.adapter_scheme
38:       @scheme
39:     end

Connects to a database. See Sequel.connect.

[Source]

    # File lib/sequel/database/connecting.rb, line 42
42:     def self.connect(conn_string, opts = {})
43:       case conn_string
44:       when String
45:         if match = /\A(jdbc|do):/o.match(conn_string)
46:           c = adapter_class(match[1].to_sym)
47:           opts = {:uri=>conn_string}.merge(opts)
48:         else
49:           uri = URI.parse(conn_string)
50:           scheme = uri.scheme
51:           scheme = :dbi if scheme =~ /\Adbi-/
52:           c = adapter_class(scheme)
53:           uri_options = c.send(:uri_to_options, uri)
54:           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?
55:           uri_options.entries.each{|k,v| uri_options[k] = URI.unescape(v) if v.is_a?(String)}
56:           opts = uri_options.merge(opts)
57:         end
58:       when Hash
59:         opts = conn_string.merge(opts)
60:         c = adapter_class(opts[:adapter] || opts['adapter'])
61:       else
62:         raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}"
63:       end
64:       # process opts a bit
65:       opts = opts.inject({}) do |m, kv| k, v = *kv
66:         k = :user if k.to_s == 'username'
67:         m[k.to_sym] = v
68:         m
69:       end
70:       begin
71:         db = c.new(opts)
72:         db.test_connection if opts[:test] && db.send(:typecast_value_boolean, opts[:test])
73:         result = yield(db) if block_given?
74:       ensure
75:         if block_given?
76:           db.disconnect if db
77:           ::Sequel::DATABASES.delete(db)
78:         end
79:       end
80:       block_given? ? result : db
81:     end

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

[Source]

    # File lib/sequel/database/connecting.rb, line 85
85:     def self.single_threaded=(value)
86:       @@single_threaded = value
87:     end

Public Instance methods

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"})

[Source]

     # File lib/sequel/database/connecting.rb, line 119
119:     def add_servers(servers)
120:       @opts[:servers] = @opts[:servers] ? @opts[:servers].merge(servers) : servers
121:       @pool.add_servers(servers.keys)
122:     end

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

[Source]

     # File lib/sequel/database/connecting.rb, line 125
125:     def connect(server)
126:       raise NotImplemented, "#connect should be overridden by adapters"
127:     end

The database type for this database object, the same as the adapter scheme by default. Should be overridden in adapters (especially shared adapters) to be the correct type, so that even if two separate Database objects are using different adapters you can tell that they are using the same database type. Even better, you can tell that two Database objects that are using the same adapter are connecting to different database types (think JDBC or DataObjects).

[Source]

     # File lib/sequel/database/connecting.rb, line 136
136:     def database_type
137:       self.class.adapter_scheme
138:     end

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

[Source]

     # File lib/sequel/database/connecting.rb, line 144
144:     def disconnect(opts = {})
145:       pool.disconnect(opts)
146:     end

Yield a new database object for every server in the connection pool. Intended for use in sharded environments where there is a need to make schema modifications (DDL queries) on each shard.

  DB.each_server{|db| db.create_table(:users){primary_key :id; String :name}}

[Source]

     # File lib/sequel/database/connecting.rb, line 153
153:     def each_server(&block)
154:       servers.each{|s| self.class.connect(server_opts(s), &block)}
155:     end

Dynamically remove existing servers from the connection pool. Intended for use with master/slave or shard configurations where it is useful to remove existing server hosts at runtime.

servers should be symbols or arrays of symbols. If a nonexistent server is specified, it is ignored. If no servers have been specified for this database, no changes are made. If you attempt to remove the :default server, an error will be raised.

  DB.remove_servers(:f1, :f2)

[Source]

     # File lib/sequel/database/connecting.rb, line 167
167:     def remove_servers(*servers)
168:       if @opts[:servers] && !@opts[:servers].empty?
169:         servs = @opts[:servers].dup
170:         servers.flatten!
171:         servers.each{|s| servs.delete(s)}
172:         @opts[:servers] = servs
173:         @pool.remove_servers(servers)
174:       end
175:     end

An array of servers/shards for this Database object.

[Source]

     # File lib/sequel/database/connecting.rb, line 178
178:     def servers
179:       pool.servers
180:     end

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

[Source]

     # File lib/sequel/database/connecting.rb, line 183
183:     def single_threaded?
184:       @single_threaded
185:     end

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

[Source]

     # File lib/sequel/database/connecting.rb, line 188
188:     def synchronize(server=nil, &block)
189:       @pool.hold(server || :default, &block)
190:     end

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

[Source]

     # File lib/sequel/database/connecting.rb, line 194
194:     def test_connection(server=nil)
195:       synchronize(server){|conn|}
196:       true
197:     end

Methods that create datasets

These methods all return instances of this database‘s dataset class.

Public Instance methods

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/dataset.rb, line 18
18:     def [](*args)
19:       (String === args.first) ? fetch(*args) : from(*args)
20:     end

Returns a blank dataset for this database

[Source]

    # File lib/sequel/database/dataset.rb, line 23
23:     def dataset
24:       ds = Sequel::Dataset.new(self)
25:     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/dataset.rb, line 40
40:     def fetch(sql, *args, &block)
41:       ds = dataset.with_sql(sql, *args)
42:       ds.each(&block) if block
43:       ds
44:     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/dataset.rb, line 48
48:     def from(*args, &block)
49:       ds = dataset.from(*args)
50:       block ? ds.filter(&block) : ds
51:     end

Returns a new dataset with the select method invoked.

[Source]

    # File lib/sequel/database/dataset.rb, line 54
54:     def select(*args, &block)
55:       dataset.select(*args, &block)
56:     end

Methods that set defaults for created datasets

This methods change the default behavior of this database‘s datasets.

Attributes

default_schema  [RW]  The default schema to use, generally should be nil.

Public Class methods

The method to call on identifiers going into the database

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 18
18:     def self.identifier_input_method
19:       @@identifier_input_method
20:     end

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

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 24
24:     def self.identifier_input_method=(v)
25:       @@identifier_input_method = v || ""
26:     end

The method to call on identifiers coming from the database

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 29
29:     def self.identifier_output_method
30:       @@identifier_output_method
31:     end

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

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 35
35:     def self.identifier_output_method=(v)
36:       @@identifier_output_method = v || ""
37:     end

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

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 41
41:     def self.quote_identifiers=(value)
42:       @@quote_identifiers = value
43:     end

Public Instance methods

The method to call on identifiers going into the database

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 49
49:     def identifier_input_method
50:       case @identifier_input_method
51:       when nil
52:         @identifier_input_method = @opts.fetch(:identifier_input_method, (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method))
53:         @identifier_input_method == "" ? nil : @identifier_input_method
54:       when ""
55:         nil
56:       else
57:         @identifier_input_method
58:       end
59:     end

Set the method to call on identifiers going into the database

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 62
62:     def identifier_input_method=(v)
63:       reset_schema_utility_dataset
64:       @identifier_input_method = v || ""
65:     end

The method to call on identifiers coming from the database

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 68
68:     def identifier_output_method
69:       case @identifier_output_method
70:       when nil
71:         @identifier_output_method = @opts.fetch(:identifier_output_method, (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method))
72:         @identifier_output_method == "" ? nil : @identifier_output_method
73:       when ""
74:         nil
75:       else
76:         @identifier_output_method
77:       end
78:     end

Set the method to call on identifiers coming from the database

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 81
81:     def identifier_output_method=(v)
82:       reset_schema_utility_dataset
83:       @identifier_output_method = v || ""
84:     end

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

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 87
87:     def quote_identifiers=(v)
88:       reset_schema_utility_dataset
89:       @quote_identifiers = v
90:     end

Returns true if the database quotes identifiers.

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 93
93:     def quote_identifiers?
94:       return @quote_identifiers unless @quote_identifiers.nil?
95:       @quote_identifiers = @opts.fetch(:quote_identifiers, (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers))
96:     end

Methods relating to logging

This methods affect relating to the logging of executed SQL.

Attributes

log_warn_duration  [RW]  Numeric specifying the duration beyond which queries are logged at warn level instead of info level.
loggers  [RW]  Array of SQL loggers to use for this database

Public Instance methods

Log a message at level info to all loggers.

[Source]

    # File lib/sequel/database/logging.rb, line 16
16:     def log_info(message, args=nil)
17:       log_each(:info, args ? "#{message}; #{args.inspect}" : message)
18:     end

Yield to the block, logging any errors at error level to all loggers, and all other queries with the duration at warn or info level.

[Source]

    # File lib/sequel/database/logging.rb, line 22
22:     def log_yield(sql, args=nil)
23:       return yield if @loggers.empty?
24:       sql = "#{sql}; #{args.inspect}" if args
25:       start = Time.now
26:       begin
27:         yield
28:       rescue => e
29:         log_each(:error, "#{e.class}: #{e.message.strip}: #{sql}")
30:         raise
31:       ensure
32:         log_duration(Time.now - start, sql) unless e
33:       end
34:     end

Remove any existing loggers and just use the given logger.

[Source]

    # File lib/sequel/database/logging.rb, line 37
37:     def logger=(logger)
38:       @loggers = Array(logger)
39:     end

Miscellaneous methods

These methods don‘t fit neatly into another category.

Attributes

opts  [R]  The options for this database

Public Class methods

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/misc.rb, line 38
38:     def initialize(opts = {}, &block)
39:       @opts ||= opts
40:       @opts = connection_pool_default_options.merge(@opts)
41:       @loggers = Array(@opts[:logger]) + Array(@opts[:loggers])
42:       self.log_warn_duration = @opts[:log_warn_duration]
43:       @opts[:disconnection_proc] ||= proc{|conn| disconnect_connection(conn)}
44:       block ||= proc{|server| connect(server)}
45:       @opts[:servers] = {} if @opts[:servers].is_a?(String)
46:       
47:       @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, @@single_threaded))
48:       @schemas = {}
49:       @default_schema = @opts.fetch(:default_schema, default_schema_default)
50:       @prepared_statements = {}
51:       @transactions = []
52:       @identifier_input_method = nil
53:       @identifier_output_method = nil
54:       @quote_identifiers = nil
55:       @pool = ConnectionPool.get_pool(@opts, &block)
56: 
57:       ::Sequel::DATABASES.push(self)
58:     end

Public Instance methods

Cast the given type to a literal type

[Source]

    # File lib/sequel/database/misc.rb, line 61
61:     def cast_type_literal(type)
62:       type_literal(:type=>type)
63:     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/misc.rb, line 68
68:     def inspect
69:       "#<#{self.class}: #{(uri rescue opts).inspect}>" 
70:     end

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

[Source]

    # File lib/sequel/database/misc.rb, line 73
73:     def literal(v)
74:       schema_utility_dataset.literal(v)
75:     end

Default serial primary key options.

[Source]

    # File lib/sequel/database/misc.rb, line 78
78:     def serial_primary_key_options
79:       {:primary_key => true, :type => Integer, :auto_increment => true}
80:     end

Whether the database and adapter support prepared transactions (two-phase commit), false by default

[Source]

    # File lib/sequel/database/misc.rb, line 84
84:     def supports_prepared_transactions?
85:       false
86:     end

Whether the database and adapter support savepoints, false by default

[Source]

    # File lib/sequel/database/misc.rb, line 89
89:     def supports_savepoints?
90:       false
91:     end

Whether the database and adapter support transaction isolation levels, false by default

[Source]

    # File lib/sequel/database/misc.rb, line 94
94:     def supports_transaction_isolation_levels?
95:       false
96:     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/misc.rb, line 103
103:     def typecast_value(column_type, value)
104:       return nil if value.nil?
105:       meth = "typecast_value_#{column_type}"
106:       begin
107:         respond_to?(meth, true) ? send(meth, value) : value
108:       rescue ArgumentError, TypeError => e
109:         raise Sequel.convert_exception_class(e, InvalidValue)
110:       end
111:     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/misc.rb, line 116
116:     def uri
117:       uri = URI::Generic.new(
118:         self.class.adapter_scheme.to_s,
119:         nil,
120:         @opts[:host],
121:         @opts[:port],
122:         nil,
123:         "/#{@opts[:database]}",
124:         nil,
125:         nil,
126:         nil
127:       )
128:       uri.user = @opts[:user]
129:       uri.password = @opts[:password] if uri.user
130:       uri.to_s
131:     end

Explicit alias of uri for easier subclassing.

[Source]

     # File lib/sequel/database/misc.rb, line 134
134:     def url
135:       uri
136:     end

Methods that execute queries and/or return results

This methods generally execute SQL code on the database server.

Constants

SQL_BEGIN = 'BEGIN'.freeze
SQL_COMMIT = 'COMMIT'.freeze
SQL_RELEASE_SAVEPOINT = 'RELEASE SAVEPOINT autopoint_%d'.freeze
SQL_ROLLBACK = 'ROLLBACK'.freeze
SQL_ROLLBACK_TO_SAVEPOINT = 'ROLLBACK TO SAVEPOINT autopoint_%d'.freeze
SQL_SAVEPOINT = 'SAVEPOINT autopoint_%d'.freeze
TRANSACTION_BEGIN = 'Transaction.begin'.freeze
TRANSACTION_COMMIT = 'Transaction.commit'.freeze
TRANSACTION_ROLLBACK = 'Transaction.rollback'.freeze
TRANSACTION_ISOLATION_LEVELS = {:uncommitted=>'READ UNCOMMITTED'.freeze, :committed=>'READ COMMITTED'.freeze, :repeatable=>'REPEATABLE READ'.freeze, :serializable=>'SERIALIZABLE'.freeze}
POSTGRES_DEFAULT_RE = /\A(?:B?('.*')::[^']+|\((-?\d+(?:\.\d+)?)\))\z/
MSSQL_DEFAULT_RE = /\A(?:\(N?('.*')\)|\(\((-?\d+(?:\.\d+)?)\)\))\z/
MYSQL_TIMESTAMP_RE = /\ACURRENT_(?:DATE|TIMESTAMP)?\z/
STRING_DEFAULT_RE = /\A'(.*)'\z/

Attributes

prepared_statements  [R]  The prepared statement objects for this database, keyed by name
transaction_isolation_level  [RW]  The default transaction isolation level for this database, used for all future transactions. For MSSQL, this should be set to something if you ever plan to use the :isolation option to Database#transaction, as on MSSQL if affects all future transactions on the same connection.

Public Instance methods

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

[Source]

    # File lib/sequel/database/query.rb, line 41
41:     def <<(sql)
42:       run(sql)
43:     end

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

[Source]

    # File lib/sequel/database/query.rb, line 47
47:     def call(ps_name, hash={})
48:       prepared_statements[ps_name].call(hash)
49:     end

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.

[Source]

    # File lib/sequel/extensions/schema_dumper.rb, line 13
13:     def dump_indexes_migration(options={})
14:       ts = tables(options)
15:       "Sequel.migration do\n  up do\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :add_index, options)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\n  \n  down do\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :drop_index, options)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\nend\n"
16:     end

Return a string that contains a Sequel::Migration subclass that when run would recreate the database structure. Options:

  • :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).

[Source]

    # File lib/sequel/extensions/schema_dumper.rb, line 38
38:     def dump_schema_migration(options={})
39:       ts = tables(options)
40:       "Sequel.migration do\n  up do\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_schema(t, options)}.join(\"\\n\\n\").gsub(/^/o, '    ')}\n  end\n  \n  down do\n    drop_table(\#{ts.sort_by{|t| t.to_s}.inspect[1...-1]})\n  end\nend\n"
41:     end

Return a string with a create table block that will recreate the given table‘s schema. Takes the same options as dump_schema_migration.

[Source]

    # File lib/sequel/extensions/schema_dumper.rb, line 56
56:     def dump_table_schema(table, options={})
57:       table = table.value.to_s if table.is_a?(SQL::Identifier)
58:       raise(Error, "must provide table as a Symbol, String, or Sequel::SQL::Identifier") unless [String, Symbol].any?{|c| table.is_a?(c)}
59:       s = schema(table).dup
60:       pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first}
61:       options = options.merge(:single_pk=>true) if pks.length == 1
62:       m = method(:column_schema_to_generator_opts)
63:       im = method(:index_to_generator_opts)
64:       begin
65:         indexes = indexes(table).sort_by{|k,v| k.to_s} if options[:indexes] != false
66:       rescue Sequel::NotImplemented
67:         nil
68:       end
69:       gen = Schema::Generator.new(self) do
70:         s.each{|name, info| send(*m.call(name, info, options))}
71:         primary_key(pks) if !@primary_key && pks.length > 0
72:         indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts))} if indexes
73:       end
74:       commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n")
75:       "create_table(#{table.inspect}#{', :ignore_index_errors=>true' if !options[:same_db] && options[:indexes] != false && indexes && !indexes.empty?}) do\n#{commands.gsub(/^/o, '  ')}\nend"
76:     end

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/query.rb, line 53
53:     def execute(sql, opts={})
54:       raise NotImplemented, "#execute should be overridden by adapters"
55:     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/query.rb, line 60
60:     def execute_ddl(sql, opts={}, &block)
61:       execute_dui(sql, opts, &block)
62:     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/query.rb, line 67
67:     def execute_dui(sql, opts={}, &block)
68:       execute(sql, opts, &block)
69:     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/query.rb, line 74
74:     def execute_insert(sql, opts={}, &block)
75:       execute_dui(sql, opts, &block)
76:     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/query.rb, line 85
85:     def get(*args, &block)
86:       dataset.get(*args, &block)
87:     end

Return a hash containing index information. 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.

[Source]

    # File lib/sequel/database/query.rb, line 95
95:     def indexes(table, opts={})
96:       raise NotImplemented, "#indexes should be overridden by adapters"
97:     end

Return a dataset modified by the query block

[Source]

    # File lib/sequel/extensions/query.rb, line 8
 8:     def query(&block)
 9:       dataset.query(&block)
10:     end

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

  • :server - The server to run the SQL on.

[Source]

     # File lib/sequel/database/query.rb, line 102
102:     def run(sql, opts={})
103:       execute_ddl(sql, opts)
104:       nil
105:     end

Parse the schema from the database. Returns the schema for the given table as an array with all members being arrays of length 2, the first member being the column name, and the second member being a hash of column information. Available options are:

  • :reload - Get fresh information from the database, instead of using cached information. If table_name is blank, :reload should be used unless you are sure that schema has not been called before with a table_name, otherwise you may only getting the schemas for tables that have been requested explicitly.
  • :schema - An explicit schema to use. It may also be implicitly provided via the table name.

[Source]

     # File lib/sequel/database/query.rb, line 119
119:     def schema(table, opts={})
120:       raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true)
121: 
122:       sch, table_name = schema_and_table(table)
123:       quoted_name = quote_schema_table(table)
124:       opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema)
125: 
126:       @schemas.delete(quoted_name) if opts[:reload]
127:       return @schemas[quoted_name] if @schemas[quoted_name]
128: 
129:       cols = schema_parse_table(table_name, opts)
130:       raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty?
131:       cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])}
132:       @schemas[quoted_name] = cols
133:     end

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

[Source]

     # File lib/sequel/database/query.rb, line 137
137:     def table_exists?(name)
138:       begin 
139:         from(name).first
140:         true
141:       rescue
142:         false
143:       end
144:     end

Return all tables in the database as an array of symbols.

[Source]

     # File lib/sequel/database/query.rb, line 147
147:     def tables(opts={})
148:       raise NotImplemented, "#tables should be overridden by adapters"
149:     end

Starts a database transaction. When a database transaction is used, either all statements are successful or none of the statements are successful. Note that MySQL MyISAM tabels do not support transactions.

The following options are respected:

:isolation :The transaction isolation level to use for this transaction, should be :uncommitted, :committed, :repeatable, or :serializable.
:prepare :A string to use as the transaction identifier for a prepared transaction (two-phase commit), if the database/adapter supports prepared transactions
: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.

[Source]

     # File lib/sequel/database/query.rb, line 167
167:     def transaction(opts={}, &block)
168:       synchronize(opts[:server]) do |conn|
169:         return yield(conn) if already_in_transaction?(conn, opts)
170:         _transaction(conn, opts, &block)
171:       end
172:     end