What different between default and clientDefault function in Exposed?

Viewed 717

I use Exposed library in Kotlin project. On my table declaration, I have a column like this:

val updatedDate = datetime("updated_dt").clientDefault { DateTime.now() }

What different if I replace clientDefault function by default as below:

val updatedDate = datetime("updated_dt").default(DateTime.now())

I've see source code of this two function, but still no idea.

clientDefault function:

fun <T:Any> Column<T>.clientDefault(defaultValue: () -> T): Column<T> {
        this.defaultValueFun = defaultValue
        this.dbDefaultValue = null
        return this
    }

default function:

fun <T:Any> Column<T>.default(defaultValue: T): Column<T> {
        this.dbDefaultValue = SqlExpressionBuilder.run {
            asLiteral(defaultValue)
        }
        this.defaultValueFun = { defaultValue }
        return this
    }
1 Answers

The difference in general is (going just by the code you quoted):

  1. default only accepts a fixed T and will generate a DEFAULT SQL clause;

  2. clientDefault accepts a function generating a T (so it can return different results for different rows) and doesn't generate a DEFAULT.

So default(DateTime.now()) is nearly certainly not what you want; it'll generate something like DEFAULT "2019-10-10T..." with the datetime it's called, not DEFAULT NOW().

Related