Class Sequel::Database
In: lib/sequel_core/adapters/jdbc.rb
lib/sequel_core/adapters/do.rb
lib/sequel_core/database.rb
lib/sequel_core/database/schema.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

Included Modules

Schema::SQL

Constants

ADAPTERS = %w'ado db2 dbi do firebird informix jdbc mysql odbc openbase oracle postgres sqlite'.collect{|x| x.to_sym}   Array of supported database adapters
SQL_BEGIN = 'BEGIN'.freeze
SQL_COMMIT = 'COMMIT'.freeze
SQL_ROLLBACK = 'ROLLBACK'.freeze

Attributes

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

Public Class methods

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

[Source]

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

Returns the scheme for the Database class.

[Source]

     # File lib/sequel_core/database.rb, line 114
114:     def self.adapter_scheme
115:       @scheme
116:     end

Connects to a database. See Sequel.connect.

[Source]

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

The method to call on identifiers going into the database

[Source]

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

Set the method to call on identifiers going into the database

[Source]

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

The method to call on identifiers coming from the database

[Source]

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

Set the method to call on identifiers coming from the database

[Source]

     # File lib/sequel_core/database.rb, line 175
175:     def self.identifier_output_method=(v)
176:       @@identifier_output_method = v || ""
177:     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_core/adapters/jdbc.rb, line 95
 95:       def initialize(opts)
 96:         @opts = opts
 97:         raise(Error, "No connection string specified") unless uri
 98:         if match = /\Ajdbc:([^:]+)/.match(uri) and prok = DATABASE_SETUP[match[1].to_sym]
 99:           prok.call(self)
100:         end
101:         super(opts)
102:       end

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_core/adapters/do.rb, line 53
53:       def initialize(opts)
54:         @opts = opts
55:         @converted_exceptions = []
56:         raise(Error, "No connection string specified") unless uri
57:         if prok = DATABASE_SETUP[subadapter.to_sym]
58:           prok.call(self)
59:         end
60:         super(opts)
61:       end

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
  • :upcase_identifiers : Whether to upcase identifiers going into the database

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_core/database.rb, line 70
70:     def initialize(opts = {}, &block)
71:       @opts ||= opts
72:       
73:       @single_threaded = opts.include?(:single_threaded) ? opts[:single_threaded] : @@single_threaded
74:       @schemas = nil
75:       @default_schema = opts.include?(:default_schema) ? opts[:default_schema] : default_schema_default
76:       @prepared_statements = {}
77:       @transactions = []
78:       if opts.include?(:upcase_identifiers)
79:         @identifier_input_method = opts[:upcase_identifiers] ? :upcase : ""
80:       end
81:       @pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(connection_pool_default_options.merge(opts), &block)
82:       @pool.connection_proc = proc{|server| connect(server)} unless block
83:       @pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc]
84: 
85:       @loggers = Array(opts[:logger]) + Array(opts[:loggers])
86:       ::Sequel::DATABASES.push(self)
87:     end

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

[Source]

     # File lib/sequel_core/database.rb, line 181
181:     def self.quote_identifiers=(value)
182:       @@quote_identifiers = value
183:     end

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

[Source]

     # File lib/sequel_core/database.rb, line 187
187:     def self.single_threaded=(value)
188:       @@single_threaded = value
189:     end

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

[Source]

     # File lib/sequel_core/database.rb, line 193
193:     def self.upcase_identifiers=(value)
194:       self.identifier_input_method = value ? :upcase : nil
195:     end

Public Instance methods

Executes the supplied SQL statement. The SQL can be supplied as a string or as an array of strings. If an array is given, comments and excessive white space are removed. See also Array#to_sql.

[Source]

     # File lib/sequel_core/database.rb, line 233
233:     def <<(sql)
234:       execute_ddl((Array === sql) ? sql.to_sql : sql)
235:     end
>>(sql, *args, &block)

