Rust ORM for ScyllaDB and Apache Cassandra
partial_! macrofind_! macroCachingSession as a session arg for operationsfind_! macro we can run complex queries that are generated at compile time
as &'static strcharybdis-migrateBefore 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.
[dependencies]
scylla = "1.4"
charybdis = "1.1" 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,
} 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.
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:
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)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:
--drop-and-replace flag)Frozen<> to satisfy ScyllaDB’s requirements. Frozen>> #[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 {...}CLUSTERING ORDER and COMPACT STORAGE options.Model dropping is not added. If you removed model, you need to drop table manually.
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.
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;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);
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);
For each operation you need to bring respective trait into scope. They are defined
in charybdis::operations module.
… let user = User {id, ..Default::default()};
let user = user.find_by_primary_key().execute(&session).await?; let users = User {id, ..Default::default()}.find_by_partition_key().execute(&session).await;let users = User::find_by_primary_key_value(val: User::PrimaryKey).execute(&session).await;…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));let user = User::from_json(json);
user.username = "scylla".to_string();
user.email = "[email protected]";
user.update().execute(&session).await;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;#[charybdis_model(
table_name = post_counters,
partition_keys = [id],
clustering_keys = [],
)]
pub struct PostCounter {
id: Uuid,
likes: Counter,
comments: Counter,
}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;No open issues yet, or sync has not completed.