Slick:如何通过isBefore Timestamp数据库属性进行过滤?

时间:2019-05-26 12:50:24

标签: scala jodatime slick slick-joda-mapper

我天真地在Slick 4.0.1上执行了以下操作。我有一个到期数据库字段,我需要找到给定时间戳记之前到期的所有行。

这是Slick映射的样子:

/** Table description of table auth_token. Objects of this class serve as prototypes for rows in queries. */
class AuthToken(_tableTag: Tag) extends profile.api.Table[AuthTokenRow](_tableTag, Some("myappdb"), "auth_token") with IdentifyableTable[Long] {
  override def id = userId

  def * = (userId, tokenId, expiry) <> (AuthTokenRow.tupled, AuthTokenRow.unapply)
  /** Maps whole row to an option. Useful for outer joins. */
  def ? = ((Rep.Some(userId), Rep.Some(tokenId), Rep.Some(expiry))).shaped.<>({ r => import r._; _1.map(_ => AuthTokenRow.tupled((_1.get, _2.get, _3.get))) }, (_: Any) => throw new Exception("Inserting into ? projection not supported."))

  /** Database column user_id SqlType(BIGINT UNSIGNED) */
  val userId: Rep[Long] = column[Long]("user_id")
  /** Database column token_id SqlType(CHAR), Length(36,false) */
  val tokenId: Rep[String] = column[String]("token_id", O.Length(36, varying = false))
  /** Database column expiry SqlType(TIMESTAMP) */
  val expiry: Rep[java.sql.Timestamp] = column[java.sql.Timestamp]("expiry")

  /** Foreign key referencing User (database name auth_token_ibfk_1) */
  lazy val userFk = foreignKey("auth_token_ibfk_1", userId, User)(r => r.id, onUpdate = ForeignKeyAction.NoAction, onDelete = ForeignKeyAction.Cascade)

  /** Index over (tokenId) (database name idx_token_id) */
  val index1 = index("idx_token_id", tokenId)
}
/** Collection-like TableQuery object for table AuthToken */
lazy val AuthToken = new TableQuery(tag => new AuthToken(tag))

然后我需要做:

/**
 * Finds expired tokens.
 *
 * @param dateTime The current date time.
 */
def findExpired(dateTime: org.joda.time.DateTime): Future[Seq[AuthTokenRow]] = {
  val action = AuthToken.filter(authToken => authToken.expiry.isBefore(dateTime)).result
  db.run(action)
}

如何在Slick中正确/正式地涵盖此用例?

1 个答案:

答案 0 :(得分:1)

我通过重用项目slick-joda-mapper解决了这个问题。由于与Slick生成器等配合使用,因此需要一些解决方案,但是它非常干净,我喜欢它。基本上,它可以将数据库日期时间类型映射到org.joda.time.DateTime之类的Joda类型。因此,我的解决方案变得像使用Joda DateTime支持的比较运算符一样简单:

/**
 * Finds expired tokens.
 *
 * @param dateTime The current date time.
 */
override def findExpired(dateTime: org.joda.time.DateTime): Future[Seq[AuthTokenRow]] = {
  val action = AuthToken.filter(authToken => authToken.expiry < dateTime).result
  db.run(action)
}