Class Index [+]

Quicksearch

Sequel::Model::InstanceMethods

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

Attributes

values[R]

The hash of attribute values. Keys are symbols with the names of the underlying database columns.

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

Public Class Methods

new(values = {}, from_db = false) click to toggle source

Creates new instance and passes the given values to set. If a block is given, yield the instance to the block unless from_db is true. This method runs the after_initialize hook after it has optionally yielded itself to the block.

Arguments:

values

should be a hash to pass to set.

from_db

only for backwards compatibility, forget it exists.

  Artist.new(:name=>'Bob')

  Artist.new do |a|
    a.name = 'Bob'
  end
     # File lib/sequel/model/base.rb, line 891
891:       def initialize(values = {}, from_db = false)
892:         if from_db
893:           set_values(values)
894:         else
895:           @values = {}
896:           @new = true
897:           @modified = true
898:           initialize_set(values)
899:           changed_columns.clear 
900:           yield self if block_given?
901:         end
902:         after_initialize
903:       end

Public Instance Methods

==(obj) click to toggle source

Alias of eql?

     # File lib/sequel/model/base.rb, line 933
933:       def ==(obj)
934:         eql?(obj)
935:       end
===(obj) click to toggle source

If pk is not nil, true only if the objects have the same class and pk. If pk is nil, false.

  Artist[1] === Artist[1] # true
  Artist.new === Artist.new # false
  Artist[1].set(:name=>'Bob') == Artist[1] # => true
     # File lib/sequel/model/base.rb, line 943
943:       def ===(obj)
944:         pk.nil? ? false : (obj.class == model) && (obj.pk == pk)
945:       end
[](column) click to toggle source

Returns value of the column’s attribute.

  Artist[1][:id] #=> 1
     # File lib/sequel/model/base.rb, line 908
908:       def [](column)
909:         @values[column]
910:       end
[]=(column, value) click to toggle source

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'}
     # File lib/sequel/model/base.rb, line 920
920:       def []=(column, value)
921:         # If it is new, it doesn't have a value yet, so we should
922:         # definitely set the new value.
923:         # If the column isn't in @values, we can't assume it is
924:         # NULL in the database, so assume it has changed.
925:         v = typecast_value(column, value)
926:         vals = @values
927:         if new? || !vals.include?(column) || v != (c = vals[column]) || v.class != c.class
928:           change_column_value(column, v)
929:         end
930:       end
autoincrementing_primary_key() click to toggle source

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.

     # File lib/sequel/model/base.rb, line 958
958:       def autoincrementing_primary_key
959:         primary_key
960:       end
changed_columns() click to toggle source

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]
     # File lib/sequel/model/base.rb, line 969
969:       def changed_columns
970:         @changed_columns ||= []
971:       end
delete() click to toggle source

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, ...}>
     # File lib/sequel/model/base.rb, line 978
978:       def delete
979:         raise Sequel::Error, "can't delete frozen object" if frozen?
980:         _delete
981:         self
982:       end
destroy(opts = {}) click to toggle source

Like delete but runs hooks before and after delete. If before_destroy returns false, returns false without deleting the object the the database. Otherwise, deletes the item from the database and returns self. 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, ...}>
     # File lib/sequel/model/base.rb, line 993
993:       def destroy(opts = {})
994:         raise Sequel::Error, "can't destroy frozen object" if frozen?
995:         checked_save_failure(opts){checked_transaction(opts){_destroy(opts)}}
996:       end
each(&block) click to toggle source

Iterates through all of the current values using each.

 Album[1].each{|k, v| puts "#{k} => #{v}"}
 # id => 1
 # name => 'Bob'
      # File lib/sequel/model/base.rb, line 1003
1003:       def each(&block)
1004:         @values.each(&block)
1005:       end
eql?(obj) click to toggle source

Compares model instances by values.

  Artist[1] == Artist[1] # => true
  Artist.new == Artist.new # => true
  Artist[1].set(:name=>'Bob') == Artist[1] # => false
      # File lib/sequel/model/base.rb, line 1012
