Using Slick (Scala), is there a way to add a column to a table 'on the fly'?
scala, slick
Solution
Yes, this is possible. When you define a column as part of a Table definition, it is done by calling the Table object's 'column' method. You can do the same from the outside, e.g.:
for {
a <- TableA
b <- TableB if a.id === b.column[String]("dynamic1")
} yield b.column[Int]("dynamic2")
The type parameter determines the right implicit ColumnType to use for the column. You can also get a ColumnType dynamically and supply that parameter explicitly.
Note that there is no requirement for the * projection of a table to contain all columns. If you want to generate the DDL for dynamically discovered columns, you can include those columns in the Seq returned by create_*.
Problem
I would like to write my Scala+Slick application so that a user could configure additional columns to a table without having to modify the source code. Is there a way to do that? Adam S - Yes, that is what I am thinking of. The program would come with a default configuration file, and the end user/administrator could optionally add new columns to some of the tables and when the program started it would add those columns. There are a few other ways I was thinking of going, such as configuring the initial table with spare columns that the user would configure (but that suffers from limiting the number of spares and pre-defining the types). Another way was to define a second table that had the same primary key(s) as the original, and have it contain only user defined data, and then the program would have to deal with maintaining both tables (each would have the same number of rows), which would allow the original default table to be handled more conventionally. The two tables might be kept in sync with database functions (which would make it database specific).