2
data class User(
    var name: String? = null,
    val mobile: String,
    var email: String? = null
) : Principal, BaseTable()

Ideally, what I would want is to have the common logic for the generation of the lastModified, createdAt fields to reside in some common class (e.g: BaseTable)

abstract class BaseTable {
    private lateinit var createdAt: DateTime
    private lateinit var lastModified: DateTime
}

Which would act as the parent of all my models since I want the createdAt and lastModified fields in every table.

To be clear, here is the behavior I want:

  • createdAt: Just store the time when the row was created, and never change again
  • lastModified: Every time a row is updated, update this field as well. When a new row is created createdAt = lastModified.

Is there a way to do this using Kotlin (Jetbrains) Exposed SQL library?

Aditya Anand
  • 776
  • 2
  • 9
  • 29
  • You could define StatementInterceptor which will actualize your fields or just use built in expressions of your database (like `ON UPDATE current_timestamp` in MySQL) – Tapac Jan 11 '20 at 09:05
  • Could you link to a sample implementation @Tapac? – Aditya Anand Jan 11 '20 at 14:12

2 Answers2

2

For createdAt case there's clientDefault function:

abstract class BaseTable : IntIdTable() {
   val createdAt = datetime("created_at").clientDefault { DateTime.now() }
}

Not aware of any solution for lastModified, though. I'm setting it in the DAO manually.

Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
  • For `createdAt` there's also `defaultExpression`, at least in current version: `val createdAt = timestamp("created_at").defaultExpression( CurrentTimestamp() )`. However, I'm still searching for an automatic solution for `lastModified`. – Tim van der Leeuw Apr 22 '21 at 09:04
1

Spent a day searching for a solution

Here is a possible recipe

I myself removed all the abstractions and implemented hooks where I needed them.

Ilya
  • 1,349
  • 11
  • 16