Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

charybdis

> 数据库
Open source

Rust ORM for ScyllaDB and Apache Cassandra

176 stars0 likes1 views
WebsiteGitHub

About

Rust ORM for ScyllaDB and Apache Cassandra

Rust ORM for ScyllaDB and Apache Cassandra

Charybdis is a ORM layer on top of ScyllaDB Rust Driver focused on easy of use and performance

Usage considerations:

  • Provide and expressive API for CRUD & Complex Statement operations on model as a whole
  • Provide easy way to work with subset of model fields by using automatically generated partial_! macro
  • Provide easy way to run complex queries by using automatically generated find_! macro
  • Automatic migration tool analyzes the project files and runs migrations according to differences between the model definition and database

Performance consideration:

  • It uses prepared statements (shard/token aware) -> bind values
  • It expects CachingSession as a session arg for operations
  • Queries are macro generated str constants (no concatenation at runtime)
  • By using find_! macro we can run complex queries that are generated at compile time as &'static str
  • Although it has expressive API it's thin layer on top of scylla_rust_driver, and it does not introduce any significant overhead

Table of Contents

  • Charybdis Models
    • Define Tables
    • Define UDTs
    • Define Materialized Views
    • Partial Models
      • Benefits
      • Requirements
      • As Native
  • Automatic migration with charybdis-migrate
  • Basic Operations
    • Insert
    • Find
      • Find by primary key
      • Find by partition key
      • Find by primary key associated
      • Available find functions
      • Custom filtering
    • Update
    • Delete
      • Macro generated delete helpers
      • Custom delete queries
  • Configuration Options
  • Batch Operations
    • Chunked Batch Operations
    • Batch Configuration
  • Callbacks
    • Implementation
    • Triggering Callbacks
  • Collection
    • Generated Collection Queries
    • Generated Collection Methods
  • Ignored fields
  • Roadmap

Charybdis Models

Before getting started, ensure that the scylla dependency is included in your Cargo.toml file. The version of scylla should match the one used by the charybdis crate.

toml
[dependencies]
scylla = "1.4"
charybdis = "1.1"

Define Tables

  use charybdis::macros::charybdis_model;
  use charybdis::types::{Text, Timestamp, Uuid};

  #[charybdis_model(
      table_name = users,
      partition_keys = [id],
      clustering_keys = [],
      global_secondary_indexes = [username],
      local_secondary_indexes = [],
      static_columns = []
  )]
  pub struct User {
      pub id: Uuid,
      pub username: Text,
      pub email: Text,
      pub created_at: Timestamp,
      pub updated_at: Timestamp,
      pub address: Address,
  }

Define UDT

 use charybdis::macros::charybdis_udt_model;
 use charybdis::types::Text;

 #[charybdis_udt_model(type_name = address)]
 pub struct Address {
     pub street: Text,
     pub city: Text,
     pub state: Option,
     pub zip: Text,
     pub country: Text,
 }

UDT fields must be in the same order as they are in the database.

Note that in order for migration to correctly detect changes on each migration, type_name has to match struct name. So if we have struct ReorderData we have to use #[charybdis_udt_model(type_name = reorderdata)] - without underscores.

Define Materialized Views

use charybdis::macros::charybdis_view_model;
use charybdis::types::{Text, Timestamp, Uuid};

#[charybdis_view_model(
    table_name=users_by_username,
    base_table=users,
    partition_keys=[username],
    clustering_keys=[id]
)]
pub struct UsersByUsername {
    pub username: Text,
    pub id: Uuid,
    pub email: Text,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

Resulting auto-generated migration query will be:

sql
CREATE MATERIALIZED VIEW IF NOT EXISTS users_by_email
AS SELECT created_at, updated_at, username, email, id
FROM users
WHERE email IS NOT NULL AND id IS NOT NULL
PRIMARY KEY (email, id)

Automatic migration

  • charybdis-migrate enables automatic migration to database without need to write migrations by hand. It iterates over project files and generates migrations based on differences between model definitions and database. It supports following operations:

    • Create new tables
    • Create new columns
    • Drop columns
    • Change field types (drop and recreate column --drop-and-replace flag)
      • ⚠️ This operation drops and recreates the column, permanently deleting any existing data in it. If the field is nested inside one or more frozen collections, ensure that all nested collections are also declared as Frozen<> to satisfy ScyllaDB’s requirements. Frozen>>
    • Create secondary indexes
    • Drop secondary indexes
    • Create UDTs
    • Create materialized views
    • Table options
        #[charybdis_model(
            table_name = commits,
            partition_keys = [object_id],
            clustering_keys = [created_at, id],
            global_secondary_indexes = [],
            local_secondary_indexes = [],
            table_options = r#"
                CLUSTERING ORDER BY (created_at DESC)
                AND gc_grace_seconds = 86400
            "#
        )]
        #[derive(Serialize, Deserialize, Default)]
        pub struct Commit {...}
      • ⚠️ If table exists, table options will result in alter table query that without CLUSTERING ORDER and COMPACT STORAGE options.

    Model dropping is not added. If you removed model, you need to drop table manually.

  • Running migration

    bash
    cargo install charybdis-migrate
    
    migrate --hosts  --keyspace  --drop-and-replace (optional)
    • ⚠️ Always run migrations from desired directories ('src' or 'test'), to avoid scanning 'target' or other large directories.

    • ⚠️ If you are working with existing datasets, before running migration you need to make sure that your model definitions structure matches the database in respect to table names, column names, column types,partition keys,clustering keys and secondary indexes so you don't alter structure accidentally. If structure is matched, it will not run any migrations. As mentioned above, in case there is no model definition for table, it will not drop it. In future, we will add modelize command that will generate src/models files from existing data source.

    • ⚠️ Make sure that nested collections are 'Frozen' as per ScyllaDB requirement, so when using --drop-and-replace flag, it will drop and recreate columns.

  • Programmatically running migrations

    Within testing or development environment, we can trigger migrations programmatically:

    use charybdis::migrate::MigrationBuilder;
    
    let migration = MigrationBuilder::new()
        .keyspace("test")
        .drop_and_replace(true)
        .build(&session)
        .await;
    
    migration.run().await;
  • Global secondary indexes

    If we have model:

    #[charybdis_model(
        table_name = users,
        partition_keys = [id],
        clustering_keys = [],
        global_secondary_indexes = [username]
    )]

    resulting query will be: CREATE INDEX ON users (username);

  • Local secondary Indexes

    Indexes that are scoped to the partition key

    #[charybdis_model(
        table_name = menus,
        partition_keys = [location],
        clustering_keys = [name, price, dish_type],
        global_secondary_indexes = [],
        local_secondary_indexes = [dish_type]
    )]

    resulting query will be: CREATE INDEX ON menus((location), dish_type);

Basic Operations:

For each operation you need to bring respective trait into scope. They are defined in charybdis::operations module.

Insert

…

Find

  • Find by primary key

      let user = User {id, ..Default::default()};
      let user = user.find_by_primary_key().execute(&session).await?;
  • Find by partition key

      let users =  User {id, ..Default::default()}.find_by_partition_key().execute(&session).await;
  • Find by primary key associated

    let users = User::find_by_primary_key_value(val: User::PrimaryKey).execute(&session).await;
  • Available find functions

…
  • Custom filtering:

    Lets use our Post model as an example:

    #[charybdis_model(
        table_name = posts,
        partition_keys = [category_id],
        clustering_keys = [date, title],
        global_secondary_indexes = []
    )]
    pub struct Post {...}

    We get automatically generated find_post! macro that follows convention find_!. It can be used to create custom queries.

    Following will return stream of Post models, and query will be constructed at compile time as &'static str.

    // automatically generated macro rule
    let posts = find_post!("category_id in ? AND date > ?", (categor_vec, date))
        .execute(session)
        .await?;

    We can also use find_first_post! macro to get single result:

    let post = find_first_post!("category_id in ? AND date > ? LIMIT 1", (date, categor_vec))
        .execute(session)
        .await?;

    If we just need the Statement and not the result, we can use find_post_query! macro:

    let query = find_post_query!("date = ? AND category_id in ?", (date, categor_vec));

Update

  • let user = User::from_json(json);
    
    user.username = "scylla".to_string();
    user.email = "[email protected]";
    
    user.update().execute(&session).await;
  • Collection:

    • Let's use our User model as an example:
      #[charybdis_model(
          table_name = users,
          partition_keys = [id],
          clustering_keys = [],
      )]
      pub struct User {
          id: Uuid,
          tags: Set,
          post_ids: List,
      }
    • push_to_ and pull_from_ methods are generated for each collection field.
      let user: User;
      
      user.push_tags(vec![tag]).execute(&session).await;
      user.pull_tags(vec![tag]).execute(&session).await;
      
      user.push_post_ids(vec![tag]).execute(&session).await;
      user.pull_post_ids(vec![tag]).execute(&session).await;
  • Counter

    • Let's define post_counter model:
      #[charybdis_model(
          table_name = post_counters,
          partition_keys = [id],
          clustering_keys = [],
      )]
      pub struct PostCounter {
          id: Uuid,
          likes: Counter,
          comments: Counter,
      }
    • We can use increment_ and decrement_ methods to update counter fields.
      let post_counter: PostCounter;
      post_counter.increment_likes(1).execute(&session).await;
      post_counter.decrement_likes(1).execute(&session).await;

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustcassandracqldatabaseorm

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库