Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. /**
  2. * Creates an update statement for a SQL db table from a type where some or all of the values might be None
  3. * If all the values are None will return empty string else it will create the appropriate strings for the Some values
  4. *
  5. * This could be much improved and generalised but its just a simple example. Useful when using db libraries
  6. * where SQL is used as with Doobie. For example, an endpoint may want to update a resource and the entity may
  7. contain many optional fields.
  8. */
  9. case class Person(name: Option[String],
  10. age: Option[Int])
  11.  
  12. type Foo = (Option[String], Option[Person])
  13.  
  14.  
  15.  
  16. def createSetStatement[B](fieldValue: Option[B], fieldName: String) =
  17. fieldValue.fold(Option.empty[String])(x => Some(s"$fieldName = $x"))
  18.  
  19. def concatSqlString(tableName: String, updates: Foo, whereField: String, whereValue: String) = {
  20. val update = {
  21. List(
  22. createSetStatement(updates._1, "team"),
  23. updates._2.fold(Option.empty[String])(t => createSetStatement(t.name, "name")),
  24. updates._2.fold(Option.empty[String])(t => createSetStatement(t.age, "age"))
  25. ) flatten
  26. } mkString ","
  27.  
  28. if (!update.isEmpty)
  29. s"UPDATE $tableName\n" +
  30. s"SET $update\n" +
  31. s"WHERE $whereField = $whereValue" else ""
  32. }
  33.  
  34. concatSqlString(
  35. tableName = "person",
  36. updates = (Some("Tottenham"), Some(Person(Some("Julian Fenner"), None))),
  37. "claimId",
  38. "1"
  39. )
  40. //res0: String = UPDATE person
  41. // SET team = Tottenham,name = Julian Fenner
  42. // WHERE claimId = 1
  43.  
  44.  
  45. concatSqlString(
  46. tableName = "person",
  47. updates = (None, None),
  48. "claimId",
  49. "1"
  50. )
  51. //res1: String =
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement