frozen-string-literal: true
SQLITE_TYPES | = | {} | Hash with string keys and callable values for converting SQLite types. | |
MYSQL_TYPES | = | {} | Hash with integer keys and callable values for converting MySQL types. | |
SQLANYWHERE_TYPES | = | {} | ||
STRING_TYPES | = | [18, 19, 25, 1042, 1043] | Type OIDs for string types used by PostgreSQL. These types don‘t have conversion procs associated with them (since the data is already in the form of a string). | |
PG_NAMED_TYPES | = | {} unless defined?(PG_NAMED_TYPES) | Hash with type name strings/symbols and callable values for converting PostgreSQL types. Non-builtin types that don‘t have fixed numbers should use this to register conversion procs. | |
PG_TYPES | = | {} unless defined?(PG_TYPES) | Hash with integer keys and callable values for converting PostgreSQL types. | |
DEFAULT_INFLECTIONS_PROC | = | proc do plural(/$/, 's') | Proc that is instance evaled to create the default inflections for both the model inflector and the inflector extension. | |
BeforeHookFailed | = | HookFailed | Alias for HookFailed, kept for backwards compatibility | |
NoExistingObject | = | Class.new(Error) | Exception class raised when require_modification is set and an UPDATE or DELETE statement to modify the dataset doesn‘t modify a single row. | |
UndefinedAssociation | = | Class.new(Error) | Raised when an undefined association is used when eager loading. | |
MassAssignmentRestriction | = | Class.new(Error) | Raised when a mass assignment method is called in strict mode with either a restricted column or a column without a setter method. | |
OPTS | = | {}.freeze | Frozen hash used as the default options hash for most options. | |
COLUMN_REF_RE1 | = | /\A((?:(?!__).)+)__((?:(?!___).)+)___(.+)\z/.freeze | ||
COLUMN_REF_RE2 | = | /\A((?:(?!___).)+)___(.+)\z/.freeze | ||
COLUMN_REF_RE3 | = | /\A((?:(?!__).)+)__(.+)\z/.freeze | ||
SPLIT_SYMBOL_CACHE | = | {} | ||
ADAPTER_MAP | = | {} | Hash of adapters that have been used. The key is the adapter scheme symbol, and the value is the Database subclass. | |
SHARED_ADAPTER_MAP | = | {} | Hash of shared adapters that have been registered. The key is the adapter scheme symbol, and the value is the Sequel module containing the shared adapter. | |
DATABASES | = | [] | Array of all databases to which Sequel has connected. If you are developing an application that can connect to an arbitrary number of databases, delete the database objects from this or they will not get garbage collected. | |
MAJOR | = | 4 | The major version of Sequel. Only bumped for major changes. | |
MINOR | = | 39 | The minor version of Sequel. Bumped for every non-patch level release, generally around once a month. | |
TINY | = | 0 | The tiny version of Sequel. Usually 0, only bumped for bugfix releases that fix regressions from previous versions. | |
VERSION | = | [MAJOR, MINOR, TINY].join('.').freeze | The version of Sequel you are using, as a string (e.g. "2.11.0") | |
AdapterNotFound | = | Class.new(Error) | Error raised when the adapter requested doesn‘t exist or can‘t be loaded. | |
DatabaseError | = | Class.new(Error) | Generic error raised by the database adapters, indicating a problem originating from the database server. Usually raised because incorrect SQL syntax is used. | |
DatabaseConnectionError | = | Class.new(DatabaseError) | Error raised when the Sequel is unable to connect to the database with the connection parameters it was given. | |
DatabaseDisconnectError | = | Class.new(DatabaseError) | Error raised by adapters when they determine that the connection to the database has been lost. Instructs the connection pool code to remove that connection from the pool so that other connections can be acquired automatically. | |
ConstraintViolation | = | Class.new(DatabaseError) | Generic error raised when Sequel determines a database constraint has been violated. | |
CheckConstraintViolation | = | Class.new(ConstraintViolation) | Error raised when Sequel determines a database check constraint has been violated. | |
ForeignKeyConstraintViolation | = | Class.new(ConstraintViolation) | Error raised when Sequel determines a database foreign key constraint has been violated. | |
NotNullConstraintViolation | = | Class.new(ConstraintViolation) | Error raised when Sequel determines a database NOT NULL constraint has been violated. | |
UniqueConstraintViolation | = | Class.new(ConstraintViolation) | Error raised when Sequel determines a database unique constraint has been violated. | |
SerializationFailure | = | Class.new(DatabaseError) | Error raised when Sequel determines a serialization failure/deadlock in the database. | |
InvalidOperation | = | Class.new(Error) | Error raised on an invalid operation, such as trying to update or delete a joined or grouped dataset. | |
InvalidValue | = | Class.new(Error) | Error raised when attempting an invalid type conversion. | |
PoolTimeout | = | Class.new(Error) | Error raised when the connection pool cannot acquire a database connection before the timeout. | |
Rollback | = | Class.new(Error) | Error that you should raise to signal a rollback of the current transaction. The transaction block will catch this exception, rollback the current transaction, and won‘t reraise it (unless a reraise is requested). | |
UnbindDuplicate | = | Class.new(Error) | Error raised when unbinding a dataset that has multiple different values for a given variable. | |
AdapterNotFound | = | AdapterNotFound | ||
InvalidOperation | = | InvalidOperation | ||
InvalidValue | = | InvalidValue | ||
PoolTimeoutError | = | PoolTimeout | ||
Rollback | = | Rollback |
expr | -> | [] |
Allow nicer syntax for creating Sequel
expressions:
Sequel[1] # => Sequel::SQL::NumericExpression: 1 Sequel["a"] # => Sequel::SQL::StringExpression: 'a' Sequel[:a] # => Sequel::SQL::Identifier: "a" Sequel[:a=>1] # => Sequel::SQL::BooleanExpression: ("a" = 1) |
convert_invalid_date_time | [RW] |
Whether to convert invalid date time values by default.
Only applies to Sequel::Database instances created after this has been set. |
convert_two_digit_years | [RW] |
Sequel converts two digit years in Dates
and DateTimes by default, so 01/02/03 is interpreted at January
2nd, 2003, and 12/13/99 is interpreted as December 13, 1999. You can
override this to treat those dates as January 2nd, 0003 and December 13,
0099, respectively, by:
Sequel.convert_two_digit_years = false |
convert_types | [RW] | Whether to convert some Java types to ruby types when retrieving rows. Uses the database‘s setting by default, can be set to false to roughly double performance when fetching rows. |
datetime_class | [RW] |
Sequel can use either Time or
DateTime for times returned from the database. It defaults to
Time. To change it to DateTime:
Sequel.datetime_class = DateTime For ruby versions less than 1.9.2, Time has a limited range (1901 to 2038), so if you use datetimes out of that range, you need to switch to DateTime. Also, before 1.9.2, Time can only handle local and UTC times, not other timezones. Note that Time and DateTime objects have a different API, and in cases where they implement the same methods, they often implement them differently (e.g. + using seconds on Time and days on DateTime). |
Delegate to Sequel::Model, only for backwards compatibility.
# File lib/sequel/model.rb, line 7 7: def self.cache_anonymous_models 8: Model.cache_anonymous_models 9: end
Delegate to Sequel::Model, only for backwards compatibility.
# File lib/sequel/model.rb, line 12 12: def self.cache_anonymous_models=(v) 13: Model.cache_anonymous_models = v 14: end
Returns true if the passed object could be a specifier of conditions, false otherwise. Currently, Sequel considers hashes and arrays of two element arrays as condition specifiers.
Sequel.condition_specifier?({}) # => true Sequel.condition_specifier?([[1, 2]]) # => true Sequel.condition_specifier?([]) # => false Sequel.condition_specifier?([1]) # => false Sequel.condition_specifier?(1) # => false
# File lib/sequel/core.rb, line 64 64: def self.condition_specifier?(obj) 65: case obj 66: when Hash 67: true 68: when Array 69: !obj.empty? && !obj.is_a?(SQL::ValueList) && obj.all?{|i| i.is_a?(Array) && (i.length == 2)} 70: else 71: false 72: end 73: end
Creates a new database object based on the supplied connection string and optional arguments. The specified scheme determines the database class used, and the rest of the string specifies the connection options. For example:
DB = Sequel.connect('sqlite:/') # Memory database DB = Sequel.connect('sqlite://blog.db') # ./blog.db DB = Sequel.connect('sqlite:///blog.db') # /blog.db DB = Sequel.connect('postgres://user:password@host:port/database_name') DB = Sequel.connect('sqlite:///blog.db', :max_connections=>10)
You can also pass a single options hash:
DB = Sequel.connect(:adapter=>'sqlite', :database=>'./blog.db')
If a block is given, it is passed the opened Database object, which is closed when the block exits. For example:
Sequel.connect('sqlite://blog.db'){|db| puts db[:users].count}
If a block is not given, a reference to this database will be held in Sequel::DATABASES until it is removed manually. This is by design, and used by Sequel::Model to pick the default database. It is recommended to pass a block if you do not want the resulting Database object to remain in memory until the process terminates.
For details, see the "Connecting to a Database" guide. To set up a master/slave or sharded database connection, see the "Master/Slave Databases and Sharding" guide.
# File lib/sequel/core.rb, line 107 107: def self.connect(*args, &block) 108: Database.connect(*args, &block) 109: end
Convert the exception to the given class. The given class should be Sequel::Error or a subclass. Returns an instance of klass with the message and backtrace of exception.
# File lib/sequel/core.rb, line 120 120: def self.convert_exception_class(exception, klass) 121: return exception if exception.is_a?(klass) 122: e = klass.new("#{exception.class}: #{exception.message}") 123: e.wrapped_exception = exception 124: e.set_backtrace(exception.backtrace) 125: e 126: end
Load all Sequel extensions given. Extensions are just files that exist under sequel/extensions in the load path, and are just required. Generally, extensions modify the behavior of Database and/or Dataset, but Sequel ships with some extensions that modify other classes that exist for backwards compatibility. In some cases, requiring an extension modifies classes directly, and in others, it just loads a module that you can extend other classes with. Consult the documentation for each extension you plan on using for usage.
Sequel.extension(:schema_dumper) Sequel.extension(:pagination, :query)
# File lib/sequel/core.rb, line 138 138: def self.extension(*extensions) 139: extensions.each{|e| Kernel.require "sequel/extensions/#{e}"} 140: end
Set the method to call on identifiers going into the database. This affects the literalization of identifiers by calling this method on them before they are input. Sequel upcases identifiers in all SQL strings for most databases, so to turn that off:
Sequel.identifier_input_method = nil
to downcase instead:
Sequel.identifier_input_method = :downcase
Other String instance methods work as well.
# File lib/sequel/core.rb, line 153 153: def self.identifier_input_method=(value) 154: Database.identifier_input_method = value 155: end
Set the method to call on identifiers coming out of the database. This affects the literalization of identifiers by calling this method on them when they are retrieved from the database. Sequel downcases identifiers retrieved for most databases, so to turn that off:
Sequel.identifier_output_method = nil
to upcase instead:
Sequel.identifier_output_method = :upcase
Other String instance methods work as well.
# File lib/sequel/core.rb, line 169 169: def self.identifier_output_method=(value) 170: Database.identifier_output_method = value 171: end
Yield the Inflections module if a block is given, and return the Inflections module.
# File lib/sequel/model/inflections.rb, line 6 6: def self.inflections 7: yield Inflections if block_given? 8: Inflections 9: end
The exception classed raised if there is an error parsing JSON. This can be overridden to use an alternative json implementation.
# File lib/sequel/core.rb, line 175 175: def self.json_parser_error_class 176: JSON::ParserError 177: end
The preferred method for writing Sequel migrations, using a DSL:
Sequel.migration do up do create_table(:artists) do primary_key :id String :name end end down do drop_table(:artists) end end
Designed to be used with the Migrator class, part of the migration extension.
# File lib/sequel/extensions/migration.rb, line 289 289: def self.migration(&block) 290: MigrationDSL.create(&block) 291: end
Convert given object to json and return the result. This can be overridden to use an alternative json implementation.
# File lib/sequel/core.rb, line 181 181: def self.object_to_json(obj, *args) 182: obj.to_json(*args) 183: end
Parse the string as JSON and return the result. This can be overridden to use an alternative json implementation.
# File lib/sequel/core.rb, line 187 187: def self.parse_json(json) 188: JSON.parse(json, :create_additions=>false) 189: end
Convert each item in the array to the correct type, handling multi-dimensional arrays. For each element in the array or subarrays, call the converter, unless the value is nil.
# File lib/sequel/core.rb, line 202 202: def self.recursive_map(array, converter) 203: array.map do |i| 204: if i.is_a?(Array) 205: recursive_map(i, converter) 206: elsif i 207: converter.call(i) 208: end 209: end 210: end
Require all given files which should be in the same or a subdirectory of this file. If a subdir is given, assume all files are in that subdir. This is used to ensure that the files loaded are from the same version of Sequel as this file.
# File lib/sequel/core.rb, line 216 216: def self.require(files, subdir=nil) 217: Array(files).each{|f| super("#{File.dirname(__FILE__).untaint}/#{"#{subdir}/" if subdir}#{f}")} 218: end
Set whether Sequel is being used in single threaded mode. By default, Sequel uses a thread-safe connection pool, which isn‘t as fast as the single threaded connection pool, and also has some additional thread safety checks. If your program will only have one thread, and speed is a priority, you should set this to true:
Sequel.single_threaded = true
# File lib/sequel/core.rb, line 227 227: def self.single_threaded=(value) 228: @single_threaded = value 229: Database.single_threaded = value 230: end
Splits the symbol into three parts. Each part will either be a string or nil.
For columns, these parts are the table, column, and alias. For tables, these parts are the schema, table, and alias.
# File lib/sequel/core.rb, line 242 242: def self.split_symbol(sym) 243: unless v = Sequel.synchronize{SPLIT_SYMBOL_CACHE[sym]} 244: v = case s = sym.to_s 245: when COLUMN_REF_RE1 246: [$1.freeze, $2.freeze, $3.freeze].freeze 247: when COLUMN_REF_RE2 248: [nil, $1.freeze, $2.freeze].freeze 249: when COLUMN_REF_RE3 250: [$1.freeze, $2.freeze, nil].freeze 251: else 252: [nil, s.freeze, nil].freeze 253: end 254: Sequel.synchronize{SPLIT_SYMBOL_CACHE[sym] = v} 255: end 256: v 257: end
Converts the given string into a Date object.
Sequel.string_to_date('2010-09-10') # Date.civil(2010, 09, 10)
# File lib/sequel/core.rb, line 262 262: def self.string_to_date(string) 263: begin 264: Date.parse(string, Sequel.convert_two_digit_years) 265: rescue => e 266: raise convert_exception_class(e, InvalidValue) 267: end 268: end
Converts the given string into a Time or DateTime object, depending on the value of Sequel.datetime_class.
Sequel.string_to_datetime('2010-09-10 10:20:30') # Time.local(2010, 09, 10, 10, 20, 30)
# File lib/sequel/core.rb, line 274 274: def self.string_to_datetime(string) 275: begin 276: if datetime_class == DateTime 277: DateTime.parse(string, convert_two_digit_years) 278: else 279: datetime_class.parse(string) 280: end 281: rescue => e 282: raise convert_exception_class(e, InvalidValue) 283: end 284: end
Converts the given string into a Sequel::SQLTime object.
v = Sequel.string_to_time('10:20:30') # Sequel::SQLTime.parse('10:20:30') DB.literal(v) # => '10:20:30'
# File lib/sequel/core.rb, line 290 290: def self.string_to_time(string) 291: begin 292: SQLTime.parse(string) 293: rescue => e 294: raise convert_exception_class(e, InvalidValue) 295: end 296: end
Unless in single threaded mode, protects access to any mutable global data structure in Sequel. Uses a non-reentrant mutex, so calling code should be careful.
# File lib/sequel/core.rb, line 304 304: def self.synchronize(&block) 305: @single_threaded ? yield : @data_mutex.synchronize(&block) 306: end
Uses a transaction on all given databases with the given options. This:
Sequel.transaction([DB1, DB2, DB3]){...}
is equivalent to:
DB1.transaction do DB2.transaction do DB3.transaction do ... end end end
except that if Sequel::Rollback is raised by the block, the transaction is rolled back on all databases instead of just the last one.
Note that this method cannot guarantee that all databases will commit or rollback. For example, if DB3 commits but attempting to commit on DB2 fails (maybe because foreign key checks are deferred), there is no way to uncommit the changes on DB3. For that kind of support, you need to have two-phase commit/prepared transactions (which Sequel supports on some databases).
# File lib/sequel/core.rb, line 331 331: def self.transaction(dbs, opts=OPTS, &block) 332: unless opts[:rollback] 333: rescue_rollback = true 334: opts = Hash[opts].merge!(:rollback=>:reraise) 335: end 336: pr = dbs.reverse.inject(block){|bl, db| proc{db.transaction(opts, &bl)}} 337: if rescue_rollback 338: begin 339: pr.call 340: rescue Sequel::Rollback 341: nil 342: end 343: else 344: pr.call 345: end 346: end
If the supplied block takes a single argument, yield an SQL::VirtualRow instance to the block argument. Otherwise, evaluate the block in the context of a SQL::VirtualRow instance.
Sequel.virtual_row{a} # Sequel::SQL::Identifier.new(:a) Sequel.virtual_row{|o| o.a{}} # Sequel::SQL::Function.new(:a)
# File lib/sequel/core.rb, line 355 355: def self.virtual_row(&block) 356: vr = VIRTUAL_ROW 357: case block.arity 358: when -1, 0 359: vr.instance_exec(&block) 360: else 361: block.call(vr) 362: end 363: end
Correctly return rows from the database and return them as hashes.
# File lib/sequel/adapters/jdbc.rb, line 737 737: def fetch_rows(sql, &block) 738: execute(sql){|result| process_result_set(result, &block)} 739: self 740: end
Create a named prepared statement that is stored in the database (and connection) for reuse.
# File lib/sequel/adapters/jdbc.rb, line 744 744: def prepare(type, name=nil, *values) 745: ps = to_prepared_statement(type, values) 746: ps.extend(PreparedStatementMethods) 747: if name 748: ps.prepared_statement_name = name 749: db.set_prepared_statement(name, ps) 750: end 751: ps 752: end