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

Database class for PostgreSQL databases used with Sequel and the pg, postgres, or postgres-pr driver.

Methods

<<   []   adapter_class   adapter_scheme   adapter_scheme   add_column   add_index   add_servers   alter_table   call   call_sproc   call_sproc   cast_type_literal   connect   connect   connect   connect   connect   connect   connect   connect   create_or_replace_view   create_table   create_table!   create_table?   create_view   database_type   dataset   dataset   dataset   dataset   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   execute   execute   execute   execute_ddl   execute_ddl   execute_ddl   execute_dui   execute_dui   execute_dui   execute_dui   execute_dui   execute_insert   execute_insert   execute_insert   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   new   new   query   quote_identifiers=   quote_identifiers=   quote_identifiers?   remove_servers   rename_column   rename_table   run   schema   select   serial_primary_key_options   server_version   servers   set_column_default   set_column_type   single_threaded=   single_threaded?   single_value   subadapter   supports_create_table_if_not_exists?   supports_prepared_transactions?   supports_savepoints?   supports_transaction_isolation_levels?   synchronize   table_exists?   tables   tables   test_connection   transaction   typecast_value   uri   uri   uri   url   views   views  

Included Modules

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 object hash for this database, keyed by name symbol
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.

  DB[:items].filter(:id=>1).prepare(:first, :sa)
  DB.call(:sa) # SELECT * FROM items WHERE id = 1

[Source]

    # File lib/sequel/database/query.rb, line 50
50:     def call(ps_name, hash={})
51:       prepared_statements[ps_name].call(hash)
52:     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 56
56:     def execute(sql, opts={})
57:       raise NotImplemented, "#execute should be overridden by adapters"
58:     end

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

[Source]

    # File lib/sequel/database/query.rb, line 63
63:     def execute_ddl(sql, opts={}, &block)
64:       execute_dui(sql, opts, &block)
65:     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 70
70:     def execute_dui(sql, opts={}, &block)
71:       execute(sql, opts, &block)
72:     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 77
77:     def execute_insert(sql, opts={}, &block)
78:       execute_dui(sql, opts, &block)
79:     end

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

  DB.get(1) # SELECT 1
  # => 1
  DB.get{version{}} # SELECT server_version()

[Source]

    # File lib/sequel/database/query.rb, line 86
86:     def get(*args, &block)
87:       dataset.get(*args, &block)
88:     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.

  DB.indexes(:artists)
  # => {:artists_name_ukey=>{:columns=>[:name], :unique=>true}}

[Source]

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

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

:server :The server to run the SQL on.
  DB.run("SET some_server_variable = 42")

[Source]

     # File lib/sequel/database/query.rb, line 108
108:     def run(sql, opts={})
109:       execute_ddl(sql, opts)
110:       nil
111:     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 :Ignore any cached results, and get fresh information from the database.
:schema :An explicit schema to use. It may also be implicitly provided via the table name.

If schema parsing is supported by the database, the column information should at least contain the following columns:

:allow_null :Whether NULL is an allowed value for the column.
:db_type :The database type for the column, as a database specific string.
:default :The database default for the column, as a database specific string.
:primary_key :Whether the columns is a primary key column. If this column is not present, it means that primary key information is unavailable, not that the column is not a primary key.
:ruby_default :The database default for the column, as a ruby object. In many cases, complex database defaults cannot be parsed into ruby objects.
:type :A symbol specifying the type, such as :integer or :string.

Example:

  DB.schema(:artists)
  # [[:id,
  #   {:type=>:integer,
  #    :primary_key=>true,
  #    :default=>"nextval('artist_id_seq'::regclass)",
  #    :ruby_default=>nil,
  #    :db_type=>"integer",
  #    :allow_null=>false}],
  #  [:name,
  #   {:type=>:string,
  #    :primary_key=>false,
  #    :default=>nil,
  #    :ruby_default=>nil,
  #    :db_type=>"text",
  #    :allow_null=>false}]]

[Source]

     # File lib/sequel/database/query.rb, line 152
152:     def schema(table, opts={})
153:       raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true)
154: 
155:       sch, table_name = schema_and_table(table)
156:       quoted_name = quote_schema_table(table)
157:       opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema)
158: 
159:       @schemas.delete(quoted_name) if opts[:reload]
160:       return @schemas[quoted_name] if @schemas[quoted_name]
161: 
162:       cols = schema_parse_table(table_name, opts)
163:       raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty?
164:       cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])}
165:       @schemas[quoted_name] = cols
166:     end

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

  DB.table_exists?(:foo) # => false

[Source]

     # File lib/sequel/database/query.rb, line 172
172:     def table_exists?(name)
173:       begin 
174:         from(name).first
175:         true
176:       rescue
177:         false
178:       end
179:     end

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

  DB.tables # => [:albums, :artists]