1012:       def eql?(obj)
1013:         (obj.class == model) && (obj.values == @values)
1014:       end
errors() click to toggle source

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

      # File lib/sequel/model/base.rb, line 1018
1018:       def errors
1019:         @errors ||= Errors.new
1020:       end
exists?() click to toggle source

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
      # File lib/sequel/model/base.rb, line 1032
1032:       def exists?
1033:         new? ? false : !this.get(1).nil?
1034:       end
extend(mod) click to toggle source

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

      # File lib/sequel/model/base.rb, line 1038
1038:       def extend(mod)
1039:         @singleton_setter_added = true
1040:         super
1041:       end
freeze() click to toggle source

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.

      # File lib/sequel/model/base.rb, line 1046
1046:       def freeze
1047:         values.freeze
1048:         changed_columns.freeze
1049:         errors
1050:         validate
1051:         errors.freeze
1052:         this.freeze unless new?
1053:         super
1054:       end
hash() click to toggle source

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
      # File lib/sequel/model/base.rb, line 1063
1063:       def hash
1064:         case primary_key
1065:         when Array
1066:           [model, !pk.all? ? @values.sort_by{|k,v| k.to_s} : pk].hash
1067:         when Symbol
1068:           [model, pk.nil? ? @values.sort_by{|k,v| k.to_s} : pk].hash
1069:         else
1070:           [model, @values.sort_by{|k,v| k.to_s}].hash
1071:         end
1072:       end
id() click to toggle source

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
      # File lib/sequel/model/base.rb, line 1078
1078:       def id
1079:         @values[:id]
1080:       end
inspect() click to toggle source

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

      # File lib/sequel/model/base.rb, line 1084
1084:       def inspect
1085:         "#<#{model.name} @values=#{inspect_values}>"
1086:       end
keys() click to toggle source

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]
      # File lib/sequel/model/base.rb, line 1093
1093:       def keys
1094:         @values.keys
1095:       end
lock!() click to toggle source

Refresh this record using for_update 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.

  a = Artist[1]
  Artist.db.transaction do
    a.lock!
    a.update(...)
  end
      # File lib/sequel/model/base.rb, line 1106
1106:       def lock!
1107:         _refresh(this.for_update) unless new?
1108:         self
1109:       end
marshallable!() click to toggle source

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

  a = Artist[1]
  a.marshallable!
  Marshal.dump(a)
      # File lib/sequel/model/base.rb, line 1116
1116:       def marshallable!
1117:         @this = nil
1118:         self
1119:       end
modified!() click to toggle source

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
      # File lib/sequel/model/base.rb, line 1128
1128:       def modified!
1129:         @modified = true
1130:       end
modified?() click to toggle source

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
      # File lib/sequel/model/base.rb, line 1140
1140:       def modified?
1141:         @modified || !changed_columns.empty?
1142:       end
new?() click to toggle source

Returns true if the current instance represents a new record.

  Artist.new.new? # => true
  Artist[1].new? # => false
      # File lib/sequel/model/base.rb, line 1148
1148:       def new?
1149:         defined?(@new) ? @new : (@new = false)
1150:       end
pk() click to toggle source

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]
      # File lib/sequel/model/base.rb, line 1158
1158:       def pk
1159:         raise(Error, "No primary key is associated with this model") unless key = primary_key
1160:         if key.is_a?(Array)
1161:           vals = @values
1162:           key.map{|k| vals[k]}
1163:         else
1164:           @values[key]
1165:         end
1166:       end
pk_hash() click to toggle source

Returns a hash identifying 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}
      # File lib/sequel/model/base.rb, line 1172
1172:       def pk_hash
1173:         model.primary_key_hash(pk)
1174:       end
refresh() click to toggle source

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'
      # File lib/sequel/model/base.rb, line 1184
1184:       def refresh
1185:         raise Sequel::Error, "can't refresh frozen object" if frozen?
1186:         _refresh(this)
1187:         self
1188:       end
reload() click to toggle source

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

      # File lib/sequel/model/base.rb, line 1191
1191:       def reload
1192:         refresh
1193:       end
save(*columns) click to toggle source

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 returns false, or

  • the record is new and before_create returns false, or

  • the record is not new and before_update returns false.

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.

You can provide an optional list of columns to update, in which case it only updates those columns, or a options hash.

Takes the following options:

:changed

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

: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

      # File lib/sequel/model/base.rb, line 1222
1222:       def save(*columns)
1223:         raise Sequel::Error, "can't save frozen object" if frozen?
1224:         opts = columns.last.is_a?(Hash) ? columns.pop : {}
1225:         set_server(opts[:server]) if opts[:server] 
1226:         if opts[:validate] != false
1227:           unless checked_save_failure(opts){_valid?(true, opts)}
1228:             raise(ValidationFailed.new(errors)) if raise_on_failure?(opts)
1229:             return
1230:           end
1231:         end
1232:         checked_save_failure(opts){checked_transaction(opts){_save(columns, opts)}}
1233:       end
save_changes(opts={}) click to toggle source

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', ...}
      # File lib/sequel/model/base.rb, line 1244
1244:       def save_changes(opts={})
1245:         save(opts.merge(:changed=>true)) || false if modified? 
1246:       end
set(hash) click to toggle source

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'
      # File lib/sequel/model/base.rb, line 1255
1255:       def set(hash)
1256:         set_restricted(hash, nil, nil)
1257:       end
set_all(hash) click to toggle source

Set all values using the entries in the hash, ignoring any setting of allowed_columns or restricted columns in the model.

  Artist.set_restricted_columns(:name)
  artist.set_all(:name=>'Jim')
  artist.name # => 'Jim'
      # File lib/sequel/model/base.rb, line 1265
1265:       def set_all(hash)
1266:         set_restricted(hash, false, false)
1267:       end
set_except(hash, *except) click to toggle source

Set all values using the entries in the hash, except for the keys given in except. You should probably use set_fields or set_only instead of this method, as blacklist approaches to security are a bad idea.

  artist.set_except({:name=>'Jim'}, :hometown)
  artist.name # => 'Jim'
      # File lib/sequel/model/base.rb, line 1275
1275:       def set_except(hash, *except)
1276:         set_restricted(hash, false, except.flatten)
1277:       end
set_fields(hash, fields, opts=nil) click to toggle source

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
      # File lib/sequel/model/base.rb, line 1305
1305:       def set_fields(hash, fields, opts=nil)
1306:         if opts
1307:           case opts[:missing]
1308:           when :skip
1309:             fields.each do |f|
1310:               if hash.has_key?(f) 
1311:                 send("#{f}=", hash[f])
1312:               elsif f.is_a?(Symbol) && hash.has_key?(sf = f.to_s)
1313:                 send("#{sf}=", hash[sf])
1314:               end
1315:             end
1316:           when :raise
1317:             fields.each do |f|
1318:               if hash.has_key?(f)
1319:                 send("#{f}=", hash[f])
1320:               elsif f.is_a?(Symbol) && hash.has_key?(sf = f.to_s)
1321:                 send("#{sf}=", hash[sf])
1322:               else
1323:                 raise(Sequel::Error, "missing field in hash: #{f.inspect} not in #{hash.inspect}")
1324:               end
1325:             end
1326:           else
1327:             fields.each{|f| send("#{f}=", hash[f])}
1328:           end
1329:         else
1330:           fields.each{|f| send("#{f}=", hash[f])}
1331:         end
1332:         self
1333:       end
set_only(hash, *only) click to toggle source

Set the values using the entries in the hash, only if the key is included in only. It may be a better idea to use set_fields instead of this method.

  artist.set_only({:name=>'Jim'}, :name)
  artist.name # => 'Jim'

  artist.set_only({:hometown=>'LA'}, :name) # Raise Error
      # File lib/sequel/model/base.rb, line 1343
1343:       def set_only(hash, *only)
1344:         set_restricted(hash, only.flatten, false)
1345:       end
set_server(s) click to toggle source

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

      # File lib/sequel/model/base.rb, line 1348
1348:       def set_server(s)
1349:         @server = s
1350:         @this.opts[:server] = s if @this
1351:         self
1352:       end
set_values(hash) click to toggle source

Replace the current values with hash. Should definitely not be used with untrusted input, and should probably not be called directly by user code.

      # File lib/sequel/model/base.rb, line 1357
1357:       def set_values(hash)
1358:         @values = hash
1359:       end
singleton_method_added(meth) click to toggle source

Clear the setter_methods cache when a method is added

      # File lib/sequel/model/base.rb, line 1362
1362:       def singleton_method_added(meth)
1363:         @singleton_setter_added = true if meth.to_s =~ SETTER_METHOD_REGEXP
1364:         super
1365:       end
this() click to toggle source

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

  Artist[1].this
  # SELECT * FROM artists WHERE (id = 1) LIMIT 1
      # File lib/sequel/model/base.rb, line 1371
1371:       def this
1372:         @this ||= use_server(model.instance_dataset.filter(pk_hash))
1373:       end
update(hash) click to toggle source

Runs # with the passed hash and then runs save_changes.

  artist.update(:name=>'Jim') # UPDATE artists SET name = 'Jim' WHERE (id = 1)
      # File lib/sequel/model/base.rb, line 1378
1378:       def update(hash)
1379:         update_restricted(hash, nil, nil)
1380:       end
update_all(hash) click to toggle source

Update all values using the entries in the hash, ignoring any setting of allowed_columns or restricted_columns in the model.

  Artist.set_restricted_columns(:name)
  artist.update_all(:name=>'Jim') # UPDATE artists SET name = 'Jim' WHERE (id = 1)
      # File lib/sequel/model/base.rb, line 1387
1387:       def update_all(hash)
1388:         update_restricted(hash, false, false)
1389:       end
update_except(hash, *except) click to toggle source

Update all values using the entries in the hash, except for the keys given in except. You should probably use update_fields or update_only instead of this method, as blacklist approaches to security are a bad idea.

  artist.update_except({:name=>'Jim'}, :hometown) # UPDATE artists SET name = 'Jim' WHERE (id = 1)
      # File lib/sequel/model/base.rb, line 1396
1396:       def update_except(hash, *except)
1397:         update_restricted(hash, false, except.flatten)
1398:       end
update_fields(hash, fields, opts=nil) click to toggle source

Update the instances values by calling set_fields with the arguments, then saves any changes to the record. Returns self.

  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)
      # File lib/sequel/model/base.rb, line 1408
1408:       def update_fields(hash, fields, opts=nil)
1409:         set_fields(hash, fields, opts)
1410:         save_changes
1411:       end
update_only(hash, *only) click to toggle source

Update the values using the entries in the hash, only if the key is included in only. It may be a better idea to use update_fields instead of this method.

  artist.update_only({:name=>'Jim'}, :name)
  # UPDATE artists SET name = 'Jim' WHERE (id = 1)

  artist.update_only({:hometown=>'LA'}, :name) # Raise Error
      # File lib/sequel/model/base.rb, line 1421
1421:       def update_only(hash, *only)
1422:         update_restricted(hash, only.flatten, false)
1423:       end
valid?(opts = {}) click to toggle source

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

  artist(:name=>'Valid').valid? # => true
  artist(:name=>'Invalid').valid? # => false
  artist.errors.full_messages # => ['name cannot be Invalid']
      # File lib/sequel/model/base.rb, line 1439
1439:       def valid?(opts = {})
1440:         _valid?(false, opts)
1441:       end
validate() click to toggle source

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.

      # File lib/sequel/model/base.rb, line 1431
1431:       def validate
1432:       end

Private Instance Methods

_delete() click to toggle source

Do the deletion of the object’s dataset, and check that the row was actually deleted.

      # File lib/sequel/model/base.rb, line 1447
1447:       def _delete
1448:         n = _delete_without_checking
1449:         raise(NoExistingObject, "Attempt to delete object did not result in a single row modification (Rows Deleted: #{n}, SQL: #{_delete_dataset.delete_sql})") if require_modification && n != 1
1450:         n
1451:       end
_delete_dataset() click to toggle source

The dataset to use when deleting the object. The same as the object’s dataset by default.

      # File lib/sequel/model/base.rb, line 1455
1455:       def _delete_dataset
1456:         this
1457:       end
_delete_without_checking() click to toggle source

Actually do the deletion of the object’s dataset. Return the number of rows modified.

      # File lib/sequel/model/base.rb, line 1461
1461:       def _delete_without_checking
1462:         if sql = (m = model).fast_instance_delete_sql
1463:           sql = sql.dup
1464:           (ds = m.dataset).literal_append(sql, pk)
1465:           ds.with_sql_delete(sql)
1466:         else
1467:           _delete_dataset.delete 
1468:         end
1469:       end
_destroy(opts) click to toggle source

Internal destroy method, separted from destroy to allow running inside a transaction

      # File lib/sequel/model/base.rb, line 1473
1473:       def _destroy(opts)
1474:         sh = {:server=>this_server}
1475:         db.after_rollback(sh){after_destroy_rollback} if uacr = use_after_commit_rollback
1476:         called = false
1477:         around_destroy do
1478:           called = true
1479:           raise_hook_failure(:destroy) if before_destroy == false
1480:           _destroy_delete
1481:           after_destroy
1482:           true
1483:         end
1484:         raise_hook_failure(:destroy) unless called
1485:         db.after_commit(sh){after_destroy_commit} if uacr
1486:         self
1487:       end
_destroy_delete() click to toggle source

Internal delete method to call when destroying an object, separated from delete to allow you to override destroy’s version without affecting delete.

      # File lib/sequel/model/base.rb, line 1492
1492:       def _destroy_delete
1493:         delete
1494:       end
_insert() click to toggle source

Insert the record into the database, returning the primary key if the record should be refreshed from the database.

      # File lib/sequel/model/base.rb, line 1498
1498:       def _insert
1499:         ds = _insert_dataset
1500:         if !ds.opts[:select] and ds.supports_insert_select? and h = _insert_select_raw(ds)
1501:           set_values(h)
1502:           nil
1503:         else
1504:           iid = _insert_raw(ds)
1505:           # if we have a regular primary key and it's not set in @values,
1506:           # we assume it's the last inserted id
1507:           if (pk = autoincrementing_primary_key) && pk.is_a?(Symbol) && !(vals = @values)[pk]
1508:             vals[pk] = iid
1509:           end
1510:           pk
1511:         end
1512:       end
_insert_dataset() click to toggle source

The dataset to use when inserting a new object. The same as the model’s dataset by default.

      # File lib/sequel/model/base.rb, line 1516
1516:       def _insert_dataset
1517:         use_server(model.instance_dataset)
1518:       end
_insert_raw(ds) click to toggle source

Insert into the given dataset and return the primary key created (if any).

      # File lib/sequel/model/base.rb, line 1521
1521:       def _insert_raw(ds)
1522:         ds.insert(@values)
1523:       end
_insert_select_raw(ds) click to toggle source

Insert into the given dataset and return the hash of column values.

      # File lib/sequel/model/base.rb, line 1526
1526:       def _insert_select_raw(ds)
1527:         ds.insert_select(@values)
1528:       end
_refresh(dataset) click to toggle source

Refresh using a particular dataset, used inside save to make sure the same server is used for reading newly inserted values from the database

      # File lib/sequel/model/base.rb, line 1532
1532:       def _refresh(dataset)
1533:         set_values(_refresh_get(dataset) || raise(Error, "Record not found"))
1534:         changed_columns.clear
1535:       end
_refresh_get(dataset) click to toggle source

Get the row of column data from the database.

      # File lib/sequel/model/base.rb, line 1538
1538:       def _refresh_get(dataset)
1539:         dataset.first
1540:       end
_save(columns, opts) click to toggle source

Internal version of save, split from save to allow running inside it’s own transaction.

      # File lib/sequel/model/base.rb, line 1544
1544:       def _save(columns, opts)
1545:         sh = {:server=>this_server}
1546:         db.after_rollback(sh){after_rollback} if uacr = use_after_commit_rollback
1547:         was_new = false
1548:         pk = nil
1549:         called_save = false
1550:         called_cu = false
1551:         around_save do
1552:           called_save = true
1553:           raise_hook_failure(:save) if before_save == false
1554:           if new?
1555:             was_new = true
1556:             around_create do
1557:               called_cu = true
1558:               raise_hook_failure(:create) if before_create == false
1559:               pk = _insert
1560:               @this = nil
1561:               @new = false
1562:               @was_new = true
1563:               after_create
1564:               true
1565:             end
1566:             raise_hook_failure(:create) unless called_cu
1567:           else
1568:             around_update do
1569:               called_cu = true
1570:               raise_hook_failure(:update) if before_update == false
1571:               if columns.empty?
1572:                 @columns_updated = if opts[:changed]
1573:                   @values.reject{|k,v| !changed_columns.include?(k)}
1574:                 else
1575:                   _save_update_all_columns_hash
1576:                 end
1577:                 changed_columns.clear
1578:               else # update only the specified columns
1579:                 @columns_updated = @values.reject{|k, v| !columns.include?(k)}
1580:                 changed_columns.reject!{|c| columns.include?(c)}
1581:               end
1582:               _update_columns(@columns_updated)
1583:               @this = nil
1584:               after_update
1585:               true
1586:             end
1587:             raise_hook_failure(:update) unless called_cu
1588:           end
1589:           after_save
1590:           true
1591:         end
1592:         raise_hook_failure(:save) unless called_save
1593:         if was_new
1594:           @was_new = nil
1595:           pk ? _save_refresh : changed_columns.clear
1596:         else
1597:           @columns_updated = nil
1598:         end
1599:         @modified = false
1600:         db.after_commit(sh){after_commit} if uacr
1601:         self
1602:       end
_save_refresh() click to toggle source

Refresh the object after saving it, used to get default values of all columns. Separated from _save so it can be overridden to avoid the refresh.

      # File lib/sequel/model/base.rb, line 1607
1607:       def _save_refresh
1608:         _refresh(this.opts[:server] ? this : this.server(:default))
1609:       end
_save_update_all_columns_hash() click to toggle source

Return a hash of values used when saving all columns of an existing object (i.e. not passing specific columns to save or using update/save_changes). Defaults to all of the object’s values except unmodified primary key columns, as some databases don’t like you setting primary key values even to their existing values.

      # File lib/sequel/model/base.rb, line 1617
1617:       def _save_update_all_columns_hash
1618:         v = @values.dup
1619:         Array(primary_key).each{|x| v.delete(x) unless changed_columns.include?(x)}
1620:         v
1621:       end
_update(columns) click to toggle source

Update this instance’s dataset with the supplied column hash, checking that only a single row was modified.

      # File lib/sequel/model/base.rb, line 1632
1632:       def _update(columns)
1633:         n = _update_without_checking(columns)
1634:         raise(NoExistingObject, "Attempt to update object did not result in a single row modification (SQL: #{_update_dataset.update_sql(columns)})") if require_modification && n != 1
1635:         n
1636:       end
_update_columns(columns) click to toggle source

Call _update with the given columns, if any are present. Plugins can override this method in order to update with additional columns, even when the column hash is initially empty.

      # File lib/sequel/model/base.rb, line 1626
1626:       def _update_columns(columns)
1627:         _update(columns) unless columns.empty?
1628:       end
_update_dataset() click to toggle source

The dataset to use when updating an object. The same as the object’s dataset by default.

      # File lib/sequel/model/base.rb, line 1640
1640:       def _update_dataset
1641:         this
1642:       end
_update_without_checking(columns) click to toggle source

Update this instances dataset with the supplied column hash.

      # File lib/sequel/model/base.rb, line 1645
