Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8804715
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T01:40:40+00:00 2026-06-14T01:40:40+00:00

I’m just getting started with Anorm and parser combinators. It seems like there is

  • 0

I’m just getting started with Anorm and parser combinators. It seems like there is an awful lot of boilerplate code. For example, I have

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
           )
  }
}

Each database field is repeated four (!) times before the whole thing is defined. It seems like the parser should be able to be deduced semi-automatically from the case class. Any tools or other techniques to suggest to reduce the work involved here?

Thanks for any pointers.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T01:40:42+00:00Added an answer on June 14, 2026 at 1:40 am

    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))
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I know there's a lot of other questions out there that deal with this
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I've got a string that has curly quotes in it. I'd like to replace
I have this code to decode numeric html entities to the UTF8 equivalent character.
I would like to run a str_replace or preg_replace which looks for certain words

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.