[Source]

     # File lib/sequel/database/query.rb, line 184
184:     def tables(opts={})
185:       raise NotImplemented, "#tables should be overridden by adapters"
186:     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, used if given and the database/adapter supports customizable transaction isolation levels.
:prepare :A string to use as the transaction identifier for a prepared transaction (two-phase commit), if the database/adapter supports prepared transactions.
: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 206
206:     def transaction(opts={}, &block)
207:       synchronize(opts[:server]) do |conn|
208:         return yield(conn) if already_in_transaction?(conn, opts)
209:         _transaction(conn, opts, &block)
210:       end
211:     end

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

  DB.views # => [:gold_albums, :artists_with_many_albums]

[Source]

     # File lib/sequel/database/query.rb, line 216
216:     def views(opts={})
217:       raise NotImplemented, "#views should be overridden by adapters"
218:     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
COLUMN_DEFINITION_ORDER = [:collate, :default, :null, :unique, :primary_key, :auto_increment, :references]   The order of column modifiers to use when defining a column.

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 33
33:     def add_column(table, *args)
34:       alter_table(table) {add_column(*args)}
35:     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 46
46:     def add_index(table, columns, options={})
47:       e = options[:ignore_errors]
48:       begin
49:         alter_table(table){add_index(columns, options)}
50:       rescue DatabaseError
51:         raise unless e
52:       end
53:     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 72
72:     def alter_table(name, generator=nil, &block)
73:       generator ||= Schema::AlterTableGenerator.new(self, &block)
74:       alter_table_sql_list(name, generator.operations).flatten.each {|sql| execute_ddl(sql)}
75:       remove_cached_schema(name)
76:       nil
77:     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 125
125:     def create_or_replace_view(name, source)
126:       source = source.sql if source.is_a?(Dataset)
127:       execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}")
128:       remove_cached_schema(name)
129:       nil
130:     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 93
 93:     def create_table(name, options={}, &block)
 94:       remove_cached_schema(name)
 95:       options = {:generator=>options} if options.is_a?(Schema::Generator)
 96:       generator = options[:generator] || Schema::Generator.new(self, &block)
 97:       create_table_from_generator(name, generator, options)
 98:       create_table_indexes_from_generator(name, generator, options)
 99:       nil
100:     end

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

  DB.create_table!(:a){Integer :a}
  # DROP TABLE a
  # CREATE TABLE a (a integer)

[Source]

     # File lib/sequel/database/schema_methods.rb, line 107
107:     def create_table!(name, options={}, &block)
108:       drop_table(name) rescue nil
109:       create_table(name, options, &block)
110:     end

Creates the table unless the table already exists

[Source]

     # File lib/sequel/database/schema_methods.rb, line 113
113:     def create_table?(name, options={}, &block)
114:       if supports_create_table_if_not_exists?
115:         create_table(name, options.merge(:if_not_exists=>true), &block)
116:       elsif !table_exists?(name)
117:         create_table(name, options, &block)
118:       end
119:     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 136
136:     def create_view(name, source)
137:       source = source.sql if source.is_a?(Dataset)
138:       execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}")
139:     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 146
146:     def drop_column(table, *args)
147:       alter_table(table) {drop_column(*args)}
148:     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 156
156:     def drop_index(table, columns, options={})
157:       alter_table(table){drop_index(columns, options)}
158:     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 163
163:     def drop_table(*names)
164:       names.each do |n|
165:         execute_ddl(drop_table_sql(n))
166:         remove_cached_schema(n)
167:       end
168:       nil
169:     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 174
174:     def drop_view(*names)
175:       names.each do |n|
176:         execute_ddl("DROP VIEW #{quote_schema_table(n)}")
177:         remove_cached_schema(n)
178:       end
179:       nil
180:     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 199
199:     def rename_column(table, *args)
200:       alter_table(table) {rename_column(*args)}
201:     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 187
187:     def rename_table(name, new_name)
188:       execute_ddl(rename_table_sql(name, new_name))
189:       remove_cached_schema(name)
190:       nil
191:     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 208
208:     def set_column_default(table, *args)
209:       alter_table(table) {set_column_default(*args)}
210:     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 217
217:     def set_column_type(table, *args)
218:       alter_table(table) {set_column_type(*args)}
219:     end

Methods that create datasets

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

Public Instance methods

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

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

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

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

[Source]

    # File lib/sequel/database/dataset.rb, line 19
19:     def [](*args)
20:       (String === args.first) ? fetch(*args) : from(*args)
21:     end

Returns a blank dataset for this database.

  DB.dataset # SELECT *
  DB.dataset.from(:items) # SELECT * FROM items

[Source]

    # File lib/sequel/database/dataset.rb, line 27
27:     def dataset
28:       ds = Sequel::Dataset.new(self)
29:     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 fetch method returns a dataset instance:

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

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

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

[Source]

    # File lib/sequel/database/dataset.rb, line 44
44:     def fetch(sql, *args, &block)
45:       ds = dataset.with_sql(sql, *args)
46:       ds.each(&block) if block
47:       ds
48:     end

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

  DB.from(:items) # SELECT * FROM items
  DB.from(:items){id > 2} # SELECT * FROM items WHERE (id > 2)

[Source]

    # File lib/sequel/database/dataset.rb, line 55
55:     def from(*args, &block)
56:       ds = dataset.from(*args)
57:       block ? ds.filter(&block) : ds
58:     end

Returns a new dataset with the select method invoked.

  DB.select(1) # SELECT 1
  DB.select{server_version{}} # SELECT server_version()
  DB.select(:id).from(:items) # SELECT id FROM items

[Source]

    # File lib/sequel/database/dataset.rb, line 65
65:     def select(*args, &block)
66:       dataset.select(*args, &block)
67:     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 mysql2 odbc openbase oracle postgres sqlite swift tinytds'.collect{|x| x.to_sym}   Array of supported database adapters

Attributes

pool  [R]  The connection pool for this Database instance. All Database instances have their own connection pools.

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:       return scheme if scheme.is_a?(Class)
19: 
20:       scheme = scheme.to_s.gsub('-', '_').to_sym
21:       
22:       unless klass = ADAPTER_MAP[scheme]
23:         # attempt to load the adapter file
24:         begin
25:           Sequel.tsk_require "sequel/adapters/#{scheme}"
26:         rescue LoadError => e
27:           raise Sequel.convert_exception_class(e, AdapterNotFound)
28:         end
29:         
30:         # make sure we actually loaded the adapter
31:         unless klass = ADAPTER_MAP[scheme]
32:           raise AdapterNotFound, "Could not load #{scheme} adapter: adapter class not registered in ADAPTER_MAP"
33:         end
34:       end
35:       klass
36:     end

Returns the scheme symbol for the Database class.

[Source]

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

Connects to a database. See Sequel.connect.

[Source]

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

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

[Source]

    # File lib/sequel/database/connecting.rb, line 88
88:     def self.single_threaded=(value)
89:       @@single_threaded = value
90:     end

Public Instance methods

Returns the scheme symbol for this instance‘s class, which reflects which adapter is being used. In some cases, this can be the same as the database_type (for native adapters), in others (i.e. adapters with subadapters), it will be different.

  Sequel.connect('jdbc:postgres://...').adapter_scheme # => :jdbc

[Source]

     # File lib/sequel/database/connecting.rb, line 120
120:     def adapter_scheme
121:       self.class.adapter_scheme
122:     end

Dynamically add new servers or modify server options at runtime. Also adds new servers to the connection pool. Intended for use with master/slave or shard configurations where it is useful to add new server hosts at runtime.

servers argument should be a hash with server name symbol keys and hash or proc values. If a servers key is already in use, it‘s value is overridden with the value provided.

  DB.add_servers(:f=>{:host=>"hash_host_f"})

[Source]

     # File lib/sequel/database/connecting.rb, line 133
133:     def add_servers(servers)
134:       @opts[:servers] = @opts[:servers] ? @opts[:servers].merge(servers) : servers
135:       @pool.add_servers(servers.keys)
136:     end

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

[Source]

     # File lib/sequel/database/connecting.rb, line 139
139:     def connect(server)
140:       raise NotImplemented, "#connect should be overridden by adapters"
141:     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).

  Sequel.connect('jdbc:postgres://...').database_type # => :postgres

[Source]

     # File lib/sequel/database/connecting.rb, line 152
152:     def database_type
153:       adapter_scheme
154:     end

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

Example:

  DB.disconnect # All servers
  DB.disconnect(:servers=>:server1) # Single server
  DB.disconnect(:servers=>[:server1, :server2]) # Multiple servers

[Source]

     # File lib/sequel/database/connecting.rb, line 166
166:     def disconnect(opts = {})
167:       pool.disconnect(opts)
168:     end

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

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

[Source]

     # File lib/sequel/database/connecting.rb, line 175
175:     def each_server(&block)
176:       servers.each{|s| self.class.connect(server_opts(s), &block)}
177:     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 189
189:     def remove_servers(*servers)
190:       if @opts[:servers] && !@opts[:servers].empty?
191:         servs = @opts[:servers].dup
192:         servers.flatten!
193:         servers.each{|s| servs.delete(s)}
194:         @opts[:servers] = servs
195:         @pool.remove_servers(servers)
196:       end
197:     end

An array of servers/shards for this Database object.

  DB.servers # Unsharded: => [:default]
  DB.servers # Sharded:   => [:default, :server1, :server2]

[Source]

     # File lib/sequel/database/connecting.rb, line 203
203:     def servers
204:       pool.servers
205:     end

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