1645:       def _update_without_checking(columns)
1646:         _update_dataset.update(columns)
1647:       end
_valid?(raise_errors, opts) click to toggle source

Internal validation method. If raise_errors is true, hook failures will be raised as HookFailure exceptions. If it is false, false will be returned instead.

      # File lib/sequel/model/base.rb, line 1652
1652:       def _valid?(raise_errors, opts)
1653:         return errors.empty? if frozen?
1654:         errors.clear
1655:         called = false
1656:         error = false
1657:         around_validation do
1658:           called = true
1659:           if before_validation == false
1660:             if raise_errors
1661:               raise_hook_failure(:validation)
1662:             else
1663:               error = true
1664:             end
1665:             false
1666:           else
1667:             validate
1668:             after_validation
1669:             errors.empty?
1670:           end
1671:         end
1672:         error = true unless called
1673:         if error
1674:           if raise_errors
1675:             raise_hook_failure(:validation)
1676:           else
1677:             false
1678:           end
1679:         else
1680:           errors.empty?
1681:         end
1682:       end
change_column_value(column, value) click to toggle source

Change the value of the column to given value, recording the change.

      # File lib/sequel/model/base.rb, line 1704
1704:       def change_column_value(column, value)
1705:         cc = changed_columns
1706:         cc << column unless cc.include?(column)
1707:         @values[column] = value
1708:       end
checked_save_failure(opts) click to toggle source

If not raising on failure, check for HookFailed being raised by yielding and swallow it.

      # File lib/sequel/model/base.rb, line 1686
1686:       def checked_save_failure(opts)
1687:         if raise_on_failure?(opts)
1688:           yield
1689:         else
1690:           begin
1691:             yield
1692:           rescue HookFailed 
1693:             nil
1694:           end
1695:         end
1696:       end
checked_transaction(opts={}) click to toggle source

If transactions should be used, wrap the yield in a transaction block.

      # File lib/sequel/model/base.rb, line 1699
1699:       def checked_transaction(opts={})
1700:         use_transaction?(opts) ? db.transaction({:server=>this_server}.merge(opts)){yield} : yield
1701:       end
initialize_set(h) click to toggle source

Set the columns with the given hash. By default, the same as set, but exists so it can be overridden. This is called only for new records, before changed_columns is cleared.

      # File lib/sequel/model/base.rb, line 1713
1713:       def initialize_set(h)
1714:         set(h) unless h.empty?
1715:       end
inspect_values() click to toggle source

Default inspection output for the values hash, overwrite to change what # displays.

      # File lib/sequel/model/base.rb, line 1718
1718:       def inspect_values
1719:         @values.inspect
1720:       end
raise_hook_failure(type) click to toggle source

Raise an error appropriate to the hook type. May be swallowed by checked_save_failure depending on the raise_on_failure? setting.

      # File lib/sequel/model/base.rb, line 1732
1732:       def raise_hook_failure(type)
1733:         raise HookFailed, "one of the before_#{type} hooks returned false"
1734:       end
raise_on_failure?(opts) click to toggle source

Whether to raise or return false if this action fails. If the :raise_on_failure option is present in the hash, use that, otherwise, fallback to the object’s raise_on_save_failure (if set), or class’s default (if not).

      # File lib/sequel/model/base.rb, line 1726
1726:       def raise_on_failure?(opts)
1727:         opts.fetch(:raise_on_failure, raise_on_save_failure)
1728:       end
set_restricted(hash, only, except) click to toggle source

Set the columns, filtered by the only and except arrays.

      # File lib/sequel/model/base.rb, line 1737
