Maniyan
Maniyan

Reputation: 35

Pattern matching using regex with Scala Anorm

I'm Using Scala(2.11) and playframework(2.3) and trying to run a query using a helper function to get results through pattern matching. The function is as follows

def resultsfunc() = {

   val gradeRegex = "^Class 5\."
   val currRegex = "\.NCERT$"

   DB.withConnection{ implicit c =>
     val filterQuery = SQL(
      """
        select * from tbl_graphs
        where graph_name REGEXP '{grade_regex}' and
        graph_name REGEXP '{curr_regex}' and org_id = 4
      """)
      .on("grade_regex" -> gradeRegex,
          "curr_regex" -> currRegex)

    filterQuery().map{ graphRecord =>
        
        new ResultObj(graphRecord[Long]("id"),
                    graphRecord[String]("name"))

       }.toList
    }
}

I don't get any errors but I get empty result even though there are multiple records that match the pattern. The same query works if I try to run in mysql workbench and when I tried to print filterQuery the arguments were also mapped correctly.

Should Pattern matching with regex must be carried out differently in Scala Anorm ?

Upvotes: 0

Views: 51

Answers (1)

cchantep
cchantep

Reputation: 9168

It has absolutely nothing to do specifically with Anorm.

  1. Make sure that executing manually the query with exactly the same data and parameter, you get result.
  2. When using JDBC (even through Anorm), string parameter must not be quoted in the query statement (... '{grade_regex}' ...).
  3. Since a long time, it's recommended to use Anorm interpolation (SQL"SELECT x FROM y WHERE z = ${v}") rather than SQL(..) function.

Upvotes: 0

Related Questions