Home > Mobile >  Kotlin Exposed selectAllWhere
Kotlin Exposed selectAllWhere

Time:01-30

I need to implement selectAll() with where query using exposed.

here is my code:

suspend fun getAll(
    page: Int, size: Int, keyword: String = ""
): List<DTO> = suspendableQuery {
    table.selectAll()
        .limit(size, page.toLong())
        .andWhere(searchCondition(keyword))
        .map(::toDTO)
}
fun searchCondition(keyword: String): 
    SqlExpressionBuilder.() -> Op<Boolean> = {
        if (keyword.isNotEmpty()) (UserTable.phone eq keyword) or 
    (UserTable.name eq keyword) else Op.TRUE
}

doesn't matter if I put empty string or a word into keyword parameter, it doesn't work any way and I get empty list as result.

the question is how can I implement search feature with kotlin exposed.

CodePudding user response:

I wrote it for me. I created extension function

fun <T> Query.addAndOp(param: T?, opBuilder: (T) -> Op<Boolean>): Query {
    return if (param != null) andWhere { opBuilder(param) } else this
}

And added my params like that

private fun Query.buildWhere(
    text: String? = null,
    language: String? = null,
    country: String? = null
): Query {
    return andWhere { PhraseTable.ban eq false }
        .addAndOp(text) { PhraseTable.phrase.lowerCase().like("%${it.lowercase()}%") }
        .addAndOp(language) { PhraseTable.lang eq it }
        .addAndOp(country) { PhraseTable.country eq it }
}

It was used here.

fun count(
    text: String? = null,
    language: String? = null,
    country: String? = null
) = transaction {
    val query = PhraseTable
        .slice(PhraseTable.id.countDistinct())
        .selectAll()
        .buildWhere(text, language, country)

    return@transaction query.first()[PhraseTable.id.countDistinct()]
}
  • Related