使用 slick, scala 将 smallint 转换为布尔值

Cast a smallint to boolean with slick, scala

我想将 postgres smallint 表示为布尔值。当使用 asColumnOf 操作时,出现错误 ERROR: operator does not exist: smallint = boolean。有没有办法使用 slick 将 smallint 转换为布尔值。

case class Bike(id: Long, hasBasket: Boolean)

trait BikeTable {
class Bikes(tag: Tag) extends Table[Bike](tag, "bike") {
  def id = column[Long]("id")
  def hasBasket = column[Boolean]("has_basket")
  overide def *  = (id,hasBasket) <> ((Bike.apply _).tupled, Bike.unapply)
}

protected val bycles = TableQuery[Bikes]
}


def getBycycleFilterDetails(bycleSearch:BycleSearch): 
Future[Seq[BycleDetails]] = {
val query = for {
  bikes <- byclces

} yield (byclces.id, byclces.hasBasket)


val possiblyFilteredByHasBasket = if (bycleSearch.hasBasket.isDefined) {
  query.withFilter(u => u._2.asColumnOf[Boolean] === bycleSearch.hasBasket.get)
} else query

val result = possiblyFilteredByHasBasket.result

如果我使用

   u => u._2.asColumnOf[Boolean] == bycleSearch.hasBasket.get or  u => u._2 == bycleSearch.hasBasket.get

我得到空结果集, 如果我使用

   u => u._2.asColumnOf[Boolean] === bycleSearch.hasBasket.get  or u => u._2 === bycleSearch.hasBasket.get

我收到 postgres 错误 above.The table 是 postgres 数据库用我无法控制的 smallint 类型表示 has_basket。

我认为,您应该在 table:

中覆盖 * 方法
trait BikeTable {
class Bikes(tag: Tag) extends Table[Bike](tag, "bike") {
  def id = column[Long]("id")
  def hasBasket = column[Boolean]("has_basket")

  override def * = (id, hasBasket).mapTo[Bike]
}

来自 Slick 的 documentation

Every table requires a * method contatining a default projection. This describes what you get back when you return rows (in the form of a table object) from a query. Slick’s * projection does not have to match the one in the database. You can add new columns (e.g. with computed values) or omit some columns as you like. The non-lifted type corresponding to the * projection is given as a type parameter to Table. For simple, non-mapped tables, this will be a single column type or a tuple of column types.

您不需要使用 asColumnOf

我认为这不受支持,请参阅 github。com/slick/slick/issues/1111

我使用的解决方法

    case class Bool(value: Boolean)

    implicit val hasBasketColumnType: BaseColumnType[Bool] = MappedColumnType.base[Bool, Short]({ b => if (b == Bool(true)) 1 else 0}, { i => if (i == 1) Bool(true)  else Bool(false) })

并在所有地方使用这种类型而不是布尔值

     u => u._2 === Bool(bycleSearch.hasBasket.get)

不知道这样做是否正确,