ADAPTERS | = | %w'ado amalgalite db2 dbi do firebird informix jdbc mysql odbc openbase oracle postgres sqlite'.collect{|x| x.to_sym} | Array of supported database adapters | |
SQL_BEGIN | = | 'BEGIN'.freeze | ||
SQL_COMMIT | = | 'COMMIT'.freeze | ||
SQL_RELEASE_SAVEPOINT | = | 'RELEASE SAVEPOINT autopoint_%d'.freeze | ||
SQL_ROLLBACK | = | 'ROLLBACK'.freeze | ||
SQL_ROLLBACK_TO_SAVEPOINT | = | 'ROLLBACK TO SAVEPOINT autopoint_%d'.freeze | ||
SQL_SAVEPOINT | = | 'SAVEPOINT autopoint_%d'.freeze | ||
TRANSACTION_BEGIN | = | 'Transaction.begin'.freeze | ||
TRANSACTION_COMMIT | = | 'Transaction.commit'.freeze | ||
TRANSACTION_ROLLBACK | = | 'Transaction.rollback'.freeze | ||
POSTGRES_DEFAULT_RE | = | /\A(?:B?('.*')::[^']+|\((-?\d+(?:\.\d+)?)\))\z/ | ||
MYSQL_TIMESTAMP_RE | = | /\ACURRENT_(?:DATE|TIMESTAMP)?\z/ | ||
STRING_DEFAULT_RE | = | /\A'(.*)'\z/ | ||
AUTOINCREMENT | = | 'AUTOINCREMENT'.freeze | ||
CASCADE | = | 'CASCADE'.freeze | ||
COMMA_SEPARATOR | = | ', '.freeze | ||
NO_ACTION | = | 'NO ACTION'.freeze | ||
NOT_NULL | = | ' NOT NULL'.freeze | ||
NULL | = | ' NULL'.freeze | ||
PRIMARY_KEY | = | ' PRIMARY KEY'.freeze | ||
RESTRICT | = | 'RESTRICT'.freeze | ||
SET_DEFAULT | = | 'SET DEFAULT'.freeze | ||
SET_NULL | = | 'SET NULL'.freeze | ||
TEMPORARY | = | 'TEMPORARY '.freeze | ||
UNDERSCORE | = | '_'.freeze | ||
UNIQUE | = | ' UNIQUE'.freeze | ||
UNSIGNED | = | ' UNSIGNED'.freeze |
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. |
converted_exceptions | [RW] | Convert the given exceptions to Sequel:Errors, necessary because DO raises errors specific to database types in certain cases. |
database_type | [R] | The type of database we are connecting to |
default_schema | [RW] | The default schema to use, generally should be nil. |
loggers | [RW] | Array of SQL loggers to use for this database |
opts | [R] | The options for this database |
pool | [R] | The connection pool for this database |
prepared_statements | [R] | The prepared statement objects for this database, keyed by name |
The Database subclass for the given adapter scheme. Raises Sequel::AdapterNotFound if the adapter could not be loaded.
# File lib/sequel/database.rb, line 104 104: def self.adapter_class(scheme) 105: scheme = scheme.to_s.gsub('-', '_').to_sym 106: 107: unless klass = ADAPTER_MAP[scheme] 108: # attempt to load the adapter file 109: begin 110: Sequel.require "adapters/#{scheme}" 111: rescue LoadError => e 112: raise AdapterNotFound, "Could not load #{scheme} adapter:\n #{e.message}" 113: end 114: 115: # make sure we actually loaded the adapter 116: unless klass = ADAPTER_MAP[scheme] 117: raise AdapterNotFound, "Could not load #{scheme} adapter" 118: end 119: end 120: klass 121: end
Connects to a database. See Sequel.connect.
# File lib/sequel/database.rb, line 129 129: def self.connect(conn_string, opts = {}, &block) 130: case conn_string 131: when String 132: if match = /\A(jdbc|do):/o.match(conn_string) 133: c = adapter_class(match[1].to_sym) 134: opts = {:uri=>conn_string}.merge(opts) 135: else 136: uri = URI.parse(conn_string) 137: scheme = uri.scheme 138: scheme = :dbi if scheme =~ /\Adbi-/ 139: c = adapter_class(scheme) 140: uri_options = c.send(:uri_to_options, uri) 141: uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v} unless uri.query.to_s.strip.empty? 142: uri_options.entries.each{|k,v| uri_options[k] = URI.unescape(v) if v.is_a?(String)} 143: opts = uri_options.merge(opts) 144: end 145: when Hash 146: opts = conn_string.merge(opts) 147: c = adapter_class(opts[:adapter] || opts['adapter']) 148: else 149: raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" 150: end 151: # process opts a bit 152: opts = opts.inject({}) do |m, kv| k, v = *kv 153: k = :user if k.to_s == 'username' 154: m[k.to_sym] = v 155: m 156: end 157: if block 158: begin 159: yield(db = c.new(opts)) 160: ensure 161: db.disconnect if db 162: ::Sequel::DATABASES.delete(db) 163: end 164: nil 165: else 166: c.new(opts) 167: end 168: 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.
# File lib/sequel/adapters/jdbc.rb, line 100 100: def initialize(opts) 101: @opts = opts 102: @convert_types = opts.include?(:convert_types) ? typecast_value_boolean(opts[:convert_types]) : true 103: raise(Error, "No connection string specified") unless uri 104: if match = /\Ajdbc:([^:]+)/.match(uri) and prok = DATABASE_SETUP[match[1].to_sym] 105: prok.call(self) 106: end 107: super(opts) 108: 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:
All options given are also passed to the ConnectionPool. If a block is given, it is used as the connection_proc for the ConnectionPool.
# File lib/sequel/database.rb, line 80 80: def initialize(opts = {}, &block) 81: @opts ||= opts 82: 83: @single_threaded = opts.include?(:single_threaded) ? typecast_value_boolean(opts[:single_threaded]) : @@single_threaded 84: @schemas = {} 85: @default_schema = opts.include?(:default_schema) ? opts[:default_schema] : default_schema_default 86: @prepared_statements = {} 87: @transactions = [] 88: @identifier_input_method = nil 89: @identifier_output_method = nil 90: @quote_identifiers = nil 91: @pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(connection_pool_default_options.merge(opts), &block) 92: @pool.connection_proc = proc{|server| connect(server)} unless block 93: @pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc] 94: 95: @loggers = Array(opts[:logger]) + Array(opts[:loggers]) 96: ::Sequel::DATABASES.push(self) 97: 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.
# File lib/sequel/adapters/do.rb, line 53 53: def initialize(opts) 54: @opts = opts 55: @converted_exceptions = [] 56: raise(Error, "No connection string specified") unless uri 57: if prok = DATABASE_SETUP[subadapter.to_sym] 58: prok.call(self) 59: end 60: super(opts) 61: end
Returns a dataset from the database. If the first argument is a string, the method acts as an alias for Database#fetch, returning a dataset for arbitrary SQL:
DB['SELECT * FROM items WHERE name = ?', my_name].all
Otherwise, acts as an alias for Database#from, setting the primary table for the dataset:
DB[:items].sql #=> "SELECT * FROM items"
# File lib/sequel/database.rb, line 253 253: def [](*args) 254: (String === args.first) ? fetch(*args) : from(*args) 255: 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.
# File lib/sequel/database/schema_methods.rb, line 10 10: def add_column(table, *args) 11: alter_table(table) {add_column(*args)} 12: end
Adds an index to a table for the given columns:
DB.add_index :posts, :title DB.add_index :posts, [:author, :title], :unique => true
Options:
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 24 24: def add_index(table, columns, options={}) 25: e = options[:ignore_errors] 26: begin 27: alter_table(table){add_index(columns, options)} 28: rescue DatabaseError 29: raise unless e 30: end 31: end
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.
# File lib/sequel/database/schema_methods.rb, line 50 50: def alter_table(name, generator=nil, &block) 51: remove_cached_schema(name) 52: generator ||= Schema::AlterTableGenerator.new(self, &block) 53: alter_table_sql_list(name, generator.operations).flatten.each {|sql| execute_ddl(sql)} 54: end
Call the prepared statement with the given name with the given hash of arguments.
# File lib/sequel/database.rb, line 259 259: def call(ps_name, hash={}) 260: prepared_statements[ps_name].call(hash) 261: end
Execute the given stored procedure with the give name. If a block is given, the stored procedure should return rows.
# File lib/sequel/adapters/jdbc.rb, line 112 112: def call_sproc(name, opts = {}) 113: args = opts[:args] || [] 114: sql = "{call #{name}(#{args.map{'?'}.join(',')})}" 115: synchronize(opts[:server]) do |conn| 116: cps = conn.prepareCall(sql) 117: 118: i = 0 119: args.each{|arg| set_ps_arg(cps, arg, i+=1)} 120: 121: begin 122: if block_given? 123: yield cps.executeQuery 124: else 125: case opts[:type] 126: when :insert 127: cps.executeUpdate 128: last_insert_id(conn, opts) 129: else 130: cps.executeUpdate 131: end 132: end 133: rescue NativeException, JavaSQL::SQLException => e 134: raise_error(e) 135: ensure 136: cps.close 137: end 138: end 139: end
Connect to the database using JavaSQL::DriverManager.getConnection.
# File lib/sequel/adapters/jdbc.rb, line 142 142: def connect(server) 143: args = [uri(server_opts(server))] 144: args.concat([opts[:user], opts[:password]]) if opts[:user] && opts[:password] 145: setup_connection(JavaSQL::DriverManager.getConnection(*args)) 146: end
Setup a DataObjects::Connection to the database.
# File lib/sequel/adapters/do.rb, line 64 64: def connect(server) 65: setup_connection(::DataObjects::Connection.new(uri(server_opts(server)))) 66: end
Connects to the database. This method should be overridden by descendants.
# File lib/sequel/database.rb, line 269 269: def connect 270: raise NotImplementedError, "#connect should be overridden by adapters" 271: 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'))
# File lib/sequel/database/schema_methods.rb, line 92 92: def create_or_replace_view(name, source) 93: remove_cached_schema(name) 94: source = source.sql if source.is_a?(Dataset) 95: execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}") 96: end
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:
See Schema::Generator.
# File lib/sequel/database/schema_methods.rb, line 70 70: def create_table(name, options={}, &block) 71: options = {:generator=>options} if options.is_a?(Schema::Generator) 72: generator = options[:generator] || Schema::Generator.new(self, &block) 73: create_table_from_generator(name, generator, options) 74: create_table_indexes_from_generator(name, generator, options) 75: end
Forcibly creates a table, attempting to drop it unconditionally (and catching any errors), then creating it.
# File lib/sequel/database/schema_methods.rb, line 78 78: def create_table!(name, options={}, &block) 79: drop_table(name) rescue nil 80: create_table(name, options, &block) 81: end
Creates the table unless the table already exists
# File lib/sequel/database/schema_methods.rb, line 84 84: def create_table?(name, options={}, &block) 85: create_table(name, options, &block) unless table_exists?(name) 86: end
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'))
# File lib/sequel/database/schema_methods.rb, line 102 102: def create_view(name, source) 103: source = source.sql if source.is_a?(Dataset) 104: execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}") 105: end
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).
# File lib/sequel/database.rb, line 280 280: def database_type 281: self.class.adapter_scheme 282: end
Return a Sequel::DataObjects::Dataset object for this database.
# File lib/sequel/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.
# File lib/sequel/adapters/jdbc.rb, line 149 149: def dataset(opts = nil) 150: JDBC::Dataset.new(self, opts) 151: end
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 112 112: def drop_column(table, *args) 113: alter_table(table) {drop_column(*args)} 114: 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.
# File lib/sequel/database/schema_methods.rb, line 122 122: def drop_index(table, columns, options={}) 123: alter_table(table){drop_index(columns, options)} 124: end
Drops one or more views corresponding to the given names:
DB.drop_view(:cheap_items)
# File lib/sequel/database/schema_methods.rb, line 139 139: def drop_view(*names) 140: names.each do |n| 141: remove_cached_schema(n) 142: execute_ddl("DROP VIEW #{quote_schema_table(n)}") 143: end 144: end
Dump indexes for all tables as a migration. This complements the :indexes=>false option to dump_schema_migration. Options:
# File lib/sequel/extensions/schema_dumper.rb, line 13 13: def dump_indexes_migration(options={}) 14: ts = tables 15: "Class.new(Sequel::Migration) do\n def up\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 def down\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:
# File lib/sequel/extensions/schema_dumper.rb, line 38 38: def dump_schema_migration(options={}) 39: ts = tables 40: "Class.new(Sequel::Migration) do\n def up\n\#{ts.sort_by{|t| t.to_s}.map{|t| dump_table_schema(t, options)}.join(\"\\n\\n\").gsub(/^/o, ' ')}\n end\n \n def down\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.
# File lib/sequel/extensions/schema_dumper.rb, line 56 56: def dump_table_schema(table, options={}) 57: s = schema(table).dup 58: pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first} 59: options = options.merge(:single_pk=>true) if pks.length == 1 60: m = method(:column_schema_to_generator_opts) 61: im = method(:index_to_generator_opts) 62: indexes = indexes(table).sort_by{|k,v| k.to_s} if options[:indexes] != false and respond_to?(:indexes) 63: gen = Schema::Generator.new(self) do 64: s.each{|name, info| send(*m.call(name, info, options))} 65: primary_key(pks) if !@primary_key && pks.length > 0 66: indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts))} if indexes 67: end 68: commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n") 69: "create_table(#{table.inspect}#{', :ignore_index_errors=>true' if !options[:same_db] && options[:indexes] != false && indexes && !indexes.empty?}) do\n#{commands.gsub(/^/o, ' ')}\nend" 70: 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.
# File lib/sequel/database.rb, line 297 297: def execute(sql, opts={}) 298: raise NotImplementedError, "#execute should be overridden by adapters" 299: 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.
# File lib/sequel/adapters/do.rb, line 78 78: def execute(sql, opts={}) 79: log_info(sql) 80: synchronize(opts[:server]) do |conn| 81: begin 82: command = conn.create_command(sql) 83: res = block_given? ? command.execute_reader : command.execute_non_query 84: rescue Exception => e 85: raise_error(e, :classes=>@converted_exceptions) 86: end 87: if block_given? 88: begin 89: yield(res) 90: ensure 91: res.close if res 92: end 93: elsif opts[:type] == :insert 94: res.insert_id 95: else 96: res.affected_rows 97: end 98: end 99: end
Execute the given SQL. If a block is given, if should be a SELECT statement or something else that returns rows.
# File lib/sequel/adapters/jdbc.rb, line 155 155: def execute(sql, opts={}, &block) 156: return call_sproc(sql, opts, &block) if opts[:sproc] 157: return execute_prepared_statement(sql, opts, &block) if [Symbol, Dataset].any?{|c| sql.is_a?(c)} 158: log_info(sql) 159: synchronize(opts[:server]) do |conn| 160: stmt = conn.createStatement 161: begin 162: if block_given? 163: yield stmt.executeQuery(sql) 164: else 165: case opts[:type] 166: when :ddl 167: stmt.execute(sql) 168: when :insert 169: stmt.executeUpdate(sql) 170: last_insert_id(conn, opts) 171: else 172: stmt.executeUpdate(sql) 173: end 174: end 175: rescue NativeException, JavaSQL::SQLException => e 176: raise_error(e) 177: ensure 178: stmt.close 179: end 180: end 181: end
Method that should be used when submitting any DDL (Data Definition Language) SQL. By default, calls execute_dui. This method should not be called directly by user code.
# File lib/sequel/database.rb, line 304 304: def execute_ddl(sql, opts={}, &block) 305: execute_dui(sql, opts, &block) 306: 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.
# File lib/sequel/database.rb, line 318 318: def execute_insert(sql, opts={}, &block) 319: execute_dui(sql, opts, &block) 320: end
Fetches records for an arbitrary SQL statement. If a block is given, it is used to iterate over the records:
DB.fetch('SELECT * FROM items'){|r| p r}
The method returns a dataset instance:
DB.fetch('SELECT * FROM items').all
Fetch can also perform parameterized queries for protection against SQL injection:
DB.fetch('SELECT * FROM items WHERE name = ?', my_name).all
# File lib/sequel/database.rb, line 335 335: def fetch(sql, *args, &block) 336: ds = dataset.with_sql(sql, *args) 337: ds.each(&block) if block 338: ds 339: end
The method to call on identifiers going into the database
# File lib/sequel/database.rb, line 360 360: def identifier_input_method 361: case @identifier_input_method 362: when nil 363: @identifier_input_method = @opts.include?(:identifier_input_method) ? @opts[:identifier_input_method] : (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method) 364: @identifier_input_method == "" ? nil : @identifier_input_method 365: when "" 366: nil 367: else 368: @identifier_input_method 369: end 370: end
The method to call on identifiers coming from the database
# File lib/sequel/database.rb, line 379 379: def identifier_output_method 380: case @identifier_output_method 381: when nil 382: @identifier_output_method = @opts.include?(:identifier_output_method) ? @opts[:identifier_output_method] : (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method) 383: @identifier_output_method == "" ? nil : @identifier_output_method 384: when "" 385: nil 386: else 387: @identifier_output_method 388: end 389: 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.
# File lib/sequel/adapters/jdbc.rb, line 200 200: def indexes(table, opts={}) 201: m = output_identifier_meth 202: im = input_identifier_meth 203: schema, table = schema_and_table(table) 204: schema ||= opts[:schema] 205: schema = im.call(schema) if schema 206: table = im.call(table) 207: indexes = {} 208: metadata(:getIndexInfo, nil, schema, table, false, true) do |r| 209: next unless name = r[:column_name] 210: next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re 211: i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>[false, 0].include?(r[:non_unique])} 212: i[:columns] << m.call(name) 213: end 214: indexes 215: 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).
# File lib/sequel/database.rb, line 400 400: def inspect 401: "#<#{self.class}: #{(uri rescue opts).inspect}>" 402: end
Remove any existing loggers and just use the given logger.
# File lib/sequel/database.rb, line 417 417: def logger=(logger) 418: @loggers = Array(logger) 419: end
Returns true if the database quotes identifiers.
# File lib/sequel/database.rb, line 428 428: def quote_identifiers? 429: return @quote_identifiers unless @quote_identifiers.nil? 430: @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers) 431: 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.
# File lib/sequel/database/schema_methods.rb, line 162 162: def rename_column(table, *args) 163: alter_table(table) {rename_column(*args)} 164: end
Renames a table:
DB.tables #=> [:items] DB.rename_table :items, :old_items DB.tables #=> [:old_items]
# File lib/sequel/database/schema_methods.rb, line 151 151: def rename_table(name, new_name) 152: remove_cached_schema(name) 153: execute_ddl(rename_table_sql(name, new_name)) 154: end
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:
# File lib/sequel/database.rb, line 458 458: def schema(table, opts={}) 459: raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true) 460: 461: sch, table_name = schema_and_table(table) 462: quoted_name = quote_schema_table(table) 463: opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema) 464: 465: @schemas.delete(quoted_name) if opts[:reload] 466: return @schemas[quoted_name] if @schemas[quoted_name] 467: 468: cols = schema_parse_table(table_name, opts) 469: raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty? 470: cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} 471: @schemas[quoted_name] = cols 472: end
Default serial primary key options.
# File lib/sequel/database/schema_sql.rb, line 19 19: def serial_primary_key_options 20: {:primary_key => true, :type => Integer, :auto_increment => true} 21: end
Sets the default value for the given column in the given table:
DB.set_column_default :items, :category, 'perl!'
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 171 171: def set_column_default(table, *args) 172: alter_table(table) {set_column_default(*args)} 173: end
Set the data type for the given column in the given table:
DB.set_column_type :items, :price, :float
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 180 180: def set_column_type(table, *args) 181: alter_table(table) {set_column_type(*args)} 182: end
Returns true if the database is using a single-threaded connection pool.
# File lib/sequel/database.rb, line 475 475: def single_threaded? 476: @single_threaded 477: end
Return the subadapter type for this database, i.e. sqlite3 for do:sqlite3::memory:.
# File lib/sequel/adapters/do.rb, line 115 115: def subadapter 116: uri.split(":").first 117: end
Whether the database and adapter support savepoints, false by default
# File lib/sequel/database.rb, line 485 485: def supports_savepoints? 486: false 487: end
Acquires a database connection, yielding it to the passed block.
# File lib/sequel/database.rb, line 480 480: def synchronize(server=nil, &block) 481: @pool.hold(server || :default, &block) 482: 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.
# File lib/sequel/database.rb, line 492 492: def table_exists?(name) 493: begin 494: from(name).first 495: true 496: rescue 497: false 498: end 499: end
Attempts to acquire a database connection. Returns true if successful. Will probably raise an error if unsuccessful.
# File lib/sequel/database.rb, line 503 503: def test_connection(server=nil) 504: synchronize(server){|conn|} 505: true 506: 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:
# File lib/sequel/database.rb, line 519 519: def transaction(opts={}, &block) 520: synchronize(opts[:server]) do |conn| 521: return yield(conn) if already_in_transaction?(conn, opts) 522: _transaction(conn, &block) 523: end 524: 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.
# File lib/sequel/database.rb, line 531 531: def typecast_value(column_type, value) 532: return nil if value.nil? 533: meth = "typecast_value_#{column_type}" 534: begin 535: respond_to?(meth, true) ? send(meth, value) : value 536: rescue ArgumentError, TypeError => exp 537: e = Sequel::InvalidValue.new("#{exp.class} #{exp.message}") 538: e.set_backtrace(exp.backtrace) 539: raise e 540: end 541: end
Returns the URI identifying the database. This method can raise an error if the database used options instead of a connection string.
# File lib/sequel/database.rb, line 546 546: def uri 547: uri = URI::Generic.new( 548: self.class.adapter_scheme.to_s, 549: nil, 550: @opts[:host], 551: @opts[:port], 552: nil, 553: "/#{@opts[:database]}", 554: nil, 555: nil, 556: nil 557: ) 558: uri.user = @opts[:user] 559: uri.password = @opts[:password] if uri.user 560: uri.to_s 561: 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.
# File lib/sequel/adapters/jdbc.rb, line 229 229: def uri(opts={}) 230: opts = @opts.merge(opts) 231: ur = opts[:uri] || opts[:url] || opts[:database] 232: ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}" 233: end
Return the DataObjects URI for the Sequel URI, removing the do: prefix.
# File lib/sequel/adapters/do.rb, line 121 121: def uri(opts={}) 122: opts = @opts.merge(opts) 123: (opts[:uri] || opts[:url]).sub(/\Ado:/, '') 124: end