# File lib/sequel/database/schema_methods.rb 935 def primary_key_constraint_sql_fragment(_) 936 'PRIMARY KEY' 937 end
class Sequel::Database
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.
Constants
- OPTS
1 - Methods that execute queries and/or return results
↑ topConstants
- COLUMN_SCHEMA_DATETIME_TYPES
- COLUMN_SCHEMA_STRING_TYPES
- INTEGER1_MIN_MAX
- INTEGER2_MIN_MAX
- INTEGER3_MIN_MAX
- INTEGER4_MIN_MAX
- INTEGER8_MIN_MAX
- UNSIGNED_INTEGER1_MIN_MAX
- UNSIGNED_INTEGER2_MIN_MAX
- UNSIGNED_INTEGER3_MIN_MAX
- UNSIGNED_INTEGER4_MIN_MAX
- UNSIGNED_INTEGER8_MIN_MAX
Attributes
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
Public Instance Methods
Source
# File lib/sequel/database/query.rb 25 def <<(sql) 26 run(sql) 27 self 28 end
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"
Source
# File lib/sequel/database/query.rb 35 def call(ps_name, hash=OPTS, &block) 36 prepared_statement(ps_name).call(hash, &block) 37 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
Source
# File lib/sequel/database/query.rb 42 def execute_ddl(sql, opts=OPTS, &block) 43 execute_dui(sql, opts, &block) 44 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.
Source
# File lib/sequel/database/query.rb 49 def execute_dui(sql, opts=OPTS, &block) 50 execute(sql, opts, &block) 51 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.
Source
# File lib/sequel/database/query.rb 56 def execute_insert(sql, opts=OPTS, &block) 57 execute_dui(sql, opts, &block) 58 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.
Source
# File lib/sequel/database/query.rb 65 def get(*args, &block) 66 @default_dataset.get(*args, &block) 67 end
Returns a single value from the database, see Dataset#get.
DB.get(1) # SELECT 1 # => 1 DB.get{server_version.function} # SELECT server_version()
Source
# File lib/sequel/database/query.rb 74 def run(sql, opts=OPTS) 75 sql = literal(sql) if sql.is_a?(SQL::PlaceholderLiteralString) 76 execute_ddl(sql, opts) 77 nil 78 end
Runs the supplied SQL statement string on the database server. Returns nil. Options:
- :server
-
The server to run the SQL on.
DB.run("SET some_server_variable = 42")
Source
# File lib/sequel/database/query.rb 121 def schema(table, opts=OPTS) 122 raise(Error, 'schema parsing is not implemented on this database') unless supports_schema_parsing? 123 124 opts = opts.dup 125 tab = if table.is_a?(Dataset) 126 o = table.opts 127 from = o[:from] 128 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) 129 table.first_source_table 130 else 131 table 132 end 133 134 qualifiers = split_qualifiers(tab) 135 table_name = qualifiers.pop 136 sch = qualifiers.pop 137 information_schema_schema = case qualifiers.length 138 when 1 139 Sequel.identifier(*qualifiers) 140 when 2 141 Sequel.qualify(*qualifiers) 142 end 143 144 if table.is_a?(Dataset) 145 quoted_name = table.literal(tab) 146 opts[:dataset] = table 147 else 148 quoted_name = schema_utility_dataset.literal(table) 149 end 150 151 opts[:schema] = sch if sch && !opts.include?(:schema) 152 opts[:information_schema_schema] = information_schema_schema if information_schema_schema && !opts.include?(:information_schema_schema) 153 154 Sequel.synchronize{@schemas.delete(quoted_name)} if opts[:reload] 155 if v = Sequel.synchronize{@schemas[quoted_name]} 156 return v 157 end 158 159 cols = schema_parse_table(table_name, opts) 160 raise(Error, "schema parsing returned no columns, table #{table_name.inspect} probably doesn't exist") if cols.nil? || cols.empty? 161 162 primary_keys = 0 163 auto_increment_set = false 164 cols.each do |_,c| 165 auto_increment_set = true if c.has_key?(:auto_increment) 166 primary_keys += 1 if c[:primary_key] 167 end 168 169 cols.each do |_,c| 170 c[:ruby_default] = column_schema_to_ruby_default(c[:default], c[:type]) unless c.has_key?(:ruby_default) 171 if c[:primary_key] && !auto_increment_set 172 # If adapter didn't set it, assume that integer primary keys are auto incrementing 173 c[:auto_increment] = primary_keys == 1 && !!(c[:db_type] =~ /int/io) 174 end 175 if !c[:max_length] && c[:type] == :string && (max_length = column_schema_max_length(c[:db_type])) 176 c[:max_length] = max_length 177 end 178 if !c[:max_value] && !c[:min_value] 179 min_max = case c[:type] 180 when :integer 181 column_schema_integer_min_max_values(c) 182 when :decimal 183 column_schema_decimal_min_max_values(c) 184 end 185 c[:min_value], c[:max_value] = min_max if min_max 186 end 187 end 188 schema_post_process(cols) 189 190 Sequel.synchronize{@schemas[quoted_name] = cols} if cache_schema 191 cols 192 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:
- :reload
-
Ignore any cached results, and get fresh information from the database.
- :schema
-
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:
- :allow_null
-
Whether NULL is an allowed value for the column.
- :db_type
-
The database type for the column, as a database specific string.
- :default
-
The database default for the column, as a database specific string, or nil if there is no default value.
- :primary_key
-
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.
- :ruby_default
-
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.
- :type
-
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}]]
Source
# File lib/sequel/database/query.rb 202 def table_exists?(name) 203 sch, table_name = schema_and_table(name) 204 name = SQL::QualifiedIdentifier.new(sch, table_name) if sch 205 ds = from(name) 206 transaction(:savepoint=>:only){_table_exists?(ds)} 207 true 208 rescue DatabaseError 209 false 210 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.
Private Instance Methods
Source
# File lib/sequel/database/query.rb 362 def _metadata_dataset 363 dataset 364 end
Uncached version of metadata_dataset
, designed for overriding.
Source
# File lib/sequel/database/query.rb 216 def _table_exists?(ds) 217 ds.get(SQL::AliasedExpression.new(Sequel::NULL, :nil)) 218 end
Should raise an error if the table doesn’t not exist, and not raise an error if the table does exist.
Source
# File lib/sequel/database/query.rb 323 def column_schema_decimal_min_max_values(column) 324 if column[:column_size] && column[:scale] 325 precision = column[:column_size] 326 scale = column[:scale] 327 elsif /\((\d+)(?:,\s*(-?\d+))?\)/ =~ column[:db_type] 328 precision = $1.to_i 329 scale = $2.to_i if $2 330 end 331 332 if precision 333 limit = BigDecimal("9" * precision) 334 if scale 335 limit /= 10**(scale) 336 end 337 [-limit, limit] 338 end 339 end
Look at the db_type and guess the minimum and maximum decimal values for the column.
Source
# File lib/sequel/database/query.rb 222 def column_schema_default_string_type?(type) 223 COLUMN_SCHEMA_STRING_TYPES.include?(type) 224 end
Whether the type should be treated as a string type when parsing the column schema default value.
Source
# File lib/sequel/database/query.rb 228 def column_schema_default_to_ruby_value(default, type) 229 case type 230 when :boolean 231 case default 232 when /[f0]/i 233 false 234 when /[t1]/i 235 true 236 end 237 when :string, :enum, :set, :interval 238 default 239 when :blob 240 Sequel::SQL::Blob.new(default) 241 when :integer 242 Integer(default) 243 when :float 244 Float(default) 245 when :date 246 Sequel.string_to_date(default) 247 when :datetime 248 Sequel.string_to_datetime(default) 249 when :time 250 Sequel.string_to_time(default) 251 when :decimal 252 BigDecimal(default) 253 end 254 end
Transform the given normalized default string into a ruby object for the given type.
Source
# File lib/sequel/database/query.rb 297 def column_schema_integer_min_max_values(column) 298 db_type = column[:db_type] 299 if /decimal|numeric|number/i =~ db_type 300 if min_max = column_schema_decimal_min_max_values(column) 301 min_max.map!(&:to_i) 302 end 303 return min_max 304 end 305 306 unsigned = /unsigned/i =~ db_type 307 case db_type 308 when /big|int8/i 309 unsigned ? UNSIGNED_INTEGER8_MIN_MAX : INTEGER8_MIN_MAX 310 when /medium/i 311 unsigned ? UNSIGNED_INTEGER3_MIN_MAX : INTEGER3_MIN_MAX 312 when /small|int2/i 313 unsigned ? UNSIGNED_INTEGER2_MIN_MAX : INTEGER2_MIN_MAX 314 when /tiny/i 315 (unsigned || column_schema_tinyint_type_is_unsigned?) ? UNSIGNED_INTEGER1_MIN_MAX : INTEGER1_MIN_MAX 316 else 317 unsigned ? UNSIGNED_INTEGER4_MIN_MAX : INTEGER4_MIN_MAX 318 end 319 end
Look at the db_type and guess the minimum and maximum integer values for the column.
Source
# File lib/sequel/database/query.rb 348 def column_schema_max_length(db_type) 349 if db_type =~ /\((\d+)\)/ 350 $1.to_i 351 end 352 end
Look at the db_type and guess the maximum length of the column. This assumes types such as varchar(255).
Source
# File lib/sequel/database/query.rb 258 def column_schema_normalize_default(default, type) 259 if column_schema_default_string_type?(type) 260 return unless m = /\A'(.*)'\z/.match(default) 261 m[1].gsub("''", "'") 262 else 263 default 264 end 265 end
Normalize the default value string for the given type and return the normalized value.
Source
# File lib/sequel/database/query.rb 342 def column_schema_tinyint_type_is_unsigned? 343 false 344 end
Whether the tinyint type (if supported by the database) is unsigned by default.
Source
# File lib/sequel/database/query.rb 269 def column_schema_to_ruby_default(default, type) 270 return default unless default.is_a?(String) 271 if COLUMN_SCHEMA_DATETIME_TYPES.include?(type) 272 if /now|today|CURRENT|getdate|\ADate\(\)\z/i.match(default) 273 if type == :date 274 return Sequel::CURRENT_DATE 275 else 276 return Sequel::CURRENT_TIMESTAMP 277 end 278 end 279 end 280 default = column_schema_normalize_default(default, type) 281 column_schema_default_to_ruby_value(default, type) rescue nil 282 end
Convert the given default, which should be a database specific string, into a ruby object.
Source
# File lib/sequel/database/query.rb 357 def input_identifier_meth(ds=nil) 358 (ds || dataset).method(:input_identifier) 359 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.
Source
# File lib/sequel/database/query.rb 369 def metadata_dataset 370 @metadata_dataset ||= _metadata_dataset 371 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.
Source
# File lib/sequel/database/query.rb 376 def output_identifier_meth(ds=nil) 377 (ds || dataset).method(:output_identifier) 378 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.
Source
# File lib/sequel/database/query.rb 381 def remove_cached_schema(table) 382 cache = @default_dataset.send(:cache) 383 Sequel.synchronize{cache.clear} 384 k = quote_schema_table(table) 385 Sequel.synchronize{@schemas.delete(k)} 386 end
Remove the cached schema for the given schema name
Source
# File lib/sequel/database/query.rb 391 def schema_column_type(db_type) 392 case db_type 393 when /\A(character( varying)?|n?(var)?char|n?text|string|clob)/io 394 :string 395 when /\A(int(eger)?|(big|small|tiny)int)/io 396 :integer 397 when /\Adate\z/io 398 :date 399 when /\A((small)?datetime|timestamp(\(\d\))?( with(out)? time zone)?)\z/io 400 :datetime 401 when /\Atime( with(out)? time zone)?\z/io 402 :time 403 when /\A(bool(ean)?)\z/io 404 :boolean 405 when /\A(real|float( unsigned)?|double( precision)?|double\(\d+,\d+\)( unsigned)?)\z/io 406 :float 407 when /\A(?:(?:(?:num(?:ber|eric)?|decimal)(?:\(\d+,\s*(-?\d+|false|true)\))?))\z/io 408 $1 && ['0', 'false'].include?($1) ? :integer : :decimal 409 when /bytea|blob|image|(var)?binary/io 410 :blob 411 when /\Aenum/io 412 :enum 413 end 414 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.
Source
# File lib/sequel/database/query.rb 417 def schema_post_process(cols) 418 # :nocov: 419 if RUBY_VERSION >= '2.5' 420 # :nocov: 421 cols.each do |_, h| 422 db_type = h[:db_type] 423 if db_type.is_a?(String) 424 h[:db_type] = -db_type 425 end 426 end 427 end 428 429 cols.each do |_,c| 430 c.each_value do |val| 431 val.freeze if val.is_a?(String) 432 end 433 end 434 end
Post process the schema values.
2 - Methods that modify the database schema
↑ topConstants
- COLUMN_DEFINITION_ORDER
-
The order of column modifiers to use when defining a column.
- COMBINABLE_ALTER_TABLE_OPS
-
The alter table operations that are combinable.
Public Instance Methods
Source
# File lib/sequel/database/schema_methods.rb 25 def add_column(table, *args) 26 alter_table(table) {add_column(*args)} 27 end
Adds a column to the specified table. This method expects a column name, a datatype and optionally a hash with additional constraints and options:
DB.add_column :items, :name, String, unique: true, null: false DB.add_column :items, :category, String, default: 'ruby'
See alter_table
.
Source
# File lib/sequel/database/schema_methods.rb 40 def add_index(table, columns, options=OPTS) 41 e = options[:ignore_errors] 42 begin 43 alter_table(table){add_index(columns, options)} 44 rescue DatabaseError 45 raise unless e 46 end 47 nil 48 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_errors
-
Ignore any DatabaseErrors that are raised
- :name
-
Name to use for index instead of default
See alter_table
.
Source
# File lib/sequel/database/schema_methods.rb 67 def alter_table(name, &block) 68 generator = alter_table_generator(&block) 69 remove_cached_schema(name) 70 apply_alter_table_generator(name, generator) 71 nil 72 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 guide.
Source
# File lib/sequel/database/schema_methods.rb 76 def alter_table_generator(&block) 77 alter_table_generator_class.new(self, &block) 78 end
Return a new Schema::AlterTableGenerator instance with the receiver as the database and the given block.
Source
# File lib/sequel/database/schema_methods.rb 119 def create_join_table(hash, options=OPTS) 120 keys = hash.keys.sort 121 create_table(join_table_name(hash, options), options) do 122 keys.each do |key| 123 v = hash[key] 124 unless v.is_a?(Hash) 125 v = {:table=>v} 126 end 127 v[:null] = false unless v.has_key?(:null) 128 foreign_key(key, v) 129 end 130 primary_key(keys) unless options[:no_primary_key] 131 index(keys.reverse, options[:index_options] || OPTS) unless options[:no_index] 132 end 133 nil 134 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.
The default table name this will create is the sorted version of the two hash values, joined by an underscore. So the following two method calls create the same table:
create_join_table(cat_id: :cats, dog_id: :dogs) # cats_dogs create_join_table(dog_id: :dogs, cat_id: :cats) # cats_dogs
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:
- :index_options
-
The options to pass to the index
- :name
-
The name of the table to create
- :no_index
-
Set to true not to create the second index.
- :no_primary_key
-
Set to true to not create the primary key.
Source
# File lib/sequel/database/schema_methods.rb 137 def create_join_table!(hash, options=OPTS) 138 drop_table?(join_table_name(hash, options)) 139 create_join_table(hash, options) 140 end
Forcibly create a join table, attempting to drop it if it already exists, then creating it.
Source
# File lib/sequel/database/schema_methods.rb 143 def create_join_table?(hash, options=OPTS) 144 if supports_create_table_if_not_exists? && options[:no_index] 145 create_join_table(hash, options.merge(:if_not_exists=>true)) 146 elsif !table_exists?(join_table_name(hash, options)) 147 create_join_table(hash, options) 148 end 149 end
Creates the join table unless it already exists.
Source
# File lib/sequel/database/schema_methods.rb 256 def create_or_replace_view(name, source, options = OPTS) 257 if supports_create_or_replace_view? && !options[:materialized] 258 options = options.merge(:replace=>true) 259 else 260 swallow_database_error{drop_view(name, options)} 261 end 262 263 create_view(name, source, options) 264 nil 265 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.
Source
# File lib/sequel/database/schema_methods.rb 204 def create_table(name, options=OPTS, &block) 205 remove_cached_schema(name) 206 if sql = options[:as] 207 raise(Error, "can't provide both :as option and block to create_table") if block 208 create_table_as(name, sql, options) 209 else 210 generator = options[:generator] || create_table_generator(&block) 211 create_table_from_generator(name, generator, options) 212 create_table_indexes_from_generator(name, generator, options) 213 end 214 nil 215 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:
- :as
-
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_index_errors
-
Ignore any errors when creating indexes.
- :temp
-
Create the table as a temporary table.
MySQL specific options:
- :charset
-
The character set to use for the table.
- :collate
-
The collation to use for the table.
- :engine
-
The table engine to use for the table.
PostgreSQL specific options:
- :on_commit
-
Either :preserve_rows (default), :drop or :delete_rows. Should only be specified when creating a temporary table.
- :foreign
-
Create a foreign table. The value should be the name of the foreign server that was specified in CREATE SERVER.
- :inherits
-
Inherit from a different table. An array can be specified to inherit from multiple tables.
- :unlogged
-
Create the table as an unlogged table.
- :options
-
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.
- :tablespace
-
The tablespace to use for the table.
SQLite specific options:
- :strict
-
Create a STRICT table, which checks that the values for the columns are the correct type (similar to all other SQL databases). Note that when using this option, all column types used should be one of the following:
int
,integer
,real
,text
,blob
, andany
. Theany
type is treated like a SQLite column in a non-strict table, allowing any type of data to be stored. This option is supported on SQLite 3.37.0+. - :using
-
Create a VIRTUAL table with the given USING clause. The value should be a string, as it is used directly in the SQL query.
- :without_rowid
-
Create a WITHOUT ROWID table. Every row in SQLite has a special ‘rowid’ column, that uniquely identifies that row within the table. If this option is used, the ‘rowid’ column is omitted, which can sometimes provide some space and speed advantages. Note that you must then provide an explicit primary key when you create the table. This option is supported on SQLite 3.8.2+.
See Schema::CreateTableGenerator
and the “Schema Modification” guide.
Source
# File lib/sequel/database/schema_methods.rb 223 def create_table!(name, options=OPTS, &block) 224 drop_table?(name) 225 create_table(name, options, &block) 226 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)
Source
# File lib/sequel/database/schema_methods.rb 233 def create_table?(name, options=OPTS, &block) 234 options = options.dup 235 generator = options[:generator] ||= create_table_generator(&block) 236 if generator.indexes.empty? && supports_create_table_if_not_exists? 237 create_table(name, options.merge!(:if_not_exists=>true)) 238 elsif !table_exists?(name) 239 create_table(name, options) 240 end 241 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
Source
# File lib/sequel/database/schema_methods.rb 245 def create_table_generator(&block) 246 create_table_generator_class.new(self, &block) 247 end
Return a new Schema::CreateTableGenerator instance with the receiver as the database and the given block.
Source
# File lib/sequel/database/schema_methods.rb 310 def create_view(name, source, options = OPTS) 311 execute_ddl(create_view_sql(name, source, options)) 312 remove_cached_schema(name) 313 nil 314 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 DB.create_view(:bar_items, DB[:items].select(:foo), columns: [:bar]) # CREATE VIEW bar_items (bar) AS # SELECT foo FROM items
Options:
- :columns
-
The column names to use for the view. If not given, automatically determined based on the input dataset.
- :check
-
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:
- :temp
-
Create a temporary view, automatically dropped on disconnect.
PostgreSQL specific options:
- :materialized
-
Creates a materialized view, similar to a regular view, but backed by a physical table.
- :recursive
-
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.
- :security_invoker
-
Set the security_invoker property on the view, making the access to the view use the current user’s permissions, instead of the view owner’s permissions.
- :tablespace
-
The tablespace to use for materialized views.
Source
# File lib/sequel/database/schema_methods.rb 321 def drop_column(table, *args) 322 alter_table(table) {drop_column(*args)} 323 end
Removes a column from the specified table:
DB.drop_column :items, :category
See alter_table
.
Source
# File lib/sequel/database/schema_methods.rb 331 def drop_index(table, columns, options=OPTS) 332 alter_table(table){drop_index(columns, options)} 333 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
.
Source
# File lib/sequel/database/schema_methods.rb 340 def drop_join_table(hash, options=OPTS) 341 drop_table(join_table_name(hash, options), options) 342 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
Source
# File lib/sequel/database/schema_methods.rb 349 def drop_table(*names) 350 options = names.last.is_a?(Hash) ? names.pop : OPTS 351 names.each do |n| 352 execute_ddl(drop_table_sql(n, options)) 353 remove_cached_schema(n) 354 end 355 nil 356 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)
Source
# File lib/sequel/database/schema_methods.rb 364 def drop_table?(*names) 365 options = names.last.is_a?(Hash) ? names.pop : OPTS 366 if supports_drop_table_if_exists? 367 options = options.merge(:if_exists=>true) 368 names.each do |name| 369 drop_table(name, options) 370 end 371 else 372 names.each do |name| 373 drop_table(name, options) if table_exists?(name) 374 end 375 end 376 nil 377 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
Source
# File lib/sequel/database/schema_methods.rb 392 def drop_view(*names) 393 options = names.last.is_a?(Hash) ? names.pop : OPTS 394 names.each do |n| 395 execute_ddl(drop_view_sql(n, options)) 396 remove_cached_schema(n) 397 end 398 nil 399 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:
- :cascade
-
Also drop objects depending on this view.
- :if_exists
-
Do not raise an error if the view does not exist.
PostgreSQL specific options:
- :materialized
-
Drop a materialized view.
Source
# File lib/sequel/database/schema_methods.rb 418 def rename_column(table, *args) 419 alter_table(table) {rename_column(*args)} 420 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
.
Source
# File lib/sequel/database/schema_methods.rb 406 def rename_table(name, new_name) 407 execute_ddl(rename_table_sql(name, new_name)) 408 remove_cached_schema(name) 409 nil 410 end
Renames a table:
DB.tables #=> [:items] DB.rename_table :items, :old_items DB.tables #=> [:old_items]
Source
# File lib/sequel/database/schema_methods.rb 427 def set_column_default(table, *args) 428 alter_table(table) {set_column_default(*args)} 429 end
Sets the default value for the given column in the given table:
DB.set_column_default :items, :category, 'perl!'
See alter_table
.
Source
# File lib/sequel/database/schema_methods.rb 436 def set_column_type(table, *args) 437 alter_table(table) {set_column_type(*args)} 438 end
Set the data type for the given column in the given table:
DB.set_column_type :items, :price, :float
See alter_table
.
Private Instance Methods
Source
# File lib/sequel/database/schema_methods.rb 476 def alter_table_add_column_sql(table, op) 477 "ADD COLUMN #{column_definition_sql(op)}" 478 end
Source
# File lib/sequel/database/schema_methods.rb 500 def alter_table_add_constraint_sql(table, op) 501 "ADD #{constraint_definition_sql(op)}" 502 end
Source
# File lib/sequel/database/schema_methods.rb 480 def alter_table_drop_column_sql(table, op) 481 "DROP COLUMN #{quote_identifier(op[:name])}#{' CASCADE' if op[:cascade]}" 482 end
Source
# File lib/sequel/database/schema_methods.rb 504 def alter_table_drop_constraint_sql(table, op) 505 quoted_name = quote_identifier(op[:name]) if op[:name] 506 if op[:type] == :foreign_key 507 quoted_name ||= quote_identifier(foreign_key_name(table, op[:columns])) 508 end 509 "DROP CONSTRAINT #{quoted_name}#{' CASCADE' if op[:cascade]}" 510 end
Source
# File lib/sequel/database/schema_methods.rb 461 def alter_table_generator_class 462 Schema::AlterTableGenerator 463 end
The class used for alter_table
generators.
Source
# File lib/sequel/database/schema_methods.rb 466 def alter_table_op_sql(table, op) 467 meth = "alter_table_#{op[:op]}_sql" 468 if respond_to?(meth, true) 469 # Allow calling private methods as alter table op sql methods are private 470 send(meth, table, op) 471 else 472 raise Error, "Unsupported ALTER TABLE operation: #{op[:op]}" 473 end 474 end
SQL fragment for given alter table operation.
Source
# File lib/sequel/database/schema_methods.rb 484 def alter_table_rename_column_sql(table, op) 485 "RENAME COLUMN #{quote_identifier(op[:name])} TO #{quote_identifier(op[:new_name])}" 486 end
Source
# File lib/sequel/database/schema_methods.rb 492 def alter_table_set_column_default_sql(table, op) 493 "ALTER COLUMN #{quote_identifier(op[:name])} SET DEFAULT #{literal(op[:default])}" 494 end
Source
# File lib/sequel/database/schema_methods.rb 496 def alter_table_set_column_null_sql(table, op) 497 "ALTER COLUMN #{quote_identifier(op[:name])} #{op[:null] ? 'DROP' : 'SET'} NOT NULL" 498 end
Source
# File lib/sequel/database/schema_methods.rb 488 def alter_table_set_column_type_sql(table, op) 489 "ALTER COLUMN #{quote_identifier(op[:name])} TYPE #{type_literal(op)}" 490 end
Source
# File lib/sequel/database/schema_methods.rb 514 def alter_table_sql(table, op) 515 case op[:op] 516 when :add_index 517 index_definition_sql(table, op) 518 when :drop_index 519 drop_index_sql(table, op) 520 else 521 if sql = alter_table_op_sql(table, op) 522 "ALTER TABLE #{quote_schema_table(table)} #{sql}" 523 end 524 end 525 end
The SQL to execute to modify the table. op should be one of the operations returned by the AlterTableGenerator.
Source
# File lib/sequel/database/schema_methods.rb 529 def alter_table_sql_list(table, operations) 530 if supports_combining_alter_table_ops? 531 grouped_ops = [] 532 last_combinable = false 533 operations.each do |op| 534 if combinable_alter_table_op?(op) 535 if sql = alter_table_op_sql(table, op) 536 grouped_ops << [] unless last_combinable 537 grouped_ops.last << sql 538 last_combinable = true 539 end 540 elsif sql = alter_table_sql(table, op) 541 Array(sql).each{|s| grouped_ops << s} 542 last_combinable = false 543 end 544 end 545 grouped_ops.map do |gop| 546 if gop.is_a?(Array) 547 "ALTER TABLE #{quote_schema_table(table)} #{gop.join(', ')}" 548 else 549 gop 550 end 551 end 552 else 553 operations.map{|op| alter_table_sql(table, op)}.flatten.compact 554 end 555 end
Array
of SQL statements used to modify the table, corresponding to changes specified by the operations.
Source
# File lib/sequel/database/schema_methods.rb 443 def apply_alter_table(name, ops) 444 alter_table_sql_list(name, ops).each{|sql| execute_ddl(sql)} 445 end
Apply the changes in the given alter table ops to the table given by name.
Source
# File lib/sequel/database/schema_methods.rb 448 def apply_alter_table_generator(name, generator) 449 ops = generator.operations 450 451 unless can_add_primary_key_constraint_on_nullable_columns? 452 if add_pk = ops.find{|op| op[:op] == :add_constraint && op[:type] == :primary_key} 453 ops = add_pk[:columns].map{|column| {:op => :set_column_null, :name => column, :null => false}} + ops 454 end 455 end 456 457 apply_alter_table(name, ops) 458 end
Apply the operations in the given generator to the table given by name.
Source
# File lib/sequel/database/schema_methods.rb 559 def auto_increment_sql 560 'AUTOINCREMENT' 561 end
The SQL string specify the autoincrement property, generally used by primary keys.
Source
# File lib/sequel/database/schema_methods.rb 577 def column_definition_auto_increment_sql(sql, column) 578 sql << " #{auto_increment_sql}" if column[:auto_increment] 579 end
Add auto increment SQL fragment to column creation SQL.
Source
# File lib/sequel/database/schema_methods.rb 582 def column_definition_collate_sql(sql, column) 583 if collate = column[:collate] 584 sql << " COLLATE #{collate}" 585 end 586 end
Add collate SQL fragment to column creation SQL.
Source
# File lib/sequel/database/schema_methods.rb 589 def column_definition_default_sql(sql, column) 590 sql << " DEFAULT #{literal(column[:default])}" if column.include?(:default) 591 end
Add default SQL fragment to column creation SQL.
Source
# File lib/sequel/database/schema_methods.rb 594 def column_definition_null_sql(sql, column) 595 null = column.fetch(:null, column[:allow_null]) 596 if null.nil? && !can_add_primary_key_constraint_on_nullable_columns? && column[:primary_key] 597 null = false 598 end 599 600 case null 601 when false 602 sql << ' NOT NULL' 603 when true 604 sql << ' NULL' 605 end 606 end
Add null/not null SQL fragment to column creation SQL.
Source
# File lib/sequel/database/schema_methods.rb 564 def column_definition_order 565 COLUMN_DEFINITION_ORDER 566 end
The order of the column definition, as an array of symbols.
Source
# File lib/sequel/database/schema_methods.rb 609 def column_definition_primary_key_sql(sql, column) 610 if column[:primary_key] 611 if name = column[:primary_key_constraint_name] 612 sql << " CONSTRAINT #{quote_identifier(name)}" 613 end 614 sql << " " << primary_key_constraint_sql_fragment(column) 615 constraint_deferrable_sql_append(sql, column[:primary_key_deferrable]) 616 end 617 end
Add primary key SQL fragment to column creation SQL.
Source
# File lib/sequel/database/schema_methods.rb 620 def column_definition_references_sql(sql, column) 621 if column[:table] 622 if name = column[:foreign_key_constraint_name] 623 sql << " CONSTRAINT #{quote_identifier(name)}" 624 end 625 sql << column_references_column_constraint_sql(column) 626 end 627 end
Add foreign key reference SQL fragment to column creation SQL.
Source
# File lib/sequel/database/schema_methods.rb 569 def column_definition_sql(column) 570 sql = String.new 571 sql << "#{quote_identifier(column[:name])} #{type_literal(column)}" 572 column_definition_order.each{|m| send(:"column_definition_#{m}_sql", sql, column)} 573 sql 574 end
SQL fragment containing the column creation SQL for the given column.
Source
# File lib/sequel/database/schema_methods.rb 630 def column_definition_unique_sql(sql, column) 631 if column[:unique] 632 if name = column[:unique_constraint_name] 633 sql << " CONSTRAINT #{quote_identifier(name)}" 634 end 635 sql << ' ' << unique_constraint_sql_fragment(column) 636 constraint_deferrable_sql_append(sql, column[:unique_deferrable]) 637 end 638 end
Add unique constraint SQL fragment to column creation SQL.
Source
# File lib/sequel/database/schema_methods.rb 641 def column_list_sql(generator) 642 (generator.columns.map{|c| column_definition_sql(c)} + generator.constraints.map{|c| constraint_definition_sql(c)}).join(', ') 643 end
SQL for all given columns, used inside a CREATE TABLE block.
Source
# File lib/sequel/database/schema_methods.rb 646 def column_references_column_constraint_sql(column) 647 column_references_sql(column) 648 end
SQL fragment for column foreign key references (column constraints)
Source
# File lib/sequel/database/schema_methods.rb 651 def column_references_sql(column) 652 sql = String.new 653 sql << " REFERENCES #{quote_schema_table(column[:table])}" 654 sql << "(#{Array(column[:key]).map{|x| quote_identifier(x)}.join(', ')})" if column[:key] 655 sql << " ON DELETE #{on_delete_clause(column[:on_delete])}" if column[:on_delete] 656 sql << " ON UPDATE #{on_update_clause(column[:on_update])}" if column[:on_update] 657 constraint_deferrable_sql_append(sql, column[:deferrable]) 658 sql 659 end
SQL fragment for column foreign key references
Source
# File lib/sequel/database/schema_methods.rb 662 def column_references_table_constraint_sql(constraint) 663 "FOREIGN KEY #{literal(constraint[:columns])}#{column_references_sql(constraint)}" 664 end
SQL fragment for table foreign key references (table constraints)
Source
# File lib/sequel/database/schema_methods.rb 667 def combinable_alter_table_op?(op) 668 COMBINABLE_ALTER_TABLE_OPS.include?(op[:op]) 669 end
Whether the given alter table operation is combinable.
Source
# File lib/sequel/database/schema_methods.rb 696 def constraint_deferrable_sql_append(sql, defer) 697 case defer 698 when nil 699 when false 700 sql << ' NOT DEFERRABLE' 701 when :immediate 702 sql << ' DEFERRABLE INITIALLY IMMEDIATE' 703 else 704 sql << ' DEFERRABLE INITIALLY DEFERRED' 705 end 706 end
SQL fragment specifying the deferrable constraint attributes.
Source
# File lib/sequel/database/schema_methods.rb 672 def constraint_definition_sql(constraint) 673 sql = String.new 674 sql << "CONSTRAINT #{quote_identifier(constraint[:name])} " if constraint[:name] 675 case constraint[:type] 676 when :check 677 check = constraint[:check] 678 check = check.first if check.is_a?(Array) && check.length == 1 679 check = filter_expr(check) 680 check = "(#{check})" unless check[0..0] == '(' && check[-1..-1] == ')' 681 sql << "CHECK #{check}" 682 when :primary_key 683 sql << "#{primary_key_constraint_sql_fragment(constraint)} #{literal(constraint[:columns])}" 684 when :foreign_key 685 sql << column_references_table_constraint_sql(constraint.merge(:deferrable=>nil)) 686 when :unique 687 sql << "#{unique_constraint_sql_fragment(constraint)} #{literal(constraint[:columns])}" 688 else 689 raise Error, "Invalid constraint type #{constraint[:type]}, should be :check, :primary_key, :foreign_key, or :unique" 690 end 691 constraint_deferrable_sql_append(sql, constraint[:deferrable]) 692 sql 693 end
SQL fragment specifying a constraint on a table.
Source
# File lib/sequel/database/schema_methods.rb 767 def create_table_as(name, sql, options) 768 sql = sql.sql if sql.is_a?(Sequel::Dataset) 769 run(create_table_as_sql(name, sql, options)) 770 end
Run SQL statement to create the table with the given name from the given SELECT sql statement.
Source
# File lib/sequel/database/schema_methods.rb 774 def create_table_as_sql(name, sql, options) 775 "#{create_table_prefix_sql(name, options)} AS #{sql}" 776 end
SQL statement for creating a table from the result of a SELECT statement. sql
should be a string representing a SELECT query.
Source
# File lib/sequel/database/schema_methods.rb 709 def create_table_from_generator(name, generator, options) 710 execute_ddl(create_table_sql(name, generator, options)) 711 end
Execute the create table statements using the generator.
Source
# File lib/sequel/database/schema_methods.rb 714 def create_table_generator_class 715 Schema::CreateTableGenerator 716 end
The class used for create_table
generators.
Source
# File lib/sequel/database/schema_methods.rb 719 def create_table_indexes_from_generator(name, generator, options) 720 e = options[:ignore_index_errors] || options[:if_not_exists] 721 generator.indexes.each do |index| 722 begin 723 transaction(:savepoint=>:only, :skip_transaction=>supports_transactional_ddl? == false) do 724 index_sql_list(name, [index]).each{|sql| execute_ddl(sql)} 725 end 726 rescue Error 727 raise unless e 728 end 729 end 730 end
Execute the create index statements using the generator.
Source
# File lib/sequel/database/schema_methods.rb 779 def create_table_prefix_sql(name, options) 780 "CREATE #{temporary_table_sql if options[:temp]}TABLE#{' IF NOT EXISTS' if options[:if_not_exists]} #{create_table_table_name_sql(name, options)}" 781 end
SQL fragment for initial part of CREATE TABLE statement
Source
# File lib/sequel/database/schema_methods.rb 733 def create_table_sql(name, generator, options) 734 unless supports_named_column_constraints? 735 # Split column constraints into table constraints if they have a name 736 generator.columns.each do |c| 737 if (constraint_name = c.delete(:foreign_key_constraint_name)) && (table = c.delete(:table)) 738 opts = {} 739 opts[:name] = constraint_name 740 [:key, :on_delete, :on_update, :deferrable].each{|k| opts[k] = c[k]} 741 generator.foreign_key([c[:name]], table, opts) 742 end 743 if (constraint_name = c.delete(:unique_constraint_name)) && c.delete(:unique) 744 generator.unique(c[:name], :name=>constraint_name) 745 end 746 if (constraint_name = c.delete(:primary_key_constraint_name)) && c.delete(:primary_key) 747 generator.primary_key([c[:name]], :name=>constraint_name) 748 end 749 end 750 end 751 752 unless can_add_primary_key_constraint_on_nullable_columns? 753 if pk = generator.constraints.find{|op| op[:type] == :primary_key} 754 pk[:columns].each do |column| 755 if matched_column = generator.columns.find{|gc| gc[:name] == column} 756 matched_column[:null] = false 757 end 758 end 759 end 760 end 761 762 "#{create_table_prefix_sql(name, options)} (#{column_list_sql(generator)})" 763 end
SQL statement for creating a table with the given name, columns, and options
Source
# File lib/sequel/database/schema_methods.rb 788 def create_table_table_name_sql(name, options) 789 options[:temp] ? create_table_temp_table_name_sql(name, options) : quote_schema_table(name) 790 end
The SQL to use for a table name when creating a table. Use of the :temp option can result in different SQL, because the rules for temp table naming can differ between databases, and temp tables should not use the default_schema.
Source
# File lib/sequel/database/schema_methods.rb 793 def create_table_temp_table_name_sql(name, _options) 794 name.is_a?(String) ? quote_identifier(name) : literal(name) 795 end
The SQL to use for the table name for a temporary table.
Source
# File lib/sequel/database/schema_methods.rb 798 def create_view_prefix_sql(name, options) 799 create_view_sql_append_columns("CREATE #{'OR REPLACE 'if options[:replace]}VIEW #{quote_schema_table(name)}", options[:columns]) 800 end
SQL fragment for initial part of CREATE VIEW statement
Source
# File lib/sequel/database/schema_methods.rb 803 def create_view_sql(name, source, options) 804 source = source.sql if source.is_a?(Dataset) 805 sql = String.new 806 sql << "#{create_view_prefix_sql(name, options)} AS #{source}" 807 if check = options[:check] 808 sql << " WITH#{' LOCAL' if check == :local} CHECK OPTION" 809 end 810 sql 811 end
SQL statement for creating a view.
Source
# File lib/sequel/database/schema_methods.rb 814 def create_view_sql_append_columns(sql, columns) 815 if columns 816 sql += ' (' 817 schema_utility_dataset.send(:identifier_list_append, sql, columns) 818 sql << ')' 819 end 820 sql 821 end
Append the column list to the SQL, if a column list is given.
Source
# File lib/sequel/database/schema_methods.rb 825 def default_index_name(table_name, columns) 826 schema, table = schema_and_table(table_name) 827 "#{"#{schema}_" if schema}#{table}_#{columns.map{|c| [String, Symbol].any?{|cl| c.is_a?(cl)} ? c : literal(c).gsub(/\W/, '_')}.join('_')}_index" 828 end
Default index name for the table and columns, may be too long for certain databases.
Source
# File lib/sequel/database/schema_methods.rb 838 def drop_index_sql(table, op) 839 "DROP INDEX #{quote_identifier(op[:name] || default_index_name(table, op[:columns]))}" 840 end
The SQL to drop an index for the table.
Source
# File lib/sequel/database/schema_methods.rb 843 def drop_table_sql(name, options) 844 "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}" 845 end
SQL DDL statement to drop the table with the given name.
Source
# File lib/sequel/database/schema_methods.rb 848 def drop_view_sql(name, options) 849 "DROP VIEW#{' IF EXISTS' if options[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}" 850 end
SQL DDL statement to drop a view with the given name.
Source
# File lib/sequel/database/schema_methods.rb 855 def filter_expr(arg=nil, &block) 856 if arg.is_a?(Proc) && !block 857 block = arg 858 arg = nil 859 elsif arg.is_a?(String) 860 arg = Sequel.lit(arg) 861 elsif arg.is_a?(Array) 862 if arg.first.is_a?(String) 863 arg = Sequel.lit(*arg) 864 elsif arg.length > 1 865 arg = Sequel.&(*arg) 866 end 867 end 868 schema_utility_dataset.literal(schema_utility_dataset.send(:filter_expr, arg, &block)) 869 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.
Source
# File lib/sequel/database/schema_methods.rb 831 def foreign_key_name(table_name, columns) 832 keys = foreign_key_list(table_name).select{|key| key[:columns] == columns} 833 raise(Error, "#{keys.empty? ? 'Missing' : 'Ambiguous'} foreign key for #{columns.inspect}") unless keys.size == 1 834 keys.first[:name] 835 end
Get foreign key name for given table and columns.
Source
# File lib/sequel/database/schema_methods.rb 873 def index_definition_sql(table_name, index) 874 index_name = index[:name] || default_index_name(table_name, index[:columns]) 875 raise Error, "Index types are not supported for this database" if index[:type] 876 raise Error, "Partial indexes are not supported for this database" if index[:where] && !supports_partial_indexes? 877 "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]}" 878 end
SQL statement for creating an index for the table with the given name and index specifications.
Source
# File lib/sequel/database/schema_methods.rb 882 def index_sql_list(table_name, indexes) 883 indexes.map{|i| index_definition_sql(table_name, i)} 884 end
Array
of SQL statements, one for each index specification, for the given table.
Source
# File lib/sequel/database/schema_methods.rb 888 def join_table_name(hash, options) 889 entries = hash.values 890 raise Error, "must have 2 entries in hash given to (create|drop)_join_table" unless entries.length == 2 891 if options[:name] 892 options[:name] 893 else 894 table_names = entries.map{|e| join_table_name_extract(e)} 895 table_names.map(&:to_s).sort.join('_') 896 end 897 end
Extract the join table name from the arguments given to create_join_table. Also does argument validation for the create_join_table
method.
Source
# File lib/sequel/database/schema_methods.rb 901 def join_table_name_extract(entry) 902 case entry 903 when Symbol, String 904 entry 905 when Hash 906 join_table_name_extract(entry[:table]) 907 else 908 raise Error, "can't extract table name from #{entry.inspect}" 909 end 910 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.
Source
# File lib/sequel/database/schema_methods.rb 925 def on_delete_clause(action) 926 action.to_s.tr("_", " ").upcase 927 end
SQL fragment to use for ON DELETE, based on the given action. The following actions are recognized:
- :cascade
-
Delete rows referencing this row.
- :no_action
-
Raise an error if other rows reference this row, allow deferring of the integrity check. This is the default.
- :restrict
-
Raise an error if other rows reference this row, but do not allow deferring the integrity check.
- :set_default
-
Set columns referencing this row to their default value.
- :set_null
-
Set columns referencing this row to NULL.
Any other object given is just converted to a string, with “_” converted to “ ” and upcased.
Source
# File lib/sequel/database/schema_methods.rb 930 def on_update_clause(action) 931 on_delete_clause(action) 932 end
Alias of on_delete_clause
, since the two usually behave the same.
Source
Add fragment for primary key specification, separated for easier overridding.
Source
# File lib/sequel/database/schema_methods.rb 940 def quote_schema_table(table) 941 schema_utility_dataset.quote_schema_table(table) 942 end
Proxy the quote_schema_table
method to the dataset
Source
# File lib/sequel/database/schema_methods.rb 945 def rename_table_sql(name, new_name) 946 "ALTER TABLE #{quote_schema_table(name)} RENAME TO #{quote_schema_table(new_name)}" 947 end
SQL statement for renaming a table.
Source
# File lib/sequel/database/schema_methods.rb 950 def schema_and_table(table_name) 951 schema_utility_dataset.schema_and_table(table_name) 952 end
Split the schema information from the table
Source
# File lib/sequel/database/schema_methods.rb 955 def schema_autoincrementing_primary_key?(schema) 956 !!(schema[:primary_key] && schema[:auto_increment]) 957 end
Return true if the given column schema represents an autoincrementing primary key.
Source
# File lib/sequel/database/schema_methods.rb 960 def schema_utility_dataset 961 @default_dataset 962 end
The dataset to use for proxying certain schema methods.
Source
# File lib/sequel/database/schema_methods.rb 965 def split_qualifiers(table_name) 966 schema_utility_dataset.split_qualifiers(table_name) 967 end
Split the schema information from the table
Source
# File lib/sequel/database/schema_methods.rb 970 def temporary_table_sql 971 'TEMPORARY ' 972 end
SQL fragment for temporary table
Source
# File lib/sequel/database/schema_methods.rb 975 def type_literal(column) 976 case column[:type] 977 when Class 978 type_literal_generic(column) 979 when :Bignum 980 type_literal_generic_bignum_symbol(column) 981 else 982 type_literal_specific(column) 983 end 984 end
SQL fragment specifying the type of a given column.
Source
# File lib/sequel/database/schema_methods.rb 988 def type_literal_generic(column) 989 meth = "type_literal_generic_#{column[:type].name.to_s.downcase}" 990 if respond_to?(meth, true) 991 # Allow calling private methods as per type literal generic methods are private 992 send(meth, column) 993 else 994 raise Error, "Unsupported ruby class used as database type: #{column[:type]}" 995 end 996 end
SQL fragment specifying the full type of a column, consider the type with possible modifiers.
Source
# File lib/sequel/database/schema_methods.rb 999 def type_literal_generic_bigdecimal(column) 1000 type_literal_generic_numeric(column) 1001 end
Alias for type_literal_generic_numeric
, to make overriding in a subclass easier.
Source
# File lib/sequel/database/schema_methods.rb 1004 def type_literal_generic_bignum_symbol(column) 1005 :bigint 1006 end
Sequel
uses the bigint type by default for :Bignum symbol.
Source
# File lib/sequel/database/schema_methods.rb 1009 def type_literal_generic_date(column) 1010 :date 1011 end
Sequel
uses the date type by default for Dates.
Source
# File lib/sequel/database/schema_methods.rb 1014 def type_literal_generic_datetime(column) 1015 :timestamp 1016 end
Sequel
uses the timestamp type by default for DateTimes.
Source
# File lib/sequel/database/schema_methods.rb 1019 def type_literal_generic_falseclass(column) 1020 type_literal_generic_trueclass(column) 1021 end
Alias for type_literal_generic_trueclass
, to make overriding in a subclass easier.
Source
# File lib/sequel/database/schema_methods.rb 1024 def type_literal_generic_file(column) 1025 :blob 1026 end
Sequel
uses the blob type by default for Files.
Source
# File lib/sequel/database/schema_methods.rb 1029 def type_literal_generic_fixnum(column) 1030 type_literal_generic_integer(column) 1031 end
Alias for type_literal_generic_integer
, to make overriding in a subclass easier.
Source
# File lib/sequel/database/schema_methods.rb 1034 def type_literal_generic_float(column) 1035 :"double precision" 1036 end
Sequel
uses the double precision type by default for Floats.
Source
# File lib/sequel/database/schema_methods.rb 1039 def type_literal_generic_integer(column) 1040 :integer 1041 end
Sequel
uses the integer type by default for integers
Source
# File lib/sequel/database/schema_methods.rb 1046 def type_literal_generic_numeric(column) 1047 column[:size] ? "numeric(#{Array(column[:size]).join(', ')})" : :numeric 1048 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.
Source
# File lib/sequel/database/schema_methods.rb 1075 def type_literal_generic_only_time(column) 1076 :time 1077 end
Use time by default for Time values if :only_time option is used.
Source
# File lib/sequel/database/schema_methods.rb 1054 def type_literal_generic_string(column) 1055 if column[:text] 1056 uses_clob_for_text? ? :clob : :text 1057 elsif column[:fixed] 1058 "char(#{column[:size]||default_string_column_size})" 1059 else 1060 "varchar(#{column[:size]||default_string_column_size})" 1061 end 1062 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.
Source
# File lib/sequel/database/schema_methods.rb 1066 def type_literal_generic_time(column) 1067 if column[:only_time] 1068 type_literal_generic_only_time(column) 1069 else 1070 type_literal_generic_datetime(column) 1071 end 1072 end
Sequel
uses the timestamp type by default for Time values. If the :only_time option is used, the time type is used.
Source
# File lib/sequel/database/schema_methods.rb 1080 def type_literal_generic_trueclass(column) 1081 :boolean 1082 end
Sequel
uses the boolean type by default for TrueClass
and FalseClass
.
Source
# File lib/sequel/database/schema_methods.rb 1086 def type_literal_specific(column) 1087 type = column[:type] 1088 type = "double precision" if type.to_s == 'double' 1089 column[:size] ||= default_string_column_size if type.to_s == 'varchar' 1090 elements = column[:size] || column[:elements] 1091 "#{type}#{literal(Array(elements)) if elements}#{' UNSIGNED' if column[:unsigned]}" 1092 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.
Source
# File lib/sequel/database/schema_methods.rb 1095 def unique_constraint_sql_fragment(_) 1096 'UNIQUE' 1097 end
Add fragment for unique specification, separated for easier overridding.
Source
# File lib/sequel/database/schema_methods.rb 1100 def uses_clob_for_text? 1101 false 1102 end
Whether clob should be used for String
text: true columns.
3 - Methods that create datasets
↑ topPublic Instance Methods
Source
# File lib/sequel/database/dataset.rb 21 def [](*args) 22 args.first.is_a?(String) ? fetch(*args) : from(*args) 23 end
Returns a dataset for the database. If the first argument is a string, the method acts as an alias for Database#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 Database#from
, setting the primary table for the dataset:
DB[:items].sql #=> "SELECT * FROM items"
Source
# File lib/sequel/database/dataset.rb 29 def dataset 30 @dataset_class.new(self) 31 end
Returns a blank dataset for this database.
DB.dataset # SELECT * DB.dataset.from(:items) # SELECT * FROM items
Source
# File lib/sequel/database/dataset.rb 59 def fetch(sql, *args, &block) 60 ds = @default_dataset.with_sql(sql, *args) 61 ds.each(&block) if block 62 ds 63 end
Returns a dataset instance for the given SQL string:
ds = DB.fetch('SELECT * FROM items')
You can then call methods on the dataset to retrieve results:
ds.all # SELECT * FROM items # => [{:column=>value, ...}, ...]
If a block is given, it is passed to each on the resulting dataset to iterate over the records returned by the query:
DB.fetch('SELECT * FROM items'){|r| p r} # {:column=>value, ...} # ...
fetch
can also perform parameterized queries for protection against SQL injection:
ds = DB.fetch('SELECT * FROM items WHERE name = ?', "my name") ds.all # SELECT * FROM items WHERE name = 'my name'
See caveats listed in Dataset#with_sql regarding datasets using custom SQL and the methods that can be called on them.
Source
# File lib/sequel/database/dataset.rb 70 def from(*args, &block) 71 if block 72 @default_dataset.from(*args, &block) 73 elsif args.length == 1 && (table = args[0]).is_a?(Symbol) 74 @default_dataset.send(:cached_dataset, :"_from_#{table}_ds"){@default_dataset.from(table)} 75 else 76 @default_dataset.from(*args) 77 end 78 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
Source
# File lib/sequel/database/dataset.rb 85 def select(*args, &block) 86 @default_dataset.select(*args, &block) 87 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
4 - Methods relating to adapters, connecting, disconnecting, and sharding
↑ topConstants
- ADAPTERS
-
Array
of supported database adapters
Attributes
Public Class Methods
Source
# File lib/sequel/database/connecting.rb 16 def self.adapter_class(scheme) 17 scheme.is_a?(Class) ? scheme : load_adapter(scheme.to_sym) 18 end
The Database
subclass for the given adapter scheme. Raises Sequel::AdapterNotFound if the adapter could not be loaded.
Source
# File lib/sequel/database/connecting.rb 21 def self.adapter_scheme 22 @scheme 23 end
Returns the scheme symbol for the Database
class.
Source
# File lib/sequel/database/connecting.rb 26 def self.connect(conn_string, opts = OPTS) 27 case conn_string 28 when String 29 if conn_string.start_with?('jdbc:') 30 c = adapter_class(:jdbc) 31 opts = opts.merge(:orig_opts=>opts.dup) 32 opts = {:uri=>conn_string}.merge!(opts) 33 else 34 uri = URI.parse(conn_string) 35 scheme = uri.scheme 36 c = adapter_class(scheme) 37 opts = c.send(:options_from_uri, uri).merge!(opts).merge!(:orig_opts=>opts.dup, :uri=>conn_string, :adapter=>scheme) 38 end 39 when Hash 40 opts = conn_string.merge(opts) 41 opts = opts.merge(:orig_opts=>opts.dup) 42 c = adapter_class(opts[:adapter_class] || opts[:adapter] || opts['adapter']) 43 else 44 raise Error, "Sequel::Database.connect takes either a Hash or a String, given: #{conn_string.inspect}" 45 end 46 47 opts = opts.inject({}) do |m, (k,v)| 48 k = :user if k.to_s == 'username' 49 m[k.to_sym] = v 50 m 51 end 52 53 begin 54 db = c.new(opts) 55 if defined?(yield) 56 return yield(db) 57 end 58 ensure 59 if defined?(yield) 60 db.disconnect if db 61 Sequel.synchronize{::Sequel::DATABASES.delete(db)} 62 end 63 end 64 db 65 end
Connects to a database. See Sequel.connect.
Source
# File lib/sequel/database/connecting.rb 73 def self.load_adapter(scheme, opts=OPTS) 74 map = opts[:map] || ADAPTER_MAP 75 if subdir = opts[:subdir] 76 file = "#{subdir}/#{scheme}" 77 else 78 file = scheme 79 end 80 81 unless obj = Sequel.synchronize{map[scheme]} 82 # attempt to load the adapter file 83 begin 84 require "sequel/adapters/#{file}" 85 rescue LoadError => e 86 # If subadapter file doesn't exist, just return, 87 # using the main adapter class without database customizations. 88 return if subdir 89 raise Sequel.convert_exception_class(e, AdapterNotFound) 90 end 91 92 # make sure we actually loaded the adapter 93 unless obj = Sequel.synchronize{map[scheme]} 94 raise AdapterNotFound, "Could not load #{file} adapter: adapter class not registered in ADAPTER_MAP" 95 end 96 end 97 98 obj 99 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:
- :map
-
The
Hash
in which to look for an already loaded adapter (defaults to ADAPTER_MAP). - :subdir
-
The subdirectory of sequel/adapters to look in, only to be used for loading subadapters.
Public Instance Methods
Source
# File lib/sequel/database/connecting.rb 158 def adapter_scheme 159 self.class.adapter_scheme 160 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
Source
# File lib/sequel/database/connecting.rb 170 def add_servers(servers) 171 unless sharded? 172 raise Error, "cannot call Database#add_servers on a Database instance that does not use a sharded connection pool" 173 end 174 175 h = @opts[:servers] 176 Sequel.synchronize{h.merge!(servers)} 177 @pool.add_servers(servers.keys) 178 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"})
Source
# File lib/sequel/database/connecting.rb 189 def database_type 190 adapter_scheme 191 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
Source
# File lib/sequel/database/connecting.rb 203 def disconnect(opts = OPTS) 204 pool.disconnect(opts) 205 end
Disconnects all available connections from the connection pool. Any connections currently in use will not be disconnected. Options:
- :server
-
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
Source
# File lib/sequel/database/connecting.rb 210 def disconnect_connection(conn) 211 conn.close 212 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.
Source
# File lib/sequel/database/connecting.rb 244 def new_connection(server) 245 conn = connect(server) 246 opts = server_opts(server) 247 248 if ac = opts[:after_connect] 249 if ac.arity == 2 250 ac.call(conn, server) 251 else 252 ac.call(conn) 253 end 254 end 255 256 if cs = opts[:connect_sqls] 257 cs.each do |sql| 258 log_connection_execute(conn, sql) 259 end 260 end 261 262 conn 263 end
Connect to the given server/shard. Handles database-generic post-connection setup not handled by connect, using the :after_connect and :connect_sqls options.
Source
# File lib/sequel/database/connecting.rb 223 def remove_servers(*servers) 224 unless sharded? 225 raise Error, "cannot call Database#remove_servers on a Database instance that does not use a sharded connection pool" 226 end 227 228 h = @opts[:servers] 229 servers.flatten.each{|s| Sequel.synchronize{h.delete(s)}} 230 @pool.remove_servers(servers) 231 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)
Source
# File lib/sequel/database/connecting.rb 237 def servers 238 pool.servers 239 end
An array of servers/shards for this Database
object.
DB.servers # Unsharded: => [:default] DB.servers # Sharded: => [:default, :server1, :server2]
Source
# File lib/sequel/database/connecting.rb 266 def single_threaded? 267 @single_threaded 268 end
Returns true if the database is using a single-threaded connection pool.
Source
# File lib/sequel/database/connecting.rb 282 def synchronize(server=nil, &block) 283 @pool.hold(server || :default, &block) 284 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
Source
# File lib/sequel/database/connecting.rb 290 def test_connection(server=nil) 291 synchronize(server){|conn|} 292 true 293 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.
Source
# File lib/sequel/database/connecting.rb 299 def valid_connection?(conn) 300 sql = valid_connection_sql 301 begin 302 log_connection_execute(conn, sql) 303 rescue Sequel::DatabaseError, *database_error_classes 304 false 305 else 306 true 307 end 308 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.
Private Instance Methods
Source
# File lib/sequel/database/connecting.rb 313 def connection_pool_default_options 314 {} 315 end
The default options for the connection pool.
Source
# File lib/sequel/database/connecting.rb 320 def server_opts(server) 321 opts = if @opts[:servers] and server_options = @opts[:servers][server] 322 case server_options 323 when Hash 324 @opts.merge(server_options) 325 when Proc 326 @opts.merge(server_options.call(self)) 327 else 328 raise Error, 'Server opts should be a hash or proc' 329 end 330 elsif server.is_a?(Hash) 331 @opts.merge(server) 332 else 333 @opts.dup 334 end 335 336 if pr = opts[:connect_opts_proc] 337 pr.call(opts) 338 end 339 340 opts.delete(:servers) 341 opts 342 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.
Source
# File lib/sequel/database/connecting.rb 345 def valid_connection_sql 346 @valid_connection_sql ||= select(nil).sql 347 end
The SQL query to issue to check if a connection is valid.
5 - Methods that set defaults for created datasets
↑ topAttributes
The class to use for creating datasets. Should respond to new with the Database
argument as the first argument, and an optional options hash.
Public Instance Methods
Source
# File lib/sequel/database/dataset_defaults.rb 18 def dataset_class=(c) 19 unless @dataset_modules.empty? 20 c = Sequel.set_temp_name(Class.new(c)){"Sequel::Dataset::_Subclass"} 21 @dataset_modules.each{|m| c.send(:include, m)} 22 end 23 @dataset_class = c 24 reset_default_dataset 25 end
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.
Source
# File lib/sequel/database/dataset_defaults.rb 62 def extend_datasets(mod=nil, &block) 63 raise(Error, "must provide either mod or block, not both") if mod && block 64 mod = Sequel.set_temp_name(Dataset::DatasetModule.new(&block)){"Sequel::Dataset::_DatasetModule(#{block.source_location.join(':')})"} if block 65 if @dataset_modules.empty? 66 @dataset_modules = [mod] 67 @dataset_class = Sequel.set_temp_name(Class.new(@dataset_class)){"Sequel::Dataset::_Subclass"} 68 else 69 @dataset_modules << mod 70 end 71 @dataset_class.send(:include, mod) 72 reset_default_dataset 73 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
Private Instance Methods
Source
# File lib/sequel/database/dataset_defaults.rb 78 def dataset_class_default 79 Sequel::Dataset 80 end
The default dataset class to use for the database
Source
# File lib/sequel/database/dataset_defaults.rb 89 def quote_identifiers_default 90 true 91 end
Whether to quote identifiers by default for this database, true by default.
Source
# File lib/sequel/database/dataset_defaults.rb 83 def reset_default_dataset 84 Sequel.synchronize{@symbol_literal_cache.clear} 85 @default_dataset = dataset 86 end
Reset the default dataset used by most Database
methods that create datasets.
6 - Methods relating to logging
↑ topAttributes
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.
Array
of SQL loggers to use for this database.
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.
Public Instance Methods
Source
# File lib/sequel/database/logging.rb 37 def log_connection_yield(sql, conn, args=nil) 38 return yield if skip_logging? 39 sql = "#{connection_info(conn) if conn && log_connection_info}#{sql}#{"; #{args.inspect}" if args}" 40 timer = Sequel.start_timer 41 42 begin 43 yield 44 rescue => e 45 log_exception(e, sql) 46 raise 47 ensure 48 log_duration(Sequel.elapsed_seconds_since(timer), sql) unless e 49 end 50 end
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.
Source
# File lib/sequel/database/logging.rb 26 def log_exception(exception, message) 27 log_each(:error, "#{exception.class}: #{exception.message.strip if exception.message}: #{message}") 28 end
Log a message at error level, with information about the exception.
Source
# File lib/sequel/database/logging.rb 31 def log_info(message, args=nil) 32 log_each(:info, args ? "#{message}; #{args.inspect}" : message) 33 end
Log a message at level info to all loggers.
Source
# File lib/sequel/database/logging.rb 55 def logger=(logger) 56 @loggers = Array(logger) 57 end
Remove any existing loggers and just use the given logger:
DB.logger = Logger.new($stdout)
Private Instance Methods
Source
# File lib/sequel/database/logging.rb 69 def connection_info(conn) 70 "(conn: #{conn.__id__}) " 71 end
String
including information about the connection, for use when logging connection info.
Source
# File lib/sequel/database/logging.rb 75 def log_connection_execute(conn, sql) 76 log_connection_yield(sql, conn){conn.public_send(connection_execute_method, sql)} 77 end
Log the given SQL and then execute it on the connection, used by the transaction code.
Source
# File lib/sequel/database/logging.rb 81 def log_duration(duration, message) 82 log_each((lwd = log_warn_duration and duration >= lwd) ? :warn : sql_log_level, "(#{sprintf('%0.6fs', duration)}) #{message}") 83 end
Log message with message prefixed by duration at info level, or warn level if duration is greater than log_warn_duration.
Source
# File lib/sequel/database/logging.rb 87 def log_each(level, message) 88 @loggers.each{|logger| logger.public_send(level, message)} 89 end
Log message at level (which should be :error, :warn, or :info) to all loggers.
Source
# File lib/sequel/database/logging.rb 63 def skip_logging? 64 @loggers.empty? 65 end
Determine if logging should be skipped. Defaults to true if no loggers have been specified.
7 - Miscellaneous methods
↑ topConstants
- CHECK_CONSTRAINT_SQLSTATES
- DEFAULT_DATABASE_ERROR_REGEXPS
-
Empty exception regexp to class map, used by default if
Sequel
doesn’t have specific support for the database in use. - DEFAULT_STRING_COLUMN_SIZE
-
The general default size for string columns for all
Sequel::Database
instances. - EXTENSIONS
-
Hash
of extension name symbols to callable objects to load the extension into theDatabase
object (usually by extending it with a module defined in the extension). - FOREIGN_KEY_CONSTRAINT_SQLSTATES
- NOT_NULL_CONSTRAINT_SQLSTATES
- SCHEMA_TYPE_CLASSES
-
Mapping of schema type symbols to class or arrays of classes for that symbol.
- SERIALIZATION_CONSTRAINT_SQLSTATES
- UNIQUE_CONSTRAINT_SQLSTATES
- URI_PARSER
-
:nocov:
Attributes
Whether to check the bytesize of strings before typecasting (to avoid typecasting strings that would be too long for the given type), true by default. Strings that are too long will raise a typecasting error.
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
.
Public Class Methods
Source
# File lib/sequel/database/misc.rb 39 def self.after_initialize(&block) 40 raise Error, "must provide block to after_initialize" unless block 41 Sequel.synchronize do 42 previous = @initialize_hook 43 @initialize_hook = proc do |db| 44 previous.call(db) 45 block.call(db) 46 end 47 end 48 end
Register a hook that will be run when a new Database
is instantiated. It is called with the new database handle.
Source
# File lib/sequel/database/misc.rb 51 def self.extension(*extensions) 52 after_initialize{|db| db.extension(*extensions)} 53 end
Apply an extension to all Database
objects created in the future.
Source
# File lib/sequel/database/misc.rb 158 def initialize(opts = OPTS) 159 @opts ||= opts 160 @opts = connection_pool_default_options.merge(@opts) 161 @loggers = Array(@opts[:logger]) + Array(@opts[:loggers]) 162 @opts[:servers] = {} if @opts[:servers].is_a?(String) 163 @sharded = !!@opts[:servers] 164 @opts[:adapter_class] = self.class 165 @opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, Sequel.single_threaded)) 166 @default_string_column_size = @opts[:default_string_column_size] || DEFAULT_STRING_COLUMN_SIZE 167 @check_string_typecast_bytesize = typecast_value_boolean(@opts.fetch(:check_string_typecast_bytesize, true)) 168 169 @schemas = {} 170 @prepared_statements = {} 171 @transactions = {} 172 @transactions.compare_by_identity if typecast_value_boolean(@opts.fetch(:compare_connections_by_identity, true)) 173 @symbol_literal_cache = {} 174 175 @timezone = nil 176 177 @dataset_class = dataset_class_default 178 @cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true)) 179 @dataset_modules = [] 180 @loaded_extensions = [] 181 @schema_type_classes = SCHEMA_TYPE_CLASSES.dup 182 183 self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info 184 self.log_warn_duration = @opts[:log_warn_duration] 185 self.log_connection_info = typecast_value_boolean(@opts[:log_connection_info]) 186 187 @pool = ConnectionPool.get_pool(self, @opts) 188 189 reset_default_dataset 190 adapter_initialize 191 192 keep_reference = typecast_value_boolean(@opts[:keep_reference]) != false 193 begin 194 Sequel.synchronize{::Sequel::DATABASES.push(self)} if keep_reference 195 Sequel::Database.run_after_initialize(self) 196 197 initialize_load_extensions(:preconnect_extensions) 198 199 if before_preconnect = @opts[:before_preconnect] 200 before_preconnect.call(self) 201 end 202 203 if typecast_value_boolean(@opts[:preconnect]) && @pool.respond_to?(:preconnect, true) 204 concurrent = typecast_value_string(@opts[:preconnect]) == "concurrently" 205 @pool.send(:preconnect, concurrent) 206 end 207 208 initialize_load_extensions(:extensions) 209 test_connection if typecast_value_boolean(@opts.fetch(:test, true)) && respond_to?(:connect, true) 210 rescue 211 Sequel.synchronize{::Sequel::DATABASES.delete(self)} if keep_reference 212 raise 213 end 214 end
Constructs a new instance of a database connection with the specified options hash.
Accepts the following options:
- :after_connect
-
A callable object called after each new connection is made, with the connection object (and server argument if the callable accepts 2 arguments), useful for customizations that you want to apply to all connections.
- :compare_connections_by_identity
-
Whether to use compare_by_identity on hashes that use connection objects as keys. Defaults to true. This should only be set to false to work around bugs in libraries or ruby implementations.
- :before_preconnect
-
Callable that runs after extensions from :preconnect_extensions are loaded, but before any connections are created.
- :cache_schema
-
Whether schema should be cached for this
Database
instance - :check_string_typecast_bytesize
-
Whether to check the bytesize of strings before typecasting.
- :connect_sqls
-
An array of sql strings to execute on each new connection, after :after_connect runs.
- :connect_opts_proc
-
Callable object for modifying options hash used when connecting, designed for cases where the option values (e.g. password) are automatically rotated on a regular basis without involvement from the application using
Sequel
. - :default_string_column_size
-
The default size of string columns, 255 by default.
- :extensions
-
Extensions to load into this
Database
instance. Can be a symbol, array of symbols, or string with extensions separated by columns. These extensions are loaded after connections are made by the :preconnect option. - :keep_reference
-
Whether to keep a reference to this instance in Sequel::DATABASES, true by default.
- :logger
-
A specific logger to use.
- :loggers
-
An array of loggers to use.
- :log_connection_info
-
Whether connection information should be logged when logging queries.
- :log_warn_duration
-
The number of elapsed seconds after which queries should be logged at warn level.
- :name
-
A name to use for the
Database
object, displayed in PoolTimeout. - :preconnect
-
Automatically create the maximum number of connections, so that they don’t need to be created as needed. This is useful when connecting takes a long time and you want to avoid possible latency during runtime. Set to :concurrently to create the connections in separate threads. Otherwise they’ll be created sequentially.
- :preconnect_extensions
-
Similar to the :extensions option, but loads the extensions before the connections are made by the :preconnect option.
- :quote_identifiers
-
Whether to quote identifiers.
- :servers
-
A hash specifying a server/shard specific options, keyed by shard symbol.
- :single_threaded
-
Whether to use a single-threaded connection pool.
- :sql_log_level
-
Method to use to log SQL to a logger, :info by default.
For sharded connection pools, :after_connect and :connect_sqls can be specified per-shard.
All options given are also passed to the connection pool. Additional options respected by the connection pool are :max_connections, :pool_timeout, :servers, and :servers_hash. See the connection pool documentation for details.
Source
# File lib/sequel/database/misc.rb 60 def self.register_extension(ext, mod=nil, &block) 61 if mod 62 raise(Error, "cannot provide both mod and block to Database.register_extension") if block 63 if mod.is_a?(Module) 64 block = proc{|db| db.extend(mod)} 65 else 66 block = mod 67 end 68 end 69 Sequel.synchronize{EXTENSIONS[ext] = block} 70 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.
Source
# File lib/sequel/database/misc.rb 73 def self.run_after_initialize(instance) 74 @initialize_hook.call(instance) 75 end
Run the after_initialize
hook for the given instance
.
Private Class Methods
Source
# File lib/sequel/database/misc.rb 90 def self.options_from_uri(uri) 91 uri_options = uri_to_options(uri) 92 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? 93 uri_options.to_a.each{|k,v| uri_options[k] = URI_PARSER.unescape(v) if v.is_a?(String)} 94 uri_options 95 end
Source
# File lib/sequel/database/misc.rb 79 def self.uri_to_options(uri) 80 { 81 :user => uri.user, 82 :password => uri.password, 83 :port => uri.port, 84 :host => uri.hostname, 85 :database => (m = /\/(.*)/.match(uri.path)) && (m[1]) 86 } 87 end
Converts a uri to an options hash. These options are then passed to a newly created database object.
Public Instance Methods
Source
# File lib/sequel/database/misc.rb 243 def cast_type_literal(type) 244 type_literal(:type=>type) 245 end
Cast the given type to a literal type
DB.cast_type_literal(Float) # double precision DB.cast_type_literal(:foo) # foo
Source
# File lib/sequel/database/misc.rb 252 def extension(*exts) 253 exts.each do |ext| 254 unless pr = Sequel.synchronize{EXTENSIONS[ext]} 255 Sequel.extension(ext) 256 pr = Sequel.synchronize{EXTENSIONS[ext]} 257 end 258 259 if pr 260 if Sequel.synchronize{@loaded_extensions.include?(ext) ? false : (@loaded_extensions << ext)} 261 pr.call(self) 262 end 263 else 264 raise(Error, "Extension #{ext} does not have specific support handling individual databases (try: Sequel.extension #{ext.inspect})") 265 end 266 end 267 self 268 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.
Source
# File lib/sequel/database/misc.rb 217 def freeze 218 valid_connection_sql 219 metadata_dataset 220 @opts.freeze 221 @loggers.freeze 222 @pool.freeze 223 @dataset_class.freeze 224 @dataset_modules.freeze 225 @schema_type_classes.freeze 226 @loaded_extensions.freeze 227 metadata_dataset 228 super 229 end
Freeze internal data structures for the Database
instance.
Source
# File lib/sequel/database/misc.rb 273 def from_application_timestamp(v) 274 Sequel.convert_output_timestamp(v, timezone) 275 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.
Source
# File lib/sequel/database/misc.rb 279 def inspect 280 s = String.new 281 s << "#<#{self.class}" 282 s << " database_type=#{database_type}" if database_type && database_type != adapter_scheme 283 284 keys = [:host, :database, :user] 285 opts = self.opts 286 if !keys.any?{|k| opts[k]} && opts[:uri] 287 opts = self.class.send(:options_from_uri, URI.parse(opts[:uri])) 288 end 289 290 keys.each do |key| 291 val = opts[key] 292 if val && val != '' 293 s << " #{key}=#{val}" 294 end 295 end 296 297 s << ">" 298 end
Returns a string representation of the Database
object, including the database type, host, database, and user, if present.
Source
# File lib/sequel/database/misc.rb 305 def literal(v) 306 schema_utility_dataset.literal(v) 307 end
Proxy the literal call to the dataset.
DB.literal(1) # 1 DB.literal(:a) # "a" # or `a`, [a], or a, depending on identifier quoting DB.literal("a") # 'a'
Source
# File lib/sequel/database/misc.rb 311 def literal_symbol(sym) 312 Sequel.synchronize{@symbol_literal_cache[sym]} 313 end
Return the literalized version of the symbol if cached, or nil if it is not cached.
Source
# File lib/sequel/database/misc.rb 316 def literal_symbol_set(sym, lit) 317 Sequel.synchronize{@symbol_literal_cache[sym] = lit} 318 end
Set the cached value of the literal symbol.
Source
# File lib/sequel/database/misc.rb 321 def prepared_statement(name) 322 Sequel.synchronize{prepared_statements[name]} 323 end
Synchronize access to the prepared statements cache.
Source
# File lib/sequel/database/misc.rb 328 def quote_identifier(v) 329 schema_utility_dataset.quote_identifier(v) 330 end
Proxy the quote_identifier
method to the dataset, useful for quoting unqualified identifiers for use outside of datasets.
Source
# File lib/sequel/database/misc.rb 333 def schema_type_class(type) 334 @schema_type_classes[type] 335 end
Return ruby class or array of classes for the given type symbol.
Source
# File lib/sequel/database/misc.rb 338 def serial_primary_key_options 339 {:primary_key => true, :type => Integer, :auto_increment => true} 340 end
Default serial primary key options, used by the table creation code.
Source
# File lib/sequel/database/misc.rb 343 def set_prepared_statement(name, ps) 344 Sequel.synchronize{prepared_statements[name] = ps} 345 end
Cache the prepared statement object at the given name.
Source
# File lib/sequel/database/misc.rb 349 def sharded? 350 @sharded 351 end
Whether this database instance uses multiple servers, either for sharding or for primary/replica configurations.
Source
# File lib/sequel/database/misc.rb 354 def timezone 355 @timezone || Sequel.database_timezone 356 end
The timezone to use for this database, defaulting to Sequel.database_timezone
.
Source
# File lib/sequel/database/misc.rb 361 def to_application_timestamp(v) 362 Sequel.convert_timestamp(v, timezone) 363 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.
Source
# File lib/sequel/database/misc.rb 370 def typecast_value(column_type, value) 371 return nil if value.nil? 372 meth = "typecast_value_#{column_type}" 373 begin 374 # Allow calling private methods as per-type typecasting methods are private 375 respond_to?(meth, true) ? send(meth, value) : value 376 rescue ArgumentError, TypeError => e 377 raise Sequel.convert_exception_class(e, InvalidValue) 378 end 379 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.
Source
# File lib/sequel/database/misc.rb 383 def uri 384 opts[:uri] 385 end
Returns the URI use to connect to the database. If a URI was not used when connecting, returns nil.
Source
# File lib/sequel/database/misc.rb 388 def url 389 uri 390 end
Explicit alias of uri for easier subclassing.
Private Instance Methods
Source
# File lib/sequel/database/misc.rb 584 def _typecast_value_string_to_decimal(value) 585 d = BigDecimal(value) 586 if d.zero? 587 # BigDecimal parsing is loose by default, returning a 0 value for 588 # invalid input. If a zero value is received, use Float to check 589 # for validity. 590 begin 591 Float(value) 592 rescue ArgumentError 593 raise InvalidValue, "invalid value for BigDecimal: #{value.inspect}" 594 end 595 end 596 d 597 end
:nocov:
Source
# File lib/sequel/database/misc.rb 395 def adapter_initialize 396 end
Per adapter initialization method, empty by default.
Source
# File lib/sequel/database/misc.rb 402 def blank_object?(obj) 403 return obj.blank? if obj.respond_to?(:blank?) 404 case obj 405 when NilClass, FalseClass 406 true 407 when Numeric, TrueClass 408 false 409 when String 410 obj.strip.empty? 411 else 412 obj.respond_to?(:empty?) ? obj.empty? : false 413 end 414 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?
Source
# File lib/sequel/database/misc.rb 425 def database_error_class(exception, opts) 426 database_specific_error_class(exception, opts) || DatabaseError 427 end
Return the Sequel::DatabaseError
subclass to wrap the given exception in.
Source
# File lib/sequel/database/misc.rb 419 def database_error_regexps 420 DEFAULT_DATABASE_ERROR_REGEXPS 421 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.
Source
# File lib/sequel/database/misc.rb 430 def database_exception_sqlstate(exception, opts) 431 nil 432 end
Return the SQLState for the given exception, if one can be determined
Source
# File lib/sequel/database/misc.rb 437 def database_specific_error_class(exception, opts) 438 return DatabaseDisconnectError if disconnect_error?(exception, opts) 439 440 if sqlstate = database_exception_sqlstate(exception, opts) 441 if klass = database_specific_error_class_from_sqlstate(sqlstate) 442 return klass 443 end 444 else 445 database_error_regexps.each do |regexp, klss| 446 return klss if exception.message =~ regexp 447 end 448 end 449 450 nil 451 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.
Source
# File lib/sequel/database/misc.rb 459 def database_specific_error_class_from_sqlstate(sqlstate) 460 case sqlstate 461 when *NOT_NULL_CONSTRAINT_SQLSTATES 462 NotNullConstraintViolation 463 when *FOREIGN_KEY_CONSTRAINT_SQLSTATES 464 ForeignKeyConstraintViolation 465 when *UNIQUE_CONSTRAINT_SQLSTATES 466 UniqueConstraintViolation 467 when *CHECK_CONSTRAINT_SQLSTATES 468 CheckConstraintViolation 469 when *SERIALIZATION_CONSTRAINT_SQLSTATES 470 SerializationFailure 471 end 472 end
Given the SQLState, return the appropriate DatabaseError subclass.
Source
# File lib/sequel/database/misc.rb 475 def disconnect_error?(exception, opts) 476 opts[:disconnect] 477 end
Return true if exception represents a disconnect error, false otherwise.
Source
# File lib/sequel/database/misc.rb 480 def initialize_load_extensions(key) 481 case exts = @opts[key] 482 when String 483 extension(*exts.split(',').map(&:to_sym)) 484 when Array 485 extension(*exts) 486 when Symbol 487 extension(exts) 488 when nil 489 # nothing 490 else 491 raise Error, "unsupported Database #{key.inspect} option: #{@opts[key].inspect}" 492 end 493 end
Load extensions during initialization from the given key in opts.
Source
# File lib/sequel/database/misc.rb 497 def raise_error(exception, opts=OPTS) 498 if !opts[:classes] || Array(opts[:classes]).any?{|c| exception.is_a?(c)} 499 raise Sequel.convert_exception_class(exception, database_error_class(exception, opts)) 500 else 501 raise exception 502 end 503 end
Convert the given exception to an appropriate Sequel::DatabaseError
subclass, keeping message and backtrace.
Source
# File lib/sequel/database/misc.rb 506 def swallow_database_error 507 yield 508 rescue Sequel::DatabaseDisconnectError, DatabaseConnectionError 509 # Always raise disconnect errors 510 raise 511 rescue Sequel::DatabaseError 512 # Don't raise other database errors. 513 nil 514 # else 515 # Don't rescue other exceptions, they will be raised normally. 516 end
Swallow database errors, unless they are connect/disconnect errors.
Source
# File lib/sequel/database/misc.rb 528 def typecast_check_length(value, max_size) 529 typecast_check_string_length(value, max_size) if String === value 530 value 531 end
Check the bytesize of the string value, if value is a string.
Source
# File lib/sequel/database/misc.rb 520 def typecast_check_string_length(string, max_size) 521 if @check_string_typecast_bytesize && string.bytesize > max_size 522 raise InvalidValue, "string too long to typecast (bytesize: #{string.bytesize}, max: #{max_size})" 523 end 524 string 525 end
Check the bytesize of a string before conversion. There is no point trying to typecast strings that would be way too long.
Source
# File lib/sequel/database/misc.rb 534 def typecast_value_blob(value) 535 value.is_a?(Sequel::SQL::Blob) ? value : Sequel::SQL::Blob.new(value) 536 end
Typecast the value to an SQL::Blob
Source
# File lib/sequel/database/misc.rb 539 def typecast_value_boolean(value) 540 case value 541 when false, 0, "0", /\Af(alse)?\z/i, /\Ano?\z/i 542 false 543 else 544 blank_object?(value) ? nil : true 545 end 546 end
Typecast the value to true, false, or nil
Source
# File lib/sequel/database/misc.rb 549 def typecast_value_date(value) 550 case value 551 when DateTime, Time 552 Date.new(value.year, value.month, value.day) 553 when Date 554 value 555 when String 556 Sequel.string_to_date(typecast_check_string_length(value, 100)) 557 when Hash 558 Date.new(*[:year, :month, :day].map{|x| typecast_check_length(value[x] || value[x.to_s], 100).to_i}) 559 else 560 raise InvalidValue, "invalid value for Date: #{value.inspect}" 561 end 562 end
Typecast the value to a Date
Source
# File lib/sequel/database/misc.rb 565 def typecast_value_datetime(value) 566 case value 567 when String 568 Sequel.typecast_to_application_timestamp(typecast_check_string_length(value, 100)) 569 when Hash 570 [:year, :month, :day, :hour, :minute, :second, :nanos, :offset].each do |x| 571 typecast_check_length(value[x] || value[x.to_s], 100) 572 end 573 Sequel.typecast_to_application_timestamp(value) 574 else 575 Sequel.typecast_to_application_timestamp(value) 576 end 577 end
Typecast the value to a DateTime or Time depending on Sequel.datetime_class
Source
# File lib/sequel/database/misc.rb 602 def typecast_value_decimal(value) 603 case value 604 when BigDecimal 605 value 606 when Numeric 607 BigDecimal(value.to_s) 608 when String 609 _typecast_value_string_to_decimal(typecast_check_string_length(value, 1000)) 610 else 611 raise InvalidValue, "invalid value for BigDecimal: #{value.inspect}" 612 end 613 end
Typecast the value to a BigDecimal
Source
# File lib/sequel/database/misc.rb 616 def typecast_value_float(value) 617 Float(typecast_check_length(value, 1000)) 618 end
Typecast the value to a Float
Source
# File lib/sequel/database/misc.rb 621 def typecast_value_integer(value) 622 case value 623 when String 624 typecast_check_string_length(value, 100) 625 if value =~ /\A-?0+(\d)/ 626 Integer(value, 10) 627 else 628 Integer(value) 629 end 630 else 631 Integer(value) 632 end 633 end
Typecast the value to an Integer
Source
# File lib/sequel/database/misc.rb 636 def typecast_value_string(value) 637 case value 638 when Hash, Array 639 raise Sequel::InvalidValue, "invalid value for String: #{value.inspect}" 640 else 641 value.to_s 642 end 643 end
Typecast the value to a String
Source
# File lib/sequel/database/misc.rb 646 def typecast_value_time(value) 647 case value 648 when Time 649 if value.is_a?(SQLTime) 650 value 651 else 652 SQLTime.create(value.hour, value.min, value.sec, value.nsec/1000.0) 653 end 654 when String 655 Sequel.string_to_time(typecast_check_string_length(value, 100)) 656 when Hash 657 SQLTime.create(*[:hour, :minute, :second].map{|x| typecast_check_length(value[x] || value[x.to_s], 100).to_i}) 658 else 659 raise Sequel::InvalidValue, "invalid value for Time: #{value.inspect}" 660 end 661 end
Typecast the value to a Time
9 - Methods that describe what the database supports
↑ topPublic Instance Methods
Source
# File lib/sequel/database/features.rb 13 def global_index_namespace? 14 true 15 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.
Source
# File lib/sequel/database/features.rb 19 def supports_create_table_if_not_exists? 20 false 21 end
Whether the database supports CREATE TABLE IF NOT EXISTS syntax, false by default.
Source
# File lib/sequel/database/features.rb 25 def supports_deferrable_constraints? 26 false 27 end
Whether the database supports deferrable constraints, false by default as few databases do.
Source
# File lib/sequel/database/features.rb 31 def supports_deferrable_foreign_key_constraints? 32 supports_deferrable_constraints? 33 end
Whether the database supports deferrable foreign key constraints, false by default as few databases do.
Source
# File lib/sequel/database/features.rb 37 def supports_drop_table_if_exists? 38 supports_create_table_if_not_exists? 39 end
Whether the database supports DROP TABLE IF EXISTS syntax, false by default.
Source
# File lib/sequel/database/features.rb 43 def supports_foreign_key_parsing? 44 respond_to?(:foreign_key_list) 45 end
Whether the database supports Database#foreign_key_list for parsing foreign keys.
Source
# File lib/sequel/database/features.rb 48 def supports_index_parsing? 49 respond_to?(:indexes) 50 end
Whether the database supports Database#indexes for parsing indexes.
Source
# File lib/sequel/database/features.rb 54 def supports_partial_indexes? 55 false 56 end
Whether the database supports partial indexes (indexes on a subset of a table), false by default.
Source
# File lib/sequel/database/features.rb 60 def supports_prepared_transactions? 61 false 62 end
Whether the database and adapter support prepared transactions (two-phase commit), false by default.
Source
# File lib/sequel/database/features.rb 65 def supports_savepoints? 66 false 67 end
Whether the database and adapter support savepoints, false by default.
Source
# File lib/sequel/database/features.rb 71 def supports_savepoints_in_prepared_transactions? 72 supports_prepared_transactions? && supports_savepoints? 73 end
Whether the database and adapter support savepoints inside prepared transactions (two-phase commit), false by default.
Source
# File lib/sequel/database/features.rb 76 def supports_schema_parsing? 77 respond_to?(:schema_parse_table, true) 78 end
Whether the database supports schema parsing via Database#schema
.
Source
# File lib/sequel/database/features.rb 81 def supports_table_listing? 82 respond_to?(:tables) 83 end
Whether the database supports Database#tables for getting list of tables.
Source
# File lib/sequel/database/features.rb 91 def supports_transaction_isolation_levels? 92 false 93 end
Whether the database and adapter support transaction isolation levels, false by default.
Source
# File lib/sequel/database/features.rb 96 def supports_transactional_ddl? 97 false 98 end
Whether DDL statements work correctly in transactions, false by default.
Source
# File lib/sequel/database/features.rb 86 def supports_view_listing? 87 respond_to?(:views) 88 end
Whether the database supports Database#views for getting list of views.
Source
# File lib/sequel/database/features.rb 101 def supports_views_with_check_option? 102 !!view_with_check_option_support 103 end
Whether CREATE VIEW … WITH CHECK OPTION is supported, false by default.
Source
# File lib/sequel/database/features.rb 106 def supports_views_with_local_check_option? 107 view_with_check_option_support == :local 108 end
Whether CREATE VIEW … WITH LOCAL CHECK OPTION is supported, false by default.
Private Instance Methods
Source
# File lib/sequel/database/features.rb 115 def can_add_primary_key_constraint_on_nullable_columns? 116 true 117 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.
Source
# File lib/sequel/database/features.rb 121 def folds_unquoted_identifiers_to_uppercase? 122 true 123 end
Whether this dataset considers unquoted identifiers as uppercase. True by default as that is the SQL standard
Source
# File lib/sequel/database/features.rb 127 def supports_combining_alter_table_ops? 128 false 129 end
Whether the database supports combining multiple alter table operations into a single query, false by default.
Source
# File lib/sequel/database/features.rb 133 def supports_create_or_replace_view? 134 false 135 end
Whether the database supports CREATE OR REPLACE VIEW. If not, support will be emulated by dropping the view first. false by default.
Source
# File lib/sequel/database/features.rb 141 def supports_named_column_constraints? 142 true 143 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.
Source
# File lib/sequel/database/features.rb 146 def view_with_check_option_support 147 nil 148 end
Don’t advertise support for WITH CHECK OPTION by default.