[Source]

     # File lib/sequel/database/connecting.rb, line 208
208:     def single_threaded?
209:       @single_threaded
210:     end

Acquires a database connection, yielding it to the passed block. This is useful if you want to make sure the same connection is used for all database queries in the block. It is also useful if you want to gain direct access to the underlying connection object if you need to do something Sequel does not natively support.

If a server option is given, acquires a connection for that specific server, instead of the :default server.

  DB.synchronize do |conn|
    ...
  end

[Source]

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

Attempts to acquire a database connection. Returns true if successful. Will probably raise an Error if unsuccessful. If a server argument is given, attempts to acquire a database connection to the given server/shard.

[Source]

     # File lib/sequel/database/connecting.rb, line 233
233:     def test_connection(server=nil)
234:       synchronize(server){|conn|}
235:       true
236:     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.
sql_log_level  [RW]  Log level at which to log SQL queries. This is actually the method sent to the logger, so it should be the method name symbol. The default is :info, it can be set to :debug to log at DEBUG level.

Public Instance methods

Log a message at level info to all loggers.

[Source]

    # File lib/sequel/database/logging.rb, line 21
21:     def log_info(message, args=nil)
22:       log_each(:info, args ? "#{message}; #{args.inspect}" : message)
23:     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 27
27:     def log_yield(sql, args=nil)
28:       return yield if @loggers.empty?
29:       sql = "#{sql}; #{args.inspect}" if args
30:       start = Time.now
31:       begin
32:         yield
33:       rescue => e
34:         log_each(:error, "#{e.class}: #{e.message.strip}: #{sql}")
35:         raise
36:       ensure
37:         log_duration(Time.now - start, sql) unless e
38:       end
39:     end

Remove any existing loggers and just use the given logger:

  DB.logger = Logger.new($stdout)

[Source]

    # File lib/sequel/database/logging.rb, line 44
44:     def logger=(logger)
45:       @loggers = Array(logger)
46:     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:

  DB[:items] # SELECT * FROM items
  DB.identifier_input_method = :upcase
  DB[:items] # SELECT * FROM ITEMS

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 66
66:     def identifier_input_method=(v)
67:       reset_schema_utility_dataset
68:       @identifier_input_method = v || ""
69:     end

The method to call on identifiers coming from the database

[Source]

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

Set the method to call on identifiers coming from the database:

  DB[:items].first # {:id=>1, :name=>'foo'}
  DB.identifier_output_method = :upcase
  DB[:items].first # {:ID=>1, :NAME=>'foo'}

[Source]

    # File lib/sequel/database/dataset_defaults.rb, line 89
89:     def identifier_output_method=(v)
90:       reset_schema_utility_dataset
91:       @identifier_output_method = v || ""
92:     end

Set whether to quote identifiers (columns and tables) for this database:

  DB[:items] # SELECT * FROM items
  DB.quote_identifiers = true
  DB[:items] # SELECT * FROM "items"

[Source]

     # File lib/sequel/database/dataset_defaults.rb, line 99
 99:     def quote_identifiers=(v)
100:       reset_schema_utility_dataset
101:       @quote_identifiers = v
102:     end

Returns true if the database quotes identifiers.

[Source]

     # File lib/sequel/database/dataset_defaults.rb, line 105
105:     def quote_identifiers?
106:       return @quote_identifiers unless @quote_identifiers.nil?
107:       @quote_identifiers = @opts.fetch(:quote_identifiers, (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers))
108:     end

Miscellaneous methods

These methods don‘t fit neatly into another category.

Constants

MYSQL_DATABASE_DISCONNECT_ERRORS = /\A(Commands out of sync; you can't run this command now|Can't connect to local MySQL server through socket|MySQL server has gone away|Lost connection to MySQL server during query)/   Mysql::Error messages that indicate the current connection should be disconnected

Attributes

conversion_procs  [R]  A hash of conversion procs, keyed by type integer (oid) and having callable values for the conversion proc for that type.
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
opts  [R]  The options hash for this database
swift_class  [RW]  The Swift adapter class being used by this database. Connections in this database‘s connection pool will be instances of this class.

Public Class methods

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

Accepts the following options:

:default_schema :The default schema to use, should generally be nil
:disconnection_proc :A proc used to disconnect the connection
:identifier_input_method :A string method symbol to call on identifiers going into the database
:identifier_output_method :A string method symbol to call on identifiers coming from the database
:logger :A specific logger to use
:loggers :An array of loggers to use
:quote_identifiers :Whether to quote identifiers
:servers :A hash specifying a server/shard specific options, keyed by shard symbol
:single_threaded :Whether to use a single-threaded connection pool
:sql_log_level :Method to use to log SQL to a logger, :info by default.

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

[Source]

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

