Class: ActiverecordHoarder::BatchQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord_hoarder/record_query.rb

Constant Summary collapse

SUBQUERY_DELETED_RECORDS =
<<~SQL.strip_heredoc
  SELECT
    %{fields}
  FROM
    %{table_name}
  WHERE
    deleted_at IS NOT NULL
SQL
SUBQUERY_NON_DELETED_RECORDS =
<<~SQL.strip_heredoc
  SELECT
    %{fields}
  FROM
    %{table_name}
  WHERE
    deleted_at IS NULL
SQL
QUERY_TEMPLATE_FOR_DATE_DELETION =
<<~SQL.strip_heredoc
  DELETE FROM %{table_name} WHERE date(created_at) = '%{date}';
SQL
QUERY_TEMPLATE_FOR_RECORD_WITH_LIMIT =
<<~SQL.strip_heredoc
  SELECT
    %{fields}
  FROM
    %{table_name}
  WHERE
    date(created_at) = (
      SELECT
        min(dates_with_deleted.creation_date)
      FROM
        (
          #{SUBQUERY_DELETED_RECORDS % {
              fields: "date(created_at) as creation_date",
              table_name: "%{table_name}"
          }}
        ) as dates_with_deleted
        LEFT OUTER JOIN
        (
          #{SUBQUERY_NON_DELETED_RECORDS % {
            fields: "date(created_at) as creation_date",
            table_name: "%{table_name}"
          }}
        ) as dates_with_non_deleted
        ON
          dates_with_deleted.creation_date = dates_with_non_deleted.creation_date
        WHERE
          dates_with_non_deleted.creation_date IS NULL
        AND
          created_at < '%{limit}'
    )
  ;
SQL

Instance Method Summary collapse

Constructor Details

#initialize(limit, model_class) ⇒ BatchQuery

Returns a new instance of BatchQuery.



58
59
60
61
# File 'lib/activerecord_hoarder/record_query.rb', line 58

def initialize(limit, model_class)
  @limit = limit
  @model_class = model_class
end

Instance Method Details

#delete(date) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/activerecord_hoarder/record_query.rb', line 63

def delete(date)
  QUERY_TEMPLATE_FOR_DATE_DELETION % {
    fields: @model_class.column_names.join(", "),
    date: date,
    table_name: table_name
  }
end

#fetchObject



71
72
73
74
75
76
77
# File 'lib/activerecord_hoarder/record_query.rb', line 71

def fetch
  QUERY_TEMPLATE_FOR_RECORD_WITH_LIMIT % {
    fields: @model_class.column_names.join(", "),
    limit: @limit,
    table_name: table_name
  }
end