12

我刚刚开始使用 Anorm 和解析器组合器。似乎有很多样板代码。例如,我有

case class Model(
    id:Int,
    field1:String,
    field2:Int,
    // a bunch of fields omitted
)

val ModelParser:RowParser[RegdataStudentClass] = {
  int("id") ~
  str("field1") ~
  int("field2") ~
  // a bunch of fields omitted
  map {
    case id ~ field1 ~ field2 //more omissions
        => Model(id, field1, field2, // still more omissions
           )
  }
}

在定义整个事物之前,每个数据库字段都会重复四次(!)。似乎解析器应该能够从案例类中半自动推导出来。有什么工具或其他技术可以建议减少这里涉及的工作吗?

感谢您的任何指示。

4

2 回答 2

3

这是我最终开发的解决方案。我目前在我的 Play 项目中将此作为课程;它可以(应该!)变成一个独立的工具。要使用它,请将tableNameval 更改为表的名称。然后使用main类底部的 运行它。它将打印案例类和解析器组合器的骨架。大多数时候,这些骨架只需要很少的调整。

拜伦

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))
  }
}
于 2012-11-02T13:22:38.067 回答
3

好吧,你实际上根本不需要重复任何事情。您可以使用flatten创建一个元组,然后从该元组创建模型实例:

(int("id") ~ str("field1") ~ int("field2"))
  .map(flatten)
  .map { tuple => (Model apply _).tupled(tuple) }

但是,如果您需要进行一些进一步的转换,则需要以某种方式修改元组:

(int("id") ~ str("field1") ~ int("field2"))
  .map(flatten)
  .map { tuple => (Model apply _).tupled(tuple.copy(_1=..., _2=....) }
于 2012-10-24T16:06:08.040 回答