How can I use the new Slick 2.0 HList to overcome 22 column limit?

后端 未结 2 1703
南笙
南笙 2021-02-05 11:18

I\'m currently writing Slick code to target an old schema with two tables > 22 columns. How do I use the new HList code? I\'ve got 2.0-M3 working fine in other respects under Sc

2条回答
  •  醉话见心
    2021-02-05 11:50

    Definition

    With Scala >= 2.10.4-RC2 (also emitted by the Slick 2.0.0 code generator):

    import scala.slick.collection.heterogenous._
    import syntax._
    class Joiners(tag: Tag) extends Table[
        Int :: Option[String] :: Option[String] :: HNil
    ](tag, "joiner") {
      ...
      def * = id :: name :: contact :: HNil
    }
    

    The above leads to exponential compilation times in Scala 2.10.3 / 2.10.4-RC1. Not feasible for more than 26 columns due to extremely long compilation.

    Workaround for Scala <= 2.10.3 / 2.10.4-RC1 (also emitted by the Slick 2.0.1 code generator)

    import scala.slick.collection.heterogenous._
    import syntax._
    class Joiners(tag: Tag) extends Table[
        HCons[Int, HCons[Option[String], HCons[Option[String], HNil]]]
    ](tag, "joiner") {
      ...
      def * = id :: name :: contact :: HNil
    }
    

    Tested by us with 30-40 columns without problems.

    There currently still seem to be a problem with occasional sporadic compilation errors in Scala 2.10.4-RC2, which looks like it will be fixed in the upcoming 2.10.4-RC3. See https://issues.scala-lang.org/browse/SI-8146

    Example usage

    Joiners.run.map( r => r(2) ) // Gets column contact. It's typesafe. .apply is a macro. Only works for literals not for variables as positions.
    

    Use tuples for < 22 to be able to map them to a case class. Use HLists for > 22 without mapping to a case class (max field limit in Scala 2.10 is 22).

    Also: Do NOT use O.Nullable. Use column[Option[String]] instead. It infers nullability.

提交回复
热议问题