Add the primary_keys and primary_key_sequences instance variables, so we can get the correct return values for inserted rows.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 209
209:       def initialize(*args)
210:         super
211:         @primary_keys = {}
212:         @primary_key_sequences = {}
213:       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 116
116:       def initialize(opts)
117:         super
118:         @convert_types = typecast_value_boolean(@opts.fetch(:convert_types, true))
119:         raise(Error, "No connection string specified") unless uri
120:         
121:         resolved_uri = jndi? ? get_uri_from_jndi : uri
122: 
123:         if match = /\Ajdbc:([^:]+)/.match(resolved_uri) and prok = DATABASE_SETUP[match[1].to_sym]
124:           @driver = prok.call(self)
125:         end        
126:       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 db_type specified, since one is required to include the correct subadapter.

[Source]

    # File lib/sequel/adapters/swift.rb, line 44
44:       def initialize(opts)
45:         super
46:         if db_type = opts[:db_type] and !db_type.to_s.empty? 
47:           if prok = DATABASE_SETUP[db_type.to_s.to_sym]
48:             prok.call(self)
49:           else
50:             raise(Error, "No :db_type option specified")
51:           end
52:         else
53:           raise(Error, ":db_type option not valid, should be postgres, mysql, or sqlite")
54:         end
55:       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 130
130:       def call_sproc(name, opts = {})
131:         args = opts[:args] || []
132:         sql = "{call #{name}(#{args.map{'?'}.join(',')})}"
133:         synchronize(opts[:server]) do |conn|
134:           cps = conn.prepareCall(sql)
135: 
136:           i = 0
137:           args.each{|arg| set_ps_arg(cps, arg, i+=1)}
138: 
139:           begin
140:             if block_given?
141:               yield log_yield(sql){cps.executeQuery}
142:             else
143:               case opts[:type]
144:               when :insert
145:                 log_yield(sql){cps.executeUpdate}
146:                 last_insert_id(conn, opts)
147:               else
148:                 log_yield(sql){cps.executeUpdate}
149:               end
150:             end
151:           rescue NativeException, JavaSQL::SQLException => e
152:             raise_error(e)
153:           ensure
154:             cps.close
155:           end
156:         end
157:       end

Support stored procedures on MySQL

[Source]

    # File lib/sequel/adapters/mysql.rb, line 94
94:       def call_sproc(name, opts={}, &block)
95:         args = opts[:args] || [] 
96:         execute("CALL #{name}#{args.empty? ? '()' : literal(args)}", opts.merge(:sproc=>false), &block)
97:       end

Cast the given type to a literal type

  DB.cast_type_literal(Float) # double precision
  DB.cast_type_literal(:foo) # foo

[Source]

    # File lib/sequel/database/misc.rb, line 67
67:     def cast_type_literal(type)
68:       type_literal(:type=>type)
69:     end

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 160
160:       def connect(server)
161:         opts = server_opts(server)
162:         conn = if jndi?
163:           get_connection_from_jndi
164:         else
165:           args = [uri(opts)]
166:           args.concat([opts[:user], opts[:password]]) if opts[:user] && opts[:password]
167:           begin
168:             JavaSQL::DriverManager.getConnection(*args)
169:           rescue => e
170:             raise e unless driver
171:             # If the DriverManager can't get the connection - use the connect
172:             # method of the driver. (This happens under Tomcat for instance)
173:             props = java.util.Properties.new
174:             if opts && opts[:user] && opts[:password]
175:               props.setProperty("user", opts[:user])
176:               props.setProperty("password", opts[:password])
177:             end
178:             opts[:jdbc_properties].each{|k,v| props.setProperty(k.to_s, v)} if opts[:jdbc_properties]
179:             begin
180:               driver.new.connect(args[0], props)
181:             rescue => e2
182:               e.message << "\n#{e2.class.name}: #{e2.message}"
183:               raise e
184:             end
185:           end
186:         end
187:         setup_connection(conn)
188:       end

Create an instance of swift_class for the given options.

[Source]

    # File lib/sequel/adapters/swift.rb, line 58
58:       def connect(server)
59:         setup_connection(swift_class.new(server_opts(server)))
60:       end

Connect to the database. Since SQLite is a file based database, the only options available are :database (to specify the database name), and :timeout, to specify how long to wait for the database to be available if it is locked, given in milliseconds (default is 5000).

[Source]

    # File lib/sequel/adapters/sqlite.rb, line 59
59:       def connect(server)
60:         opts = server_opts(server)
61:         opts[:database] = ':memory:' if blank_object?(opts[:database])
62:         db = ::SQLite3::Database.new(opts[:database])
63:         db.busy_timeout(opts.fetch(:timeout, 5000))
64:         
65:         connection_pragmas.each{|s| log_yield(s){db.execute_batch(s)}}
66:         
67:         class << db
68:           attr_reader :prepared_statements
69:         end
70:         db.instance_variable_set(:@prepared_statements, {})
71:         
72:         db
73:       end

