如何使用exported根据传入参数添加多个或过滤条件?

Jeb*_*bin 3 kotlin kotlin-exposed

我必须or使用参数值向查询添加条件。

例子:select * from users where email = "abc@xyz.com" or phone="1234123412";

用户可以发送两个字段或仅发送一个字段。我想在每个字段的循环中执行此操作,并将每个字段添加到or where条件中。

val query = Users.selectAll()
**var predicates = Op.build { Users.id inList listOf<Int>()}**
for((k, v) in params) {
    val value = URLDecoder.decode(v.first(), "UTF-8")
    predicates = when(k) {
        "email" -> predicates.or(Users.email eq value)
        "phone" -> predicates.or(Users.phone eq value)
    }
}
query.andWhere { predicates }
Run Code Online (Sandbox Code Playgroud)

上面的 DSL 生成下面的 SQL。

SELECT * from users where (((false = true) OR (users.email = "abc@xyz.com")) OR (users.phone = "1234567890"))
Run Code Online (Sandbox Code Playgroud)

看到了吗false = true?那是因为,要使用.or方法,我必须用条件进行初始化。下面给出的代码片段是为初始化谓词而添加的不必要的代码行。

var predicates = Op.build { Users.id inList listOf<Int>()}
Run Code Online (Sandbox Code Playgroud)

初始化它的正确方法是什么,以便我可以无缝地将多个谓词添加orand查询中?

Tap*_*pac 5

首先,我建议优化您的代码,例如:

    val params = mapOf<String, List<String>>()
    val emails = params.filterKeys { it == "email" }.map { URLDecoder.decode(it.value.first(), "UTF-8") }
    val phones = params.filterKeys { it == "phone" }.map { URLDecoder.decode(it.value.first(), "UTF-8") }

    if (emails.isEmpty() && phones.isEmpty()) {
        error("No suitable params were provided")
    } else {
        Users.select {
            Users.email inList emails or (Users.phone inList phones)
        }
    }
Run Code Online (Sandbox Code Playgroud)

UPD:orWhere 函数自 0.16.1 版本起在 Exposed 中可用。

如果您想使用模式匹配 ( ),请以相同的方式when定义您的本地函数:orWhereandWhere

fun Query.orWhere(andPart: SqlExpressionBuilder.() -> Op<Boolean>) = adjustWhere {
    val expr = Op.build { andPart() }
    if(this == null) expr
    else this or expr
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

val query = Users.selectAll()
for((k, v) in params) {
    val value = URLDecoder.decode(v.first(), "UTF-8")
    predicates = when(k) {
        "email" -> query.orWhere { Users.email eq value }
        "phone" -> query.orWhere{ Users.phone eq value }
    }
}

Run Code Online (Sandbox Code Playgroud)