Meredith Meredith - 8 months ago 38
Scala Question

Access database column names from a Table?

Let's say I have a table:

object Suppliers extends Table[(Int, String, String, String)]("SUPPLIERS") {
def id = column[Int]("SUP_ID", O.PrimaryKey)
def name = column[String]("SUP_NAME")
def state = column[String]("STATE")
def zip = column[String]("ZIP")
def * = id ~ name ~ state ~ zip

Table's database name

The table's database name can be accessed by going:

This is supported by the Scaladoc on AbstractTable.

For example, the above table's database name is "SUPPLIERS".

Columns' database names

Looking through AbstractTable,
looked promising. No column names in their string representations though.

I assume that * means "all the columns I'm usually interested in."
is a MappedProjection, which has this signature:

final case class MappedProjection[T, P <: Product](
child: Node,
f: (P) ⇒ T,
g: (T) ⇒ Option[P])(proj: Projection[P])
extends ColumnBase[T] with UnaryNode with Product with Serializable

contains a huge sequence of numbers, and I realized that at this point I'm just doing a brute force inspection of everything in the API for possibly finding the column names in the String.

Has anybody also encountered this problem before, or could anybody give me a better understanding of how MappedProjection works?


It requires you to rely on Slick internals, which may change between versions, but it is possible. Here is how it works for Slick 1.0.1: You have to go via the FieldSymbol. Then you can extract the information you want like how columnInfo(driver: JdbcDriver, column: FieldSymbol): ColumnInfo does it.

To get a FieldSymbol from a Column you can use fieldSym(node: Node): Option[FieldSymbol] and fieldSym(column: Column[_]): FieldSymbol.