Vistritium
Vistritium

Reputation: 26

Filtering on slick table query is not working when using column not defined in projection

I need to use column that is not used in the projection - column value. Then I'm using this column for filtering. But I'm getting class cast exception.

import slick.ast.BaseTypedType
import slick.jdbc.JdbcType
import slick.jdbc.PostgresProfile.api.*
import slick.lifted.ProvenShape

import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.*

case class Foo(value: WrappedString)
case class WrappedString(s: String)

object ClassCastException {

  implicit val wrappedMap: JdbcType[WrappedString] & BaseTypedType[WrappedString] = MappedColumnType.base[WrappedString, String](
    wrapped => wrapped.s,
    str => WrappedString(str)
  )

  class FooTable(tag: Tag) extends Table[Foo](tag, "foo") {

    def valueWrapped: Rep[WrappedString] = column[WrappedString]("value", O.PrimaryKey)
    def value: Rep[String] = column("value")

    def * = valueWrapped.<>(
      (wrapped: WrappedString) => Foo(wrapped),
      (foo: Foo) => Some(foo.value)
    )
  }

  val database = Database.forURL(
    url = "jdbc:postgresql://127.0.0.1:5432/bug",
    user = "postgres",
    password = "pass",
    driver = "org.postgresql.Driver"
  )

  val fooTableQuery = TableQuery[FooTable]

  def main(args: Array[String]): Unit = {
    Await.result(database.run(
      for {
        _ <- fooTableQuery.schema.createIfNotExists
        _ <- fooTableQuery.delete
        _ <- fooTableQuery += Foo(WrappedString("example"))
        _ <- fooTableQuery.result // works
        _ <- fooTableQuery.filter(_.value === "example").result // java.lang.ClassCastException:
        // class WrappedString cannot be cast to class java.lang.String
      } yield {}
    ), 10.seconds)
  }
}

Why is it not working, how can I make it work?

Upvotes: 0

Views: 53

Answers (0)

Related Questions