Skip to content

Commit

Permalink
Make coalesce support multiple arguments #1352 / Fixes and improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Tapac committed Oct 25, 2021
1 parent fb8d322 commit 4fcb50b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -300,11 +300,13 @@ class CaseWhenElse<T, R : T>(val caseWhen: CaseWhen<T>, val elseResult: Expressi
/**
* Represents an SQL function that returns the first of its arguments that is not null.
*/
class Coalesce<out T>(
private vararg val expressions: ExpressionWithColumnType<T?>,
) : Function<R>(expressions.first().columnType) {
class Coalesce<out T, S : T?, R : T>(
private val expr: ExpressionWithColumnType<S>,
private val alternate: Expression<out T>,
private vararg val others: Expression<out T>
) : Function<R>(expr.columnType) {
override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder {
expressions.toList().appendTo(
(listOf(expr, alternate) + others).appendTo(
prefix = "COALESCE(",
postfix = ")",
separator = ", "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,8 +364,11 @@ interface ISqlExpressionBuilder {
// Conditional Expressions

/** Returns the first of its arguments that is not null. */
fun <T, S : T?, E : ExpressionWithColumnType<S>, R : T> coalesce(expr: E, alternate: ExpressionWithColumnType<out T>): Coalesce<T?, S, R> =
Coalesce(expr, alternate)
fun <T, S : T?, A : Expression<out T>, R : T> coalesce(
expr: ExpressionWithColumnType<S>,
alternate: A,
vararg others: A
): Coalesce<T?, S, R> = Coalesce(expr, alternate, others = others)

fun case(value: Expression<*>? = null): Case = Case(value)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,10 +427,22 @@ class FunctionsTests : DatabaseTestsBase() {

users.slice(users.cityId, coalesceExp1).selectAll().forEach {
val cityId = it[users.cityId]
if (cityId != null)
if (cityId != null) {
assertEquals(cityId, it[coalesceExp1])
else
} else {
assertEquals(1000, it[coalesceExp1])
}
}

val coalesceExp2 = Coalesce(users.cityId, Op.nullOp<Int>(), intLiteral(1000))

users.slice(users.cityId, coalesceExp2).selectAll().forEach {
val cityId = it[users.cityId]
if (cityId != null) {
assertEquals(cityId, it[coalesceExp2])
} else {
assertEquals(1000, it[coalesceExp2])
}
}
}
}
Expand Down

0 comments on commit 4fcb50b

Please sign in to comment.