Alias for fetch

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].print

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_core/database.rb, line 247
247:     def [](*args, &block)
248:       (String === args.first) ? fetch(*args, &block) : from(*args, &block)
249:     end

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

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

See alter_table.

[Source]

    # File lib/sequel_core/database/schema.rb, line 10
10:     def add_column(table, *args)
11:       alter_table(table) {add_column(*args)}
12:     end

Adds an index to a table for the given columns:

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

See alter_table.

[Source]

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

Alters the given table with the specified block. Here are the currently available operations:

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

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

See Schema::AlterTableGenerator.

[Source]

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

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

[Source]

     # File lib/sequel_core/database.rb, line 253
253:     def call(ps_name, hash={})
254:       prepared_statements[ps_name].call(hash)
255:     end

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

[Source]

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

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

[Source]

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

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

[Source]

     # File lib/sequel_core/database.rb, line 258
258:     def connect
259:       raise NotImplementedError, "#connect should be overridden by adapters"
260:     end

Setup a DataObjects::Connection to the database.

[Source]

    # File lib/sequel_core/adapters/do.rb, line 64
64:       def connect(server)
65:         setup_connection(::DataObjects::Connection.new(uri(server_opts(server))))
66:       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_core/database/schema.rb, line 73
73:     def create_or_replace_view(name, source)
74:       remove_cached_schema(name)
75:       source = source.sql if source.is_a?(Dataset)
76:       execute_ddl("CREATE OR REPLACE VIEW #{quote_identifier(name)} AS #{source}")
77:     end

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

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

See Schema::Generator.

[Source]

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

Forcibly creates a table. If the table already exists it is dropped.

[Source]

    # File lib/sequel_core/database/schema.rb, line 64
64:     def create_table!(name, options={}, &block)
65:       drop_table(name) rescue nil
66:       create_table(name, options, &block)
67:     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_core/database/schema.rb, line 83
83:     def create_view(name, source)
84:       source = source.sql if source.is_a?(Dataset)
85:       execute_ddl("CREATE VIEW #{quote_identifier(name)} AS #{source}")
86:     end

Returns a blank dataset

[Source]

     # File lib/sequel_core/database.rb, line 263
263:     def dataset
264:       ds = Sequel::Dataset.new(self)
265:     end

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

[Source]

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

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

[Source]

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

Disconnects all available connections from the connection pool. If any connections are currently in use, they will not be disconnected.

[Source]

     # File lib/sequel_core/database.rb, line 269
269:     def disconnect
270:       pool.disconnect
271:     end

Removes a column from the specified table:

  DB.drop_column :items, :category

See alter_table.

[Source]

    # File lib/sequel_core/database/schema.rb, line 93
93:     def drop_column(table, *args)
94:       alter_table(table) {drop_column(*args)}
95:     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_core/database/schema.rb, line 103
103:     def drop_index(table, columns)
104:       alter_table(table) {drop_index(columns)}
105:     end

Drops one or more tables corresponding to the given table names:

  DB.drop_table(:posts, :comments)

[Source]

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

Drops a view:

  DB.drop_view(:cheap_items)

[Source]

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

Executes the given SQL. This method should be overridden in descendants.

[Source]

     # File lib/sequel_core/database.rb, line 274
274:     def execute(sql, opts={})
275:       raise NotImplementedError, "#execute should be overridden by adapters"
276:     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_core/adapters/do.rb, line 78
78:       def execute(sql, opts={})
79:         log_info(sql)
80:         synchronize(opts[:server]) do |conn|
81:           begin
82:             command = conn.create_command(sql)
83:             res = block_given? ? command.execute_reader : command.execute_non_query
84:           rescue Exception => e
85:             raise_error(e, :classes=>@converted_exceptions)
86:           end
87:           if block_given?
88:             begin
89:               yield(res)
90:             ensure
91:              res.close if res
92:             end
93:           elsif opts[:type] == :insert
94:             res.insert_id
95:           else
96:             res.affected_rows
97:           end
98:         end
99:       end

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

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

