essential-slick
essential-slick copied to clipboard
Mention nesting tuples
In chapter 5, in the nested case class example, we should point out that for >22 columns you can nest the tuple in the mapping to avoid having a >22 tuple:
E.g.,
// Packing a row into the structure we want:
def pack(row: (String, String, (String, String, String), Long)): User =
User(
EmailContact(row._1, row._2),
Address(row._3._1, row._3._2, row._3._3), row._4)
// Unpacking our structure into a row representation:
def unpack(user: User): Option[(String, String, (String, String, String), Long)] = Some(
(user.contact.name, user.contact.email, (user.address.street, user.address.city, user.address.country), user.id)
)
// We only project the columns we are interested in:
def * = (name, email, (street, city, country), id) <> (pack, unpack)
... the point being that the * projection there has a tree structure too so is only a tuple of length 3, despite containing 6 values.
This is all horrible. Can shapeless make it better?
We should also mention you can define projections for each type you want to nest. Here's an example:
def * = (name, address) <> (Person.tupled, Person.unapply)
def name = (givenName, familyName) <> (Name.tupled, Name.unapply)
def address = (street, city) <> (Address.tupled, Address.unapply)
...where Person is something like case class Person(name: Name, addr: Address)
Note the * projection delegates to the name and address projections. I think they should probably be private, but I've not tried it out.
(from https://groups.google.com/forum/#!msg/scalaquery/agAgJPuXYG8/AMAv04Z2USQJ)
With mapTo in Slick 3.2 I don't think this is relevant anymore.
This is still relevant because you just can't write a tuple with >22 elements for the left-hand side of mapTo. So if you want to avoid HLists for some reason, you need these tricks.