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.
Whether the schema should be cached for this database. True by default for performance, can be set to false to always issue a database query to get the schema.
The prepared statement object hash for this database, keyed by name symbol
Runs the supplied SQL statement string on the database server. Returns self so it can be safely chained:
DB << "UPDATE albums SET artist_id = NULL" << "DROP TABLE artists"
# File lib/sequel/database/query.rb, line 25 def <<(sql) run(sql) self end
Call the prepared statement with the given name with the given hash of arguments.
DB[:items].where(id: 1).prepare(:first, :sa) DB.call(:sa) # SELECT * FROM items WHERE id = 1
# File lib/sequel/database/query.rb, line 35 def call(ps_name, hash={}, &block) prepared_statement(ps_name).call(hash, &block) end
Method that should be used when submitting any DDL (Data Definition
Language) SQL, such as create_table
.
By default, calls execute_dui
. This method should not be
called directly by user code.
# File lib/sequel/database/query.rb, line 42 def execute_ddl(sql, opts=OPTS, &block) execute_dui(sql, opts, &block) end
Method that should be used when issuing a DELETE or UPDATE statement. By default, calls execute. This method should not be called directly by user code.
# File lib/sequel/database/query.rb, line 49 def execute_dui(sql, opts=OPTS, &block) execute(sql, opts, &block) 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/query.rb, line 56 def execute_insert(sql, opts=OPTS, &block) execute_dui(sql, opts, &block) end
Returns a single value from the database, see Sequel::Dataset#get.
DB.get(1) # SELECT 1 # => 1 DB.get{server_version.function} # SELECT server_version()
# File lib/sequel/database/query.rb, line 65 def get(*args, &block) @default_dataset.get(*args, &block) end
Runs the supplied SQL statement string on the database server. Returns nil. Options:
The server to run the SQL on.
DB.run("SET some_server_variable = 42")
# File lib/sequel/database/query.rb, line 74 def run(sql, opts=OPTS) sql = literal(sql) if sql.is_a?(SQL::PlaceholderLiteralString) execute_ddl(sql, opts) nil end
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. The table argument can also be a dataset, as long as it only has one table. Available options are:
Ignore any cached results, and get fresh information from the database.
An explicit schema to use. It may also be implicitly provided via the table name.
If schema parsing is supported by the database, the column information hash should contain at least the following entries:
Whether NULL is an allowed value for the column.
The database type for the column, as a database specific string.
The database default for the column, as a database specific string, or nil if there is no default value.
Whether the columns is a primary key column. If this column is not present, it means that primary key information is unavailable, not that the column is not a primary key.
The database default for the column, as a ruby object. In many cases, complex database defaults cannot be parsed into ruby objects, in which case nil will be used as the value.
A symbol specifying the type, such as :integer or :string.
Example:
DB.schema(:artists) # [[:id, # {:type=>:integer, # :primary_key=>true, # :default=>"nextval('artist_id_seq'::regclass)", # :ruby_default=>nil, # :db_type=>"integer", # :allow_null=>false}], # [:name, # {:type=>:string, # :primary_key=>false, # :default=>nil, # :ruby_default=>nil, # :db_type=>"text", # :allow_null=>false}]]
# File lib/sequel/database/query.rb, line 121 def schema(table, opts=OPTS) raise(Error, 'schema parsing is not implemented on this database') unless supports_schema_parsing? opts = opts.dup tab = if table.is_a?(Dataset) o = table.opts from = o[:from] raise(Error, "can only parse the schema for a dataset with a single from table") unless from && from.length == 1 && !o.include?(:join) && !o.include?(:sql) table.first_source_table else table end qualifiers = split_qualifiers(tab) table_name = qualifiers.pop sch = qualifiers.pop information_schema_schema = case qualifiers.length when 1 Sequel.identifier(*qualifiers) when 2 Sequel.qualify(*qualifiers) end if table.is_a?(Dataset) quoted_name = table.literal(tab) opts[:dataset] = table else quoted_name = schema_utility_dataset.literal(table) end opts[:schema] = sch if sch && !opts.include?(:schema) opts[:information_schema_schema] = information_schema_schema if information_schema_schema && !opts.include?(:information_schema_schema) Sequel.synchronize{@schemas.delete(quoted_name)} if opts[:reload] if v = Sequel.synchronize{@schemas[quoted_name]} return v end cols = schema_parse_table(table_name, opts) raise(Error, "schema parsing returned no columns, table #{table_name.inspect} probably doesn't exist") if cols.nil? || cols.empty? primary_keys = 0 auto_increment_set = false cols.each do |_,c| auto_increment_set = true if c.has_key?(:auto_increment) primary_keys += 1 if c[:primary_key] end cols.each do |_,c| c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type]) unless c.has_key?(:ruby_default) if c[:primary_key] && !auto_increment_set # If adapter didn't set it, assume that integer primary keys are auto incrementing c[:auto_increment] = primary_keys == 1 && !!(c[:db_type] =~ /int/o) end if !c[:max_length] && c[:type] == :string && (max_length = column_schema_max_length(c[:db_type])) c[:max_length] = max_length end end schema_post_process(cols) Sequel.synchronize{@schemas[quoted_name] = cols} if cache_schema cols end
Returns true if a table with the given name exists. This requires a query to the database.
DB.table_exists?(:foo) # => false # SELECT NULL FROM foo LIMIT 1
Note that since this does a SELECT from the table, it can give false negatives if you don't have permission to SELECT from the table.
# File lib/sequel/database/query.rb, line 193 def table_exists?(name) sch, table_name = schema_and_table(name) name = SQL::QualifiedIdentifier.new(sch, table_name) if sch ds = from(name) transaction(:savepoint=>:only){_table_exists?(ds)} true rescue DatabaseError false end
Uncached version of #metadata_dataset, designed for overriding.
# File lib/sequel/database/query.rb, line 291 def _metadata_dataset dataset end
Should raise an error if the table doesn't not exist, and not raise an error if the table does exist.
# File lib/sequel/database/query.rb, line 207 def _table_exists?(ds) ds.get(SQL::AliasedExpression.new(Sequel::NULL, :nil)) end
Whether the type should be treated as a string type when parsing the column schema default value.
# File lib/sequel/database/query.rb, line 213 def column_schema_default_string_type?(type) COLUMN_SCHEMA_STRING_TYPES.include?(type) end
Transform the given normalized default string into a ruby object for the given type.
# File lib/sequel/database/query.rb, line 219 def column_schema_default_to_ruby_value(default, type) case type when :boolean case default when /[f0]/ false when /[t1]/ true end when :string, :enum, :set, :interval default when :blob Sequel::SQL::Blob.new(default) when :integer Integer(default) when :float Float(default) when :date Sequel.string_to_date(default) when :datetime DateTime.parse(default) when :time Sequel.string_to_time(default) when :decimal BigDecimal.new(default) end end
Look at the db_type and guess the maximum length of the column. This assumes types such as varchar(255).
# File lib/sequel/database/query.rb, line 277 def column_schema_max_length(db_type) if db_type =~ /\((\d+)\)/ $1.to_i end end
Normalize the default value string for the given type and return the normalized value.
# File lib/sequel/database/query.rb, line 249 def column_schema_normalize_default(default, type) if column_schema_default_string_type?(type) return unless m = /\A'(.*)'\z/.match(default) m[1].gsub("''", "'") else default end end
Convert the given default, which should be a database specific string, into a ruby object.
# File lib/sequel/database/query.rb, line 260 def column_schema_to_ruby_default(default, type) return default unless default.is_a?(String) if COLUMN_SCHEMA_DATETIME_TYPES.include?(type) if /now|today|CURRENT|getdate|\ADate\(\)\z/.match(default) if type == :date return Sequel::CURRENT_DATE else return Sequel::CURRENT_TIMESTAMP end end end default = column_schema_normalize_default(default, type) column_schema_default_to_ruby_value(default, type) rescue nil end
Return a Method object for the dataset's output_identifier_method. Used in metadata parsing to make sure the returned information is in the correct format.
# File lib/sequel/database/query.rb, line 286 def input_identifier_meth(ds=nil) (ds || dataset).method(:input_identifier) end
Return a dataset that uses the default identifier input and output methods for this database. Used when parsing metadata so that column symbols are returned as expected.
# File lib/sequel/database/query.rb, line 298 def metadata_dataset @metadata_dataset ||= _metadata_dataset end
Return a Method object for the dataset's output_identifier_method. Used in metadata parsing to make sure the returned information is in the correct format.
# File lib/sequel/database/query.rb, line 305 def output_identifier_meth(ds=nil) (ds || dataset).method(:output_identifier) end
Remove the cached schema for the given schema name
# File lib/sequel/database/query.rb, line 310 def remove_cached_schema(table) cache = @default_dataset.send(:cache) Sequel.synchronize{cache.clear} k = quote_schema_table(table) Sequel.synchronize{@schemas.delete(k)} end
Match the database's column type to a ruby type via a regular expression, and return the ruby type as a symbol such as :integer or :string.
# File lib/sequel/database/query.rb, line 320 def schema_column_type(db_type) case db_type when /\A(character( varying)?|n?(var)?char|n?text|string|clob)/o :string when /\A(int(eger)?|(big|small|tiny)int)/o :integer when /\Adate\z/o :date when /\A((small)?datetime|timestamp( with(out)? time zone)?)(\(\d+\))?\z/o :datetime when /\Atime( with(out)? time zone)?\z/o :time when /\A(bool(ean)?)\z/o :boolean when /\A(real|float|double( precision)?|double\(\d+,\d+\)( unsigned)?)\z/o :float when /\A(?:(?:(?:num(?:ber|eric)?|decimal)(?:\(\d+,\s*(\d+|false|true)\))?))\z/o $1 && ['0', 'false'].include?($1) ? :integer : :decimal when /bytea|blob|image|(var)?binary/o :blob when /\Aenum/o :enum end end
Post process the schema values.
# File lib/sequel/database/query.rb, line 346 def schema_post_process(cols) if RUBY_VERSION >= '2.5' cols.each do |_, h| db_type = h[:db_type] if db_type.is_a?(String) h[:db_type] = -db_type end end end cols.each do |_,c| c.each_value do |val| val.freeze if val.is_a?(String) end end end
The order of column modifiers to use when defining a column.
The alter table operations that are combinable.
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, String, unique: true, null: false DB.add_column :items, :category, String, default: 'ruby'
See alter_table
.
# File lib/sequel/database/schema_methods.rb, line 25 def add_column(table, *args) alter_table(table) {add_column(*args)} end
Adds an index to a table for the given columns:
DB.add_index :posts, :title DB.add_index :posts, [:author, :title], unique: true
Options:
Ignore any DatabaseErrors that are raised
Name to use for index instead of default
See alter_table
.
# File lib/sequel/database/schema_methods.rb, line 40 def add_index(table, columns, options=OPTS) e = options[:ignore_errors] begin alter_table(table){add_index(columns, options)} rescue DatabaseError raise unless e end nil end
Alters the given table with the specified block. Example:
DB.alter_table :items do add_column :category, String, default: 'ruby' drop_column :category rename_column :cntr, :counter set_column_type :value, Float set_column_default :value, 4.2 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
and the “Migrations and Schema Modification”
guide
# File lib/sequel/database/schema_methods.rb, line 67 def alter_table(name, &block) generator = alter_table_generator(&block) remove_cached_schema(name) apply_alter_table_generator(name, generator) nil end
Return a new Schema::AlterTableGenerator instance with the receiver as the database and the given block.
# File lib/sequel/database/schema_methods.rb, line 76 def alter_table_generator(&block) alter_table_generator_class.new(self, &block) end
Create a join table using a hash of foreign keys to referenced table names. Example:
create_join_table:cat_id: :cats, dog_id: :dogs) # CREATE TABLE cats_dogs ( # cat_id integer NOT NULL REFERENCES cats, # dog_id integer NOT NULL REFERENCES dogs, # PRIMARY KEY (cat_id, dog_id) # ) # CREATE INDEX cats_dogs_dog_id_cat_id_index ON cats_dogs(dog_id, cat_id)
The primary key and index are used so that almost all operations on the table can benefit from one of the two indexes, and the primary key ensures that entries in the table are unique, which is the typical desire for a join table.
You can provide column options by making the values in the hash be option hashes, so long as the option hashes have a :table entry giving the table referenced:
create_join_table(cat_id: {table: :cats, type: :Bignum}, dog_id: :dogs)
You can provide a second argument which is a table options hash:
create_join_table({cat_id: :cats, dog_id: :dogs}, temp: true)
Some table options are handled specially:
The options to pass to the index
The name of the table to create
Set to true not to create the second index.
Set to true to not create the primary key.
# File lib/sequel/database/schema_methods.rb, line 112 def create_join_table(hash, options=OPTS) keys = hash.keys.sort create_table(join_table_name(hash, options), options) do keys.each do |key| v = hash[key] unless v.is_a?(Hash) v = {:table=>v} end v[:null] = false unless v.has_key?(:null) foreign_key(key, v) end primary_key(keys) unless options[:no_primary_key] index(keys.reverse, options[:index_options] || {}) unless options[:no_index] end nil end
Forcibly create a join table, attempting to drop it if it already exists, then creating it.
# File lib/sequel/database/schema_methods.rb, line 130 def create_join_table!(hash, options=OPTS) drop_table?(join_table_name(hash, options)) create_join_table(hash, options) end
Creates the join table unless it already exists.
# File lib/sequel/database/schema_methods.rb, line 136 def create_join_table?(hash, options=OPTS) if supports_create_table_if_not_exists? && options[:no_index] create_join_table(hash, options.merge(:if_not_exists=>true)) elsif !table_exists?(join_table_name(hash, options)) create_join_table(hash, options) end end
Creates a view, replacing a view with the same name if one already exists.
DB.create_or_replace_view(:some_items, "SELECT * FROM items WHERE price < 100") DB.create_or_replace_view(:some_items, DB[:items].where(category: 'ruby'))
For databases where replacing a view is not natively supported, support is emulated by dropping a view with the same name before creating the view.
# File lib/sequel/database/schema_methods.rb, line 231 def create_or_replace_view(name, source, options = OPTS) if supports_create_or_replace_view? options = options.merge(:replace=>true) else drop_view(name) rescue nil end create_view(name, source, options) nil end
Creates a table with the columns given in the provided block:
DB.create_table :posts do primary_key :id column :title, String String :content index :title end
General options:
Create the table using the value, which should be either a dataset or a literal SQL string. If this option is used, a block should not be given to the method.
Ignore any errors when creating indexes.
Create the table as a temporary table.
MySQL specific options:
The character set to use for the table.
The collation to use for the table.
The table engine to use for the table.
PostgreSQL specific options:
Either :preserve_rows (default), :drop or :delete_rows. Should only be specified when creating a temporary table.
Create a foreign table. The value should be the name of the foreign server that was specified in CREATE SERVER.
Inherit from a different table. An array can be specified to inherit from multiple tables.
Create the table as an unlogged table.
The OPTIONS clause to use for foreign tables. Should be a hash where keys are option names and values are option values. Note that option names are unquoted, so you should not use untrusted keys.
See Schema::CreateTableGenerator
and the “Schema Modification” guide
# File lib/sequel/database/schema_methods.rb, line 179 def create_table(name, options=OPTS, &block) remove_cached_schema(name) if sql = options[:as] raise(Error, "can't provide both :as option and block to create_table") if block create_table_as(name, sql, options) else generator = options[:generator] || create_table_generator(&block) create_table_from_generator(name, generator, options) create_table_indexes_from_generator(name, generator, options) end nil end
Forcibly create a table, attempting to drop it if it already exists, then creating it.
DB.create_table!(:a){Integer :a} # SELECT NULL FROM a LIMIT 1 -- check existence # DROP TABLE a -- drop table if already exists # CREATE TABLE a (a integer)
# File lib/sequel/database/schema_methods.rb, line 198 def create_table!(name, options=OPTS, &block) drop_table?(name) create_table(name, options, &block) end
Creates the table unless the table already exists.
DB.create_table?(:a){Integer :a} # SELECT NULL FROM a LIMIT 1 -- check existence # CREATE TABLE a (a integer) -- if it doesn't already exist
# File lib/sequel/database/schema_methods.rb, line 208 def create_table?(name, options=OPTS, &block) options = options.dup generator = options[:generator] ||= create_table_generator(&block) if generator.indexes.empty? && supports_create_table_if_not_exists? create_table(name, options.merge!(:if_not_exists=>true)) elsif !table_exists?(name) create_table(name, options) end end
Return a new Schema::CreateTableGenerator instance with the receiver as the database and the given block.
# File lib/sequel/database/schema_methods.rb, line 220 def create_table_generator(&block) create_table_generator_class.new(self, &block) end
Creates a view based on a dataset or an SQL string:
DB.create_view(:cheap_items, "SELECT * FROM items WHERE price < 100") # CREATE VIEW cheap_items AS # SELECT * FROM items WHERE price < 100 DB.create_view(:ruby_items, DB[:items].where(category: 'ruby')) # CREATE VIEW ruby_items AS # SELECT * FROM items WHERE (category = 'ruby') DB.create_view(:checked_items, DB[:items].where(:foo), check: true) # CREATE VIEW checked_items AS # SELECT * FROM items WHERE foo # WITH CHECK OPTION
Options:
The column names to use for the view. If not given, automatically determined based on the input dataset.
Adds a WITH CHECK OPTION clause, so that attempting to modify rows in the underlying table that would not be returned by the view is not allowed. This can be set to :local to use WITH LOCAL CHECK OPTION.
PostgreSQL/SQLite specific option:
Create a temporary view, automatically dropped on disconnect.
PostgreSQL specific options:
Creates a materialized view, similar to a regular view, but backed by a physical table.
Creates a recursive view. As columns must be specified for recursive views, you can also set them as the value of this option. Since a recursive view requires a union that isn't in a subquery, if you are providing a Dataset as the source argument, if should probably call the union method with the all: true and from_self: false options.
# File lib/sequel/database/schema_methods.rb, line 277 def create_view(name, source, options = OPTS) execute_ddl(create_view_sql(name, source, options)) remove_cached_schema(name) nil end
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table
.
# File lib/sequel/database/schema_methods.rb, line 288 def drop_column(table, *args) alter_table(table) {drop_column(*args)} 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 298 def drop_index(table, columns, options=OPTS) alter_table(table){drop_index(columns, options)} end
Drop the join table that would have been created with the same arguments to #create_join_table:
drop_join_table(cat_id: :cats, dog_id: :dogs) # DROP TABLE cats_dogs
# File lib/sequel/database/schema_methods.rb, line 307 def drop_join_table(hash, options=OPTS) drop_table(join_table_name(hash, options), options) end
Drops one or more tables corresponding to the given names:
DB.drop_table(:posts) # DROP TABLE posts DB.drop_table(:posts, :comments) DB.drop_table(:posts, :comments, cascade: true)
# File lib/sequel/database/schema_methods.rb, line 316 def drop_table(*names) options = names.last.is_a?(Hash) ? names.pop : {} names.each do |n| execute_ddl(drop_table_sql(n, options)) remove_cached_schema(n) end nil end
Drops the table if it already exists. If it doesn't exist, does nothing.
DB.drop_table?(:a) # SELECT NULL FROM a LIMIT 1 -- check existence # DROP TABLE a -- if it already exists
# File lib/sequel/database/schema_methods.rb, line 331 def drop_table?(*names) options = names.last.is_a?(Hash) ? names.pop : {} if supports_drop_table_if_exists? options = options.merge(:if_exists=>true) names.each do |name| drop_table(name, options) end else names.each do |name| drop_table(name, options) if table_exists?(name) end end nil end
Drops one or more views corresponding to the given names:
DB.drop_view(:cheap_items) DB.drop_view(:cheap_items, :pricey_items) DB.drop_view(:cheap_items, :pricey_items, cascade: true) DB.drop_view(:cheap_items, :pricey_items, if_exists: true)
Options:
Also drop objects depending on this view.
Do not raise an error if the view does not exist.
PostgreSQL specific options:
Drop a materialized view.
# File lib/sequel/database/schema_methods.rb, line 359 def drop_view(*names) options = names.last.is_a?(Hash) ? names.pop : {} names.each do |n| execute_ddl(drop_view_sql(n, options)) remove_cached_schema(n) end nil 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 385 def rename_column(table, *args) alter_table(table) {rename_column(*args)} 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 373 def rename_table(name, new_name) execute_ddl(rename_table_sql(name, new_name)) remove_cached_schema(name) nil 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 394 def set_column_default(table, *args) alter_table(table) {set_column_default(*args)} 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 403 def set_column_type(table, *args) alter_table(table) {set_column_type(*args)} end
# File lib/sequel/database/schema_methods.rb, line 443 def alter_table_add_column_sql(table, op) "ADD COLUMN #{column_definition_sql(op)}" end
# File lib/sequel/database/schema_methods.rb, line 467 def alter_table_add_constraint_sql(table, op) "ADD #{constraint_definition_sql(op)}" end
# File lib/sequel/database/schema_methods.rb, line 447 def alter_table_drop_column_sql(table, op) "DROP COLUMN #{quote_identifier(op[:name])}#{' CASCADE' if op[:cascade]}" end
# File lib/sequel/database/schema_methods.rb, line 471 def alter_table_drop_constraint_sql(table, op) quoted_name = quote_identifier(op[:name]) if op[:name] if op[:type] == :foreign_key quoted_name ||= quote_identifier(foreign_key_name(table, op[:columns])) end "DROP CONSTRAINT #{quoted_name}#{' CASCADE' if op[:cascade]}" end
The class used for #alter_table generators.
# File lib/sequel/database/schema_methods.rb, line 428 def alter_table_generator_class Schema::AlterTableGenerator end
SQL fragment for given alter table operation.
# File lib/sequel/database/schema_methods.rb, line 433 def alter_table_op_sql(table, op) meth = "alter_table_#{op[:op]}_sql" if respond_to?(meth, true) # Allow calling private methods as alter table op sql methods are private send(meth, table, op) else raise Error, "Unsupported ALTER TABLE operation: #{op[:op]}" end end
# File lib/sequel/database/schema_methods.rb, line 451 def alter_table_rename_column_sql(table, op) "RENAME COLUMN #{quote_identifier(op[:name])} TO #{quote_identifier(op[:new_name])}" end
# File lib/sequel/database/schema_methods.rb, line 459 def alter_table_set_column_default_sql(table, op) "ALTER COLUMN #{quote_identifier(op[:name])} SET DEFAULT #{literal(op[:default])}" end
# File lib/sequel/database/schema_methods.rb, line 463 def alter_table_set_column_null_sql(table, op) "ALTER COLUMN #{quote_identifier(op[:name])} #{op[:null] ? 'DROP' : 'SET'} NOT NULL" end
# File lib/sequel/database/schema_methods.rb, line 455 def alter_table_set_column_type_sql(table, op) "ALTER COLUMN #{quote_identifier(op[:name])} TYPE #{type_literal(op)}" end
The SQL to execute to modify the table. op should be one of the operations returned by the AlterTableGenerator.
# File lib/sequel/database/schema_methods.rb, line 481 def alter_table_sql(table, op) case op[:op] when :add_index index_definition_sql(table, op) when :drop_index drop_index_sql(table, op) else "ALTER TABLE #{quote_schema_table(table)} #{alter_table_op_sql(table, op)}" end end
Array of SQL statements used to modify the table, corresponding to changes specified by the operations.
# File lib/sequel/database/schema_methods.rb, line 494 def alter_table_sql_list(table, operations) if supports_combining_alter_table_ops? grouped_ops = [] last_combinable = false operations.each do |op| if combinable_alter_table_op?(op) if sql = alter_table_op_sql(table, op) grouped_ops << [] unless last_combinable grouped_ops.last << sql last_combinable = true end elsif sql = alter_table_sql(table, op) Array(sql).each{|s| grouped_ops << s} last_combinable = false end end grouped_ops.map do |gop| if gop.is_a?(Array) "ALTER TABLE #{quote_schema_table(table)} #{gop.join(', ')}" else gop end end else operations.map{|op| alter_table_sql(table, op)}.flatten.compact end end
Apply the changes in the given alter table ops to the table given by name.
# File lib/sequel/database/schema_methods.rb, line 410 def apply_alter_table(name, ops) alter_table_sql_list(name, ops).each{|sql| execute_ddl(sql)} end
Apply the operations in the given generator to the table given by name.
# File lib/sequel/database/schema_methods.rb, line 415 def apply_alter_table_generator(name, generator) ops = generator.operations unless can_add_primary_key_constraint_on_nullable_columns? if add_pk = ops.find{|op| op[:op] == :add_constraint && op[:type] == :primary_key} ops = add_pk[:columns].map{|column| {:op => :set_column_null, :name => column, :null => false}} + ops end end apply_alter_table(name, ops) end
The SQL string specify the autoincrement property, generally used by primary keys.
# File lib/sequel/database/schema_methods.rb, line 524 def auto_increment_sql 'AUTOINCREMENT' end
Add null/not null SQL fragment to column creation SQL.
# File lib/sequel/database/schema_methods.rb, line 559 def column_definition_null_sql(sql, column) null = column.fetch(:null, column[:allow_null]) if null.nil? && !can_add_primary_key_constraint_on_nullable_columns? && column[:primary_key] null = false end case null when false sql << ' NOT NULL' when true sql << ' NULL' end end
The order of the column definition, as an array of symbols.
# File lib/sequel/database/schema_methods.rb, line 529 def column_definition_order COLUMN_DEFINITION_ORDER end
Add primary key SQL fragment to column creation SQL.
# File lib/sequel/database/schema_methods.rb, line 574 def column_definition_primary_key_sql(sql, column) if column[:primary_key] if name = column[:primary_key_constraint_name] sql << " CONSTRAINT #{quote_identifier(name)}" end sql << ' PRIMARY KEY' end end
Add foreign key reference SQL fragment to column creation SQL.
# File lib/sequel/database/schema_methods.rb, line 584 def column_definition_references_sql(sql, column) if column[:table] if name = column[:foreign_key_constraint_name] sql << " CONSTRAINT #{quote_identifier(name)}" end sql << column_references_column_constraint_sql(column) end end
SQL fragment containing the column creation SQL for the given column.
# File lib/sequel/database/schema_methods.rb, line 534 def column_definition_sql(column) sql = String.new sql << "#{quote_identifier(column[:name])} #{type_literal(column)}" column_definition_order.each{|m| send(:"column_definition_#{m}_sql", sql, column)} sql end
SQL for all given columns, used inside a CREATE TABLE block.
# File lib/sequel/database/schema_methods.rb, line 604 def column_list_sql(generator) (generator.columns.map{|c| column_definition_sql(c)} + generator.constraints.map{|c| constraint_definition_sql(c)}).join(', ') end
SQL fragment for column foreign key references (column constraints)
# File lib/sequel/database/schema_methods.rb, line 609 def column_references_column_constraint_sql(column) column_references_sql(column) end
SQL fragment for column foreign key references
# File lib/sequel/database/schema_methods.rb, line 614 def column_references_sql(column) sql = String.new sql << " REFERENCES #{quote_schema_table(column[:table])}" sql << "(#{Array(column[:key]).map{|x| quote_identifier(x)}.join(', ')})" if column[:key] sql << " ON DELETE #{on_delete_clause(column[:on_delete])}" if column[:on_delete] sql << " ON UPDATE #{on_update_clause(column[:on_update])}" if column[:on_update] constraint_deferrable_sql_append(sql, column[:deferrable]) sql end
SQL fragment for table foreign key references (table constraints)
# File lib/sequel/database/schema_methods.rb, line 625 def column_references_table_constraint_sql(constraint) "FOREIGN KEY #{literal(constraint[:columns])}#{column_references_sql(constraint)}" end
Whether the given alter table operation is combinable.
# File lib/sequel/database/schema_methods.rb, line 630 def combinable_alter_table_op?(op) COMBINABLE_ALTER_TABLE_OPS.include?(op[:op]) end
SQL fragment specifying the deferrable constraint attributes.
# File lib/sequel/database/schema_methods.rb, line 659 def constraint_deferrable_sql_append(sql, defer) case defer when nil when false sql << ' NOT DEFERRABLE' when :immediate sql << ' DEFERRABLE INITIALLY IMMEDIATE' else sql << ' DEFERRABLE INITIALLY DEFERRED' end end
SQL fragment specifying a constraint on a table.
# File lib/sequel/database/schema_methods.rb, line 635 def constraint_definition_sql(constraint) sql = String.new sql << "CONSTRAINT #{quote_identifier(constraint[:name])} " if constraint[:name] case constraint[:type] when :check check = constraint[:check] check = check.first if check.is_a?(Array) && check.length == 1 check = filter_expr(check) check = "(#{check})" unless check[0..0] == '(' && check[-1..-1] == ')' sql << "CHECK #{check}" when :primary_key sql << "PRIMARY KEY #{literal(constraint[:columns])}" when :foreign_key sql << column_references_table_constraint_sql(constraint.merge(:deferrable=>nil)) when :unique sql << "UNIQUE #{literal(constraint[:columns])}" else raise Error, "Invalid constraint type #{constraint[:type]}, should be :check, :primary_key, :foreign_key, or :unique" end constraint_deferrable_sql_append(sql, constraint[:deferrable]) sql end
Run SQL statement to create the table with the given name from the given SELECT sql statement.
# File lib/sequel/database/schema_methods.rb, line 729 def create_table_as(name, sql, options) sql = sql.sql if sql.is_a?(Sequel::Dataset) run(create_table_as_sql(name, sql, options)) end
SQL statement for creating a table from the result
of a SELECT statement. sql
should be a string representing a
SELECT query.
# File lib/sequel/database/schema_methods.rb, line 736 def create_table_as_sql(name, sql, options) "#{create_table_prefix_sql(name, options)} AS #{sql}" end
Execute the create table statements using the generator.
# File lib/sequel/database/schema_methods.rb, line 672 def create_table_from_generator(name, generator, options) execute_ddl(create_table_sql(name, generator, options)) end
The class used for #create_table generators.
# File lib/sequel/database/schema_methods.rb, line 677 def create_table_generator_class Schema::CreateTableGenerator end
Execute the create index statements using the generator.
# File lib/sequel/database/schema_methods.rb, line 682 def create_table_indexes_from_generator(name, generator, options) e = options[:ignore_index_errors] || options[:if_not_exists] generator.indexes.each do |index| begin pr = proc{index_sql_list(name, [index]).each{|sql| execute_ddl(sql)}} supports_transactional_ddl? ? transaction(:savepoint=>:only, &pr) : pr.call rescue Error raise unless e end end end
SQL fragment for initial part of CREATE TABLE statement
# File lib/sequel/database/schema_methods.rb, line 741 def create_table_prefix_sql(name, options) "CREATE #{temporary_table_sql if options[:temp]}TABLE#{' IF NOT EXISTS' if options[:if_not_exists]} #{options[:temp] ? quote_identifier(name) : quote_schema_table(name)}" end
SQL statement for creating a table with the given name, columns, and options
# File lib/sequel/database/schema_methods.rb, line 695 def create_table_sql(name, generator, options) unless supports_named_column_constraints? # Split column constraints into table constraints if they have a name generator.columns.each do |c| if (constraint_name = c.delete(:foreign_key_constraint_name)) && (table = c.delete(:table)) opts = {} opts[:name] = constraint_name [:key, :on_delete, :on_update, :deferrable].each{|k| opts[k] = c[k]} generator.foreign_key([c[:name]], table, opts) end if (constraint_name = c.delete(:unique_constraint_name)) && c.delete(:unique) generator.unique(c[:name], :name=>constraint_name) end if (constraint_name = c.delete(:primary_key_constraint_name)) && c.delete(:primary_key) generator.primary_key([c[:name]], :name=>constraint_name) end end end unless can_add_primary_key_constraint_on_nullable_columns? if pk = generator.constraints.find{|op| op[:type] == :primary_key} pk[:columns].each do |column| if matched_column = generator.columns.find{|gc| gc[:name] == column} matched_column[:null] = false end end end end "#{create_table_prefix_sql(name, options)} (#{column_list_sql(generator)})" end
SQL fragment for initial part of CREATE VIEW statement
# File lib/sequel/database/schema_methods.rb, line 746 def create_view_prefix_sql(name, options) create_view_sql_append_columns("CREATE #{'OR REPLACE 'if options[:replace]}VIEW #{quote_schema_table(name)}", options[:columns]) end
SQL statement for creating a view.
# File lib/sequel/database/schema_methods.rb, line 751 def create_view_sql(name, source, options) source = source.sql if source.is_a?(Dataset) sql = String.new sql << "#{create_view_prefix_sql(name, options)} AS #{source}" if check = options[:check] sql << " WITH#{' LOCAL' if check == :local} CHECK OPTION" end sql end
Append the column list to the SQL, if a column list is given.
# File lib/sequel/database/schema_methods.rb, line 762 def create_view_sql_append_columns(sql, columns) if columns sql += ' (' schema_utility_dataset.send(:identifier_list_append, sql, columns) sql << ')' end sql end
Default index name for the table and columns, may be too long for certain databases.
# File lib/sequel/database/schema_methods.rb, line 773 def default_index_name(table_name, columns) schema, table = schema_and_table(table_name) "#{"#{schema}_" if schema}#{table}_#{columns.map{|c| [String, Symbol].any?{|cl| c.is_a?(cl)} ? c : literal(c).gsub(/\W/, '_')}.join('_')}_index" end
The SQL to drop an index for the table.
# File lib/sequel/database/schema_methods.rb, line 786 def drop_index_sql(table, op) "DROP INDEX #{quote_identifier(op[:name] || default_index_name(table, op[:columns]))}" end
SQL DDL statement to drop the table with the given name.
# File lib/sequel/database/schema_methods.rb, line 791 def drop_table_sql(name, options) "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}" end
SQL DDL statement to drop a view with the given name.
# File lib/sequel/database/schema_methods.rb, line 796 def drop_view_sql(name, options) "DROP VIEW#{' IF EXISTS' if options[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}" end
Proxy the #filter_expr call to the dataset, used for creating constraints. Support passing Proc arguments as blocks, as well as treating plain strings as literal strings, so that previous migrations that used this API do not break.
# File lib/sequel/database/schema_methods.rb, line 803 def filter_expr(*args, &block) if args.length == 1 arg = args.first if arg.is_a?(Proc) && !block block = args.first args = nil elsif arg.is_a?(String) args = [Sequel.lit(*args)] elsif arg.is_a?(Array) if arg.first.is_a?(String) args = [Sequel.lit(*arg)] elsif arg.length > 1 args = [Sequel.&(*arg)] end end end schema_utility_dataset.literal(schema_utility_dataset.send(:filter_expr, *args, &block)) end
Get foreign key name for given table and columns.
# File lib/sequel/database/schema_methods.rb, line 779 def foreign_key_name(table_name, columns) keys = foreign_key_list(table_name).select{|key| key[:columns] == columns} raise(Error, "#{keys.empty? ? 'Missing' : 'Ambiguous'} foreign key for #{columns.inspect}") unless keys.size == 1 keys.first[:name] end
SQL statement for creating an index for the table with the given name and index specifications.
# File lib/sequel/database/schema_methods.rb, line 824 def index_definition_sql(table_name, index) index_name = index[:name] || default_index_name(table_name, index[:columns]) raise Error, "Index types are not supported for this database" if index[:type] raise Error, "Partial indexes are not supported for this database" if index[:where] && !supports_partial_indexes? "CREATE #{'UNIQUE ' if index[:unique]}INDEX #{quote_identifier(index_name)} ON #{quote_schema_table(table_name)} #{literal(index[:columns])}#{" WHERE #{filter_expr(index[:where])}" if index[:where]}" end
Extract the join table name from the arguments given to create_join_table. Also does argument validation for the #create_join_table method.
# File lib/sequel/database/schema_methods.rb, line 839 def join_table_name(hash, options) entries = hash.values raise Error, "must have 2 entries in hash given to (create|drop)_join_table" unless entries.length == 2 if options[:name] options[:name] else table_names = entries.map{|e| join_table_name_extract(e)} table_names.map(&:to_s).sort.join('_') end end
Extract an individual join table name, which should either be a string or symbol, or a hash containing one of those as the value for :table.
# File lib/sequel/database/schema_methods.rb, line 852 def join_table_name_extract(entry) case entry when Symbol, String entry when Hash join_table_name_extract(entry[:table]) else raise Error, "can't extract table name from #{entry.inspect}" end end
SQL fragment to use for ON DELETE, based on the given action. The following actions are recognized:
Delete rows referencing this row.
Raise an error if other rows reference this row, allow deferring of the integrity check. This is the default.
Raise an error if other rows reference this row, but do not allow deferring the integrity check.
Set columns referencing this row to their default value.
Set columns referencing this row to NULL.
Any other object given is just converted to a string, with “_” converted to “ ” and upcased.
# File lib/sequel/database/schema_methods.rb, line 876 def on_delete_clause(action) action.to_s.gsub("_", " ").upcase end
Alias of on_delete_clause, since the two usually behave the same.
# File lib/sequel/database/schema_methods.rb, line 881 def on_update_clause(action) on_delete_clause(action) end
Proxy the #quote_schema_table method to the dataset
# File lib/sequel/database/schema_methods.rb, line 886 def quote_schema_table(table) schema_utility_dataset.quote_schema_table(table) end
SQL statement for renaming a table.
# File lib/sequel/database/schema_methods.rb, line 891 def rename_table_sql(name, new_name) "ALTER TABLE #{quote_schema_table(name)} RENAME TO #{quote_schema_table(new_name)}" end
Split the schema information from the table
# File lib/sequel/database/schema_methods.rb, line 896 def schema_and_table(table_name) schema_utility_dataset.schema_and_table(table_name) end
Return true if the given column schema represents an autoincrementing primary key.
# File lib/sequel/database/schema_methods.rb, line 901 def schema_autoincrementing_primary_key?(schema) !!(schema[:primary_key] && schema[:auto_increment]) end
The dataset to use for proxying certain schema methods.
# File lib/sequel/database/schema_methods.rb, line 906 def schema_utility_dataset @default_dataset end
Split the schema information from the table
# File lib/sequel/database/schema_methods.rb, line 911 def split_qualifiers(table_name) schema_utility_dataset.split_qualifiers(table_name) end
SQL fragment for temporary table
# File lib/sequel/database/schema_methods.rb, line 916 def temporary_table_sql 'TEMPORARY ' end
SQL fragment specifying the type of a given column.
# File lib/sequel/database/schema_methods.rb, line 921 def type_literal(column) case column[:type] when Class type_literal_generic(column) when :Bignum type_literal_generic_bignum_symbol(column) else type_literal_specific(column) end end
SQL fragment specifying the full type of a column, consider the type with possible modifiers.
# File lib/sequel/database/schema_methods.rb, line 934 def type_literal_generic(column) meth = "type_literal_generic_#{column[:type].name.to_s.downcase}" if respond_to?(meth, true) # Allow calling private methods as per type literal generic methods are private send(meth, column) else raise Error, "Unsupported ruby class used as database type: #{column[:type]}" end end
Alias for #type_literal_generic_numeric, to make overriding in a subclass easier.
# File lib/sequel/database/schema_methods.rb, line 945 def type_literal_generic_bigdecimal(column) type_literal_generic_numeric(column) end
Sequel uses the bigint type by default for :Bignum symbol.
# File lib/sequel/database/schema_methods.rb, line 950 def type_literal_generic_bignum_symbol(column) :bigint end
Sequel uses the date type by default for Dates.
# File lib/sequel/database/schema_methods.rb, line 955 def type_literal_generic_date(column) :date end
Sequel uses the timestamp type by default for DateTimes.
# File lib/sequel/database/schema_methods.rb, line 960 def type_literal_generic_datetime(column) :timestamp end
Alias for #type_literal_generic_trueclass, to make overriding in a subclass easier.
# File lib/sequel/database/schema_methods.rb, line 965 def type_literal_generic_falseclass(column) type_literal_generic_trueclass(column) end
Sequel uses the blob type by default for Files.
# File lib/sequel/database/schema_methods.rb, line 970 def type_literal_generic_file(column) :blob end
Alias for #type_literal_generic_integer, to make overriding in a subclass easier.
# File lib/sequel/database/schema_methods.rb, line 975 def type_literal_generic_fixnum(column) type_literal_generic_integer(column) end
Sequel uses the double precision type by default for Floats.
# File lib/sequel/database/schema_methods.rb, line 980 def type_literal_generic_float(column) :"double precision" end
Sequel uses the integer type by default for integers
# File lib/sequel/database/schema_methods.rb, line 985 def type_literal_generic_integer(column) :integer end
Sequel uses the numeric type by default for Numerics and BigDecimals. If a size is given, it is used, otherwise, it will default to whatever the database default is for an unsized value.
# File lib/sequel/database/schema_methods.rb, line 992 def type_literal_generic_numeric(column) column[:size] ? "numeric(#{Array(column[:size]).join(', ')})" : :numeric end
Use time by default for Time values if :only_time option is used.
# File lib/sequel/database/schema_methods.rb, line 1021 def type_literal_generic_only_time(column) :time end
Sequel uses the varchar type by default for Strings. If a size isn't present, Sequel assumes a size of 255. If the :fixed option is used, Sequel uses the char type. If the :text option is used, Sequel uses the :text type.
# File lib/sequel/database/schema_methods.rb, line 1000 def type_literal_generic_string(column) if column[:text] uses_clob_for_text? ? :clob : :text elsif column[:fixed] "char(#{column[:size]||default_string_column_size})" else "varchar(#{column[:size]||default_string_column_size})" end end
Sequel uses the timestamp type by default for Time values. If the :only_time option is used, the time type is used.
# File lib/sequel/database/schema_methods.rb, line 1012 def type_literal_generic_time(column) if column[:only_time] type_literal_generic_only_time(column) else type_literal_generic_datetime(column) end end
Sequel uses the boolean type by default for TrueClass and FalseClass.
# File lib/sequel/database/schema_methods.rb, line 1026 def type_literal_generic_trueclass(column) :boolean end
SQL fragment for the given type of a column if the column is not one of the generic types specified with a ruby class.
# File lib/sequel/database/schema_methods.rb, line 1032 def type_literal_specific(column) type = column[:type] type = "double precision" if type.to_s == 'double' column[:size] ||= default_string_column_size if type.to_s == 'varchar' elements = column[:size] || column[:elements] "#{type}#{literal(Array(elements)) if elements}#{' UNSIGNED' if column[:unsigned]}" end
Whether clob should be used for String text: true columns.
# File lib/sequel/database/schema_methods.rb, line 1041 def uses_clob_for_text? false end
Returns a dataset for the database. If the first argument is a string, the method acts as an alias for #fetch, returning a dataset for arbitrary SQL, with or without placeholders:
DB['SELECT * FROM items'].all DB['SELECT * FROM items WHERE name = ?', my_name].all
Otherwise, acts as an alias for #from, setting the primary table for the dataset:
DB[:items].sql #=> "SELECT * FROM items"
# File lib/sequel/database/dataset.rb, line 21 def [](*args) args.first.is_a?(String) ? fetch(*args) : from(*args) end
Returns a blank dataset for this database.
DB.dataset # SELECT * DB.dataset.from(:items) # SELECT * FROM items
# File lib/sequel/database/dataset.rb, line 29 def dataset @dataset_class.new(self) 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 fetch
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
See caveats listed in Sequel::Dataset#with_sql regarding datasets using custom SQL and the methods that can be called on them.
# File lib/sequel/database/dataset.rb, line 49 def fetch(sql, *args, &block) ds = @default_dataset.with_sql(sql, *args) ds.each(&block) if block ds end
Returns a new dataset with the from
method invoked. If a block
is given, it acts as a virtual row block
DB.from(:items) # SELECT * FROM items DB.from{schema[:table]} # SELECT * FROM schema.table
# File lib/sequel/database/dataset.rb, line 60 def from(*args, &block) if block @default_dataset.from(*args, &block) elsif args.length == 1 && (table = args[0]).is_a?(Symbol) @default_dataset.send(:cached_dataset, :"_from_#{table}_ds"){@default_dataset.from(table)} else @default_dataset.from(*args) end end
Returns a new dataset with the select method invoked.
DB.select(1) # SELECT 1 DB.select{server_version.function} # SELECT server_version() DB.select(:id).from(:items) # SELECT id FROM items
# File lib/sequel/database/dataset.rb, line 75 def select(*args, &block) @default_dataset.select(*args, &block) end
Array of supported database adapters
The Database subclass for the given adapter scheme. Raises Sequel::AdapterNotFound if the adapter could not be loaded.
# File lib/sequel/database/connecting.rb, line 16 def self.adapter_class(scheme) scheme.is_a?(Class) ? scheme : load_adapter(scheme.to_sym) end
Returns the scheme symbol for the Database class.
# File lib/sequel/database/connecting.rb, line 21 def self.adapter_scheme @scheme end
Connects to a database. See Sequel.connect.
# File lib/sequel/database/connecting.rb, line 26 def self.connect(conn_string, opts = OPTS) case conn_string when String if conn_string.start_with?('jdbc:') c = adapter_class(:jdbc) opts = opts.merge(:orig_opts=>opts.dup) opts = {:uri=>conn_string}.merge!(opts) else uri = URI.parse(conn_string) scheme = uri.scheme c = adapter_class(scheme) uri_options = c.send(:uri_to_options, uri) uri.query.split('&').map{|s| s.split('=')}.each{|k,v| uri_options[k.to_sym] = v if k && !k.empty?} unless uri.query.to_s.strip.empty? uri_options.to_a.each{|k,v| uri_options[k] = (defined?(URI::DEFAULT_PARSER) ? URI::DEFAULT_PARSER : URI).unescape(v) if v.is_a?(String)} opts = uri_options.merge(opts).merge!(:orig_opts=>opts.dup, :uri=>conn_string, :adapter=>scheme) end when Hash opts = conn_string.merge(opts) opts = opts.merge(:orig_opts=>opts.dup) c = adapter_class(opts[:adapter_class] || opts[:adapter] || opts['adapter']) else raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" end opts = opts.inject({}) do |m, (k,v)| k = :user if k.to_s == 'username' m[k.to_sym] = v m end begin db = c.new(opts) db.test_connection if db.send(:typecast_value_boolean, opts.fetch(:test, true)) if block_given? return yield(db) end ensure if block_given? db.disconnect if db Sequel.synchronize{::Sequel::DATABASES.delete(db)} end end db end
Load the adapter from the file system. Raises Sequel::AdapterNotFound if the adapter cannot be loaded, or if the adapter isn't registered correctly after being loaded. Options:
The Hash in which to look for an already loaded adapter (defaults to ADAPTER_MAP).
The subdirectory of sequel/adapters to look in, only to be used for loading subadapters.
# File lib/sequel/database/connecting.rb, line 77 def self.load_adapter(scheme, opts=OPTS) map = opts[:map] || ADAPTER_MAP if subdir = opts[:subdir] file = "#{subdir}/#{scheme}" else file = scheme end unless obj = Sequel.synchronize{map[scheme]} # attempt to load the adapter file begin require "sequel/adapters/#{file}" rescue LoadError => e # If subadapter file doesn't exist, just return, # using the main adapter class without database customizations. return if subdir raise Sequel.convert_exception_class(e, AdapterNotFound) end # make sure we actually loaded the adapter unless obj = Sequel.synchronize{map[scheme]} raise AdapterNotFound, "Could not load #{file} adapter: adapter class not registered in ADAPTER_MAP" end end obj end
Returns the scheme symbol for this instance's class, which reflects
which adapter is being used. In some cases, this can be the same as the
database_type
(for native adapters), in others (i.e. adapters
with subadapters), it will be different.
Sequel.connect('jdbc:postgres://...').adapter_scheme # => :jdbc
# File lib/sequel/database/connecting.rb, line 162 def adapter_scheme self.class.adapter_scheme end
Dynamically add new servers or modify server options at runtime. Also adds new servers to the connection pool. Only usable when using a sharded connection pool.
servers argument should be a hash with server name symbol keys and hash or proc values. If a servers key is already in use, it's value is overridden with the value provided.
DB.add_servers(f: {host: "hash_host_f"})
# File lib/sequel/database/connecting.rb, line 174 def add_servers(servers) unless sharded? raise Error, "cannot call Database#add_servers on a Database instance that does not use a sharded connection pool" end h = @opts[:servers] Sequel.synchronize{h.merge!(servers)} @pool.add_servers(servers.keys) 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.
Sequel.connect('jdbc:postgres://...').database_type # => :postgres
# File lib/sequel/database/connecting.rb, line 193 def database_type adapter_scheme end
Disconnects all available connections from the connection pool. Any connections currently in use will not be disconnected. Options:
Should be a symbol specifing the server to disconnect from,
or an array of symbols to specify multiple servers.
Example:
DB.disconnect # All servers DB.disconnect(server: :server1) # Single server DB.disconnect(server: [:server1, :server2]) # Multiple servers
# File lib/sequel/database/connecting.rb, line 207 def disconnect(opts = OPTS) pool.disconnect(opts) end
Should only be called by the connection pool code to disconnect a connection. By default, calls the close method on the connection object, since most adapters use that, but should be overwritten on other adapters.
# File lib/sequel/database/connecting.rb, line 214 def disconnect_connection(conn) conn.close end
Dynamically remove existing servers from the connection pool. Only usable when using a sharded connection pool
servers should be symbols or arrays of symbols. If a nonexistent server is specified, it is ignored. If no servers have been specified for this database, no changes are made. If you attempt to remove the :default server, an error will be raised.
DB.remove_servers(:f1, :f2)
# File lib/sequel/database/connecting.rb, line 227 def remove_servers(*servers) unless sharded? raise Error, "cannot call Database#remove_servers on a Database instance that does not use a sharded connection pool" end h = @opts[:servers] servers.flatten.each{|s| Sequel.synchronize{h.delete(s)}} @pool.remove_servers(servers) end
An array of servers/shards for this Database object.
DB.servers # Unsharded: => [:default] DB.servers # Sharded: => [:default, :server1, :server2]
# File lib/sequel/database/connecting.rb, line 241 def servers pool.servers end
Returns true if the database is using a single-threaded connection pool.
# File lib/sequel/database/connecting.rb, line 246 def single_threaded? @single_threaded end
Acquires a database connection, yielding it to the passed block. This is useful if you want to make sure the same connection is used for all database queries in the block. It is also useful if you want to gain direct access to the underlying connection object if you need to do something Sequel does not natively support.
If a server option is given, acquires a connection for that specific server, instead of the :default server.
DB.synchronize do |conn| # ... end
# File lib/sequel/database/connecting.rb, line 263 def synchronize(server=nil) @pool.hold(server || :default){|conn| yield conn} end
Attempts to acquire a database connection. Returns true if successful. Will probably raise an Error if unsuccessful. If a server argument is given, attempts to acquire a database connection to the given server/shard.
# File lib/sequel/database/connecting.rb, line 278 def test_connection(server=nil) synchronize(server){|conn|} true end
Check whether the given connection is currently valid, by running a query against it. If the query fails, the connection should probably be removed from the connection pool.
# File lib/sequel/database/connecting.rb, line 287 def valid_connection?(conn) sql = valid_connection_sql begin log_connection_execute(conn, sql) rescue Sequel::DatabaseError, *database_error_classes false else true end end
The default options for the connection pool.
# File lib/sequel/database/connecting.rb, line 301 def connection_pool_default_options {} end
Return the options for the given server by merging the generic options for all server with the specific options for the given server specified in the :servers option.
# File lib/sequel/database/connecting.rb, line 308 def server_opts(server) opts = if @opts[:servers] and server_options = @opts[:servers][server] case server_options when Hash @opts.merge(server_options) when Proc @opts.merge(server_options.call(self)) else raise Error, 'Server opts should be a hash or proc' end elsif server.is_a?(Hash) @opts.merge(server) else @opts.dup end opts.delete(:servers) opts end
The SQL query to issue to check if a connection is valid.
# File lib/sequel/database/connecting.rb, line 328 def valid_connection_sql @valid_connection_sql ||= select(nil).sql end
The class to use for creating datasets. Should respond to new with the Database argument as the first argument, and an optional options hash.
If the database has any dataset modules associated with it, use a subclass of the given class that includes the modules as the dataset class.
# File lib/sequel/database/dataset_defaults.rb, line 18 def dataset_class=(c) unless @dataset_modules.empty? c = Class.new(c) @dataset_modules.each{|m| c.send(:include, m)} end @dataset_class = c reset_default_dataset end
Equivalent to extending all datasets produced by the database with a module. What it actually does is use a subclass of the current #dataset_class as the new #dataset_class, and include the module in the subclass. Instead of a module, you can provide a block that is used to create an anonymous module.
This allows you to override any of the dataset methods even if they are defined directly on the dataset class that this Database object uses.
If a block is given, a Dataset::DatasetModule instance is created, allowing for the easy creation of named dataset methods that will do caching.
Examples:
# Introspect columns for all of DB's datasets DB.extend_datasets(Sequel::ColumnsIntrospection) # Trace all SELECT queries by printing the SQL and the full backtrace DB.extend_datasets do def fetch_rows(sql) puts sql puts caller super end end # Add some named dataset methods DB.extend_datasets do order :by_id, :id select :with_id_and_name, :id, :name where :active, :active end DB[:table].active.with_id_and_name.by_id # SELECT id, name FROM table WHERE active ORDER BY id
# File lib/sequel/database/dataset_defaults.rb, line 62 def extend_datasets(mod=nil, &block) raise(Error, "must provide either mod or block, not both") if mod && block mod = Dataset::DatasetModule.new(&block) if block if @dataset_modules.empty? @dataset_modules = [mod] @dataset_class = Class.new(@dataset_class) else @dataset_modules << mod end @dataset_class.send(:include, mod) reset_default_dataset end
The default dataset class to use for the database
# File lib/sequel/database/dataset_defaults.rb, line 78 def dataset_class_default Sequel::Dataset end
Whether to quote identifiers by default for this database, true by default.
# File lib/sequel/database/dataset_defaults.rb, line 89 def quote_identifiers_default true end
Reset the default dataset used by most Database methods that create datasets.
# File lib/sequel/database/dataset_defaults.rb, line 83 def reset_default_dataset Sequel.synchronize{@symbol_literal_cache.clear} @default_dataset = dataset end
Whether to include information about the connection in use when logging queries.
Numeric specifying the duration beyond which queries are logged at warn level instead of info level.
Log level at which to log SQL queries. This is actually the method sent to the logger, so it should be the method name symbol. The default is :info, it can be set to :debug to log at DEBUG level.
Yield to the block, logging any errors at error level to all loggers, and all other queries with the duration at warn or info level.
# File lib/sequel/database/logging.rb, line 37 def log_connection_yield(sql, conn, args=nil) return yield if @loggers.empty? sql = "#{connection_info(conn) if conn && log_connection_info}#{sql}#{"; #{args.inspect}" if args}" timer = Sequel.start_timer begin yield rescue => e log_exception(e, sql) raise ensure log_duration(Sequel.elapsed_seconds_since(timer), sql) unless e end end
Log a message at error level, with information about the exception.
# File lib/sequel/database/logging.rb, line 26 def log_exception(exception, message) log_each(:error, "#{exception.class}: #{exception.message.strip if exception.message}: #{message}") end
Log a message at level info to all loggers.
# File lib/sequel/database/logging.rb, line 31 def log_info(message, args=nil) log_each(:info, args ? "#{message}; #{args.inspect}" : message) end
Remove any existing loggers and just use the given logger:
DB.logger = Logger.new($stdout)
# File lib/sequel/database/logging.rb, line 55 def logger=(logger) @loggers = Array(logger) end
String including information about the connection, for use when logging connection info.
# File lib/sequel/database/logging.rb, line 63 def connection_info(conn) "(conn: #{conn.__id__}) " end
Log the given SQL and then execute it on the connection, used by the transaction code.
# File lib/sequel/database/logging.rb, line 69 def log_connection_execute(conn, sql) log_connection_yield(sql, conn){conn.public_send(connection_execute_method, sql)} end
Log message with message prefixed by duration at info level, or warn level if duration is greater than log_warn_duration.
# File lib/sequel/database/logging.rb, line 75 def log_duration(duration, message) log_each((lwd = log_warn_duration and duration >= lwd) ? :warn : sql_log_level, "(#{sprintf('%0.6fs', duration)}) #{message}") end
Log message at level (which should be :error, :warn, or :info) to all loggers.
# File lib/sequel/database/logging.rb, line 81 def log_each(level, message) @loggers.each{|logger| logger.public_send(level, message)} end
Empty exception regexp to class map, used by default if Sequel doesn't have specific support for the database in use.
The general default size for string columns for all Sequel::Database instances.
Hash of extension name symbols to callable objects to load the extension into the Database object (usually by extending it with a module defined in the extension).
Mapping of schema type symbols to class or arrays of classes for that symbol.
The specific default size of string columns for this Sequel::Database, usually 255 by default.
The options hash for this database
Set the timezone to use for this database, overridding
Sequel.database_timezone
.
Register a hook that will be run when a new Database is instantiated. It is called with the new database handle.
# File lib/sequel/database/misc.rb, line 34 def self.after_initialize(&block) raise Error, "must provide block to after_initialize" unless block Sequel.synchronize do previous = @initialize_hook @initialize_hook = Proc.new do |db| previous.call(db) block.call(db) end end end
Apply an extension to all Database objects created in the future.
# File lib/sequel/database/misc.rb, line 46 def self.extension(*extensions) after_initialize{|db| db.extension(*extensions)} end
Constructs a new instance of a database connection with the specified options hash.
Accepts the following options:
Whether schema should be cached for this Database instance
The default size of string columns, 255 by default.
Whether to keep a reference to this instance in Sequel::DATABASES, true by default.
A specific logger to use.
An array of loggers to use.
Whether connection information should be logged when logging queries.
The number of elapsed seconds after which queries should be logged at warn level.
A name to use for the Database object.
Whether to automatically connect to the maximum number of servers. Can use a valid of 'concurrently' to preconnect in separate threads.
Whether to quote identifiers.
A hash specifying a server/shard specific options, keyed by shard symbol .
Whether to use a single-threaded connection pool.
Method to use to log SQL to a logger, :info by default.
All options given are also passed to the connection pool.
# File lib/sequel/database/misc.rb, line 114 def initialize(opts = OPTS) @opts ||= opts @opts = connection_pool_default_options.merge(@opts) @loggers = Array(@opts[:logger]) + Array(@opts[:loggers]) @opts[:servers] = {} if @opts[:servers].is_a?(String) @sharded = !!@opts[:servers] @opts[:adapter_class] = self.class @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, Sequel.single_threaded)) @default_string_column_size = @opts[:default_string_column_size] || DEFAULT_STRING_COLUMN_SIZE @schemas = {} @prepared_statements = {} @transactions = {} @symbol_literal_cache = {} @timezone = nil @dataset_class = dataset_class_default @cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true)) @dataset_modules = [] @loaded_extensions = [] @schema_type_classes = SCHEMA_TYPE_CLASSES.dup self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info self.log_warn_duration = @opts[:log_warn_duration] self.log_connection_info = typecast_value_boolean(@opts[:log_connection_info]) @pool = ConnectionPool.get_pool(self, @opts) reset_default_dataset adapter_initialize unless typecast_value_boolean(@opts[:keep_reference]) == false Sequel.synchronize{::Sequel::DATABASES.push(self)} end Sequel::Database.run_after_initialize(self) if typecast_value_boolean(@opts[:preconnect]) && @pool.respond_to?(:preconnect, true) concurrent = typecast_value_string(@opts[:preconnect]) == "concurrently" @pool.send(:preconnect, concurrent) end case exts = @opts[:extensions] when String extension(*exts.split(',').map(&:to_sym)) when Array extension(*exts) when Symbol extension(exts) when nil # nothing else raise Error, "unsupported Database :extensions option: #{@opts[:extensions].inspect}" end end
Register an extension callback for Database objects. ext should be the extension name symbol, and mod should either be a Module that the database is extended with, or a callable object called with the database object. If mod is not provided, a block can be provided and is treated as the mod object.
# File lib/sequel/database/misc.rb, line 55 def self.register_extension(ext, mod=nil, &block) if mod raise(Error, "cannot provide both mod and block to Database.register_extension") if block if mod.is_a?(Module) block = proc{|db| db.extend(mod)} else block = mod end end Sequel.synchronize{EXTENSIONS[ext] = block} end
Run the ::after_initialize hook
for the given instance
.
# File lib/sequel/database/misc.rb, line 68 def self.run_after_initialize(instance) @initialize_hook.call(instance) end
Converts a uri to an options hash. These options are then passed to a newly created database object.
# File lib/sequel/database/misc.rb, line 74 def self.uri_to_options(uri) { :user => uri.user, :password => uri.password, :port => uri.port, :host => uri.hostname, :database => (m = /\/(.*)/.match(uri.path)) && (m[1]) } end
Cast the given type to a literal type
DB.cast_type_literal(Float) # double precision DB.cast_type_literal(:foo) # foo
# File lib/sequel/database/misc.rb, line 194 def cast_type_literal(type) type_literal(:type=>type) end
Load an extension into the receiver. In addition to requiring the extension file, this also modifies the database to work with the extension (usually extending it with a module defined in the extension file). If no related extension file exists or the extension does not have specific support for Database objects, an Error will be raised. Returns self.
# File lib/sequel/database/misc.rb, line 203 def extension(*exts) Sequel.extension(*exts) exts.each do |ext| if pr = Sequel.synchronize{EXTENSIONS[ext]} unless Sequel.synchronize{@loaded_extensions.include?(ext)} Sequel.synchronize{@loaded_extensions << ext} pr.call(self) end else raise(Error, "Extension #{ext} does not have specific support handling individual databases (try: Sequel.extension #{ext.inspect})") end end self end
Freeze internal data structures for the Database instance.
# File lib/sequel/database/misc.rb, line 170 def freeze valid_connection_sql metadata_dataset @opts.freeze @loggers.freeze @pool.freeze @dataset_class.freeze @dataset_modules.freeze @schema_type_classes.freeze @loaded_extensions.freeze metadata_dataset super end
Convert the given timestamp from the application's timezone, to the databases's timezone or the default database timezone if the database does not have a timezone.
# File lib/sequel/database/misc.rb, line 221 def from_application_timestamp(v) Sequel.convert_output_timestamp(v, timezone) end
Returns a string representation of the database object including the class name and connection URI and options used when connecting (if any).
# File lib/sequel/database/misc.rb, line 227 def inspect a = [] a << uri.inspect if uri if (oo = opts[:orig_opts]) && !oo.empty? a << oo.inspect end "#<#{self.class}: #{a.join(' ')}>" end
Proxy the literal call to the dataset.
DB.literal(1) # 1 DB.literal(:a) # a DB.literal('a') # 'a'
# File lib/sequel/database/misc.rb, line 241 def literal(v) schema_utility_dataset.literal(v) end
Return the literalized version of the symbol if cached, or nil if it is not cached.
# File lib/sequel/database/misc.rb, line 247 def literal_symbol(sym) Sequel.synchronize{@symbol_literal_cache[sym]} end
Set the cached value of the literal symbol.
# File lib/sequel/database/misc.rb, line 252 def literal_symbol_set(sym, lit) Sequel.synchronize{@symbol_literal_cache[sym] = lit} end
Synchronize access to the prepared statements cache.
# File lib/sequel/database/misc.rb, line 257 def prepared_statement(name) Sequel.synchronize{prepared_statements[name]} end
Proxy the #quote_identifier method to the dataset, useful for quoting unqualified identifiers for use outside of datasets.
# File lib/sequel/database/misc.rb, line 264 def quote_identifier(v) schema_utility_dataset.quote_identifier(v) end
Return ruby class or array of classes for the given type symbol.
# File lib/sequel/database/misc.rb, line 269 def schema_type_class(type) @schema_type_classes[type] end
Default serial primary key options, used by the table creation code.
# File lib/sequel/database/misc.rb, line 274 def serial_primary_key_options {:primary_key => true, :type => Integer, :auto_increment => true} end
Cache the prepared statement object at the given name.
# File lib/sequel/database/misc.rb, line 279 def set_prepared_statement(name, ps) Sequel.synchronize{prepared_statements[name] = ps} end
Whether this database instance uses multiple servers, either for sharding or for master/slave.
# File lib/sequel/database/misc.rb, line 285 def sharded? @sharded end
The timezone to use for this database, defaulting to
Sequel.database_timezone
.
# File lib/sequel/database/misc.rb, line 290 def timezone @timezone || Sequel.database_timezone end
Convert the given timestamp to the application's timezone, from the databases's timezone or the default database timezone if the database does not have a timezone.
# File lib/sequel/database/misc.rb, line 297 def to_application_timestamp(v) Sequel.convert_timestamp(v, timezone) 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/misc.rb, line 306 def typecast_value(column_type, value) return nil if value.nil? meth = "typecast_value_#{column_type}" begin # Allow calling private methods as per-type typecasting methods are private respond_to?(meth, true) ? send(meth, value) : value rescue ArgumentError, TypeError => e raise Sequel.convert_exception_class(e, InvalidValue) end end
Returns the URI use to connect to the database. If a URI was not used when connecting, returns nil.
# File lib/sequel/database/misc.rb, line 319 def uri opts[:uri] end
Explicit alias of uri for easier subclassing.
# File lib/sequel/database/misc.rb, line 324 def url uri end
Typecast a string to a BigDecimal
# File lib/sequel/database/misc.rb, line 463 def _typecast_value_string_to_decimal(value) BigDecimal.new(value) end
Per adapter initialization method, empty by default.
# File lib/sequel/database/misc.rb, line 331 def adapter_initialize end
Returns true when the object is considered blank. The only objects that are blank are nil, false, strings with all whitespace, and ones that respond true to empty?
# File lib/sequel/database/misc.rb, line 338 def blank_object?(obj) return obj.blank? if obj.respond_to?(:blank?) case obj when NilClass, FalseClass true when Numeric, TrueClass false when String obj.strip.empty? else obj.respond_to?(:empty?) ? obj.empty? : false end end
Return the Sequel::DatabaseError subclass to wrap the given exception in.
# File lib/sequel/database/misc.rb, line 361 def database_error_class(exception, opts) database_specific_error_class(exception, opts) || DatabaseError end
An enumerable yielding pairs of regexps and exception classes, used to match against underlying driver exception messages in order to raise a more specific Sequel::DatabaseError subclass.
# File lib/sequel/database/misc.rb, line 355 def database_error_regexps DEFAULT_DATABASE_ERROR_REGEXPS end
Return the SQLState for the given exception, if one can be determined
# File lib/sequel/database/misc.rb, line 366 def database_exception_sqlstate(exception, opts) nil end
Return a specific Sequel::DatabaseError exception class if one is appropriate for the underlying exception, or nil if there is no specific exception class.
# File lib/sequel/database/misc.rb, line 373 def database_specific_error_class(exception, opts) return DatabaseDisconnectError if disconnect_error?(exception, opts) if sqlstate = database_exception_sqlstate(exception, opts) if klass = database_specific_error_class_from_sqlstate(sqlstate) return klass end else database_error_regexps.each do |regexp, klss| return klss if exception.message =~ regexp end end nil end
Given the SQLState, return the appropriate DatabaseError subclass.
# File lib/sequel/database/misc.rb, line 395 def database_specific_error_class_from_sqlstate(sqlstate) case sqlstate when *NOT_NULL_CONSTRAINT_SQLSTATES NotNullConstraintViolation when *FOREIGN_KEY_CONSTRAINT_SQLSTATES ForeignKeyConstraintViolation when *UNIQUE_CONSTRAINT_SQLSTATES UniqueConstraintViolation when *CHECK_CONSTRAINT_SQLSTATES CheckConstraintViolation when *SERIALIZATION_CONSTRAINT_SQLSTATES SerializationFailure end end
Return true if exception represents a disconnect error, false otherwise.
# File lib/sequel/database/misc.rb, line 411 def disconnect_error?(exception, opts) opts[:disconnect] end
Convert the given exception to an appropriate Sequel::DatabaseError subclass, keeping message and backtrace.
# File lib/sequel/database/misc.rb, line 417 def raise_error(exception, opts=OPTS) if !opts[:classes] || Array(opts[:classes]).any?{|c| exception.is_a?(c)} raise Sequel.convert_exception_class(exception, database_error_class(exception, opts)) else raise exception end end
Typecast the value to an SQL::Blob
# File lib/sequel/database/misc.rb, line 426 def typecast_value_blob(value) value.is_a?(Sequel::SQL::Blob) ? value : Sequel::SQL::Blob.new(value) end
Typecast the value to true, false, or nil
# File lib/sequel/database/misc.rb, line 431 def typecast_value_boolean(value) case value when false, 0, "0", /\Af(alse)?\z/, /\Ano?\z/ false else blank_object?(value) ? nil : true end end
Typecast the value to a Date
# File lib/sequel/database/misc.rb, line 441 def typecast_value_date(value) case value when DateTime, Time Date.new(value.year, value.month, value.day) when Date value when String Sequel.string_to_date(value) when Hash Date.new(*[:year, :month, :day].map{|x| (value[x] || value[x.to_s]).to_i}) else raise InvalidValue, "invalid value for Date: #{value.inspect}" end end
Typecast the value to a DateTime or Time depending on Sequel.datetime_class
# File lib/sequel/database/misc.rb, line 457 def typecast_value_datetime(value) Sequel.typecast_to_application_timestamp(value) end
Typecast the value to a BigDecimal
# File lib/sequel/database/misc.rb, line 486 def typecast_value_decimal(value) case value when BigDecimal value when Numeric BigDecimal.new(value.to_s) when String _typecast_value_string_to_decimal(value) else raise InvalidValue, "invalid value for BigDecimal: #{value.inspect}" end end
Typecast the value to a Float
# File lib/sequel/database/misc.rb, line 500 def typecast_value_float(value) Float(value) end
Typecast the value to an Integer
# File lib/sequel/database/misc.rb, line 505 def typecast_value_integer(value) (value.is_a?(String) && value =~ /\A0+(\d)/) ? Integer(value, 10) : Integer(value) end
Typecast the value to a String
# File lib/sequel/database/misc.rb, line 510 def typecast_value_string(value) case value when Hash, Array raise Sequel::InvalidValue, "invalid value for String: #{value.inspect}" else value.to_s end end
Typecast the value to a Time
# File lib/sequel/database/misc.rb, line 520 def typecast_value_time(value) case value when Time if value.is_a?(SQLTime) value else SQLTime.create(value.hour, value.min, value.sec, value.nsec/1000.0) end when String Sequel.string_to_time(value) when Hash SQLTime.create(*[:hour, :minute, :second].map{|x| (value[x] || value[x.to_s]).to_i}) else raise Sequel::InvalidValue, "invalid value for Time: #{value.inspect}" end end
Whether the database uses a global namespace for the index, true by default. If false, the indexes are going to be namespaced per table.
# File lib/sequel/database/features.rb, line 13 def global_index_namespace? true end
Whether the database supports CREATE TABLE IF NOT EXISTS syntax, false by default.
# File lib/sequel/database/features.rb, line 19 def supports_create_table_if_not_exists? false end
Whether the database supports deferrable constraints, false by default as few databases do.
# File lib/sequel/database/features.rb, line 25 def supports_deferrable_constraints? false end
Whether the database supports deferrable foreign key constraints, false by default as few databases do.
# File lib/sequel/database/features.rb, line 31 def supports_deferrable_foreign_key_constraints? supports_deferrable_constraints? end
Whether the database supports DROP TABLE IF EXISTS syntax, false by default.
# File lib/sequel/database/features.rb, line 37 def supports_drop_table_if_exists? supports_create_table_if_not_exists? end
Whether the database supports Database#foreign_key_list for parsing foreign keys.
# File lib/sequel/database/features.rb, line 43 def supports_foreign_key_parsing? respond_to?(:foreign_key_list) end
Whether the database supports Database#indexes for parsing indexes.
# File lib/sequel/database/features.rb, line 48 def supports_index_parsing? respond_to?(:indexes) end
Whether the database supports partial indexes (indexes on a subset of a table), false by default.
# File lib/sequel/database/features.rb, line 54 def supports_partial_indexes? false end
Whether the database and adapter support prepared transactions (two-phase commit), false by default.
# File lib/sequel/database/features.rb, line 60 def supports_prepared_transactions? false end
Whether the database and adapter support savepoints, false by default.
# File lib/sequel/database/features.rb, line 65 def supports_savepoints? false end
Whether the database and adapter support savepoints inside prepared transactions (two-phase commit), false by default.
# File lib/sequel/database/features.rb, line 71 def supports_savepoints_in_prepared_transactions? supports_prepared_transactions? && supports_savepoints? end
Whether the database supports schema parsing via #schema.
# File lib/sequel/database/features.rb, line 76 def supports_schema_parsing? respond_to?(:schema_parse_table, true) end
Whether the database supports Database#tables for getting list of tables.
# File lib/sequel/database/features.rb, line 81 def supports_table_listing? respond_to?(:tables) end
Whether the database and adapter support transaction isolation levels, false by default.
# File lib/sequel/database/features.rb, line 91 def supports_transaction_isolation_levels? false end
Whether DDL statements work correctly in transactions, false by default.
# File lib/sequel/database/features.rb, line 96 def supports_transactional_ddl? false end
Whether the database supports Database#views for getting list of views.
# File lib/sequel/database/features.rb, line 86 def supports_view_listing? respond_to?(:views) end
Whether CREATE VIEW … WITH CHECK OPTION is supported, false by default.
# File lib/sequel/database/features.rb, line 101 def supports_views_with_check_option? !!view_with_check_option_support end
Whether CREATE VIEW … WITH LOCAL CHECK OPTION is supported, false by default.
# File lib/sequel/database/features.rb, line 106 def supports_views_with_local_check_option? view_with_check_option_support == :local end
Whether the database supports adding primary key constraints on NULLable columns, automatically making them NOT NULL. If false, the columns must be set NOT NULL before the primary key constraint is added.
# File lib/sequel/database/features.rb, line 115 def can_add_primary_key_constraint_on_nullable_columns? true end
Whether this dataset considers unquoted identifiers as uppercase. True by default as that is the SQL standard
# File lib/sequel/database/features.rb, line 121 def folds_unquoted_identifiers_to_uppercase? true end
Whether the database supports combining multiple alter table operations into a single query, false by default.
# File lib/sequel/database/features.rb, line 127 def supports_combining_alter_table_ops? false end
Whether the database supports CREATE OR REPLACE VIEW. If not, support will be emulated by dropping the view first. false by default.
# File lib/sequel/database/features.rb, line 133 def supports_create_or_replace_view? false end
Whether the database supports named column constraints. True by default. Those that don't support named column constraints have to have column constraints converted to table constraints if the column constraints have names.
# File lib/sequel/database/features.rb, line 141 def supports_named_column_constraints? true end
Don't advertise support for WITH CHECK OPTION by default.
# File lib/sequel/database/features.rb, line 146 def view_with_check_option_support nil end