[Source]

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

Method that should be used when submitting any DDL (Data Definition Language) SQL. By default, calls execute_dui.

[Source]

     # File lib/sequel_core/database.rb, line 280
280:     def execute_ddl(sql, opts={}, &block)
281:       execute_dui(sql, opts, &block)
282:     end
execute_dui(sql, opts={}, &block)

Alias for execute

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

[Source]

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

Method that should be used when issuing a DELETE, UPDATE, or INSERT statement. By default, calls execute.

[Source]

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

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

[Source]

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

Method that should be used when issuing a INSERT statement. By default, calls execute_dui.

[Source]

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

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

[Source]

     # File lib/sequel_core/adapters/jdbc.rb, line 184
184:       def execute_insert(sql, opts={})
185:         execute(sql, {:type=>:insert}.merge(opts))
186:       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').print

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

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

[Source]

     # File lib/sequel_core/database.rb, line 309
309:     def fetch(sql, *args, &block)
310:       ds = dataset
311:       ds.opts[:sql] = Sequel::SQL::PlaceholderLiteralString.new(sql, args)
312:       ds.each(&block) if block
313:       ds
314:     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_core/database.rb, line 319
319:     def from(*args, &block)
320:       ds = dataset.from(*args)
321:       block ? ds.filter(&block) : ds
322:     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_core/database.rb, line 331
331:     def get(expr)
332:       dataset.get(expr)
333:     end

The method to call on identifiers going into the database

[Source]

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

Set the method to call on identifiers going into the database

[Source]

     # File lib/sequel_core/database.rb, line 349
349:     def identifier_input_method=(v)
350:       reset_schema_utility_dataset
351:       @identifier_input_method = v || ""
352:     end

The method to call on identifiers coming from the database

[Source]

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

Set the method to call on identifiers coming from the database

[Source]

     # File lib/sequel_core/database.rb, line 368
368:     def identifier_output_method=(v)
369:       reset_schema_utility_dataset
370:       @identifier_output_method = v || ""
371:     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_core/database.rb, line 376
376:     def inspect
377:       "#<#{self.class}: #{(uri rescue opts).inspect}>" 
378:     end

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

[Source]

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

Return the first logger or nil if no loggers are being used. Should only be used for backwards compatibility.

[Source]

     # File lib/sequel_core/database.rb, line 389
389:     def logger
390:       @loggers.first
391:     end

Replace the array of loggers with the given logger(s).

[Source]

     # File lib/sequel_core/database.rb, line 394
394:     def logger=(logger)
395:       @loggers = Array(logger)
396:     end

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

[Source]

     # File lib/sequel_core/database.rb, line 399
399:     def multi_threaded?
400:       !@single_threaded
401:     end

Returns a dataset modified by the given query block. See Dataset#query.

[Source]

     # File lib/sequel_core/database.rb, line 404
404:     def query(&block)
405:       dataset.query(&block)
406:     end

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

[Source]

     # File lib/sequel_core/database.rb, line 409
409:     def quote_identifiers=(v)
410:       reset_schema_utility_dataset
411:       @quote_identifiers = v
412:     end

Returns true if the database quotes identifiers.

[Source]

     # File lib/sequel_core/database.rb, line 415
415:     def quote_identifiers?
416:       return @quote_identifiers unless @quote_identifiers.nil?
417:       @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers)
418:     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_core/database/schema.rb, line 142
142:     def rename_column(table, *args)
143:       alter_table(table) {rename_column(*args)}
144:     end

Renames a table:

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

[Source]

     # File lib/sequel_core/database/schema.rb, line 132
132:     def rename_table(*args)
133:       execute_ddl(rename_table_sql(*args))
134:     end

Returns a new dataset with the select method invoked.

