How do I set the current date in db using Exposed and Kotlin
Asked Answered
E

1

14

I want to define a column of type date. This column should hold the current date of the resource created. How do i set this up? I'm new to kotlin.

In python, one would impletement it this way: date_created = db.Column(db.DateTime, default=db.func.current_timestamp())

What's the kotlin equivalent?

Elated answered 28/1, 2020 at 16:5 Comment(0)
C
30

If you want to just have a datetime column with a default value which will be evaluated on insert of a new record please use defaultExpression function:

object YourTable : IntIdTable() {
   val dateCreated = datetime("date_created").defaultExpression(CurrentDateTime)
}

If you want to generate datetime value on the client side:

object YourTable : IntIdTable() {
   val dateCreated = datetime("date_created").clientDefault{ DateTime.now() }
}
Consistency answered 29/1, 2020 at 8:59 Comment(3)
It's a class in Exposed which equals to CURRENT_TIMESTAMP SQL expressionConsistency
datetime requires exposed-java-time e.g: implementation("org.jetbrains.exposed:exposed-java-time:0.30.1")Catacomb
Very well explained, worked here.Rowdyish

© 2022 - 2024 — McMap. All rights reserved.