Connect to the database. In addition to the usual database options, the following options have effect:

  • :auto_is_null - Set to true to use MySQL default behavior of having a filter for an autoincrement column equals NULL to return the last inserted row.
  • :charset - Same as :encoding (:encoding takes precendence)
  • :compress - Set to false to not compress results from the server
  • :config_default_group - The default group to read from the in the MySQL config file.
  • :config_local_infile - If provided, sets the Mysql::OPT_LOCAL_INFILE option on the connection with the given value.
  • :connect_timeout - Set the timeout in seconds before a connection attempt is abandoned.
  • :encoding - Set all the related character sets for this connection (connection, client, database, server, and results).
  • :read_timeout - Set the timeout in seconds for reading back results to a query.
  • :socket - Use a unix socket file instead of connecting via TCP/IP.
  • :timeout - Set the timeout in seconds before the server will disconnect this connection (a.k.a @@wait_timeout).

[Source]

     # File lib/sequel/adapters/mysql.rb, line 120
120:       def connect(server)
121:         opts = server_opts(server)
122:         conn = Mysql.init
123:         conn.options(Mysql::READ_DEFAULT_GROUP, opts[:config_default_group] || "client")
124:         conn.options(Mysql::OPT_LOCAL_INFILE, opts[:config_local_infile]) if opts.has_key?(:config_local_infile)
125:         conn.ssl_set(opts[:sslkey], opts[:sslcert], opts[:sslca], opts[:sslcapath], opts[:sslcipher]) if opts[:sslca] || opts[:sslkey]
126:         if encoding = opts[:encoding] || opts[:charset]
127:           # Set encoding before connecting so that the mysql driver knows what
128:           # encoding we want to use, but this can be overridden by READ_DEFAULT_GROUP.
129:           conn.options(Mysql::SET_CHARSET_NAME, encoding)
130:         end
131:         if read_timeout = opts[:read_timeout] and defined? Mysql::OPT_READ_TIMEOUT
132:           conn.options(Mysql::OPT_READ_TIMEOUT, read_timeout)
133:         end
134:         if connect_timeout = opts[:connect_timeout] and defined? Mysql::OPT_CONNECT_TIMEOUT
135:           conn.options(Mysql::OPT_CONNECT_TIMEOUT, connect_timeout)
136:         end
137:         conn.real_connect(
138:           opts[:host] || 'localhost',
139:           opts[:user],
140:           opts[:password],
141:           opts[:database],
142:           opts[:port],
143:           opts[:socket],
144:           Mysql::CLIENT_MULTI_RESULTS +
145:           Mysql::CLIENT_MULTI_STATEMENTS +
146:           (opts[:compress] == false ? 0 : Mysql::CLIENT_COMPRESS)
147:         )
148:         sqls = []
149:         # Set encoding a slightly different way after connecting,
150:         # in case the READ_DEFAULT_GROUP overrode the provided encoding.
151:         # Doesn't work across implicit reconnects, but Sequel doesn't turn on
152:         # that feature.
153:         sqls << "SET NAMES #{literal(encoding.to_s)}" if encoding
154: 
155:         # Increase timeout so mysql server doesn't disconnect us
156:         # Value used by default is maximum allowed value on Windows.
157:         sqls << "SET @@wait_timeout = #{opts[:timeout] || 2147483}"
158: 
159:         # By default, MySQL 'where id is null' selects the last inserted id
160:         sqls << "SET SQL_AUTO_IS_NULL=0" unless opts[:auto_is_null]
161: 
162:         sqls.each{|sql| log_yield(sql){conn.query(sql)}}
163: 
164:         class << conn
165:           attr_accessor :prepared_statements
166:         end
167:         conn.prepared_statements = {}
168:         conn
169:       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

Connects to the database. In addition to the standard database options, using the :encoding or :charset option changes the client encoding for the connection.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 218
218:       def connect(server)
219:         opts = server_opts(server)
220:         conn = Adapter.connect(
221:           (opts[:host] unless blank_object?(opts[:host])),
222:           opts[:port] || 5432,
223:           nil, '',
224:           opts[:database],
225:           opts[:user],
226:           opts[:password]
227:         )
228:         if encoding = opts[:encoding] || opts[:charset]
229:           if conn.respond_to?(:set_client_encoding)
230:             conn.set_client_encoding(encoding)
231:           else
232:             conn.async_exec("set client_encoding to '#{encoding}'")
233:           end
234:         end
235:         conn.db = self
236:         conn.apply_connection_settings
237:         @conversion_procs ||= get_conversion_procs(conn)
238:         conn
239:       end

Return instance of Sequel::SQLite::Dataset with the given options.

[Source]

    # File lib/sequel/adapters/sqlite.rb, line 76
