Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Creates an update statement for a SQL db table from a type where some or all of the values might be None
- * If all the values are None will return empty string else it will create the appropriate strings for the Some values
- *
- * This could be much improved and generalised but its just a simple example. Useful when using db libraries
- * where SQL is used as with Doobie. For example, an endpoint may want to update a resource and the entity may
- contain many optional fields.
- */
- case class Person(name: Option[String],
- age: Option[Int])
- type Foo = (Option[String], Option[Person])
- def createSetStatement[B](fieldValue: Option[B], fieldName: String) =
- fieldValue.fold(Option.empty[String])(x => Some(s"$fieldName = $x"))
- def concatSqlString(tableName: String, updates: Foo, whereField: String, whereValue: String) = {
- val update = {
- List(
- createSetStatement(updates._1, "team"),
- updates._2.fold(Option.empty[String])(t => createSetStatement(t.name, "name")),
- updates._2.fold(Option.empty[String])(t => createSetStatement(t.age, "age"))
- ) flatten
- } mkString ","
- if (!update.isEmpty)
- s"UPDATE $tableName\n" +
- s"SET $update\n" +
- s"WHERE $whereField = $whereValue" else ""
- }
- concatSqlString(
- tableName = "person",
- updates = (Some("Tottenham"), Some(Person(Some("Julian Fenner"), None))),
- "claimId",
- "1"
- )
- //res0: String = UPDATE person
- // SET team = Tottenham,name = Julian Fenner
- // WHERE claimId = 1
- concatSqlString(
- tableName = "person",
- updates = (None, None),
- "claimId",
- "1"
- )
- //res1: String =
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement