Files
ubicloud/lib/sem_snap.rb
Burak Yucesoy 06b9eb8296 Use destroy instead of delete
In a subsequent commit, We will start to archive deleted records to a separate
table. Archiving will be done in before_destroy hook. Sequel does not trigger
any hooks for delete calls, so we are converting all delete calls to destroy.
Both calls are quite similar with few notable differences;
- delete does not trigger any hooks but destroy does.
- delete is more efficient while working with datasets, it directly runs DELETE
query with the given conditions of the dataset, but destroy instantiates each
object and calls destroy on the resulting object. For models, their performance
is comparable; only additional overhead comes from triggering hooks.
- Since destroy instantiates each object, it needs primary key. Thus we added
primary key to AppliedTag model.
- destroy does not work properly with returning as it processes each row one by
one.
2023-08-01 11:58:57 +03:00

56 lines
1.1 KiB
Ruby

# frozen_string_literal: true
class SemSnap
def initialize(strand_id, deferred: false)
@deferred = deferred
@strand_id = strand_id
@extant = Hash.new { |h, k| h[k.intern] = [] }
@defer_delete = []
Semaphore.where(strand_id: @strand_id).each do |sem|
add_semaphore_instance_to_snapshot(sem)
end
end
def self.use(strand_id)
new(strand_id, deferred: true).use do |snap|
yield snap
end
end
def use
yield self
ensure
apply
end
def set?(name)
name = name.intern
@extant.include?(name)
end
def decr(name)
name = name.intern
ids = @extant.delete(name)
return unless ids && ids.length > 0
@defer_delete.concat(ids)
apply unless @deferred
end
def incr(name)
add_semaphore_instance_to_snapshot(Semaphore.incr(@strand_id, name))
end
private
def apply
return if @defer_delete.empty?
Semaphore.where(strand_id: @strand_id, id: @defer_delete).destroy
@defer_delete.clear
end
def add_semaphore_instance_to_snapshot(sem)
@extant[sem.name.intern] << sem.id
end
end