scala - Slick:如何按 isBefore Timestamp 数据库属性过滤?
问题描述
我在 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 中正确/正式地覆盖这个用例?
解决方案
我通过重用项目slick-joda-mapper解决了这个问题。由于使用了 Slick 生成器等,该解决方案有点涉及,但它非常干净,我喜欢它。基本上,它可以将数据库日期时间类型映射到 Joda 类型,例如org.joda.time.DateTime
. 因此,我的解决方案变得像使用 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)
}
推荐阅读
- javascript - 在重定向期间将令牌从 API 传递到前端
- r - 如何从下拉列表中过滤数据?
- flutter - 如何在颤动的下拉列表中显示 Json 数据
- c# - 如何修复“Zlib 异常:错误状态(不正确的数据检查)”
- schema.org - 如何使用 JSON-LD 将自定义属性添加到“产品”类型?
- android - 为什么物理模拟器不显示?
- javascript - React App Clickhandler 验证问题
- sql-server - 使表格自动更新行
- python - 为什么我不能在 python CMD 模块中使用彩色提示?
- kubernetes - Kubernetes 应用层服务发现的最佳实践是什么?