# Uploads not getting orphaned and purged

**URL:** <https://meta.discourse.org/t/uploads-not-getting-orphaned-and-purged/259036>\
**Category:** Product Support\
**Created:** [March 22, 2023, 1:47pm UTC](https://meta.discourse.org/t/uploads-not-getting-orphaned-and-purged/259036 "2023-03-22T13:47:52Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![Simon\_Manning](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/simon_manning/32/198596_2.png) [@Simon\_Manning](https://meta.discourse.org/u/Simon_Manning)\
**Post date:** [March 22, 2023, 5:57pm UTC](https://meta.discourse.org/t/uploads-not-getting-orphaned-and-purged/259036/4 "2023-03-22T17:57:15Z")

</div>

This is purely speculative but from a quick look at the post, post\_upload and upload models, you can probably find out if you have orphaned uploads (database objects) with this:

```plaintext
Upload.find_by_sql("select * from uploads where id in (select upload_id from post_uploads where post_id not in (select id from posts))")

```

I haven’t tested that so I can’t be sure if it will find orphaned uploads correctly or even execute without error. In case it doesn’t work as-is and someone else might be able to make it work, as well as just for anyone else interested, I’ll break down the intent.

1. `Upload.find_by_sql()` returns a collection of Upload objects that are matched by the provided SQL query.
2. `(select id from posts)` gets all of the IDs for existing posts.
3. `(select upload_id from post_uploads where post_id not in ()` gets all of the IDs for post uploads for which no post exists.
4. `select * from uploads where id in ()` gets all of the uploads matching those post upload IDs.

* * *

That’s just one possible avenue to investigate though, unfortunately I don’t know the upload system well enough to really contribute much otherwise, except to say that the above definitely does _ **not** _ account for all situations. Edited rather than deleted posts being an obvious one.

There are also other types of uploads not accounted for like user uploads which I assume is things like uploading a profile picture.

Plugins can also create and hold on to uploads, I don’t know what happens with those if say the plugin is removed. I think plugin data remains in the database after a plugin is removed which potentially means any uploads created by that plugin are never removed in that situation.

---

_[View the full topic](https://meta.discourse.org/t/uploads-not-getting-orphaned-and-purged/259036)._
