Search code examples
postgresqlkotlinkotlin-exposed

Delete query with complex filter using Kotlin Exposed


I am creating a deletion query in which I need to call native Postgres functions to filter the records that should be removed.

In summary, the query is as follows: delete all records that have the start_at column (timestamp) older than 5 days (dynamic parameter for the query).

For native SQL, the query would be as follows:

delete from my_table t where date_part ('day', (current_date - t.start_at))> = 5

In my Kotlin coding, I am not able to implement this query. The examples in the exposed documentation don't have code with more complex filters like that. I know it's something like:

(1)

transaction {
   MyTable.deleteWhere {
     MyTable.startAt greaterEq ??????
   }
}

or

(2)

transaction {
   exec ("delete query here> = $ {daysToFilter}")
}

Is there a way to do this query in code following example (1)? If not, what would be the best way to do this query?

Sample DataSet:

id start_at
1 2020-09-01 09:00:00
2 2020-09-02 09:00:00
3 2020-09-03 09:00:00
4 2020-09-04 09:00:00

Solution

  • the final solution was the following:

    fun my_function(days: Int) {
        val startAt = DateTime.now()
                    .withTimeAtStartOfDay()
                    .minusDays(days)
    
        transaction {
            MyTable.deleteWhere {
                MyTable.startAt greaterEq startAt         
            }     
        } 
    }