1737:       def set_restricted(hash, only, except)
1738:         return self if hash.empty?
1739:         meths = if only.nil? && except.nil? && !@singleton_setter_added
1740:           model.setter_methods
1741:         else
1742:           setter_methods(only, except)
1743:         end
1744:         strict = strict_param_setting
1745:         hash.each do |k,v|
1746:           m = "#{k}="
1747:           if meths.include?(m)
1748:             send(m, v)
1749:           elsif strict
1750:             # Avoid using respond_to? or creating symbols from user input
1751:             if public_methods.map{|s| s.to_s}.include?(m)
1752:               if Array(model.primary_key).map{|s| s.to_s}.member?(k.to_s) && model.restrict_primary_key?
1753:                 raise Error, "#{k} is a restricted primary key"
1754:               else
1755:                 raise Error, "#{k} is a restricted column"
1756:               end
1757:             else
1758:               raise Error, "method #{m} doesn't exist"
1759:             end
1760:           end
1761:         end
1762:         self
1763:       end
setter_methods(only, except) click to toggle source

Returns all methods that can be used for attribute assignment (those that end with =), modified by the only and except arguments:

  • only

    • false - Don’t modify the results

    • nil - if the model has allowed_columns, use only these, otherwise, don’t modify

    • Array - allow only the given methods to be used

  • except

    • false - Don’t modify the results

    • nil - if the model has restricted_columns, remove these, otherwise, don’t modify

    • Array - remove the given methods

only takes precedence over except, and if only is not used, certain methods are always restricted (RESTRICTED_SETTER_METHODS). The primary key is restricted by default as well, see Model.unrestrict_primary_key to change this.

      # File lib/sequel/model/base.rb, line 1781
1781:       def setter_methods(only, except)
1782:         only = only.nil? ? model.allowed_columns : only
1783:         except = except.nil? ? model.restricted_columns : except
1784:         if only
1785:           only.map{|x| "#{x}="}
1786:         else
1787:           meths = methods.collect{|x| x.to_s}.grep(SETTER_METHOD_REGEXP) - RESTRICTED_SETTER_METHODS
1788:           meths -= Array(primary_key).map{|x| "#{x}="} if primary_key && model.restrict_primary_key?
1789:           meths -= except.map{|x| "#{x}="} if except
1790:           meths
1791:         end
1792:       end
this_server() click to toggle source

The server/shard that the model object’s dataset uses, or :default if the model object’s dataset does not have an associated shard.

      # File lib/sequel/model/base.rb, line 1796
1796:       def this_server
1797:         if (s = @server)
1798:           s
1799:         elsif (t = @this)
1800:           t.opts[:server] || :default
1801:         else
1802:           model.dataset.opts[:server] || :default
1803:         end
1804:       end
typecast_value(column, value) click to toggle source

Typecast the value to the column’s type if typecasting. Calls the database’s typecast_value method, so database adapters can override/augment the handling for database specific column types.

      # File lib/sequel/model/base.rb, line 1809
1809:       def typecast_value(column, value)
1810:         return value unless typecast_on_assignment && db_schema && (col_schema = db_schema[column])
1811:         value = nil if '' == value and typecast_empty_string_to_nil and col_schema[:type] and ![:string, :blob].include?(col_schema[:type])
1812:         raise(InvalidValue, "nil/NULL is not allowed for the #{column} column") if raise_on_typecast_failure && value.nil? && (col_schema[:allow_null] == false)
1813:         begin
1814:           model.db.typecast_value(col_schema[:type], value)
1815:         rescue InvalidValue
1816:           raise_on_typecast_failure ? raise : value
1817:         end
1818:       end
update_restricted(hash, only, except) click to toggle source

Set the columns, filtered by the only and except arrays.

      # File lib/sequel/model/base.rb, line 1821
1821:       def update_restricted(hash, only, except)
1822:         set_restricted(hash, only, except)
1823:         save_changes
1824:       end
use_server(ds) click to toggle source

Set the given dataset to use the current object’s shard.

      # File lib/sequel/model/base.rb, line 1827
1827:       def use_server(ds)
1828:         @server ? ds.server(@server) : ds
1829:       end
use_transaction?(opts = {}) click to toggle source

Whether to use a transaction for this action. If the :transaction option is present in the hash, use that, otherwise, fallback to the object’s default (if set), or class’s default (if not).

      # File lib/sequel/model/base.rb, line 1834
1834:       def use_transaction?(opts = {})
1835:         opts.fetch(:transaction, use_transactions)
1836:       end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.