After 15 minutes trying to figure out why Slick wan’t giving me the possibility to filter an Option column, I will write a little post about it.
Base camp
My problem started because of the schema definition that I had. Notice that in order to tell Slick that it should map bar as Option, I was doing it with bar.?
1 |
case class Foo(id: String, bar: Option[String]) |
1 2 3 4 5 6 7 8 |
class FooTable(tag: Tag) extends Table[Foo](tag, "FOO") { def id = column[String]("id", O.PrimaryKey) def bar = column[String]("bar") def * = (id, bar.?) <> (Foo.tupled, Foo.unapply) } |
In the DAO I want to have a method that filters the rows for which bar is empty. With the initial schema definition, the methods isNull & isNotNull from trait ColumnExtensionMethods are deprecated. As everyone already knows, it isn’t a good idea to use deprecated methods, because the sooner or later they will be removed and that would make upgrades a harder task.
isEmpty & isDefined
Looking below at the code, I realized that the methods that I was looking for, isEmpty & isDefined, were defined inside the class AnyOptionExtensionMethods. In order to be able to use them, simply modify your schema definition by using column[Option[String]] instead of column[String]. Notice that for the mapping I don’t use .? anymore.
1 2 3 4 5 6 7 8 |
class FooTable(tag: Tag) extends Table[Foo](tag, "FOO") { def id = column[String]("id", O.PrimaryKey) def bar = column[Option[String]]("bar") def * = (id, bar) <> (Foo.tupled, Foo.unapply) } |
I hope this post helps you to save time or at least teach you something. If you liked it, share it! and if you want to get my new posts in your inbox, subscribe!