JetBrains / Exposed

Kotlin SQL Framework
http://jetbrains.github.io/Exposed/
Apache License 2.0
8.05k stars 674 forks source link

feat: EXPOSED-403 Implement `EntityClass.restriction` - a means of providing soft deletes #2114

Open bystam opened 3 weeks ago

bystam commented 3 weeks ago

This is my attempt at showcasing/drafting a version of "DAO restrictions", similarly to how @SQLRestriction works in Hibernate (which can be used for soft deletes), but without the magic annotation setup.

Youtrack: https://youtrack.jetbrains.com/newIssue?project=EXPOSED&draftId=25-5413167

Usage:

object BlogPosts : LongIdTable() {
  val text = text("text")
  val isDeleted = bool("is_deleted").default(false)
}

class BlogPost(id: EntityID<Long>) : LongIdEntity(id) {
  var text: String by BlogPosts.text

  override fun delete() {
      // instead of regular hard delete, override it to simply "mark as deleted"
      BlogPosts.update({ BlogPosts.id eq id }) {
          it[isDeleted] = true
      }
  }

  companion object : LongIdEntityClass<BlogPost>(BlogPosts) {
    // this will automatically make sure only non-deleted BlogPost entities show up
    override val restriction: Op<Boolean> = BlogPosts.isDeleted eq false
  }
}

val post = BlogPost.new {
  text = "Nice blog"
}
post.delete()

BlogPost.all() // 0 elements

val actual = PostPosts.selectAll().single() // but will show up in DB

Why "restriction"?

bystam commented 3 weeks ago

I have one test failure on Sqlite, and looking more closely at it, it feels light it might be a separate SQLite-oriented bug perhaps?

The table/entity pair is declared like this - where requestId is the id column of the entity image

I noticed when running SQL logging that the following: image seems to perform soft delete on the wrong ID:

SQL: INSERT INTO Requests (requestId) VALUES ('123')
SQL: UPDATE Requests SET deleted_at='2024-06-07 07:11:38.703' WHERE Requests.requestId = '1'

and indeed, the Entity instance seems to have been given the wrong ID: image

bystam commented 3 weeks ago

Bug has been filed and reproduced in tests here:

obabichevjb commented 3 weeks ago

Thank you for PR, it looks interesting, I'll create an issue in YouTrack for the discussion of it,

Also thank you for describing the bug, I checked another PR and related YT issue, here (/pull/2119) is a PR that should fix it.

bystam commented 2 weeks ago

Thank you for PR, it looks interesting, I'll create an issue in YouTrack for the discussion of it,

I have one here: https://youtrack.jetbrains.com/issue/EXPOSED-403/DAO-soft-delete-restriction-support Unless you meant something else :)