nodecosmos / charybdis

Rust ORM for ScyllaDB and Apache Cassandra
MIT License
108 stars 6 forks source link

Handling Counters #6

Closed DanielHe4rt closed 5 months ago

DanielHe4rt commented 5 months ago

Hey!

There's any example on how to increment/decrement using counters? I tried to look at the docs or even inspecting the charybdis counter type but with no luck.

GoranBrkuljan commented 5 months ago

We don't have macro-generated direct methods, I might implement them. For now you could use something like following:


#[charybdis_model(
    table_name = node_counters,
    partition_keys = [id],
    clustering_keys = [branch_id],
    global_secondary_indexes = []
)]
#[derive(Serialize, Deserialize, Default, Debug)]
pub struct NodeCounter {
    #[serde(rename = "branchId")]
    pub branch_id: Uuid,

    #[serde(rename = "id")]
    pub id: Uuid,

    #[serde(rename = "likeCount")]
    pub like_count: Option<Counter>,

    #[serde(rename = "descendantsCount")]
    pub descendants_count: Option<Counter>,
}

impl NodeCounter {
    async fn increment_like(data: &RequestData, id: Uuid, branch_id: Uuid) -> Result<(), NodecosmosError> {
        execute(
            data.db_session(),
            update_node_counter_query!("like_count = like_count + 1"),
            (id, branch_id),
        )
        .await?;

        Ok(())
    }

    async fn decrement_like(data: &RequestData, id: Uuid, branch_id: Uuid) -> Result<(), NodecosmosError> {
        execute(
            data.db_session(),
            update_node_counter_query!("like_count = like_count - 1"),
            (id, branch_id),
        )
        .await?;

        Ok(())
    }
}

Note automatically generated update_node_counter_query rule. This will automatically generate static str constant that combines update clause with provided set clause. So here

      execute(
            data.db_session(),
            update_node_counter_query!("like_count = like_count + 1"),
            (id, branch_id),
        )
        .await?;

query here will be UPDATE node_counters SET like_count = like_count + 1 WHERE id = ? AND branch_id = ?. As id and branch_id are primary keys.

So convention is update<model_name>_query.
This is definitely not the best, but might be useful for now until we implement some better solution. In future we can add macro-generated funs where we would do model.increment_counter(increment: u32).await?;