MohammadBaqer
MohammadBaqer

Reputation: 1415

Kotlin Exposed selectAllWhere

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.

Upvotes: 0

Views: 825

Answers (2)

MohammadBaqer
MohammadBaqer

Reputation: 1415

you just should use Table.select{ Table.someColumn eq something } and the result would be a list of resultRow and you can map them by .map extension function.

Upvotes: 0

Andrei Naumets
Andrei Naumets

Reputation: 494

I wrote it for myself. I created an extension function.

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

And added parameters 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 }
}

this is how I'm using it.

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()]
}

Upvotes: 1

Related Questions