[Source]

     # File lib/sequel_core/database.rb, line 421
421:     def select(*args)
422:       dataset.select(*args)
423:     end

Default serial primary key options.

[Source]

     # File lib/sequel_core/database.rb, line 426
426:     def serial_primary_key_options
427:       {:primary_key => true, :type => Integer, :auto_increment => true}
428:     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_core/database/schema.rb, line 151
151:     def set_column_default(table, *args)
152:       alter_table(table) {set_column_default(*args)}
153:     end

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

  DB.set_column_type :items, :price, :float

See alter_table.

[Source]

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

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

[Source]

     # File lib/sequel_core/database.rb, line 431
431:     def single_threaded?
432:       @single_threaded
433:     end

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

[Source]

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

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

[Source]

     # File lib/sequel_core/database.rb, line 436
436:     def synchronize(server=nil, &block)
437:       @pool.hold(server || :default, &block)
438:     end

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

[Source]

     # File lib/sequel_core/database.rb, line 443
443:     def table_exists?(name)
444:       if @schemas && @schemas[name]
445:         true
446:       else
447:         begin 
448:           from(name).first
449:           true
450:         rescue
451:           false
452:         end
453:       end
454:     end

All tables in this database

[Source]

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

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

[Source]

     # File lib/sequel_core/database.rb, line 458
458:     def test_connection(server=nil)
459:       synchronize(server){|conn|}
460:       true
461:     end

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

[Source]

     # File lib/sequel_core/database.rb, line 467
467:     def transaction(server=nil)
468:       synchronize(server) do |conn|
469:         return yield(conn) if @transactions.include?(Thread.current)
470:         log_info(begin_transaction_sql)
471:         conn.execute(begin_transaction_sql)
472:         begin
473:           @transactions << Thread.current
474:           yield(conn)
475:         rescue Exception => e
476:           log_info(rollback_transaction_sql)
477:           conn.execute(rollback_transaction_sql)
478:           transaction_error(e)
479:         ensure
480:           unless e
481:             log_info(commit_transaction_sql)
482:             conn.execute(commit_transaction_sql)
483:           end
484:           @transactions.delete(Thread.current)
485:         end
486:       end
487:     end

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

[Source]

     # File lib/sequel_core/adapters/do.rb, line 123
123:       def transaction(server=nil)
124:         th = Thread.current
125:         synchronize(server) do |conn|
126:           return yield(conn) if @transactions.include?(th)
127:           t = ::DataObjects::Transaction.create_for_uri(uri)
128:           t.instance_variable_get(:@connection).close
129:           t.instance_variable_set(:@connection, conn)
130:           begin
131:             log_info("Transaction.begin")
132:             t.begin
133:             @transactions << th
134:             yield(conn)
135:           rescue Exception => e
136:             log_info("Transaction.rollback")
137:             t.rollback
138:             transaction_error(e)
139:           ensure
140:             unless e
141:               log_info("Transaction.commit")
142:               t.prepare
143:               t.commit 
144:             end
145:             @transactions.delete(th)
146:           end
147:         end
148:       end

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

[Source]

     # File lib/sequel_core/adapters/jdbc.rb, line 199
199:       def transaction(server=nil)
200:         synchronize(server) do |conn|
201:           return yield(conn) if @transactions.include?(Thread.current)
202:           stmt = conn.createStatement
203:           begin
204:             log_info(begin_transaction_sql)
205:             stmt.execute(begin_transaction_sql)
206:             @transactions << Thread.current
207:             yield(conn)
208:           rescue Exception => e
209:             log_info(rollback_transaction_sql)
210:             stmt.execute(rollback_transaction_sql)
211:             transaction_error(e)
212:           ensure
213:             unless e
214:               log_info(commit_transaction_sql)
215:               stmt.execute(commit_transaction_sql)
216:             end
217:             stmt.close
218:             @transactions.delete(Thread.current)
219:           end
220:         end
221:       end

Typecast the value to the given column_type. Can be overridden in adapters to support database specific column types. This method should raise Sequel::Error::InvalidValue if assigned value is invalid.

[Source]

     # File lib/sequel_core/database.rb, line 493
493:     def typecast_value(column_type, value)
494:       return nil if value.nil?
495:       case column_type
496:       when :integer
497:         begin
498:           Integer(value)
499:         rescue ArgumentError => e
500:           raise Sequel::Error::InvalidValue, e.message.inspect
501:         end
502:       when :string
503:         value.to_s
504:       when :float
505:         begin
506:           Float(value)
507:         rescue ArgumentError => e
508:           raise Sequel::Error::InvalidValue, e.message.inspect
509:         end
510:       when :decimal
511:         case value
512:         when BigDecimal
513:           value
514:         when String, Float
515:           value.to_d
516:         when Integer
517:           value.to_s.to_d
518:         else
519:           raise Sequel::Error::InvalidValue, "invalid value for BigDecimal: #{value.inspect}"
520:         end
521:       when :boolean
522:         case value
523:         when false, 0, "0", /\Af(alse)?\z/i
524:           false
525:         else
526:           value.blank? ? nil : true
527:         end
528:       when :date
529:         case value
530:         when Date
531:           value
532:         when DateTime, Time
533:           Date.new(value.year, value.month, value.day)
534:         when String
535:           value.to_date
536:         else
537:           raise Sequel::Error::InvalidValue, "invalid value for Date: #{value.inspect}"
538:         end
539:       when :time
540:         case value
541:         when Time
542:           value
543:         when String
544:           value.to_time
545:         else
546:           raise Sequel::Error::InvalidValue, "invalid value for Time: #{value.inspect}"
547:         end
548:       when :datetime
549:         raise(Sequel::Error::InvalidValue, "invalid value for Datetime: #{value.inspect}") unless value.is_one_of?(DateTime, Date, Time, String)
550:         if Sequel.datetime_class === value
551:           # Already the correct class, no need to convert
552:           value
553:         else
554:           # First convert it to standard ISO 8601 time, then
555:           # parse that string using the time class.
556:           (Time === value ? value.iso8601 : value.to_s).to_sequel_time
557:         end
558:       when :blob
559:         value.to_blob
560:       else
561:         value
562:       end
563:     end

Set whether to upcase identifiers going into the database.

[Source]

     # File lib/sequel_core/database.rb, line 566
566:     def upcase_identifiers=(v)
567:       self.identifier_input_method = v ? :upcase : nil
568:     end

Returns true if the database upcases identifiers.

[Source]

     # File lib/sequel_core/database.rb, line 571
571:     def upcase_identifiers?
572:       identifier_input_method == :upcase
573:     end

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

[Source]

     # File lib/sequel_core/adapters/do.rb, line 152
152:       def uri(opts={})
153:         opts = @opts.merge(opts)
154:         (opts[:uri] || opts[:url]).sub(/\Ado:/, '')
155:       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_core/adapters/jdbc.rb, line 227
227:       def uri(opts={})
228:         opts = @opts.merge(opts)
229:         ur = opts[:uri] || opts[:url] || opts[:database]
230:         ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}"
231:       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_core/database.rb, line 578
578:     def uri
579:       uri = URI::Generic.new(
580:         self.class.adapter_scheme.to_s,
581:         nil,
582:         @opts[:host],
583:         @opts[:port],
584:         nil,
585:         "/#{@opts[:database]}",
586:         nil,
587:         nil,
588:         nil
589:       )
590:       uri.user = @opts[:user]
591:       uri.password = @opts[:password] if uri.user
592:       uri.to_s
593:     end

Explicit alias of uri for easier subclassing.

[Source]

     # File lib/sequel_core/database.rb, line 596
596:     def url
597:       uri
598:     end

[Validate]