Skip to content

Instantly share code, notes, and snippets.

@IlyaGulya
Created August 24, 2018 08:25
Show Gist options
  • Save IlyaGulya/872ddb5f976d0dc54ce8a740847c6ef7 to your computer and use it in GitHub Desktop.
Save IlyaGulya/872ddb5f976d0dc54ce8a740847c6ef7 to your computer and use it in GitHub Desktop.
Simple Realm Kotlin query builder
val query: RealmQuery<Model> = ...
query.build {
group {
equalTo(linkedField(Column.PARAMS, Column.FIELD_TYPE), DCParamModel.FieldType.BOOLEAN)
and
equalTo(linkedField(Column.PARAMS, Column.KEY), DCParamObject.FAVORITE)
and
equalTo(linkedField(Column.PARAMS, Column.F_BOOL), true)
}
}
------
//It is equal to this:
query
.beginGroup()
.equalTo("${Column.PARAMS}.${Column.FIELD_TYPE}", DCParamModel.FieldType.BOOLEAN)
.equalTo("${Column.PARAMS}.${Column.KEY}", DCParamObject.FAVORITE)
.equalTo("${Column.PARAMS}.${Column.F_BOOL}", true)
.endGroup()
fun <T> buildQuery(query: RealmQuery<T>, build: RealmQuery<T>.() -> Unit): RealmQuery<T> {
query.build()
return query
}
fun <T> RealmQuery<T>.build(build: RealmQuery<T>.() -> Unit): RealmQuery<T> {
return buildQuery(this, build)
}
fun <T> RealmQuery<T>.group(build: RealmQuery<T>.() -> Unit) {
beginGroup()
build()
endGroup()
}
fun <T> RealmQuery<T>.not(build: RealmQuery<T>.() -> Unit) {
beginGroup()
not()
build()
endGroup()
}
fun <T> RealmQuery<T>.linkedField(vararg fieldNames: String): String {
return RealmUtil.getField(*fieldNames)
}
val <T> RealmQuery<T>.or: Unit
get() {
or()
}
val <T> RealmQuery<T>.and: Unit
get() {
and()
}
infix fun <T> RealmQuery<T>.or(first: Any) {
or()
}
infix fun <T> RealmQuery<T>.and(first: Any) {
and()
}
infix fun <T> RealmQuery<T>.not(first: Any) {
not()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment