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

Gustav Elmgren

02/08/2022, 4:24 PM
Hi everyone. I'm trying to add a custom function for postgres (the
nullif
function). But I have no idea what to specify the column type as. Any thoughts?
b

Bogdan

02/08/2022, 7:54 PM
do with generic
g

Gustav Elmgren

02/09/2022, 4:57 PM
I'm not sure how that would help me. A function requires a column type, but the
nullif
does not have one I guess?
b

Bogdan

02/10/2022, 3:41 PM
Copy code
class NullIf<T>(expr: ExpressionWithColumnType<T>, default: Expression<T>) :
    CustomFunction<T>("nullif", expr.columnType, expr, default)
or
Copy code
class NullIf<T>(expr: Expression<T>, default: Expression<T>, columnType: IColumnType) :
    CustomFunction<T>("nullif", columnType, expr, default)

fun <T> nullif(expr: ExpressionWithColumnType<T>, default: Expression<T>): NullIf<T> =
    NullIf(expr, default, expr.columnType)

fun <T> nullif(expr: Expression<T>, default: ExpressionWithColumnType<T>): NullIf<T> =
    NullIf(expr, default, default.columnType)

// optimistic: VarCharColumnType
fun <T> nullif(expr: Expression<T>, default: Expression<T>): NullIf<T> =
    NullIf(expr, default, VarCharColumnType())
Copy code
fun <T> nullif(expr: ExpressionWithColumnType<T>, default: T): NullIf<T> =
    NullIf(expr, QueryParameter(default, expr.columnType), expr.columnType)
g

Gustav Elmgren

02/10/2022, 3:57 PM
Ah, I see. But in the cases where it returns null, it would still think it would be of type T, which cant be null?
b

Bogdan

02/10/2022, 4:38 PM
Yes. Need a question mark
Copy code
fun <T> nullif(expr: ExpressionWithColumnType<T>, default: T): NullIf<T?> =
+-
I showed an example. Experiment with generics to get the results you want
g

Gustav Elmgren

02/11/2022, 11:11 AM
I see. Thanks!!
5 Views