| 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 | ||
| TEMPORARY | = | 'TEMPORARY '.freeze | ||
| 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 93
93: def self.adapter_class(scheme)
94: scheme = scheme.to_s.gsub('-', '_').to_sym
95:
96: unless klass = ADAPTER_MAP[scheme]
97: # attempt to load the adapter file
98: begin
99: Sequel.require "adapters/#{scheme}"
100: rescue LoadError => e
101: raise AdapterNotFound, "Could not load #{scheme} adapter:\n #{e.message}"
102: end
103:
104: # make sure we actually loaded the adapter
105: unless klass = ADAPTER_MAP[scheme]
106: raise AdapterNotFound, "Could not load #{scheme} adapter"
107: end
108: end
109: klass
110: end
Connects to a database. See Sequel.connect.
# File lib/sequel/database.rb, line 118
118: def self.connect(conn_string, opts = {}, &block)
119: if conn_string.is_a?(String)
120: if match = /\A(jdbc|do):/o.match(conn_string)
121: c = adapter_class(match[1].to_sym)
122: opts = {:uri=>conn_string}.merge(opts)
123: else
124: uri = URI.parse(conn_string)
125: scheme = uri.scheme
126: scheme = :dbi if scheme =~ /\Adbi-/
127: c = adapter_class(scheme)
128: uri_options = {}
129: uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v} unless uri.query.to_s.strip.empty?
130: opts = c.send(:uri_to_options, uri).merge(uri_options).merge(opts)
131: end
132: else
133: opts = conn_string.merge(opts)
134: c = adapter_class(opts[:adapter] || opts['adapter'])
135: end
136: # process opts a bit
137: opts = opts.inject({}) do |m, kv| k, v = *kv
138: k = :user if k.to_s == 'username'
139: m[k.to_sym] = v
140: m
141: end
142: if block
143: begin
144: yield(db = c.new(opts))
145: ensure
146: db.disconnect if db
147: ::Sequel::DATABASES.delete(db)
148: end
149: nil
150: else
151: c.new(opts)
152: end
153: 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: @pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(connection_pool_default_options.merge(opts), &block)
81: @pool.connection_proc = proc{|server| connect(server)} unless block
82: @pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc]
83:
84: @loggers = Array(opts[:logger]) + Array(opts[:loggers])
85: ::Sequel::DATABASES.push(self)
86: 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
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
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 237
237: def [](*args)
238: (String === args.first) ? fetch(*args) : from(*args)
239: 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 243
243: def call(ps_name, hash={})
244: prepared_statements[ps_name].call(hash)
245: 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 77
77: def create_or_replace_view(name, source)
78: remove_cached_schema(name)
79: source = source.sql if source.is_a?(Dataset)
80: execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}")
81: 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 60
60: def create_table(name, options={}, &block)
61: options = {:generator=>options} if options.is_a?(Schema::Generator)
62: generator = options[:generator] || Schema::Generator.new(self, &block)
63: execute_ddl(create_table_sql(name, generator, options))
64: index_sql_list(name, generator.indexes).each{|sql| execute_ddl(sql)}
65: 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 68
68: def create_table!(name, options={}, &block)
69: drop_table(name) rescue nil
70: create_table(name, options, &block)
71: 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 87
87: def create_view(name, source)
88: source = source.sql if source.is_a?(Dataset)
89: execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}")
90: 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 264
264: def database_type
265: self.class.adapter_scheme
266: 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 97
97: def drop_column(table, *args)
98: alter_table(table) {drop_column(*args)}
99: 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 107
107: def drop_index(table, columns, options={})
108: alter_table(table){drop_index(columns, options)}
109: end
Drops one or more views corresponding to the given names:
DB.drop_view(:cheap_items)
# File lib/sequel/database/schema_methods.rb, line 124
124: def drop_view(*names)
125: names.each do |n|
126: remove_cached_schema(n)
127: execute_ddl("DROP VIEW #{quote_schema_table(n)}")
128: end
129: end
Dump indexes for all tables as a migration. This complements the :indexes=>false option to dump_schema_migration.
# File lib/sequel/extensions/schema_dumper.rb, line 5 5: def dump_indexes_migration 6: ts = tables 7: "Class.new(Sequel::Migration) do\n def up\n\#{ts.map{|t| dump_table_indexes(t, :add_index)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, ' ')}\n end\n \n def down\n\#{ts.map{|t| dump_table_indexes(t, :drop_index)}.reject{|x| x == ''}.join(\"\\n\\n\").gsub(/^/o, ' ')}\n end\nend\n" 8: 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 30
30: def dump_schema_migration(options={})
31: ts = tables
32: "Class.new(Sequel::Migration) do\n def up\n\#{ts.map{|t| dump_table_schema(t, options)}.join(\"\\n\\n\").gsub(/^/o, ' ')}\n end\n \n def down\n drop_table(\#{ts.inspect[1...-1]})\n end\nend\n"
33: 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 48
48: def dump_table_schema(table, options={})
49: s = schema(table).dup
50: pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first}
51: options = options.merge(:single_pk=>true) if pks.length == 1
52: m = method(:column_schema_to_generator_opts)
53: im = method(:index_to_generator_opts)
54: indexes = indexes(table).sort_by{|k,v| k.to_s} if options[:indexes] != false and respond_to?(:indexes)
55: gen = Schema::Generator.new(self) do
56: s.each{|name, info| send(*m.call(name, info, options))}
57: primary_key(pks) if !@primary_key && pks.length > 0
58: indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts))} if indexes
59: end
60: commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n")
61: "create_table(#{table.inspect}) do\n#{commands.gsub(/^/o, ' ')}\nend"
62: 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 281
281: def execute(sql, opts={})
282: raise NotImplementedError, "#execute should be overridden by adapters"
283: 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 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 288
288: def execute_ddl(sql, opts={}, &block)
289: execute_dui(sql, opts, &block)
290: 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 302
302: def execute_insert(sql, opts={}, &block)
303: execute_dui(sql, opts, &block)
304: 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 319
319: def fetch(sql, *args, &block)
320: ds = dataset.with_sql(sql, *args)
321: ds.each(&block) if block
322: ds
323: end
The method to call on identifiers going into the database
# File lib/sequel/database.rb, line 344
344: def identifier_input_method
345: case @identifier_input_method
346: when nil
347: @identifier_input_method = @opts.include?(:identifier_input_method) ? @opts[:identifier_input_method] : (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method)
348: @identifier_input_method == "" ? nil : @identifier_input_method
349: when ""
350: nil
351: else
352: @identifier_input_method
353: end
354: end
The method to call on identifiers coming from the database
# File lib/sequel/database.rb, line 363
363: def identifier_output_method
364: case @identifier_output_method
365: when nil
366: @identifier_output_method = @opts.include?(:identifier_output_method) ? @opts[:identifier_output_method] : (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method)
367: @identifier_output_method == "" ? nil : @identifier_output_method
368: when ""
369: nil
370: else
371: @identifier_output_method
372: end
373: 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 192
192: def indexes(table)
193: indexes = {}
194: m = output_identifier_meth
195: metadata(:getIndexInfo, nil, nil, input_identifier_meth.call(table), false, true) do |r|
196: next unless name = r[:column_name]
197: next if respond_to?(:primary_key_index_re, true) and r[:index_name] =~ primary_key_index_re
198: i = indexes[m.call(r[:index_name])] ||= {:columns=>[], :unique=>!r[:non_unique]}
199: i[:columns] << m.call(name)
200: end
201: indexes
202: 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 384
384: def inspect
385: "#<#{self.class}: #{(uri rescue opts).inspect}>"
386: end
Remove any existing loggers and just use the given logger.
# File lib/sequel/database.rb, line 401
401: def logger=(logger)
402: @loggers = Array(logger)
403: end
Returns true if the database quotes identifiers.
# File lib/sequel/database.rb, line 412
412: def quote_identifiers?
413: return @quote_identifiers unless @quote_identifiers.nil?
414: @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers)
415: 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 147
147: def rename_column(table, *args)
148: alter_table(table) {rename_column(*args)}
149: 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 136
136: def rename_table(name, new_name)
137: remove_cached_schema(name)
138: execute_ddl(rename_table_sql(name, new_name))
139: 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 434
434: def schema(table, opts={})
435: raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true)
436:
437: sch, table_name = schema_and_table(table)
438: quoted_name = quote_schema_table(table)
439: opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema)
440:
441: @schemas.delete(quoted_name) if opts[:reload] && @schemas
442: return @schemas[quoted_name] if @schemas && @schemas[quoted_name]
443:
444: @schemas ||= Hash.new do |h,k|
445: quote_name = quote_schema_table(k)
446: h[quote_name] if h.include?(quote_name)
447: end
448:
449: cols = schema_parse_table(table_name, opts)
450: raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty?
451: @schemas[quoted_name] = cols
452: 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 156
156: def set_column_default(table, *args)
157: alter_table(table) {set_column_default(*args)}
158: 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 165
165: def set_column_type(table, *args)
166: alter_table(table) {set_column_type(*args)}
167: end
Returns true if the database is using a single-threaded connection pool.
# File lib/sequel/database.rb, line 455
455: def single_threaded?
456: @single_threaded
457: 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 460
460: def synchronize(server=nil, &block)
461: @pool.hold(server || :default, &block)
462: 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 467
467: def table_exists?(name)
468: if @schemas && @schemas[name]
469: true
470: else
471: begin
472: from(name).first
473: true
474: rescue
475: false
476: end
477: end
478: end
Attempts to acquire a database connection. Returns true if successful. Will probably raise an error if unsuccessful.
# File lib/sequel/database.rb, line 482
482: def test_connection(server=nil)
483: synchronize(server){|conn|}
484: true
485: 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 215
215: def transaction(opts={})
216: synchronize(opts[:server]) do |conn|
217: return yield(conn) if @transactions.include?(Thread.current)
218: stmt = conn.createStatement
219: begin
220: log_info(begin_transaction_sql)
221: stmt.execute(begin_transaction_sql)
222: @transactions << Thread.current
223: yield(conn)
224: rescue Exception => e
225: log_info(rollback_transaction_sql)
226: stmt.execute(rollback_transaction_sql)
227: transaction_error(e)
228: ensure
229: unless e
230: log_info(commit_transaction_sql)
231: stmt.execute(commit_transaction_sql)
232: end
233: stmt.close
234: @transactions.delete(Thread.current)
235: end
236: end
237: 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: th = Thread.current
125: synchronize(opts[: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
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 491
491: def transaction(opts={})
492: synchronize(opts[:server]) do |conn|
493: return yield(conn) if @transactions.include?(Thread.current)
494: log_info(begin_transaction_sql)
495: conn.execute(begin_transaction_sql)
496: begin
497: @transactions << Thread.current
498: yield(conn)
499: rescue Exception => e
500: log_info(rollback_transaction_sql)
501: conn.execute(rollback_transaction_sql)
502: transaction_error(e)
503: ensure
504: unless e
505: log_info(commit_transaction_sql)
506: conn.execute(commit_transaction_sql)
507: end
508: @transactions.delete(Thread.current)
509: end
510: end
511: 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 518
518: def typecast_value(column_type, value)
519: return nil if value.nil?
520: meth = "typecast_value_#{column_type}"
521: begin
522: respond_to?(meth, true) ? send(meth, value) : value
523: rescue ArgumentError, TypeError => exp
524: e = Sequel::InvalidValue.new("#{exp.class} #{exp.message}")
525: e.set_backtrace(exp.backtrace)
526: raise e
527: end
528: end
Return the DataObjects URI for the Sequel URI, removing the do: prefix.
# File lib/sequel/adapters/do.rb, line 152
152: def uri(opts={})
153: opts = @opts.merge(opts)
154: (opts[:uri] || opts[:url]).sub(/\Ado:/, '')
155: 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 533
533: def uri
534: uri = URI::Generic.new(
535: self.class.adapter_scheme.to_s,
536: nil,
537: @opts[:host],
538: @opts[:port],
539: nil,
540: "/#{@opts[:database]}",
541: nil,
542: nil,
543: nil
544: )
545: uri.user = @opts[:user]
546: uri.password = @opts[:password] if uri.user
547: uri.to_s
548: 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 243
243: def uri(opts={})
244: opts = @opts.merge(opts)
245: ur = opts[:uri] || opts[:url] || opts[:database]
246: ur =~ /^\Ajdbc:/ ? ur : "jdbc:#{ur}"
247: end