How would I write a room query over a complex data...
# room
v
How would I write a room query over a complex data type (like
LocalDateTime
). I'm trying to write a query which would return all events in the last X number of days:
Copy code
fun getEventsWithin(days: Int): Flow<List<Event>>
I'm really struggling to work out what the SQL would be. The
Event
entity has a column called
dateTime
of type
LocalDateTime
and I have written two
@TypeConverter
functions which convert between
LocalDateTime
and
Long
values.
Certainly I can't do it in the
@Query()
SQL block. (How do
@TypeConverters
work, anyway? The name of the annotated function seems relevant, I guess it's just doing a compile time check of types?)
I've got it working through a `@RawQuery`:
Copy code
@RawQuery(observedEntities = [Event::class])
    fun getEventsWithin(query: SupportSQLiteQuery): Flow<List<Event>>
And in my repository:
Copy code
fun getEventsWithin(days: Int): Flow<List<Event>> {
        if(days <= 0) {
            return dao.getAll()
        }
        val now = LocalDateTime.now()
        val xDaysAgo = now.minusDays(days.toLong())
        val xDaysAgoAsLong = xDaysAgo.toEpochSecond(ZoneOffset.UTC)
        return dao.getEventsWithin(SimpleSQLiteQuery("SELECT * FROM Event WHERE dateTime > ? ORDER BY dateTime DESC",
            arrayOf(xDaysAgoAsLong)
        ))
    }
I thought I'd share this because I really couldn't find any examples of this online.