Module: Sequel::Model::InstanceMethods

Defined in:
lib/sequel/model/base.rb

Overview

Sequel::Model instance methods that implement basic model functionality.

  • All of the model before/after/around hooks are implemented as instance methods that are called by Sequel when the appropriate action occurs. For example, when destroying a model object, Sequel will call around_destroy, which will call before_destroy, do the destroy, and then call after_destroy.

  • The following instance_methods all call the class method of the same name: columns, db, primary_key, db_schema.

  • The following accessor methods are defined via metaprogramming: raise_on_save_failure, raise_on_typecast_failure, require_modification, strict_param_setting, typecast_empty_string_to_nil, typecast_on_assignment, and use_transactions. The setter methods will change the setting for the instance, and the getter methods will check for an instance setting, then try the class setting if no instance setting has been set.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#valuesObject (readonly) Also known as: to_hash, _insert_values

The hash of attribute values. Keys are symbols with the names of the underlying database columns. The returned hash is a reference to the receiver's values hash, and modifying it will also modify the receiver's values.

Artist.new(name: 'Bob').values # => {:name=>'Bob'}
Artist[1].values # => {:id=>1, :name=>'Jim', ...}

1060
1061
1062
# File 'lib/sequel/model/base.rb', line 1060

def values
  @values
end

Instance Method Details

#==(obj) ⇒ Object

Alias of eql?


1125
1126
1127
# File 'lib/sequel/model/base.rb', line 1125

def ==(obj)
  eql?(obj)
end

#===(obj) ⇒ Object Also known as: pk_equal?

Case equality. By default, checks equality of the primary key value, see pk_equal?.

Artist[1] === Artist[1] # => true
Artist.new === Artist.new # => false
Artist[1].set(:name=>'Bob') === Artist[1] # => true

1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
# File 'lib/sequel/model/base.rb', line 1135

def ===(obj)
  case pkv = pk
  when nil
    return false
  when Array
    return false if pkv.any?(&:nil?)
  end

  (obj.class == model) && (obj.pk == pkv)
end

#[](column) ⇒ Object

Returns value of the column's attribute.

Artist[1][:id] #=> 1

1100
1101
1102
# File 'lib/sequel/model/base.rb', line 1100

def [](column)
  @values[column]
end

#[]=(column, value) ⇒ Object

Sets the value for the given column. If typecasting is enabled for this object, typecast the value based on the column's type. If this is a new record or the typecasted value isn't the same as the current value for the column, mark the column as changed.

a = Artist.new
a[:name] = 'Bob'
a.values #=> {:name=>'Bob'}

1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
# File 'lib/sequel/model/base.rb', line 1112

def []=(column, value)
  # If it is new, it doesn't have a value yet, so we should
  # definitely set the new value.
  # If the column isn't in @values, we can't assume it is
  # NULL in the database, so assume it has changed.
  v = typecast_value(column, value)
  vals = @values
  if new? || !vals.include?(column) || v != (c = vals[column]) || v.class != c.class
    change_column_value(column, v)
  end
end

#autoincrementing_primary_keyObject

The autoincrementing primary key for this model object. Should be overridden if you have a composite primary key with one part of it being autoincrementing.


1167
1168
1169
# File 'lib/sequel/model/base.rb', line 1167

def autoincrementing_primary_key
  primary_key
end

#cancel_action(msg = nil) ⇒ Object

Cancel the current action. Should be called in before hooks to halt the processing of the action. If a msg argument is given and the model instance is configured to raise exceptions on failure, sets the message to use for the raised HookFailed exception.


1175
1176
1177
# File 'lib/sequel/model/base.rb', line 1175

def cancel_action(msg=nil)
  raise_hook_failure(msg)
end

#changed_columnsObject

The columns that have been updated. This isn't completely accurate, as it could contain columns whose values have not changed.

a = Artist[1]
a.changed_columns # => []
a.name = 'Bob'
a.changed_columns # => [:name]

1186
1187
1188
# File 'lib/sequel/model/base.rb', line 1186

def changed_columns
  _changed_columns
end

#deleteObject

Deletes and returns self. Does not run destroy hooks. Look into using destroy instead.

Artist[1].delete # DELETE FROM artists WHERE (id = 1)
# => #<Artist {:id=>1, ...}>

Raises:


