1# frozen_string_literal: true
2
3module Ci
4  class DeletedObject < Ci::ApplicationRecord
5    mount_uploader :file, DeletedObjectUploader
6
7    scope :ready_for_destruction, ->(limit) do
8      where('pick_up_at < ?', Time.current).limit(limit)
9    end
10
11    scope :lock_for_destruction, ->(limit) do
12      ready_for_destruction(limit)
13        .select(:id)
14        .order(:pick_up_at)
15        .lock('FOR UPDATE SKIP LOCKED')
16    end
17
18    def self.bulk_import(artifacts, pick_up_at = nil)
19      attributes = artifacts.each.with_object([]) do |artifact, accumulator|
20        record = artifact.to_deleted_object_attrs(pick_up_at)
21        accumulator << record if record[:store_dir] && record[:file]
22      end
23
24      self.insert_all(attributes) if attributes.any?
25    end
26
27    def delete_file_from_storage
28      file.remove!
29      true
30    rescue StandardError => exception
31      Gitlab::ErrorTracking.track_exception(exception)
32      false
33    end
34  end
35end
36