How would I go about expressing something like "no...
# exposed
u
How would I go about expressing something like "now + 5 minutes" as a column default? I know I can solve it via
clientDefault()
but it should be doable with
defaultExpression()
too I think.
Copy code
datetime("expires_at").clientDefault { (Clock.System.now() + 5.minutes).toLocalDateTime(TimeZone.UTC) }
c
Hi @Up All time math options are not currently available out-of-the-box, so you can just create the SQL function or operator that you require. The exact implementation comes down to what SQL you are trying to generate for your database. For example: If you're using MySQL, one of the options could be:
DEFAULT (TIMESTAMPADD(MINUTE, 5, NOW())) NOT NULL
If you're using PostgreSQL, maybe this is what you want:
DEFAULT NOW() + INTERVAL '5 MINUTE' NOT NULL
The following example shows how you could generate this SQL:
Copy code
// Exposed provides CURRENT_TIMESTAMP()
// so this is only if you would prefer NOW() specifically
object NowDateTime : Function<LocalDateTime>(KotlinLocalDateTimeColumnType()) {
    override fun toQueryBuilder(queryBuilder: QueryBuilder) {
        queryBuilder { +"NOW()" }
    }
}

class AddTs(
    val expr: Expression<LocalDateTime>,
    val interval: Int,
    val unit: DateTimeUnit,
) : Function<LocalDateTime>(KotlinLocalDateTimeColumnType()) {
    override fun toQueryBuilder(queryBuilder: QueryBuilder) {
        queryBuilder {
            // simplify to the exact db & SQL function you need
            when (currentDialect) {
                is MysqlDialect -> {
                    +"TIMESTAMPADD("
                    append("$unit, $interval, ", expr)
                    +")"
                }
                is PostgreSQLDialect -> {
                    append(expr, " + INTERVAL ")
                    append("'$interval $unit'")
                }
                else -> error("Not implemented")
            }
        }
    }
}

fun ExpressionWithColumnType<LocalDateTime>.plus(
    interval: Int,
    unit: DateTimeUnit,
) = AddTs(this, interval, unit)

// example usage
val expiresAt = datetime("expires_at")
            .defaultExpression(NowDateTime.plus(5, DateTimeUnit.MINUTE))
u
I see, thank you