1195
1196
1197
1198
1199
# File 'lib/sequel/model/base.rb', line 1195

def delete
  raise Sequel::Error, "can't delete frozen object" if frozen?
  _delete
  self
end

#destroy(opts = OPTS) ⇒ Object

Like delete but runs hooks before and after delete. Uses a transaction if use_transactions is true or if the :transaction option is given and true.

Artist[1].destroy # BEGIN; DELETE FROM artists WHERE (id = 1); COMMIT;
# => #<Artist {:id=>1, ...}>

Raises:


1207
1208
1209
1210
# File 'lib/sequel/model/base.rb', line 1207

def destroy(opts = OPTS)
  raise Sequel::Error, "can't destroy frozen object" if frozen?
  checked_save_failure(opts){checked_transaction(opts){_destroy(opts)}}
end

#each(&block) ⇒ Object

Iterates through all of the current values using each.

Album[1].each{|k, v| puts "#{k} => #{v}"}
# id => 1
# name => 'Bob'

1217
1218
1219
# File 'lib/sequel/model/base.rb', line 1217

def each(&block)
  @values.each(&block)
end

#eql?(obj) ⇒ Boolean

Compares model instances by values.

Artist[1] == Artist[1] # => true
Artist.new == Artist.new # => true
Artist[1].set(:name=>'Bob') == Artist[1] # => false

Returns:

  • (Boolean)

1226
1227
1228
# File 'lib/sequel/model/base.rb', line 1226

def eql?(obj)
  (obj.class == model) && (obj.values == @values)
end

#errorsObject

Returns the validation errors associated with this object. See Errors.


1232
1233
1234
# File 'lib/sequel/model/base.rb', line 1232

def errors
  @errors ||= errors_class.new
end

#exists?Boolean

Returns true when current instance exists, false otherwise. Generally an object that isn't new will exist unless it has been deleted. Uses a database query to check for existence, unless the model object is new, in which case this is always false.

Artist[1].exists? # SELECT 1 FROM artists WHERE (id = 1)
# => true
Artist.new.exists?
# => false

Returns:

  • (Boolean)

1246
1247
1248
# File 'lib/sequel/model/base.rb', line 1246

def exists?
  new? ? false : !this.get(SQL::AliasedExpression.new(1, :one)).nil?
end

#extend(mod) ⇒ Object

Ignore the model's setter method cache when this instances extends a module, as the module may contain setter methods.


1252
1253
1254
1255
# File 'lib/sequel/model/base.rb', line 1252

def extend(mod)
  @singleton_setter_added = true
  super
end

#freezeObject

Freeze the object in such a way that it is still usable but not modifiable. Once an object is frozen, you cannot modify it's values, changed_columns, errors, or dataset.


1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
# File 'lib/sequel/model/base.rb', line 1260

def freeze
  unless errors.frozen?
    validate
    errors.freeze
  end
  values.freeze
  _changed_columns.freeze
  this if !new? && model.primary_key
  super
end

#hashObject

Value that should be unique for objects with the same class and pk (if pk is not nil), or the same class and values (if pk is nil).

Artist[1].hash == Artist[1].hash # true
Artist[1].set(name: 'Bob').hash == Artist[1].hash # true
Artist.new.hash == Artist.new.hash # true
Artist.new(name: 'Bob').hash == Artist.new.hash # false

1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
# File 'lib/sequel/model/base.rb', line 1278

def hash
  case primary_key
  when Array
    [model, !pk.all? ? @values : pk].hash
  when Symbol
    [model, pk.nil? ? @values : pk].hash
  else
    [model, @values].hash
  end
end

#idObject

Returns value for the :id attribute, even if the primary key is not id. To get the primary key value, use pk.

Artist[1].id # => 1

1293
1294
1295
# File 'lib/sequel/model/base.rb', line 1293

def id
  @values[:id]
end

#initialize(values = OPTS) {|_self| ... } ⇒ Object

Creates new instance and passes the given values to set. If a block is given, yield the instance to the block.

Arguments:

values

should be a hash to pass to set.

Artist.new(name: 'Bob')

Artist.new do |a|
  a.name = 'Bob'
end

Yields:

  • (_self)

Yield Parameters:


1088
1089
1090
1091
1092
1093
1094
1095
# File 'lib/sequel/model/base.rb', line 1088

def initialize(values = OPTS)
  @values = {}
  @new = true
  @modified = true
  initialize_set(values)
  _clear_changed_columns(:initialize)
  yield self if defined?(yield)
end

#inspectObject

Returns a string representation of the model instance including the class name and values.


1299
1300
1301
# File 'lib/sequel/model/base.rb', line 1299

def inspect
  "#<#{model.name} @values=#{inspect_values}>"
end

#keysObject

Returns the keys in values. May not include all column names.

Artist.new.keys # => []
Artist.new(name: 'Bob').keys # => [:name]
Artist[1].keys # => [:id, :name]

1308
1309
1310
# File 'lib/sequel/model/base.rb', line 1308

def keys
  @values.keys
end

#lock!(style = :update) ⇒ Object

Refresh this record using for_update (by default, or the specified style when given) unless this is a new record. Returns self. This can be used to make sure no other process is updating the record at the same time.

If style is a string, it will be used directly. You should never pass a string to this method that is derived from user input, as that can lead to SQL injection.

A symbol may be used for database independent locking behavior, but all supported symbols have separate methods (e.g. for_update).

a = Artist[1]
Artist.db.transaction do
  a.lock!
  a.update(:name=>'A')
end

a = Artist[2]
Artist.db.transaction do
  a.lock!('FOR NO KEY UPDATE')
  a.update(:name=>'B')
end

1335
1336
1337
1338
# File 'lib/sequel/model/base.rb', line 1335

def lock!(style=:update)
  _refresh(this.lock_style(style)) unless new?
  self
end

#marshallable!Object

Remove elements of the model object that make marshalling fail. Returns self.

a = Artist[1]
a.marshallable!
Marshal.dump(a)

1345
1346
1347
1348
# File 'lib/sequel/model/base.rb', line 1345

def marshallable!
  @this = nil
  self
end

#modified!(column = nil) ⇒ Object

Explicitly mark the object as modified, so save_changes/update will run callbacks even if no columns have changed.

a = Artist[1]
a.save_changes # No callbacks run, as no changes
a.modified!
a.save_changes # Callbacks run, even though no changes made

If a column is given, specifically marked that column as modified, so that save_changes/update will include that column in the update. This should be used if you plan on mutating the column value instead of assigning a new column value:

a.modified!(:name)
a.name.gsub!(/[aeou]/, 'i')

1365
1366
1367
1368
# File 'lib/sequel/model/base.rb', line 1365

def modified!(column=nil)
  _add_changed_column(column) if column
  @modified = true
end

#modified?(column = nil) ⇒ Boolean

Whether this object has been modified since last saved, used by save_changes to determine whether changes should be saved. New values are always considered modified.

a = Artist[1]
a.modified? # => false
a.set(name: 'Jim')
a.modified? # => true

If a column is given, specifically check if the given column has been modified:

a.modified?(:num_albums) # => false
a.num_albums = 10
a.modified?(:num_albums) # => true

Returns:

  • (Boolean)

1385
1386
1387
1388
1389
1390
1391
# File 'lib/sequel/model/base.rb', line 1385

def modified?(column=nil)
  if column
    changed_columns.include?(column)
  else
    @modified || !changed_columns.empty?
  end
end

#new?Boolean

Returns true if the current instance represents a new record.

Artist.new.new? # => true
Artist[1].new? # => false

Returns:

  • (Boolean)

1397
1398
1399
# File 'lib/sequel/model/base.rb', line 1397

def new?
  defined?(@new) ? @new : (@new = false)
end

#pkObject

Returns the primary key value identifying the model instance. Raises an Error if this model does not have a primary key. If the model has a composite primary key, returns an array of values.

Artist[1].pk # => 1
Artist[[1, 2]].pk # => [1, 2]

Raises:


1407
1408
1409
1410
1411
1412
1413
1414
1415
# File 'lib/sequel/model/base.rb', line 1407

def pk
  raise(Error, "No primary key is associated with this model") unless key = primary_key
  if key.is_a?(Array)
    vals = @values
    key.map{|k| vals[k]}
  else
    @values[key]
  end
end

#pk_hashObject

Returns a hash mapping the receivers primary key column(s) to their values.

Artist[1].pk_hash # => {:id=>1}
Artist[[1, 2]].pk_hash # => {:id1=>1, :id2=>2}

