DANG Fan
DANG Fan

Reputation: 864

How can I reuse Slick query

My table definitions are

class Ipv4ToCountries(tag: Tag) extends Table[(Long, String)](tag, "IP2COUNTRIES") {
  def ip = column[Long]("IP")
  def country = column[String]("COUNTRY")

  def * = (ip, country)
}

class Ipv6ToCountries(tag: Tag) extends Table[(BigDecimal, String)](tag, "IPV6_2COUNTRIES") {
  def ip = column[BigDecimal]("IP")
  def country = column[String]("COUNTRY")

  def * = (ip, country)
}

class Country2Languages(tag: Tag) extends Table[(String, String, String)](tag, "COUNTRY2LANGUAGES") {
  def code = column[String]("CODE")
  def lang_code = column[String]("LANG_CODE")
  def iso_country = column[String]("ISO_COUNTRY")

  def * = (code, lang_code, iso_country)
}

Note that the only difference between Ipv4ToCountries and Ipv6ToCountries is the type of ip column. Here is my query function:

  def getLangCode(ip: String): Future[String] = {
    InetAddress.getByName(ip) match {
      case ipv4: Inet4Address =>
        val q = (for {
          i <- ipv4s.sortBy(_.ip.desc) if i.ip < ipv4ToLong(ipv4)
          c <- ip2nationCountries if i.country === c.code
        } yield c.lang_code).take(1)
        db.run(q.result.head)
      case ipv6: Inet6Address =>
        val q = (for {
          i <- ipv6s.sortBy(_.ip.desc) if i.ip < ipv6ToDecimal(ipv6)
          c <- ip2nationCountries if i.country === c.code
        } yield c.lang_code).take(1)
        db.run(q.result.head)
    }
  }

The query for IPv4 and IPv6 is almost identical but the condition if i.ip < addrToNumeric.

Is there any way to reuse the query?

Upvotes: 1

Views: 257

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

You can have a common parametrized class like

class IpToContries[A: TypeMapper](t: Tag, s: String) extends Table[(A, String)](t, s) {
  def ip = column[A]("IP")
  def country = column[String]("COUNTRY")

  def * = (ip, country)
}

and then use it like

class Ipv4Countries(tag: Tag) extends IpToContries[Long](tag, "IP2COUNTRIES")
class Ipv6Countries(tag: Tag) extends IpToContries[BigDecimal](tag, "IPV6_2COUNTRIES")

I haven't tested it, but the TypeMapper context bound on A should specify the generic type enough to be used in that fashion.

Upvotes: 1

Related Questions