https://kotlinlang.org logo
#exposed
Title
# exposed
m

Mranders

09/01/2020, 8:35 AM
What is the correct way to create a NULL valued expression? Let's say I want a branch of a case/when/else to result in NULL.
k

Kenneth Wußmann

09/01/2020, 10:14 AM
Hey, not quite sure if I got your question right, but you can do something like this:
Copy code
Person.find {
    when (something) {
        "ABC" -> Persons.age eq 21
        else -> Persons.age.isNull()
    }
}
m

Mranders

09/01/2020, 11:17 AM
I'm referring to an SQL case statement (using SqlExpressionBuilder), like this:
Copy code
private fun SqlExpressionBuilder.filteredString(expr: Expression<String?>): Expression<String?> {
    return case()
            .When(expr neq stringLiteral("foo"), expr)
            .Else(???)
}
What is an appropriate way to fill the else part? The isNull extension returns an Op<Boolean>, which can't be used in this case.
k

Kenneth Wußmann

09/01/2020, 11:29 AM
Hm, not sure if there is one included but you can write one yourself:
Copy code
fun <T> nullExpr() = object : Expression<T>() {
    override fun toQueryBuilder(queryBuilder: QueryBuilder) {
        queryBuilder {
            append("NULL")
        }
    }
}
👍 1
m

Mranders

09/01/2020, 11:52 AM
I was just wondering if there was some built in function to do it. I ended up creating the following function:
Copy code
private fun <T> nullLiteral(columnType: IColumnType): LiteralOp<T?> =
        LiteralOp(columnType.apply { nullable = true }, null)
t

tapac

09/01/2020, 1:21 PM
I would advice to use @Kenneth Wußmann code as your function will mutate original columnType and if you call it like
nullLiteral(MyTable.notNullColumn)
you will end up with wrong behavior on
notNullColumn
. I will add similar code into the next release.
👍 2
2 Views