76:       def dataset(opts = nil)
77:         SQLite::Dataset.new(self, opts)
78:       end

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 191
191:       def dataset(opts = nil)
192:         JDBC::Dataset.new(self, opts)
193:       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

Return instance of Sequel::Postgres::Dataset with the given options.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 242
242:       def dataset(opts = nil)
243:         Postgres::Dataset.new(self, opts)
244:       end

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

[Source]

    # File lib/sequel/adapters/swift.rb, line 63
63:       def dataset(opts = nil)
64:         Swift::Dataset.new(self, opts)
65:       end

Returns instance of Sequel::MySQL::Dataset with the given options.

[Source]

     # File lib/sequel/adapters/mysql.rb, line 172
172:       def dataset(opts = nil)
173:         MySQL::Dataset.new(self, opts)
174:       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

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 197
197:       def execute(sql, opts={}, &block)
198:         return call_sproc(sql, opts, &block) if opts[:sproc]
199:         return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)}
200:         synchronize(opts[:server]) do |conn|
201:           statement(conn) do |stmt|
202:             if block
203:               yield log_yield(sql){stmt.executeQuery(sql)}
204:             else
205:               case opts[:type]
206:               when :ddl
207:                 log_yield(sql){stmt.execute(sql)}
208:               when :insert
209:                 log_yield(sql) do
210:                   if requires_return_generated_keys?
211:                     stmt.executeUpdate(sql, JavaSQL::Statement.RETURN_GENERATED_KEYS)
212:                   else
213:                     stmt.executeUpdate(sql)
214:                   end
215:                 end
216:                 last_insert_id(conn, opts.merge(:stmt=>stmt))
217:               else
218:                 log_yield(sql){stmt.executeUpdate(sql)}
219:               end
220:             end
221:           end
222:         end
223:       end

Run the given SQL with the given arguments and yield each row.

[Source]

    # File lib/sequel/adapters/sqlite.rb, line 81
81:       def execute(sql, opts={}, &block)
82:         _execute(:select, sql, opts, &block)
83:       end

Execute the given SQL, yielding a Swift::Result if a block is given.

[Source]

    # File lib/sequel/adapters/swift.rb, line 68
68:       def execute(sql, opts={})
69:         synchronize(opts[:server]) do |conn|
70:           begin
71:             res = log_yield(sql){conn.execute(sql)}
72:             yield res if block_given?
73:             nil
74:           rescue SwiftError => e
75:             raise_error(e)
76:           end
77:         end
78:       end

Executes the given SQL using an available connection, yielding the connection if the block is given.

[Source]

     # File lib/sequel/adapters/mysql.rb, line 178
178:       def execute(sql, opts={}, &block)
179:         if opts[:sproc]
180:           call_sproc(sql, opts, &block)
181:         elsif sql.is_a?(Symbol)
182:           execute_prepared_statement(sql, opts, &block)
183:         else
184:           synchronize(opts[:server]){|conn| _execute(conn, sql, opts, &block)}
185:         end
186:       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 SQL with the given args on an available connection.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 247
247:       def execute(sql, opts={}, &block)
248:         check_database_errors do
249:           return execute_prepared_statement(sql, opts, &block) if Symbol === sql
250:           synchronize(opts[:server]){|conn| conn.execute(sql, opts[:arguments], &block)}
251:         end
252:       end

Drop any prepared statements on the connection when executing DDL. This is because prepared statements lock the table in such a way that you can‘t drop or alter the table while a prepared statement that references it still exists.

[Source]

    # File lib/sequel/adapters/sqlite.rb, line 93
93:       def execute_ddl(sql, opts={})
94:         synchronize(opts[:server]) do |conn|
95:           conn.prepared_statements.values.each{|cps, s| cps.close}
96:           conn.prepared_statements.clear
97:           super
98:         end
99:       end

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

[Source]

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

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

[Source]

    # File lib/sequel/adapters/swift.rb, line 82
82:       def execute_dui(sql, opts={})
83:         synchronize(opts[:server]) do |conn|
84:           begin
85:             log_yield(sql){conn.execute(sql).rows}
86:           rescue SwiftError => e
87:             raise_error(e)
88:           end
89:         end
90:       end

Run the given SQL with the given arguments and return the number of changed rows.

[Source]

    # File lib/sequel/adapters/sqlite.rb, line 86
86:       def execute_dui(sql, opts={})
87:         _execute(:update, sql, opts)
88:       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 SQL on this database, returning the primary key of the table being inserted to.

[Source]

     # File lib/sequel/adapters/swift.rb, line 94
 94:       def execute_insert(sql, opts={})
 95:         synchronize(opts[:server]) do |conn|
 96:           begin
 97:             log_yield(sql){conn.execute(sql).insert_id}
 98:           rescue SwiftError => e
 99:             raise_error(e)
100:           end
101:         end
102:       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

Insert the values into the table and return the primary key (if automatically generated).