1421
1422
1423
# File 'lib/sequel/model/base.rb', line 1421

def pk_hash
  model.primary_key_hash(pk)
end

#qualified_pk_hash(qualifier = model.table_name) ⇒ Object

Returns a hash mapping the receivers qualified primary key column(s) to their values.

Artist[1].qualified_pk_hash
# => {Sequel[:artists][:id]=>1}
Artist[[1, 2]].qualified_pk_hash
# => {Sequel[:artists][:id1]=>1, Sequel[:artists][:id2]=>2}

1431
1432
1433
# File 'lib/sequel/model/base.rb', line 1431

def qualified_pk_hash(qualifier=model.table_name)
  model.qualified_primary_key_hash(pk, qualifier)
end

#refreshObject

Reloads attributes from database and returns self. Also clears all changed_columns information. Raises an Error if the record no longer exists in the database.

a = Artist[1]
a.name = 'Jim'
a.refresh
a.name # => 'Bob'

Raises:


1443
1444
1445
1446
1447
# File 'lib/sequel/model/base.rb', line 1443

def refresh
  raise Sequel::Error, "can't refresh frozen object" if frozen?
  _refresh(this)
  self
end

#reloadObject

Alias of refresh, but not aliased directly to make overriding in a plugin easier.


1450
1451
1452
# File 'lib/sequel/model/base.rb', line 1450

def reload
  refresh
end

#save(opts = OPTS) ⇒ Object

Creates or updates the record, after making sure the record is valid and before hooks execute successfully. Fails if:

  • the record is not valid, or

  • before_save calls cancel_action, or

  • the record is new and before_create calls cancel_action, or

  • the record is not new and before_update calls cancel_action.

If save fails and either raise_on_save_failure or the :raise_on_failure option is true, it raises ValidationFailed or HookFailed. Otherwise it returns nil.

If it succeeds, it returns self.

Takes the following options:

:changed

save all changed columns, instead of all columns or the columns given

:columns

array of specific columns that should be saved.

:raise_on_failure

set to true or false to override the current raise_on_save_failure setting

:server

set the server/shard on the object before saving, and use that server/shard in any transaction.

:transaction

set to true or false to override the current use_transactions setting

:validate

set to false to skip validation

Raises:


1479
1480
1481
1482
1483
1484
1485
1486
1487
# File 'lib/sequel/model/base.rb', line 1479

def save(opts=OPTS)
  raise Sequel::Error, "can't save frozen object" if frozen?
  set_server(opts[:server]) if opts[:server] 
  unless _save_valid?(opts)
    raise(validation_failed_error) if raise_on_failure?(opts)
    return
  end
  checked_save_failure(opts){checked_transaction(opts){_save(opts)}}
end

#save_changes(opts = OPTS) ⇒ Object

Saves only changed columns if the object has been modified. If the object has not been modified, returns nil. If unable to save, returns false unless raise_on_save_failure is true.

a = Artist[1]
a.save_changes # => nil
a.name = 'Jim'
a.save_changes # UPDATE artists SET name = 'Bob' WHERE (id = 1)
# => #<Artist {:id=>1, :name=>'Jim', ...}

1498
1499
1500
# File 'lib/sequel/model/base.rb', line 1498

def save_changes(opts=OPTS)
  save(Hash[opts].merge!(:changed=>true)) || false if modified? 
end

#set(hash) ⇒ Object

Updates the instance with the supplied values with support for virtual attributes, raising an exception if a value is used that doesn't have a setter method (or ignoring it if strict_param_setting = false). Does not save the record.

artist.set(name: 'Jim')
artist.name # => 'Jim'

1509
1510
1511
# File 'lib/sequel/model/base.rb', line 1509

def set(hash)
  set_restricted(hash, :default)
end

#set_fields(hash, fields, opts = nil) ⇒ Object

For each of the fields in the given array fields, call the setter method with the value of that hash entry for the field. Returns self.

You can provide an options hash, with the following options currently respected:

:missing

Can be set to :skip to skip missing entries or :raise to raise an Error for missing entries. The default behavior is not to check for missing entries, in which case the default value is used. To be friendly with most web frameworks, the missing check will also check for the string version of the argument in the hash if given a symbol.

Examples:

artist.set_fields({name: 'Jim'}, [:name])
artist.name # => 'Jim'

