realm / realm-core

Core database component for the Realm Mobile Database SDKs
https://realm.io
Apache License 2.0
1.01k stars 152 forks source link

Date-relative queries #2986

Open astigsen opened 6 years ago

astigsen commented 6 years ago

Given that our queries are live, it would be very useful to have a way to express date-relative queries. Today we can do conditions against fixed dates, but we cannot do queries relative to the current date.

An example of a usage for this would to implement TTL (time-to-live) in a cache. It would be really useful (and elegant) if you could express this in the form of a single changehandler:

// Find objects older than one day (diff expressed in milliseconds)
let expiredObjects = realm.objects(CacheObject.self).filter("creationDate < NOW() - 86400000")

// Delete objects as soon as they expire
expiredObjects.observe(_ in
     realm.write {
          realm.delete(expiredObjects)
     }
)

Another example would be for partial sync, where you would often want to query for something like news articles for the last 5 days, or notifications from today, and have the result continually updated as time go by.

ironage commented 6 years ago

Implementation on the parser side of things is easy, but the interesting part of this feature is how to implement the auto updating current time. As far as I understand, queries are “live” given that we know when to trigger notifications because we know when the stored data changes. But for this feature, we would need to trigger a notification even though none of the stored data changes. I imagine there will have to be a millisecond timer somewhere in core to check and trigger updates (or to rerun a query) which does not seem congruent to our current designs. Another question is which timezone does NOW() refer to (UTC)? Also, will it be a problem to (partial-)sync that different clients or the server could produce different values for NOW() (producing different results for the same query over the same dataset)? Note that this behaviour can be emulated today by users, but would require them to manually update a custom expired field which is updated by their own timers.