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/ | ||
MSSQL_DEFAULT_RE | = | /\A(?:\(N?('.*')\)|\(\((-?\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. |
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 105 105: def self.adapter_class(scheme) 106: scheme = scheme.to_s.gsub('-', '_').to_sym 107: 108: unless klass = ADAPTER_MAP[scheme] 109: # attempt to load the adapter file 110: begin 111: Sequel.require "adapters/#{scheme}" 112: rescue LoadError => e 113: raise Sequel.convert_exception_class(e, AdapterNotFound) 114: end 115: 116: # make sure we actually loaded the adapter 117: unless klass = ADAPTER_MAP[scheme] 118: raise AdapterNotFound, "Could not load #{scheme} adapter" 119: end 120: end 121: klass 122: end
Connects to a database. See Sequel.connect.
# File lib/sequel/database.rb, line 130 130: def self.connect(conn_string, opts = {}, &block) 131: case conn_string 132: when String 133: if match = /\A(jdbc|do):/o.match(conn_string) 134: c = adapter_class(match[1].to_sym) 135: opts = {:uri=>conn_string}.merge(opts) 136: else 137: uri = URI.parse(conn_string) 138: scheme = uri.scheme 139: scheme = :dbi if scheme =~ /\Adbi-/ 140: c = adapter_class(scheme) 141: uri_options = c.send(:uri_to_options, uri) 142: uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v} unless uri.query.to_s.strip.empty? 143: uri_options.entries.each{|k,v| uri_options[k] = URI.unescape(v) if v.is_a?(String)} 144: opts = uri_options.merge(opts) 145: end 146: when Hash 147: opts = conn_string.merge(opts) 148: c = adapter_class(opts[:adapter] || opts['adapter']) 149: else 150: raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" 151: end 152: # process opts a bit 153: opts = opts.inject({}) do |m, kv| k, v = *kv 154: k = :user if k.to_s == 'username' 155: m[k.to_sym] = v 156: m 157: end 158: if block 159: begin 160: yield(db = c.new(opts)) 161: ensure 162: db.disconnect if db 163: ::Sequel::DATABASES.delete(db) 164: end 165: nil 166: else 167: c.new(opts) 168: end 169: 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 81 81: def initialize(opts = {}, &block) 82: @opts ||= opts 83: 84: @single_threaded = opts.include?(:single_threaded) ? typecast_value_boolean(opts[:single_threaded]) : @@single_threaded 85: @schemas = {} 86: @default_schema = opts.include?(:default_schema) ? opts[:default_schema] : default_schema_default 87: @prepared_statements = {} 88: @transactions = [] 89: @identifier_input_method = nil 90: @identifier_output_method = nil 91: @quote_identifiers = nil 92: @pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(connection_pool_default_options.merge(opts), &block) 93: @pool.connection_proc = proc{|server| connect(server)} unless block 94: @pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc] 95: 96: @loggers = Array(opts[:logger]) + Array(opts[:loggers]) 97: ::Sequel::DATABASES.push(self) 98: 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 45 45: def initialize(opts) 46: @opts = opts 47: raise(Error, "No connection string specified") unless uri 48: if prok = DATABASE_SETUP[subadapter.to_sym] 49: prok.call(self) 50: end 51: super(opts) 52: 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 254 254: def [](*args) 255: (String === args.first) ? fetch(*args) : from(*args) 256: 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 260 260: def call(ps_name, hash={}) 261: prepared_statements[ps_name].call(hash) 262: 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 55 55: def connect(server) 56: setup_connection(::DataObjects::Connection.new(uri(server_opts(server)))) 57: end
Connects to the database. This method should be overridden by descendants.
# File lib/sequel/database.rb, line 270 270: def connect 271: raise NotImplementedError, "#connect should be overridden by adapters" 272: 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 281 281: def database_type 282: self.class.adapter_scheme 283: end
Return a Sequel::DataObjects::Dataset object for this database.
# File lib/sequel/adapters/do.rb, line 60 60: def dataset(opts = nil) 61: DataObjects::Dataset.new(self, opts) 62: 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 298 298: def execute(sql, opts={}) 299: raise NotImplementedError, "#execute should be overridden by adapters" 300: 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 69 69: def execute(sql, opts={}) 70: log_info(sql) 71: synchronize(opts[:server]) do |conn| 72: begin 73: command = conn.create_command(sql) 74: res = block_given? ? command.execute_reader : command.execute_non_query 75: rescue ::DataObjects::Error => e 76: raise_error(e) 77: end 78: if block_given? 79: begin 80: yield(res) 81: ensure 82: res.close if res 83: end 84: elsif opts[:type] == :insert 85: res.insert_id 86: else 87: res.affected_rows 88: end 89: end 90: 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.merge(:stmt=>stmt)) 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 305 305: def execute_ddl(sql, opts={}, &block) 306: execute_dui(sql, opts, &block) 307: 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 319 319: def execute_insert(sql, opts={}, &block) 320: execute_dui(sql, opts, &block) 321: 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 336 336: def fetch(sql, *args, &block) 337: ds = dataset.with_sql(sql, *args) 338: ds.each(&block) if block 339: ds 340: end
The method to call on identifiers going into the database
# File lib/sequel/database.rb, line 361 361: def identifier_input_method 362: case @identifier_input_method 363: when nil 364: @identifier_input_method = @opts.include?(:identifier_input_method) ? @opts[:identifier_input_method] : (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method) 365: @identifier_input_method == "" ? nil : @identifier_input_method 366: when "" 367: nil 368: else 369: @identifier_input_method 370: end 371: end
The method to call on identifiers coming from the database
# File lib/sequel/database.rb, line 380 380: def identifier_output_method 381: case @identifier_output_method 382: when nil 383: @identifier_output_method = @opts.include?(:identifier_output_method) ? @opts[:identifier_output_method] : (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method) 384: @identifier_output_method == "" ? nil : @identifier_output_method 385: when "" 386: nil 387: else 388: @identifier_output_method 389: end 390: 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 401 401: def inspect 402: "#<#{self.class}: #{(uri rescue opts).inspect}>" 403: end
Remove any existing loggers and just use the given logger.
# File lib/sequel/database.rb, line 418 418: def logger=(logger) 419: @loggers = Array(logger) 420: end
Returns true if the database quotes identifiers.
# File lib/sequel/database.rb, line 429 429: def quote_identifiers? 430: return @quote_identifiers unless @quote_identifiers.nil? 431: @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers) 432: 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 459 459: def schema(table, opts={}) 460: raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true) 461: 462: sch, table_name = schema_and_table(table) 463: quoted_name = quote_schema_table(table) 464: opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema) 465: 466: @schemas.delete(quoted_name) if opts[:reload] 467: return @schemas[quoted_name] if @schemas[quoted_name] 468: 469: cols = schema_parse_table(table_name, opts) 470: raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty? 471: cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} 472: @schemas[quoted_name] = cols 473: 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 476 476: def single_threaded? 477: @single_threaded 478: end
Return the subadapter type for this database, i.e. sqlite3 for do:sqlite3::memory:.
# File lib/sequel/adapters/do.rb, line 106 106: def subadapter 107: uri.split(":").first 108: end
Whether the database and adapter support savepoints, false by default
# File lib/sequel/database.rb, line 486 486: def supports_savepoints? 487: false 488: end
Acquires a database connection, yielding it to the passed block.
# File lib/sequel/database.rb, line 481 481: def synchronize(server=nil, &block) 482: @pool.hold(server || :default, &block) 483: 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 493 493: def table_exists?(name) 494: begin 495: from(name).first 496: true 497: rescue 498: false 499: end 500: end
Attempts to acquire a database connection. Returns true if successful. Will probably raise an error if unsuccessful.
# File lib/sequel/database.rb, line 504 504: def test_connection(server=nil) 505: synchronize(server){|conn|} 506: true 507: 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 520 520: def transaction(opts={}, &block) 521: synchronize(opts[:server]) do |conn| 522: return yield(conn) if already_in_transaction?(conn, opts) 523: _transaction(conn, &block) 524: end 525: 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 532 532: def typecast_value(column_type, value) 533: return nil if value.nil? 534: meth = "typecast_value_#{column_type}" 535: begin 536: respond_to?(meth, true) ? send(meth, value) : value 537: rescue ArgumentError, TypeError => e 538: raise Sequel.convert_exception_class(e, InvalidValue) 539: end 540: 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 545 545: def uri 546: uri = URI::Generic.new( 547: self.class.adapter_scheme.to_s, 548: nil, 549: @opts[:host], 550: @opts[:port], 551: nil, 552: "/#{@opts[:database]}", 553: nil, 554: nil, 555: nil 556: ) 557: uri.user = @opts[:user] 558: uri.password = @opts[:password] if uri.user 559: uri.to_s 560: 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 112 112: def uri(opts={}) 113: opts = @opts.merge(opts) 114: (opts[:uri] || opts[:url]).sub(/\Ado:/, '') 115: end