artist.set_fields({hometown: 'LA'}, [:name])
artist.name # => nil
artist.hometown # => 'Sac'

artist.name # => 'Jim'
artist.set_fields({}, [:name], missing: :skip)
artist.name # => 'Jim'

artist.name # => 'Jim'
artist.set_fields({}, [:name], missing: :raise)
# Sequel::Error raised

1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
# File 'lib/sequel/model/base.rb', line 1539

def set_fields(hash, fields, opts=nil)
  opts = if opts
    model.default_set_fields_options.merge(opts)
  else
    model.default_set_fields_options
  end

  case missing = opts[:missing]
  when :skip, :raise
    do_raise = true if missing == :raise
    fields.each do |f|
      if hash.has_key?(f) 
        set_column_value("#{f}=", hash[f])
      elsif f.is_a?(Symbol) && hash.has_key?(sf = f.to_s)
        set_column_value("#{sf}=", hash[sf])
      elsif do_raise
        raise(Sequel::Error, "missing field in hash: #{f.inspect} not in #{hash.inspect}")
      end
    end
  else
    fields.each{|f| set_column_value("#{f}=", hash[f])}
  end
  self
end

#set_server(s) ⇒ Object

Set the shard that this object is tied to. Returns self.


1565
1566
1567
1568
1569
# File 'lib/sequel/model/base.rb', line 1565

def set_server(s)
  @server = s
  @this = @this.server(s) if @this
  self
end

#singleton_method_added(meth) ⇒ Object

Clear the setter_methods cache when a method is added


1572
1573
1574
1575
# File 'lib/sequel/model/base.rb', line 1572

def singleton_method_added(meth)
  @singleton_setter_added = true if meth.to_s.end_with?('=')
  super
end

#skip_validation_on_next_save!Object

Skip all validation of the object on the next call to #save, including the running of validation hooks. This is designed for and should only be used in cases where #valid? is called before saving and the validate: false option cannot be passed to #save.


1582
1583
1584
# File 'lib/sequel/model/base.rb', line 1582

def skip_validation_on_next_save!
  @skip_validation_on_next_save = true
end

#thisObject

Returns (naked) dataset that should return only this instance.

Artist[1].this
# SELECT * FROM artists WHERE (id = 1) LIMIT 1

Raises:


1590
1591
1592
1593
1594
# File 'lib/sequel/model/base.rb', line 1590

def this
  return @this if @this
  raise Error, "No dataset for model #{model}" unless ds = model.instance_dataset
  @this = use_server(ds.where(pk_hash))
end

#update(hash) ⇒ Object

Runs #set with the passed hash and then runs save_changes.

artist.update(name: 'Jim') # UPDATE artists SET name = 'Jim' WHERE (id = 1)

1599
1600
1601
# File 'lib/sequel/model/base.rb', line 1599

def update(hash)
  update_restricted(hash, :default)
end

#update_fields(hash, fields, opts = nil) ⇒ Object

Update the instance's values by calling set_fields with the arguments, then calls save_changes.

artist.update_fields({name: 'Jim'}, [:name])
# UPDATE artists SET name = 'Jim' WHERE (id = 1)

artist.update_fields({hometown: 'LA'}, [:name])
# UPDATE artists SET name = NULL WHERE (id = 1)

1611
1612
1613
1614
# File 'lib/sequel/model/base.rb', line 1611

def update_fields(hash, fields, opts=nil)
  set_fields(hash, fields, opts)
  save_changes
end

#valid?(opts = OPTS) ⇒ Boolean

Validates the object and returns true if no errors are reported.

artist.set(name: 'Valid').valid? # => true
artist.set(name: 'Invalid').valid? # => false
artist.errors.full_messages # => ['name cannot be Invalid']

Returns:

  • (Boolean)

1630
1631
1632
1633
1634
# File 'lib/sequel/model/base.rb', line 1630

def valid?(opts = OPTS)
  _valid?(opts)
rescue HookFailed
  false
end

#validateObject

Validates the object. If the object is invalid, errors should be added to the errors attribute. By default, does nothing, as all models are valid by default. See the “Model Validations” guide. for details about validation. Should not be called directly by user code, call valid? instead to check if an object is valid.


1622
1623
# File 'lib/sequel/model/base.rb', line 1622

def validate
end