Scala + Cassandra + Phantom. Modeling Multiple Tables for Same Entity

587 views Asked by At

In my Cassandra keyspace i have a main offer table and three more copies of same table, oriented to different query arguments, as follow:

offer (primary key offer_id) (... some attributes)
offer_by_product (primary key product_id, offer_id) (... some attributes)
offer_by_seller (primary key seller_id, offer_id) (... some attributes)
offer_by_sku (primary key sku_id, offer_id) (... some attributes)

All columns are exact the same, changing only the partition key and clustering key, but i need to duplicate a lot of code to implement CRUD operations for all four tables using Scala+Phantom.

There are any way to implement my repository, using Scala+Phantom, without code duplication for CRUD operations or some good pratice with less duplication?

2

There are 2 answers

0
Thiago Pereira On BEST ANSWER

Well, as @flavian already said, you cannot do that, nonetheless I could at least extract the objects into a trait like this.

trait MyCommonModel[O <: CassandraTable[O, R], R] {

  var cassandra: O = _

  object commonField extends StringColumn(cassandra)
  ...

}

Then you can use like this in your model:

sealed class MyModel extends CassandraTable[MyModel, Model] with MyCommonModel[MyModel, Model]

Thus you will inherit all objects from the CommonModel.

UPDATE

I've created a github project to show how to model cassandra tables in scala using phantom-dsl following the documentation. Check out here.

https://github.com/iamthiago/cassandra-phantom

0
flavian On

You cannot currently get away without the duplication. The upcoming enterprise version of phantom features automated code generation and schema migrations, so you will be able to use autotables to generate all Cassandra code directly from case class definitions.

For now, repetition is the way forward, but your work is extremely limited as you can mostly copy paste with minimal changes. It's not 100% ideal, yet it's still a vast improvement over any other option.