module SequenceOn::SequencedOn::InstanceMethods

Private Instance Methods

generate_sequence_id() click to toggle source
# File lib/sequence_on/sequenced_on.rb, line 22
def generate_sequence_id
  return if self.sequential_id
  options = self.class.sequence_options
  scope = self.class.class_exec(self, &options[:lmd])
  lock_candidates = scope.values
  lock_key = Digest::MD5.hexdigest(lock_candidates.join).unpack('L').join

  self.class.connection.execute("SELECT pg_advisory_xact_lock('#{self.class.table_name}'::regclass::integer, #{lock_key})", "sequence_on") if postgresql?
  last_record = if self.persisted?
                  self.class
                    .unscoped
                    .where(scope).
                    order("#{options[:column]} DESC").
                    where("NOT id = ?", self.id).
                    first
                else
                  self.class
                    .unscoped
                    .where(scope).
                    order("#{options[:column]} DESC").
                    first
                end

  self.sequential_id = if last_record
                         (last_record.send(options[:column]) || 0) + 1
                       else
                         options[:start_at]
                       end
end
postgresql?() click to toggle source
# File lib/sequence_on/sequenced_on.rb, line 17
def postgresql?
  defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) &&
    self.class.connection.instance_of?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter)
end