[Source]

     # File lib/sequel/adapters/postgres.rb, line 256
256:       def execute_insert(sql, opts={})
257:         return execute(sql, opts) if Symbol === sql
258:         check_database_errors do
259:           synchronize(opts[:server]) do |conn|
260:             conn.execute(sql, opts[:arguments])
261:             insert_result(conn, opts[:table], opts[:values])
262:           end
263:         end
264:       end

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

[Source]

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

Run the given SQL with the given arguments and return the last inserted row id.

[Source]

     # File lib/sequel/adapters/sqlite.rb, line 102
102:       def execute_insert(sql, opts={})
103:         _execute(:insert, sql, opts)
104:       end

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

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 239
239:       def indexes(table, opts={})
240:         m = output_identifier_meth
241:         im = input_identifier_meth
242:         schema, table = schema_and_table(table)
243:         schema ||= opts[:schema]
244:         schema = im.call(schema) if schema
245:         table = im.call(table)
246:         indexes = {}
247:         metadata(:getIndexInfo, nil, schema, table, false, true) do |r|
248:           next unless name = r[:column_name]
249:           next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re 
250:           i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>[false, 0].include?(r[:non_unique])}
251:           i[:columns] << m.call(name)
252:         end
253:         indexes
254:       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 74
74:     def inspect
75:       "#<#{self.class}: #{(uri rescue opts).inspect}>" 
76:     end

Whether or not JNDI is being used for this connection.

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 257
257:       def jndi?
258:         !!(uri =~ JNDI_URI_REGEXP)
259:       end

Proxy the literal call to the dataset.

  DB.literal(1) # 1
  DB.literal(:a) # a
  DB.literal('a') # 'a'

[Source]

    # File lib/sequel/database/misc.rb, line 83
83:     def literal(v)
84:       schema_utility_dataset.literal(v)
85:     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

Default serial primary key options, used by the table creation code.

[Source]

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

Return the version of the MySQL server two which we are connecting.

[Source]

     # File lib/sequel/adapters/mysql.rb, line 189
189:       def server_version(server=nil)
190:         @server_version ||= (synchronize(server){|conn| conn.server_version if conn.respond_to?(:server_version)} || super)
191:       end

Run the given SQL with the given arguments and return the first value of the first row.

[Source]

     # File lib/sequel/adapters/sqlite.rb, line 107
107:       def single_value(sql, opts={})
108:         _execute(:single_value, sql, opts)
109:       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

Whether the database supports CREATE TABLE IF NOT EXISTS syntax, false by default.

[Source]

    # File lib/sequel/database/misc.rb, line 95
95:     def supports_create_table_if_not_exists?
96:       false
97:     end

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

[Source]

     # File lib/sequel/database/misc.rb, line 101
101:     def supports_prepared_transactions?
102:       false
103:     end

Whether the database and adapter support savepoints, false by default.

[Source]

     # File lib/sequel/database/misc.rb, line 106
106:     def supports_savepoints?
107:       false
108:     end

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

[Source]

     # File lib/sequel/database/misc.rb, line 111
111:     def supports_transaction_isolation_levels?
112:       false
113:     end

All tables in this database

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 262
262:       def tables(opts={})
263:         get_tables('TABLE', opts)
264:       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 120
120:     def typecast_value(column_type, value)
121:       return nil if value.nil?
122:       meth = "typecast_value_#{column_type}"
123:       begin
124:         respond_to?(meth, true) ? send(meth, value) : value
125:       rescue ArgumentError, TypeError => e
126:         raise Sequel.convert_exception_class(e, InvalidValue)
127:       end
128:     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 270
270:       def uri(opts={})
271:         opts = @opts.merge(opts)
272:         ur = opts[:uri] || opts[:url] || opts[:database]
273:         ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}"
274:       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

Returns the URI identifying the database, which may not be the same as the URI used when connecting. This method can raise an error if the database used options instead of a connection string, and will not include uri parameters.

  Sequel.connect('postgres://localhost/db?user=billg').url
  # => "postgres://billg@localhost/db"

[Source]

     # File lib/sequel/database/misc.rb, line 138
138:     def uri
139:       uri = URI::Generic.new(
140:         adapter_scheme.to_s,
141:         nil,
142:         @opts[:host],
143:         @opts[:port],
144:         nil,
145:         "/#{@opts[:database]}",
146:         nil,
147:         nil,
148:         nil
149:       )
150:       uri.user = @opts[:user]
151:       uri.password = @opts[:password] if uri.user
152:       uri.to_s
153:     end

Explicit alias of uri for easier subclassing.

[Source]

     # File lib/sequel/database/misc.rb, line 156
156:     def url
157:       uri
158:     end

All views in this database

[Source]

     # File lib/sequel/adapters/jdbc.rb, line 277
277:       def views(opts={})
278:         get_tables('VIEW', opts)
279:       end