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 | ||
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 | ||
TYPES | = | Hash.new {|h, k| k} | ||
UNDERSCORE | = | '_'.freeze | ||
UNIQUE | = | ' UNIQUE'.freeze | ||
UNSIGNED | = | ' UNSIGNED'.freeze |
column_references_sql | -> | default_column_references_sql |
Keep default column_references_sql for add_foreign_key support |
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 97 97: def self.adapter_class(scheme) 98: scheme = scheme.to_s.gsub('-', '_').to_sym 99: 100: unless klass = ADAPTER_MAP[scheme] 101: # attempt to load the adapter file 102: begin 103: Sequel.require "adapters/#{scheme}" 104: rescue LoadError => e 105: raise AdapterNotFound, "Could not load #{scheme} adapter:\n #{e.message}" 106: end 107: 108: # make sure we actually loaded the adapter 109: unless klass = ADAPTER_MAP[scheme] 110: raise AdapterNotFound, "Could not load #{scheme} adapter" 111: end 112: end 113: klass 114: end
Connects to a database. See Sequel.connect.
# File lib/sequel/database.rb, line 122 122: def self.connect(conn_string, opts = {}, &block) 123: if conn_string.is_a?(String) 124: if match = /\A(jdbc|do):/o.match(conn_string) 125: c = adapter_class(match[1].to_sym) 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.to_s.strip.empty? 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
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 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
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 69 69: def initialize(opts = {}, &block) 70: @opts ||= opts 71: 72: @single_threaded = opts.include?(:single_threaded) ? opts[:single_threaded] : @@single_threaded 73: @schemas = nil 74: @default_schema = opts.include?(:default_schema) ? opts[:default_schema] : default_schema_default 75: @prepared_statements = {} 76: @transactions = [] 77: @identifier_input_method = nil 78: @identifier_output_method = nil 79: @quote_identifiers = nil 80: if opts.include?(:upcase_identifiers) 81: Deprecation.deprecate('The :upcase_identifiers Database option', 'Use the :identifier_input_method => :upcase option instead') 82: @identifier_input_method = opts[:upcase_identifiers] ? :upcase : "" 83: end 84: @pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(connection_pool_default_options.merge(opts), &block) 85: @pool.connection_proc = proc{|server| connect(server)} unless block 86: @pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc] 87: 88: @loggers = Array(opts[:logger]) + Array(opts[:loggers]) 89: ::Sequel::DATABASES.push(self) 90: 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
# File lib/sequel/deprecated.rb, line 66 66: def self.upcase_identifiers=(value) 67: Deprecation.deprecate('Sequel::Database.upcase_identifiers=', 'Use Sequel::Database.identifier_input_method = :upcase or nil') 68: self.identifier_input_method = value ? :upcase : nil 69: end
# File lib/sequel/deprecated.rb, line 81 81: def >>(*args, &block) 82: Deprecation.deprecate('Sequel::Database#>>', 'Use Sequel::Database#fetch') 83: fetch(*args, &block) 84: 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 242 242: def [](*args) 243: (String === args.first) ? fetch(*args) : from(*args) 244: 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
See alter_table.
# File lib/sequel/database/schema_methods.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. 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 41 41: def alter_table(name, generator=nil, &block) 42: remove_cached_schema(name) 43: generator ||= Schema::AlterTableGenerator.new(self, &block) 44: alter_table_sql_list(name, generator.operations).flatten.each {|sql| execute_ddl(sql)} 45: end
Call the prepared statement with the given name with the given hash of arguments.
# File lib/sequel/database.rb, line 248 248: def call(ps_name, hash={}) 249: prepared_statements[ps_name].call(hash) 250: 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 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
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 253 253: def connect 254: raise NotImplementedError, "#connect should be overridden by adapters" 255: end
Connect to the database using JavaSQL::DriverManager.getConnection.
# File lib/sequel/adapters/jdbc.rb, line 136 136: def connect(server) 137: setup_connection(JavaSQL::DriverManager.getConnection(uri(server_opts(server)))) 138: 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 72 72: def create_or_replace_view(name, source) 73: remove_cached_schema(name) 74: source = source.sql if source.is_a?(Dataset) 75: execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}") 76: 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
See Schema::Generator.
# File lib/sequel/database/schema_methods.rb, line 57 57: def create_table(name, options={}, &block) 58: options = {:generator=>options} if options.is_a?(Schema::Generator) 59: create_table_sql_list(name, *((options[:generator] || Schema::Generator.new(self, &block)).create_info << options)).flatten.each {|sql| execute_ddl(sql)} 60: 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 63 63: def create_table!(name, options={}, &block) 64: drop_table(name) rescue nil 65: create_table(name, options, &block) 66: 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 82 82: def create_view(name, source) 83: source = source.sql if source.is_a?(Dataset) 84: execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}") 85: end
Return instances of JDBC::Dataset with the given opts.
# File lib/sequel/adapters/jdbc.rb, line 141 141: def dataset(opts = nil) 142: JDBC::Dataset.new(self, opts) 143: 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
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table.
# File lib/sequel/database/schema_methods.rb, line 92 92: def drop_column(table, *args) 93: alter_table(table) {drop_column(*args)} 94: 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 102 102: def drop_index(table, columns) 103: alter_table(table) {drop_index(columns)} 104: end
Drops one or more views corresponding to the given names:
DB.drop_view(:cheap_items)
# File lib/sequel/database/schema_methods.rb, line 119 119: def drop_view(*names) 120: names.each do |n| 121: remove_cached_schema(n) 122: execute_ddl("DROP VIEW #{quote_schema_table(n)}") 123: end 124: 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
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 270 270: def execute(sql, opts={}) 271: raise NotImplementedError, "#execute should be overridden by adapters" 272: 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 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 [Symbol, Dataset].any?{|c| sql.is_a?(c)} 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
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 277 277: def execute_ddl(sql, opts={}, &block) 278: execute_dui(sql, opts, &block) 279: 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 291 291: def execute_insert(sql, opts={}, &block) 292: execute_dui(sql, opts, &block) 293: 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 308 308: def fetch(sql, *args, &block) 309: ds = dataset.with_sql(sql, *args) 310: ds.each(&block) if block 311: ds 312: end
The method to call on identifiers going into the database
# File lib/sequel/database.rb, line 333 333: def identifier_input_method 334: case @identifier_input_method 335: when nil 336: @identifier_input_method = @opts.include?(:identifier_input_method) ? @opts[:identifier_input_method] : (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method) 337: @identifier_input_method == "" ? nil : @identifier_input_method 338: when "" 339: nil 340: else 341: @identifier_input_method 342: end 343: end
The method to call on identifiers coming from the database
# File lib/sequel/database.rb, line 352 352: def identifier_output_method 353: case @identifier_output_method 354: when nil 355: @identifier_output_method = @opts.include?(:identifier_output_method) ? @opts[:identifier_output_method] : (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method) 356: @identifier_output_method == "" ? nil : @identifier_output_method 357: when "" 358: nil 359: else 360: @identifier_output_method 361: end 362: 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 373 373: def inspect 374: "#<#{self.class}: #{(uri rescue opts).inspect}>" 375: end
# File lib/sequel/deprecated.rb, line 91 91: def logger 92: Deprecation.deprecate('Sequel::Database#logger', 'Use Sequel::Database#loggers') 93: @loggers.first 94: end
# File lib/sequel/deprecated.rb, line 96 96: def multi_threaded? 97: Deprecation.deprecate('Sequel::Database#multi_threaded?', 'Use !database.single_threaded?') 98: !@single_threaded 99: end
# File lib/sequel/deprecated.rb, line 86 86: def query(&block) 87: Deprecation.deprecate('Sequel::Database#query', 'require "sequel/extensions/query" first') 88: dataset.query(&block) 89: end
Returns true if the database quotes identifiers.
# File lib/sequel/database.rb, line 401 401: def quote_identifiers? 402: return @quote_identifiers unless @quote_identifiers.nil? 403: @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers) 404: 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 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]
# File lib/sequel/database/schema_methods.rb, line 131 131: def rename_table(name, new_name) 132: remove_cached_schema(name) 133: execute_ddl(rename_table_sql(name, new_name)) 134: end
Parse the schema from the database. If the table_name is not given, returns the schema for all tables as a hash. If the table_name is given, returns the schema for a single table as an array with all members being arrays of length 2. Available options are:
# File lib/sequel/database.rb, line 423 423: def schema(table = nil, opts={}) 424: Deprecation.deprecate('Calling Database#schema without a table argument', 'Use database.tables.inject({}){|h, m| h[m] = database.schema(m); h}') unless table 425: raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true) 426: 427: if table 428: sch, table_name = schema_and_table(table) 429: quoted_name = quote_schema_table(table) 430: end 431: opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema) 432: if opts[:reload] && @schemas 433: if table_name 434: @schemas.delete(quoted_name) 435: else 436: @schemas = nil 437: end 438: end 439: 440: if @schemas 441: if table_name 442: return @schemas[quoted_name] if @schemas[quoted_name] 443: else 444: return @schemas 445: end 446: end 447: 448: raise(Error, '#tables does not exist, you must provide a specific table to #schema') if table.nil? && !respond_to?(:tables, true) 449: 450: @schemas ||= Hash.new do |h,k| 451: quote_name = quote_schema_table(k) 452: h[quote_name] if h.include?(quote_name) 453: end 454: 455: if table_name 456: cols = schema_parse_table(table_name, opts) 457: raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty? 458: @schemas[quoted_name] = cols 459: else 460: tables.each{|t| @schemas[quote_schema_table(t)] = schema_parse_table(t.to_s, opts)} 461: @schemas 462: end 463: end
Default serial primary key options.
# File lib/sequel/database/schema_sql.rb, line 24 24: def serial_primary_key_options 25: {:primary_key => true, :type => Integer, :auto_increment => true} 26: 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 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.
# File lib/sequel/database/schema_methods.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.
# File lib/sequel/database.rb, line 466 466: def single_threaded? 467: @single_threaded 468: 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
Acquires a database connection, yielding it to the passed block.
# File lib/sequel/database.rb, line 471 471: def synchronize(server=nil, &block) 472: @pool.hold(server || :default, &block) 473: 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 478 478: def table_exists?(name) 479: if @schemas && @schemas[name] 480: true 481: else 482: begin 483: from(name).first 484: true 485: rescue 486: false 487: end 488: end 489: end
Attempts to acquire a database connection. Returns true if successful. Will probably raise an error if unsuccessful.
# File lib/sequel/database.rb, line 493 493: def test_connection(server=nil) 494: synchronize(server){|conn|} 495: true 496: 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.
# File lib/sequel/adapters/do.rb, line 123 123: def transaction(opts={}) 124: unless opts.is_a?(Hash) 125: Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})") 126: opts = {:server=>opts} 127: end 128: th = Thread.current 129: synchronize(opts[:server]) do |conn| 130: return yield(conn) if @transactions.include?(th) 131: t = ::DataObjects::Transaction.create_for_uri(uri) 132: t.instance_variable_get(:@connection).close 133: t.instance_variable_set(:@connection, conn) 134: begin 135: log_info("Transaction.begin") 136: t.begin 137: @transactions << th 138: yield(conn) 139: rescue Exception => e 140: log_info("Transaction.rollback") 141: t.rollback 142: transaction_error(e) 143: ensure 144: unless e 145: log_info("Transaction.commit") 146: t.prepare 147: t.commit 148: end 149: @transactions.delete(th) 150: end 151: end 152: 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.
# File lib/sequel/database.rb, line 502 502: def transaction(opts={}) 503: unless opts.is_a?(Hash) 504: Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})") 505: opts = {:server=>opts} 506: end 507: synchronize(opts[:server]) do |conn| 508: return yield(conn) if @transactions.include?(Thread.current) 509: log_info(begin_transaction_sql) 510: conn.execute(begin_transaction_sql) 511: begin 512: @transactions << Thread.current 513: yield(conn) 514: rescue Exception => e 515: log_info(rollback_transaction_sql) 516: conn.execute(rollback_transaction_sql) 517: transaction_error(e) 518: ensure 519: unless e 520: log_info(commit_transaction_sql) 521: conn.execute(commit_transaction_sql) 522: end 523: @transactions.delete(Thread.current) 524: end 525: end 526: 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.
# File lib/sequel/adapters/jdbc.rb, line 199 199: def transaction(opts={}) 200: unless opts.is_a?(Hash) 201: Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})") 202: opts = {:server=>opts} 203: end 204: synchronize(opts[:server]) do |conn| 205: return yield(conn) if @transactions.include?(Thread.current) 206: stmt = conn.createStatement 207: begin 208: log_info(begin_transaction_sql) 209: stmt.execute(begin_transaction_sql) 210: @transactions << Thread.current 211: yield(conn) 212: rescue Exception => e 213: log_info(rollback_transaction_sql) 214: stmt.execute(rollback_transaction_sql) 215: transaction_error(e) 216: ensure 217: unless e 218: log_info(commit_transaction_sql) 219: stmt.execute(commit_transaction_sql) 220: end 221: stmt.close 222: @transactions.delete(Thread.current) 223: end 224: end 225: 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 533 533: def typecast_value(column_type, value) 534: return nil if value.nil? 535: meth = "typecast_value_#{column_type}" 536: begin 537: respond_to?(meth, true) ? send(meth, value) : value 538: rescue ArgumentError, TypeError => exp 539: e = Sequel::InvalidValue.new("#{exp.class} #{exp.message}") 540: e.set_backtrace(exp.backtrace) 541: raise e 542: end 543: end
# File lib/sequel/deprecated.rb, line 71 71: def upcase_identifiers=(v) 72: Deprecation.deprecate('Sequel::Database#upcase_identifiers=', 'Use Sequel::Database#identifier_input_method = :upcase or nil') 73: self.identifier_input_method = v ? :upcase : nil 74: end
# File lib/sequel/deprecated.rb, line 76 76: def upcase_identifiers? 77: Deprecation.deprecate('Sequel::Database#upcase_identifiers?', 'Use Sequel::Database#identifier_input_method == :upcase') 78: identifier_input_method == :upcase 79: 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 548 548: def uri 549: uri = URI::Generic.new( 550: self.class.adapter_scheme.to_s, 551: nil, 552: @opts[:host], 553: @opts[:port], 554: nil, 555: "/#{@opts[:database]}", 556: nil, 557: nil, 558: nil 559: ) 560: uri.user = @opts[:user] 561: uri.password = @opts[:password] if uri.user 562: uri.to_s 563: end
Return the DataObjects URI for the Sequel URI, removing the do: prefix.
# File lib/sequel/adapters/do.rb, line 156 156: def uri(opts={}) 157: opts = @opts.merge(opts) 158: (opts[:uri] || opts[:url]).sub(/\Ado:/, '') 159: 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 231 231: def uri(opts={}) 232: opts = @opts.merge(opts) 233: ur = opts[:uri] || opts[:url] || opts[:database] 234: ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}" 235: end