I'm using Room databse, trying to write a query in my Dao, which will delete all records older than specific amount of days. Here is what i come to:
@Query("DELETE FROM my_table WHERE dateFrom <= date('now','-:days day')")
fun deleteAllOlderThan(days: Int)
However, when i try to build my project i get an error in my Gradle Console:
error: Unused parameter: days
I am using Kotlin, so it also show me this:
Error:Execution failed for task ':nexo:kaptDebugKotlin'. Internal compiler error. See log for more details
What is wrong with my Query?
UPDATE
I am also getting an error about converting Date. Here is my converter:
class Converter {
@TypeConverter
fun fromTimestamp(value: Long?) = value?.let { Date(it) }
@TypeConverter
fun dateToTimestamp(date: Date?) = date?.time
}
I am also adding it to my Database with annotation:
@TypeConverters(Converter::class)
Here is specific error i get:
Cannot figure out how to save this field into database. You can consider adding a type converter for it. e: e:private final java.util.Date dateFrom = null;
SUMMARY
I was trying to use Converter with sealed class which in Room it causes problems, so i decided to keep my date parameter as Long.
Check Emmanuel S answer. It should be:
@Query("DELETE FROM my_table WHERE dateFrom <= date('now', '-' || :days || ' days')")
fun deleteAllOlderThan(days: Int)
I think CW gave the answer already for your: days issue.
Your days must be quoted as a string like
"-20 days"
@Query("DELETE FROM my_table WHERE dateFrom <= date('now', :days)")
fun deleteAllOlderThan(days: String)
If it's not working, concat may help.
Try:
@Query("DELETE FROM my_table WHERE dateFrom <= date('now', '-' || :days || ' days')")
fun deleteAllOlderThan(days: Int)
For your Converter issue, you may want to use
@TypeConverter
fun fromTimestamp(value: Long?) = value?.let { Date(it) }
@TypeConverter
fun dateToTimestamp(date: Date?) = date?.time
which works just fine.
Don't use a companion object. Just use
class DBConverters {
@TypeConverter
fun fromTimestamp(value: Long?) = value?.let { Date(it) }
@TypeConverter
fun dateToTimestamp(date: Date?) = date?.time
}
and add the Converter to your abstract DB class like
@TypeConverters(DBConverters::class)
abstract class YourDb : RoomDatabase() {}
Inside the @Query string you need to put a :
before days
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With