我正在Scala应用程序中使用Slick 3.2。
在我的应用程序中,所有表都将created_at
和updated_at
作为其字段。
例如,users
表具有created_at
和updated_at
。
当我通过实现扩展方法的Slick更新这些表时,我想隐式更新updated_at
。
有没有办法实现这种方法?
package com.example
object Main {
import slick.jdbc.MySQLProfile.api._
import java.time.Instant
import slick.jdbc.JdbcType
import java.sql.Timestamp
implicit val instantColumnType: JdbcType[Instant] with BaseTypedType[Instant] = ??? // definition is omitted.
case class User(id: Int, name: String, mail: String, createdAt: Instant, updatedAt: Instant)
abstract class AppTable[T](tag: Tag, tableName: String) extends Table[T](tag, tableName) {
def createdAt = column[Instant]("created_at")
def updatedAt = column[Instant]("updated_at")
}
class UserTable(tag: Tag) extends AppTable[User](tag, "users") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def mail = column[String]("mail")
def * = (id, name, mail, createdAt, updatedAt) <> ((User.apply _).tupled, User.unapply)
}
val users: TableQuery[UserTable] = ??? // instantiation of users is omitted.
def main(args: Array[String]): Unit = {
// This needs to execute SQL like
// UPDATE users SET name = 'foo', mail = 'bar@example.com', updated_at = '2019-06-02T02:27:43'
users
.filter(record => record.id === 42)
.updateExtra(
record => (record.name, record.mail),
("foo", "bar@example.com"),
)
}
}
答案 0 :(得分:0)
也许不是您要找的解决方案,但是我将使用触发器将这一功能推送到数据库中。可能可以在Slick中进行定义,但是很可能甚至更容易使用SQL。像这样
create trigger before update on users
for each row
set NEW.updated_at = UTC_TIMESTAMP
end;