Passing JsValue or JsObject as parameters • Passing as parameters any type, that can be written as JSON using Writes : anorm.postgresql.asJson[T: Writes]
Passing JsValue or JsObject as parameters • Passing as parameters any type, that can be written as JSON using Writes • Parsing textual or JSONB column as JsValue
selectJsValue(implicit con: Connection) = SQL"""SELECT json FROM test WHERE id = ${"foo"}""". as(SqlParser.scalar[JsValue].single) def selectJsObject(implicit con: Connection) = SQL"""SELECT json FROM test WHERE id = ${"foo"}""". as(SqlParser.scalar[JsObject].single)
Passing JsValue or JsObject as parameters • Passing as parameters any type, that can be written as JSON using Writes • Parsing textual or JSONB column as JsValue • Parsing any type stored as JSON column, provided appropriate Reads: anorm.postgresql.fromJson[T: Reads]
trait MyEnum case object Bar extends MyEnum case object Lorem extends MyEnum // Define the typeclass instance implicit val r: Reads[MyEnum] = Reads[MyEnum] { js => (js \ "bar").validate[Int].map { case 1 => Bar case _ => Lorem } } def selectFromJson(implicit con: Connection) = SQL"""SELECT json FROM test WHERE id = ${"foo"}""". as(SqlParser.scalar(fromJson[MyEnum]).single)
extends Family case object Lorem extends Family // First, RowParser instances for all the subtypes must be provided, // either by macros or by custom parsers implicit val barParser = Macro.namedParser[Bar] implicit val loremParser = RowParser[Lorem.type] { anyRowDiscriminatedAsLorem => Success(Lorem) } val familyParser = Macro.sealedParser[Family]
FROM test WHERE parent_id ISNULL) t2 ON t1.parent_id=t2.id WHERE t1.id='bar'; id | value | parent_id | id | value | parent_id -----+--------+-----------+-----+--------+----------- bar | value2 | foo | foo | value1 | (1 row) Consider the following query results:
SqlParser.str("id") ~ SqlParser.str("value") ~ SqlParser.str("parent.value") ~ SqlParser.str("parent.parent_id").? map(SqlParser.flatten) val aliaser: ColumnAliaser = ColumnAliaser.withPattern((3 to 6).toSet, "parent.") val res: Try[(String, String, String, Option[String])] = SQL"""SELECT * FROM test t1 JOIN (SELECT * FROM test WHERE parent_id ISNULL) t2 ON t1.parent_id=t2.id WHERE t1.id=${"bar"}""". asTry(parser.single, aliaser)