Here's the solution I eventually developed. I currently have this as a class in my Play project; it could (should!) be turned into a stand-alone tool. To use it, change the tableName
val to the name of your table. Then run it using the main
at the bottom of the class. It will print a skeleton of the case class and the parser combinator. Most of the time these skeletons require very little tweaking.
Byron
package tools
import scala.sys.process._
import anorm._
/**
* Generate a parser combinator for a specified table in the database.
* Right now it's just specified with the val "tableName" a few lines
* down.
*
* 20121024 bwbecker
*/
object ParserGenerator {
val tableName = "uwdata.uwdir_person_by_student_id"
/**
* Convert the sql type to an equivalent Scala type.
*/
def fieldType(field:MetaDataItem):String = {
val t = field.clazz match {
case "java.lang.String" => "String"
case "java.lang.Boolean" => "Boolean"
case "java.lang.Integer" => "Int"
case "java.math.BigDecimal" => "BigDecimal"
case other => other
}
if (field.nullable) "Option[%s]" format (t)
else t
}
/**
* Drop the schema name from a string (tablename or fieldname)
*/
def dropSchemaName(str:String):String =
str.dropWhile(c => c != '.').drop(1)
def formatField(field:MetaDataItem):String = {
"\t" + dropSchemaName(field.column) + " : " + fieldType(field)
}
/**
* Derive the class name from the table name: drop the schema,
* remove the underscores, and capitalize the leading letter of each word.
*/
def deriveClassName(tableName:String) =
dropSchemaName(tableName).split("_").map(w => w.head.toUpper + w.tail).mkString
/**
* Query the database to get the metadata for the given table.
*/
def getFieldList(tableName:String):List[MetaDataItem] = {
val sql = SQL("""select * from %s limit 1""" format (tableName))
val results:Stream[SqlRow] = util.Util.DB.withConnection { implicit connection => sql() }
results.head.metaData.ms
}
/**
* Generate a case class definition with one data member for each field in
* the database table.
*/
def genClassDef(className:String, fields:List[MetaDataItem]):String = {
val fieldList = fields.map(formatField(_)).mkString(",\n")
""" case class %s (
%s
)
""" format (className, fieldList )
}
/**
* Generate a parser for the table.
*/
def genParser(className:String, fields:List[MetaDataItem]):String = {
val header:String = "val " + className.take(1).toLowerCase() + className.drop(1) +
"Parser:RowParser[" + className + "] = {\n"
val getters = fields.map(f =>
"\tget[" + fieldType(f) + "](\"" + dropSchemaName(f.column) + "\")"
).mkString(" ~ \n")
val mapper = " map {\n case " + fields.map(f => dropSchemaName(f.column)).mkString(" ~ ") +
" =>\n\t" + className + "(" + fields.map(f => dropSchemaName(f.column)).mkString(", ") + ")\n\t}\n}"
header + getters + mapper
}
def main(args:Array[String]) = {
val className = deriveClassName(tableName)
val fields = getFieldList(tableName)
println( genClassDef(className, fields) )
println( genParser(className, fields))
}
}