scalacassandraphantom-dsl

How to model nested class with Phantom Cassandra driver


I have a case class that has a number of nested classes. How do I model with is Phantom DSL

Putting it all into one case class is not an option.

For example:

case class Car(age: Int,size: Int,door: Door)
case class Door(color:String, size:Int)

Thanks


Solution

  • Well, when modeling things on Cassandra, you should have in mind that it does not work like relational databases and phantom is not a kind of hibernate.

    One important thing when modeling is to consider the queries you want to do, but let's get to the point.

    Phantom does allow you to model nested classes, using the json table.

    Consider the following:

    case class JsonTest(prop1: String, prop2: String)
    
    case class JsonClass(
      id: UUID,
      name: String,
      json: JsonTest,
      jsonList: List[JsonTest],
      jsonSet: Set[JsonTest]
    )
    

    You have inside the JsonClass 3 columns with JsonTest case class type.

    When declaring your fields, you should do something like this:

    object json extends JsonColumn[ConcreteJsonTable, JsonClass, JsonTest](this) {
        override def fromJson(obj: String): JsonTest = {
          JsonParser.parse(obj).extract[JsonTest]
        }
    
        override def toJson(obj: JsonTest): String = {
          compactRender(Extraction.decompose(obj))
        }
      }
    
      object jsonList extends JsonListColumn[ConcreteJsonTable, JsonClass, JsonTest](this) {
        override def fromJson(obj: String): JsonTest = {
          JsonParser.parse(obj).extract[JsonTest]
        }
    
        override def toJson(obj: JsonTest): String = {
          compactRender(Extraction.decompose(obj))
        }
      }
    
      object jsonSet extends JsonSetColumn[ConcreteJsonTable, JsonClass, JsonTest](this) {
        override def fromJson(obj: String): JsonTest = {
          JsonParser.parse(obj).extract[JsonTest]
        }
    
        override def toJson(obj: JsonTest): String = {
          compactRender(Extraction.decompose(obj))
        }
      }
    

    Basically what phantom is doing is to save a string json representation inside a string column.

    source: https://github.com/outworkers/phantom/blob/develop/phantom-dsl/src/test/scala/com/websudos/phantom/tables/JsonTable.scala