# Badge Backfill Code

**URL:** <https://meta.discourse.org/t/badge-backfill-code/174120>\
**Category:** Feature\
**Created:** [December 23, 2020, 4:32pm UTC](https://meta.discourse.org/t/badge-backfill-code/174120 "2020-12-23T16:32:14Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![Ghan](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/ghan/32/177964_2.png) [@Ghan](https://meta.discourse.org/u/Ghan)\
**Post date:** [December 23, 2020, 4:32pm UTC](https://meta.discourse.org/t/badge-backfill-code/174120/1 "2020-12-23T16:32:14Z")

</div>

I’m looking at the badge backfill process happening here:

> <https://github.com/discourse/discourse/blob/main/app/services/badge_granter.rb>

In particular, the following query seems to have some issues (see [Long-Running Sidekiq Jobs](https://meta.discourse.org/t/long-running-sidekiq-jobs/173974))

```plaintext
    sql = <<~SQL
      DELETE FROM user_badges
        WHERE id IN (
          SELECT ub.id
          FROM user_badges ub
          LEFT JOIN (
            #{badge.query}
          ) q ON q.user_id = ub.user_id
          #{post_clause}
          WHERE ub.badge_id = :id AND q.user_id IS NULL
        )
    SQL

```

This query does a LEFT JOIN so all results from user\_badges will be returned regardless if there is a match, but this part seems very confusing:

```plaintext
ON q.user_id = ub.user_id
...
AND q.user_id IS NULL

```

The query joins on rows where the user\_id matches, but then discards those rows via the WHERE clause, making the join there kind of moot. So I’m wondering:

1. What is the purpose of the backfill function? It appears to completely wipe the badge being processed and then rebuilds it all at once. Is this necessary?

2. What is the difference between a badge that targets posts and one that does not with regard to this function? With a LEFT JOIN, does this even matter when finding the correct badge\_id to wipe for the rebuild?

---

_[View the full topic](https://meta.discourse.org/t/badge-backfill-code/174120)._
