Class: Sequel::Database
- Extended by:
- Metaprogramming
- Includes:
- Metaprogramming
- Defined in:
- lib/sequel/database.rb,
lib/sequel/extensions/query.rb,
lib/sequel/database/schema_sql.rb,
lib/sequel/database/schema_methods.rb,
lib/sequel/extensions/schema_dumper.rb
Overview
A Database object represents a virtual connection to a database. The Database class is meant to be subclassed by database adapters in order to provide the functionality needed for executing queries.
Direct Known Subclasses
ADO::Database, Amalgalite::Database, Sequel::DB2::Database, Sequel::DBI::Database, Sequel::DataObjects::Database, Firebird::Database, Informix::Database, JDBC::Database, MySQL::Database, ODBC::Database, OpenBase::Database, Oracle::Database, Postgres::Database, SQLite::Database
Constant Summary collapse
- ADAPTERS =
Array of supported database adapters
%w'ado amalgalite db2 dbi do firebird informix jdbc mysql odbc openbase oracle postgres sqlite'.collect{|x| x.to_sym}
- 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
- @@identifier_input_method =
The identifier input method to use by default
nil
- @@identifier_output_method =
The identifier output method to use by default
nil
- @@single_threaded =
Whether to use the single threaded connection pool by default
false
- @@quote_identifiers =
Whether to quote identifiers (columns and tables) by default
nil
Instance Attribute Summary collapse
-
#default_schema ⇒ Object
The default schema to use, generally should be nil.
-
#loggers ⇒ Object
Array of SQL loggers to use for this database.
-
#opts ⇒ Object
readonly
The options for this database.
-
#pool ⇒ Object
readonly
The connection pool for this database.
-
#prepared_statements ⇒ Object
readonly
The prepared statement objects for this database, keyed by name.
Class Method Summary collapse
-
.adapter_class(scheme) ⇒ Object
The Database subclass for the given adapter scheme.
-
.adapter_scheme ⇒ Object
Returns the scheme for the Database class.
-
.connect(conn_string, opts = {}, &block) ⇒ Object
Connects to a database.
-
.identifier_input_method ⇒ Object
The method to call on identifiers going into the database.
-
.identifier_input_method=(v) ⇒ Object
Set the method to call on identifiers going into the database See Sequel.identifier_input_method=.
-
.identifier_output_method ⇒ Object
The method to call on identifiers coming from the database.
-
.identifier_output_method=(v) ⇒ Object
Set the method to call on identifiers coming from the database See Sequel.identifier_output_method=.
-
.quote_identifiers=(value) ⇒ Object
Sets the default quote_identifiers mode for new databases.
-
.single_threaded=(value) ⇒ Object
Sets the default single_threaded mode for new databases.
Instance Method Summary collapse
-
#<<(sql) ⇒ Object
Executes the supplied SQL statement string.
-
#[](*args) ⇒ Object
Returns a dataset from the database.
-
#add_column(table, *args) ⇒ Object
Adds a column to the specified table.
-
#add_index(table, columns, options = {}) ⇒ Object
Adds an index to a table for the given columns:.
-
#alter_table(name, generator = nil, &block) ⇒ Object
Alters the given table with the specified block.
-
#call(ps_name, hash = {}) ⇒ Object
Call the prepared statement with the given name with the given hash of arguments.
-
#cast_type_literal(type) ⇒ Object
Cast the given type to a literal type.
-
#connect ⇒ Object
Connects to the database.
-
#create_or_replace_view(name, source) ⇒ Object
Creates a view, replacing it if it already exists:.
-
#create_table(name, options = {}, &block) ⇒ Object
Creates a table with the columns given in the provided block:.
-
#create_table!(name, options = {}, &block) ⇒ Object
Forcibly creates a table, attempting to drop it unconditionally (and catching any errors), then creating it.
-
#create_table?(name, options = {}, &block) ⇒ Boolean
Creates the table unless the table already exists.
-
#create_view(name, source) ⇒ Object
Creates a view based on a dataset or an SQL string:.
-
#database_type ⇒ Object
The database type for this database object, the same as the adapter scheme by default.
-
#dataset ⇒ Object
Returns a blank dataset for this database.
-
#disconnect ⇒ Object
Disconnects all available connections from the connection pool.
-
#drop_column(table, *args) ⇒ Object
Removes a column from the specified table:.
-
#drop_index(table, columns, options = {}) ⇒ Object
Removes an index for the given table and column/s:.
-
#drop_table(*names) ⇒ Object
Drops one or more tables corresponding to the given names:.
-
#drop_view(*names) ⇒ Object
Drops one or more views corresponding to the given names:.
-
#dump_indexes_migration(options = {}) ⇒ Object
Dump indexes for all tables as a migration.
-
#dump_schema_migration(options = {}) ⇒ Object
Return a string that contains a Sequel::Migration subclass that when run would recreate the database structure.
-
#dump_table_schema(table, options = {}) ⇒ Object
Return a string with a create table block that will recreate the given table’s schema.
-
#execute(sql, opts = {}) ⇒ Object
Executes the given SQL on the database.
-
#execute_ddl(sql, opts = {}, &block) ⇒ Object
Method that should be used when submitting any DDL (Data Definition Language) SQL.
-
#execute_dui(sql, opts = {}, &block) ⇒ Object
Method that should be used when issuing a DELETE, UPDATE, or INSERT statement.
-
#execute_insert(sql, opts = {}, &block) ⇒ Object
Method that should be used when issuing a INSERT statement.
-
#fetch(sql, *args, &block) ⇒ Object
Fetches records for an arbitrary SQL statement.
-
#from(*args, &block) ⇒ Object
Returns a new dataset with the from method invoked.
-
#get(*args, &block) ⇒ Object
Returns a single value from the database, e.g.:.
-
#identifier_input_method ⇒ Object
The method to call on identifiers going into the database.
-
#identifier_input_method=(v) ⇒ Object
Set the method to call on identifiers going into the database.
-
#identifier_output_method ⇒ Object
The method to call on identifiers coming from the database.
-
#identifier_output_method=(v) ⇒ Object
Set the method to call on identifiers coming from the database.
-
#initialize(opts = {}, &block) ⇒ Database
constructor
Constructs a new instance of a database connection with the specified options hash.
-
#inspect ⇒ Object
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).
-
#literal(v) ⇒ Object
Proxy the literal call to the dataset, used for default values.
-
#log_info(message, args = nil) ⇒ Object
Log a message at level info to all loggers.
-
#logger=(logger) ⇒ Object
Remove any existing loggers and just use the given logger.
-
#query(&block) ⇒ Object
Return a dataset modified by the query block.
-
#quote_identifiers=(v) ⇒ Object
Whether to quote identifiers (columns and tables) for this database.
-
#quote_identifiers? ⇒ Boolean
Returns true if the database quotes identifiers.
-
#rename_column(table, *args) ⇒ Object
Renames a column in the specified table.
-
#rename_table(name, new_name) ⇒ Object
Renames a table:.
-
#schema(table, opts = {}) ⇒ Object
Parse the schema from the database.
-
#select(*args, &block) ⇒ Object
Returns a new dataset with the select method invoked.
-
#serial_primary_key_options ⇒ Object
Default serial primary key options.
-
#set_column_default(table, *args) ⇒ Object
Sets the default value for the given column in the given table:.
-
#set_column_type(table, *args) ⇒ Object
Set the data type for the given column in the given table:.
-
#single_threaded? ⇒ Boolean
Returns true if the database is using a single-threaded connection pool.
-
#supports_savepoints? ⇒ Boolean
Whether the database and adapter support savepoints, false by default.
-
#synchronize(server = nil, &block) ⇒ Object
Acquires a database connection, yielding it to the passed block.
-
#table_exists?(name) ⇒ Boolean
Returns true if a table with the given name exists.
-
#test_connection(server = nil) ⇒ Object
Attempts to acquire a database connection.
-
#transaction(opts = {}, &block) ⇒ Object
Starts a database transaction.
-
#typecast_value(column_type, value) ⇒ Object
Typecast the value to the given column_type.
-
#uri ⇒ Object
Returns the URI identifying the database.
-
#url ⇒ Object
Explicit alias of uri for easier subclassing.
Methods included from Metaprogramming
Constructor Details
#initialize(opts = {}, &block) ⇒ Database
Constructs a new instance of a database connection with the specified options hash.
Sequel::Database is an abstract class that is not useful by itself.
Takes the following options:
-
:default_schema : The default schema to use, should generally be nil
-
:disconnection_proc: A proc used to disconnect the connection.
-
:identifier_input_method: A string method symbol to call on identifiers going into the database
-
:identifier_output_method: A string method symbol to call on identifiers coming from the database
-
:loggers : An array of loggers to use.
-
:quote_identifiers : Whether to quote identifiers
-
:single_threaded : Whether to use a single-threaded connection pool
All options given are also passed to the ConnectionPool. If a block is given, it is used as the connection_proc for the ConnectionPool.
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/sequel/database.rb', line 80 def initialize(opts = {}, &block) @opts ||= opts @single_threaded = opts.include?(:single_threaded) ? typecast_value_boolean(opts[:single_threaded]) : @@single_threaded @schemas = {} @default_schema = opts.include?(:default_schema) ? opts[:default_schema] : default_schema_default @prepared_statements = {} @transactions = [] @identifier_input_method = nil @identifier_output_method = nil @quote_identifiers = nil @pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(.merge(opts), &block) @pool.connection_proc = proc{|server| connect(server)} unless block @pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc] @loggers = Array(opts[:logger]) + Array(opts[:loggers]) ::Sequel::DATABASES.push(self) end |
Instance Attribute Details
#default_schema ⇒ Object
The default schema to use, generally should be nil.
50 51 52 |
# File 'lib/sequel/database.rb', line 50 def default_schema @default_schema end |
#loggers ⇒ Object
Array of SQL loggers to use for this database
53 54 55 |
# File 'lib/sequel/database.rb', line 53 def loggers @loggers end |
#opts ⇒ Object (readonly)
The options for this database
56 57 58 |
# File 'lib/sequel/database.rb', line 56 def opts @opts end |
#pool ⇒ Object (readonly)
The connection pool for this database
59 60 61 |
# File 'lib/sequel/database.rb', line 59 def pool @pool end |
#prepared_statements ⇒ Object (readonly)
The prepared statement objects for this database, keyed by name
62 63 64 |
# File 'lib/sequel/database.rb', line 62 def prepared_statements @prepared_statements end |
Class Method Details
.adapter_class(scheme) ⇒ Object
The Database subclass for the given adapter scheme. Raises Sequel::AdapterNotFound if the adapter could not be loaded.
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/sequel/database.rb', line 104 def self.adapter_class(scheme) scheme = scheme.to_s.gsub('-', '_').to_sym unless klass = ADAPTER_MAP[scheme] # attempt to load the adapter file begin Sequel.require "adapters/#{scheme}" rescue LoadError => e raise AdapterNotFound, "Could not load #{scheme} adapter:\n #{e.}" end # make sure we actually loaded the adapter unless klass = ADAPTER_MAP[scheme] raise AdapterNotFound, "Could not load #{scheme} adapter" end end klass end |
.adapter_scheme ⇒ Object
Returns the scheme for the Database class.
124 125 126 |
# File 'lib/sequel/database.rb', line 124 def self.adapter_scheme @scheme end |
.connect(conn_string, opts = {}, &block) ⇒ Object
Connects to a database. See Sequel.connect.
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/sequel/database.rb', line 129 def self.connect(conn_string, opts = {}, &block) case conn_string when String if match = /\A(jdbc|do):/o.match(conn_string) c = adapter_class(match[1].to_sym) opts = {:uri=>conn_string}.merge(opts) else uri = URI.parse(conn_string) scheme = uri.scheme scheme = :dbi if scheme =~ /\Adbi-/ c = adapter_class(scheme) = {} uri.query.split('&').collect{|s| s.split('=')}.each{|k,v| [k.to_sym] = v} unless uri.query.to_s.strip.empty? opts = c.send(:uri_to_options, uri).merge().merge(opts) end when Hash opts = conn_string.merge(opts) c = adapter_class(opts[:adapter] || opts['adapter']) else raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" end # process opts a bit opts = opts.inject({}) do |m, kv| k, v = *kv k = :user if k.to_s == 'username' m[k.to_sym] = v m end if block begin yield(db = c.new(opts)) ensure db.disconnect if db ::Sequel::DATABASES.delete(db) end nil else c.new(opts) end end |
.identifier_input_method ⇒ Object
The method to call on identifiers going into the database
170 171 172 |
# File 'lib/sequel/database.rb', line 170 def self.identifier_input_method @@identifier_input_method end |
.identifier_input_method=(v) ⇒ Object
Set the method to call on identifiers going into the database See Sequel.identifier_input_method=.
176 177 178 |
# File 'lib/sequel/database.rb', line 176 def self.identifier_input_method=(v) @@identifier_input_method = v || "" end |
.identifier_output_method ⇒ Object
The method to call on identifiers coming from the database
181 182 183 |
# File 'lib/sequel/database.rb', line 181 def self.identifier_output_method @@identifier_output_method end |
.identifier_output_method=(v) ⇒ Object
Set the method to call on identifiers coming from the database See Sequel.identifier_output_method=.
187 188 189 |
# File 'lib/sequel/database.rb', line 187 def self.identifier_output_method=(v) @@identifier_output_method = v || "" end |
.quote_identifiers=(value) ⇒ Object
Sets the default quote_identifiers mode for new databases. See Sequel.quote_identifiers=.
193 194 195 |
# File 'lib/sequel/database.rb', line 193 def self.quote_identifiers=(value) @@quote_identifiers = value end |
.single_threaded=(value) ⇒ Object
Sets the default single_threaded mode for new databases. See Sequel.single_threaded=.
199 200 201 |
# File 'lib/sequel/database.rb', line 199 def self.single_threaded=(value) @@single_threaded = value end |
Instance Method Details
#<<(sql) ⇒ Object
Executes the supplied SQL statement string.
237 238 239 |
# File 'lib/sequel/database.rb', line 237 def <<(sql) execute_ddl(sql) end |
#[](*args) ⇒ Object
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"
251 252 253 |
# File 'lib/sequel/database.rb', line 251 def [](*args) (String === args.first) ? fetch(*args) : from(*args) end |
#add_column(table, *args) ⇒ Object
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.
10 11 12 |
# File 'lib/sequel/database/schema_methods.rb', line 10 def add_column(table, *args) alter_table(table) {add_column(*args)} end |
#add_index(table, columns, options = {}) ⇒ Object
Adds an index to a table for the given columns:
DB.add_index :posts, :title
DB.add_index :posts, [:author, :title], :unique => true
Options:
-
:ignore_errors - Ignore any DatabaseErrors that are raised
See alter_table.
24 25 26 27 28 29 30 31 |
# File 'lib/sequel/database/schema_methods.rb', line 24 def add_index(table, columns, ={}) e = [:ignore_errors] begin alter_table(table){add_index(columns, )} rescue DatabaseError raise unless e end end |
#alter_table(name, generator = nil, &block) ⇒ Object
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.
50 51 52 53 54 |
# File 'lib/sequel/database/schema_methods.rb', line 50 def alter_table(name, generator=nil, &block) remove_cached_schema(name) generator ||= Schema::AlterTableGenerator.new(self, &block) alter_table_sql_list(name, generator.operations).flatten.each {|sql| execute_ddl(sql)} end |
#call(ps_name, hash = {}) ⇒ Object
Call the prepared statement with the given name with the given hash of arguments.
257 258 259 |
# File 'lib/sequel/database.rb', line 257 def call(ps_name, hash={}) prepared_statements[ps_name].call(hash) end |
#cast_type_literal(type) ⇒ Object
Cast the given type to a literal type
262 263 264 |
# File 'lib/sequel/database.rb', line 262 def cast_type_literal(type) type_literal(:type=>type) end |
#connect ⇒ Object
Connects to the database. This method should be overridden by descendants.
267 268 269 |
# File 'lib/sequel/database.rb', line 267 def connect raise NotImplementedError, "#connect should be overridden by adapters" end |
#create_or_replace_view(name, source) ⇒ Object
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'))
92 93 94 95 96 |
# File 'lib/sequel/database/schema_methods.rb', line 92 def create_or_replace_view(name, source) remove_cached_schema(name) source = source.sql if source.is_a?(Dataset) execute_ddl("CREATE OR REPLACE VIEW #{quote_schema_table(name)} AS #{source}") end |
#create_table(name, options = {}, &block) ⇒ Object
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:
-
:temp - Create the table as a temporary table.
-
:ignore_index_errors - Ignore any errors when creating indexes.
See Schema::Generator.
70 71 72 73 74 75 |
# File 'lib/sequel/database/schema_methods.rb', line 70 def create_table(name, ={}, &block) = {:generator=>} if .is_a?(Schema::Generator) generator = [:generator] || Schema::Generator.new(self, &block) create_table_from_generator(name, generator, ) create_table_indexes_from_generator(name, generator, ) end |
#create_table!(name, options = {}, &block) ⇒ Object
Forcibly creates a table, attempting to drop it unconditionally (and catching any errors), then creating it.
78 79 80 81 |
# File 'lib/sequel/database/schema_methods.rb', line 78 def create_table!(name, ={}, &block) drop_table(name) rescue nil create_table(name, , &block) end |
#create_table?(name, options = {}, &block) ⇒ Boolean
Creates the table unless the table already exists
84 85 86 |
# File 'lib/sequel/database/schema_methods.rb', line 84 def create_table?(name, ={}, &block) create_table(name, , &block) unless table_exists?(name) end |
#create_view(name, source) ⇒ Object
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'))
102 103 104 105 |
# File 'lib/sequel/database/schema_methods.rb', line 102 def create_view(name, source) source = source.sql if source.is_a?(Dataset) execute_ddl("CREATE VIEW #{quote_schema_table(name)} AS #{source}") end |
#database_type ⇒ Object
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).
278 279 280 |
# File 'lib/sequel/database.rb', line 278 def database_type self.class.adapter_scheme end |
#dataset ⇒ Object
Returns a blank dataset for this database
283 284 285 |
# File 'lib/sequel/database.rb', line 283 def dataset ds = Sequel::Dataset.new(self) end |
#disconnect ⇒ Object
Disconnects all available connections from the connection pool. Any connections currently in use will not be disconnected.
289 290 291 |
# File 'lib/sequel/database.rb', line 289 def disconnect pool.disconnect end |
#drop_column(table, *args) ⇒ Object
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table.
112 113 114 |
# File 'lib/sequel/database/schema_methods.rb', line 112 def drop_column(table, *args) alter_table(table) {drop_column(*args)} end |
#drop_index(table, columns, options = {}) ⇒ Object
Removes an index for the given table and column/s:
DB.drop_index :posts, :title
DB.drop_index :posts, [:author, :title]
See alter_table.
122 123 124 |
# File 'lib/sequel/database/schema_methods.rb', line 122 def drop_index(table, columns, ={}) alter_table(table){drop_index(columns, )} end |
#drop_table(*names) ⇒ Object
Drops one or more tables corresponding to the given names:
DB.drop_table(:posts, :comments)
129 130 131 132 133 134 |
# File 'lib/sequel/database/schema_methods.rb', line 129 def drop_table(*names) names.each do |n| remove_cached_schema(n) execute_ddl(drop_table_sql(n)) end end |
#drop_view(*names) ⇒ Object
Drops one or more views corresponding to the given names:
DB.drop_view(:cheap_items)
139 140 141 142 143 144 |
# File 'lib/sequel/database/schema_methods.rb', line 139 def drop_view(*names) names.each do |n| remove_cached_schema(n) execute_ddl("DROP VIEW #{quote_schema_table(n)}") end end |
#dump_indexes_migration(options = {}) ⇒ Object
Dump indexes for all tables as a migration. This complements the :indexes=>false option to dump_schema_migration. Options:
-
:same_db - Create a dump for the same database type, so don’t ignore errors if the index statements fail.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/sequel/extensions/schema_dumper.rb', line 13 def dump_indexes_migration(={}) ts = tables <<END_MIG Class.new(Sequel::Migration) do def up #{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :add_index, )}.reject{|x| x == ''}.join("\n\n").gsub(/^/o, ' ')} end def down #{ts.sort_by{|t| t.to_s}.map{|t| dump_table_indexes(t, :drop_index, )}.reject{|x| x == ''}.join("\n\n").gsub(/^/o, ' ')} end end END_MIG end |
#dump_schema_migration(options = {}) ⇒ Object
Return a string that contains a Sequel::Migration subclass that when run would recreate the database structure. Options:
-
:same_db - Don’t attempt to translate database types to ruby types. If this isn’t set to true, all database types will be translated to ruby types, but there is no guarantee that the migration generated will yield the same type. Without this set, types that aren’t recognized will be translated to a string-like type.
-
:indexes - If set to false, don’t dump indexes (they can be added later via dump_index_migration).
37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/sequel/extensions/schema_dumper.rb', line 37 def dump_schema_migration(={}) ts = tables <<END_MIG Class.new(Sequel::Migration) do def up #{ts.sort_by{|t| t.to_s}.map{|t| dump_table_schema(t, )}.join("\n\n").gsub(/^/o, ' ')} end def down drop_table(#{ts.sort_by{|t| t.to_s}.inspect[1...-1]}) end end END_MIG end |
#dump_table_schema(table, options = {}) ⇒ Object
Return a string with a create table block that will recreate the given table’s schema. Takes the same options as dump_schema_migration.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/sequel/extensions/schema_dumper.rb', line 54 def dump_table_schema(table, ={}) s = schema(table).dup pks = s.find_all{|x| x.last[:primary_key] == true}.map{|x| x.first} = .merge(:single_pk=>true) if pks.length == 1 m = method(:column_schema_to_generator_opts) im = method(:index_to_generator_opts) indexes = indexes(table).sort_by{|k,v| k.to_s} if [:indexes] != false and respond_to?(:indexes) gen = Schema::Generator.new(self) do s.each{|name, info| send(*m.call(name, info, ))} primary_key(pks) if !@primary_key && pks.length > 0 indexes.each{|iname, iopts| send(:index, iopts[:columns], im.call(table, iname, iopts))} if indexes end commands = [gen.dump_columns, gen.dump_constraints, gen.dump_indexes].reject{|x| x == ''}.join("\n\n") "create_table(#{table.inspect}#{', :ignore_index_errors=>true' if ![:same_db] && [:indexes] != false && indexes && !indexes.empty?}) do\n#{commands.gsub(/^/o, ' ')}\nend" end |
#execute(sql, opts = {}) ⇒ Object
Executes the given SQL on the database. This method should be overridden in descendants. This method should not be called directly by user code.
295 296 297 |
# File 'lib/sequel/database.rb', line 295 def execute(sql, opts={}) raise NotImplementedError, "#execute should be overridden by adapters" end |
#execute_ddl(sql, opts = {}, &block) ⇒ Object
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.
302 303 304 |
# File 'lib/sequel/database.rb', line 302 def execute_ddl(sql, opts={}, &block) execute_dui(sql, opts, &block) end |
#execute_dui(sql, opts = {}, &block) ⇒ Object
Method that should be used when issuing a DELETE, UPDATE, or INSERT statement. By default, calls execute. This method should not be called directly by user code.
309 310 311 |
# File 'lib/sequel/database.rb', line 309 def execute_dui(sql, opts={}, &block) execute(sql, opts, &block) end |
#execute_insert(sql, opts = {}, &block) ⇒ Object
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.
316 317 318 |
# File 'lib/sequel/database.rb', line 316 def execute_insert(sql, opts={}, &block) execute_dui(sql, opts, &block) end |
#fetch(sql, *args, &block) ⇒ Object
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
333 334 335 336 337 |
# File 'lib/sequel/database.rb', line 333 def fetch(sql, *args, &block) ds = dataset.with_sql(sql, *args) ds.each(&block) if block ds end |
#from(*args, &block) ⇒ Object
Returns a new dataset with the from method invoked. If a block is given, it is used as a filter on the dataset.
341 342 343 344 |
# File 'lib/sequel/database.rb', line 341 def from(*args, &block) ds = dataset.from(*args) block ? ds.filter(&block) : ds end |
#get(*args, &block) ⇒ Object
Returns a single value from the database, e.g.:
# SELECT 1
DB.get(1) #=> 1
# SELECT version()
DB.get(:version.sql_function) #=> ...
353 354 355 |
# File 'lib/sequel/database.rb', line 353 def get(*args, &block) dataset.get(*args, &block) end |
#identifier_input_method ⇒ Object
The method to call on identifiers going into the database
358 359 360 361 362 363 364 365 366 367 368 |
# File 'lib/sequel/database.rb', line 358 def identifier_input_method case @identifier_input_method when nil @identifier_input_method = @opts.include?(:identifier_input_method) ? @opts[:identifier_input_method] : (@@identifier_input_method.nil? ? identifier_input_method_default : @@identifier_input_method) @identifier_input_method == "" ? nil : @identifier_input_method when "" nil else @identifier_input_method end end |
#identifier_input_method=(v) ⇒ Object
Set the method to call on identifiers going into the database
371 372 373 374 |
# File 'lib/sequel/database.rb', line 371 def identifier_input_method=(v) reset_schema_utility_dataset @identifier_input_method = v || "" end |
#identifier_output_method ⇒ Object
The method to call on identifiers coming from the database
377 378 379 380 381 382 383 384 385 386 387 |
# File 'lib/sequel/database.rb', line 377 def identifier_output_method case @identifier_output_method when nil @identifier_output_method = @opts.include?(:identifier_output_method) ? @opts[:identifier_output_method] : (@@identifier_output_method.nil? ? identifier_output_method_default : @@identifier_output_method) @identifier_output_method == "" ? nil : @identifier_output_method when "" nil else @identifier_output_method end end |
#identifier_output_method=(v) ⇒ Object
Set the method to call on identifiers coming from the database
390 391 392 393 |
# File 'lib/sequel/database.rb', line 390 def identifier_output_method=(v) reset_schema_utility_dataset @identifier_output_method = v || "" end |
#inspect ⇒ Object
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).
398 399 400 |
# File 'lib/sequel/database.rb', line 398 def inspect "#<#{self.class}: #{(uri rescue opts).inspect}>" end |
#literal(v) ⇒ Object
Proxy the literal call to the dataset, used for default values.
403 404 405 |
# File 'lib/sequel/database.rb', line 403 def literal(v) schema_utility_dataset.literal(v) end |
#log_info(message, args = nil) ⇒ Object
Log a message at level info to all loggers. All SQL logging goes through this method.
409 410 411 412 |
# File 'lib/sequel/database.rb', line 409 def log_info(, args=nil) = "#{}; #{args.inspect}" if args @loggers.each{|logger| logger.info()} end |
#logger=(logger) ⇒ Object
Remove any existing loggers and just use the given logger.
415 416 417 |
# File 'lib/sequel/database.rb', line 415 def logger=(logger) @loggers = Array(logger) end |
#query(&block) ⇒ Object
Return a dataset modified by the query block
8 9 10 |
# File 'lib/sequel/extensions/query.rb', line 8 def query(&block) dataset.query(&block) end |
#quote_identifiers=(v) ⇒ Object
Whether to quote identifiers (columns and tables) for this database
420 421 422 423 |
# File 'lib/sequel/database.rb', line 420 def quote_identifiers=(v) reset_schema_utility_dataset @quote_identifiers = v end |
#quote_identifiers? ⇒ Boolean
Returns true if the database quotes identifiers.
426 427 428 429 |
# File 'lib/sequel/database.rb', line 426 def quote_identifiers? return @quote_identifiers unless @quote_identifiers.nil? @quote_identifiers = @opts.include?(:quote_identifiers) ? @opts[:quote_identifiers] : (@@quote_identifiers.nil? ? quote_identifiers_default : @@quote_identifiers) end |
#rename_column(table, *args) ⇒ Object
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.
162 163 164 |
# File 'lib/sequel/database/schema_methods.rb', line 162 def rename_column(table, *args) alter_table(table) {rename_column(*args)} end |
#rename_table(name, new_name) ⇒ Object
Renames a table:
DB.tables #=> [:items]
DB.rename_table :items, :old_items
DB.tables #=> [:old_items]
151 152 153 154 |
# File 'lib/sequel/database/schema_methods.rb', line 151 def rename_table(name, new_name) remove_cached_schema(name) execute_ddl(rename_table_sql(name, new_name)) end |
#schema(table, opts = {}) ⇒ Object
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:
-
:reload - Get fresh information from the database, instead of using cached information. If table_name is blank, :reload should be used unless you are sure that schema has not been called before with a table_name, otherwise you may only getting the schemas for tables that have been requested explicitly.
-
:schema - An explicit schema to use. It may also be implicitly provided via the table name.
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 |
# File 'lib/sequel/database.rb', line 448 def schema(table, opts={}) raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true) sch, table_name = schema_and_table(table) quoted_name = quote_schema_table(table) opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema) @schemas.delete(quoted_name) if opts[:reload] return @schemas[quoted_name] if @schemas[quoted_name] cols = schema_parse_table(table_name, opts) raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty? cols.each{|_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type])} @schemas[quoted_name] = cols end |
#select(*args, &block) ⇒ Object
Returns a new dataset with the select method invoked.
432 433 434 |
# File 'lib/sequel/database.rb', line 432 def select(*args, &block) dataset.select(*args, &block) end |
#serial_primary_key_options ⇒ Object
Default serial primary key options.
19 20 21 |
# File 'lib/sequel/database/schema_sql.rb', line 19 def {:primary_key => true, :type => Integer, :auto_increment => true} end |
#set_column_default(table, *args) ⇒ Object
Sets the default value for the given column in the given table:
DB.set_column_default :items, :category, 'perl!'
See alter_table.
171 172 173 |
# File 'lib/sequel/database/schema_methods.rb', line 171 def set_column_default(table, *args) alter_table(table) {set_column_default(*args)} end |
#set_column_type(table, *args) ⇒ Object
Set the data type for the given column in the given table:
DB.set_column_type :items, :price, :float
See alter_table.
180 181 182 |
# File 'lib/sequel/database/schema_methods.rb', line 180 def set_column_type(table, *args) alter_table(table) {set_column_type(*args)} end |
#single_threaded? ⇒ Boolean
Returns true if the database is using a single-threaded connection pool.
465 466 467 |
# File 'lib/sequel/database.rb', line 465 def single_threaded? @single_threaded end |
#supports_savepoints? ⇒ Boolean
Whether the database and adapter support savepoints, false by default
475 476 477 |
# File 'lib/sequel/database.rb', line 475 def supports_savepoints? false end |
#synchronize(server = nil, &block) ⇒ Object
Acquires a database connection, yielding it to the passed block.
470 471 472 |
# File 'lib/sequel/database.rb', line 470 def synchronize(server=nil, &block) @pool.hold(server || :default, &block) end |
#table_exists?(name) ⇒ Boolean
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.
482 483 484 485 486 487 488 489 |
# File 'lib/sequel/database.rb', line 482 def table_exists?(name) begin from(name).first true rescue false end end |
#test_connection(server = nil) ⇒ Object
Attempts to acquire a database connection. Returns true if successful. Will probably raise an error if unsuccessful.
493 494 495 496 |
# File 'lib/sequel/database.rb', line 493 def test_connection(server=nil) synchronize(server){|conn|} true end |
#transaction(opts = {}, &block) ⇒ Object
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:
-
:server - The server to use for the transaction
-
:savepoint - Whether to create a new savepoint for this transaction, only respected if the database adapter supports savepoints. By default Sequel will reuse an existing transaction, so if you want to use a savepoint you must use this option.
509 510 511 512 513 514 |
# File 'lib/sequel/database.rb', line 509 def transaction(opts={}, &block) synchronize(opts[:server]) do |conn| return yield(conn) if already_in_transaction?(conn, opts) _transaction(conn, &block) end end |
#typecast_value(column_type, value) ⇒ Object
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.
521 522 523 524 525 526 527 528 529 530 531 |
# File 'lib/sequel/database.rb', line 521 def typecast_value(column_type, value) return nil if value.nil? meth = "typecast_value_#{column_type}" begin respond_to?(meth, true) ? send(meth, value) : value rescue ArgumentError, TypeError => exp e = Sequel::InvalidValue.new("#{exp.class} #{exp.}") e.set_backtrace(exp.backtrace) raise e end end |
#uri ⇒ Object
Returns the URI identifying the database. This method can raise an error if the database used options instead of a connection string.
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
# File 'lib/sequel/database.rb', line 536 def uri uri = URI::Generic.new( self.class.adapter_scheme.to_s, nil, @opts[:host], @opts[:port], nil, "/#{@opts[:database]}", nil, nil, nil ) uri.user = @opts[:user] uri.password = @opts[:password] if uri.user uri.to_s end |
#url ⇒ Object
Explicit alias of uri for easier subclassing.
554 555 556 |
# File 'lib/sequel/database.rb', line 554 def url uri end |